Search in sources :

Example 16 with PsiFileFactory

use of com.intellij.psi.PsiFileFactory in project intellij-community by JetBrains.

the class CommandModeConsumer method consume.

@Override
public void consume(final String t) {
    /**
     * We need to: 1) parse input 2) fetch command 3) split its arguments.
     */
    final PsiFileFactory fileFactory = PsiFileFactory.getInstance(myModule.getProject());
    final CommandLineFile file = PyUtil.as(fileFactory.createFileFromText(CommandLineLanguage.INSTANCE, t), CommandLineFile.class);
    if (file == null) {
        return;
    }
    final String commandName = file.getCommand();
    final List<String> commandAndArgs = Arrays.asList(EMPTY_SPACE.split(file.getText().trim()));
    // 1 because we need to remove command which is on the first place
    final List<String> args = (commandAndArgs.size() > 1 ? commandAndArgs.subList(1, commandAndArgs.size()) : Collections.<String>emptyList());
    for (final Command command : myCommands) {
        if (command.getName().equals(commandName)) {
            command.execute(commandName, myModule, args, myConsole);
            return;
        }
    }
    if (myDefaultExecutor != null && !commandAndArgs.isEmpty()) {
        // Unknown command execution is delegated to default executor
        myDefaultExecutor.execute(commandAndArgs.get(0), myModule, args, myConsole);
    } else {
        myConsole.print(PyBundle.message("commandLine.commandNotFound", commandName), ConsoleViewContentType.ERROR_OUTPUT);
        myConsole.print("", ConsoleViewContentType.SYSTEM_OUTPUT);
    }
}
Also used : PsiFileFactory(com.intellij.psi.PsiFileFactory) Command(com.jetbrains.commandInterface.command.Command) CommandLineFile(com.jetbrains.commandInterface.commandLine.psi.CommandLineFile)

Example 17 with PsiFileFactory

use of com.intellij.psi.PsiFileFactory in project intellij-community by JetBrains.

the class GenerationNode method invokeXmlTemplate.

private TemplateImpl invokeXmlTemplate(final TemplateToken token, CustomTemplateCallback callback, @Nullable ZenCodingGenerator generator, final boolean hasChildren) {
    ZenCodingGenerator zenCodingGenerator = ObjectUtils.notNull(generator, XmlZenCodingGeneratorImpl.INSTANCE);
    Map<String, String> attributes = token.getAttributes();
    TemplateImpl template = token.getTemplate();
    assert template != null;
    PsiFileFactory fileFactory = PsiFileFactory.getInstance(callback.getProject());
    PsiFile dummyFile = fileFactory.createFileFromText("dummy.html", callback.getFile().getLanguage(), token.getTemplateText(), false, true);
    XmlTag tag = PsiTreeUtil.findChildOfType(dummyFile, XmlTag.class);
    if (tag != null) {
        // autodetect href
        if (EmmetOptions.getInstance().isHrefAutoDetectEnabled() && StringUtil.isNotEmpty(mySurroundedText)) {
            final boolean isEmptyLinkTag = "a".equalsIgnoreCase(tag.getName()) && isEmptyValue(tag.getAttributeValue("href"));
            if (!hasChildren && isEmptyLinkTag) {
                if (HREF_PATTERN.matcher(mySurroundedText).matches()) {
                    attributes.put("href", PROTOCOL_PATTERN.matcher(mySurroundedText).find() ? mySurroundedText.trim() : "http://" + mySurroundedText.trim());
                } else if (EMAIL_PATTERN.matcher(mySurroundedText).matches()) {
                    attributes.put("href", "mailto:" + mySurroundedText.trim());
                }
            }
        }
        for (Map.Entry<String, String> attribute : attributes.entrySet()) {
            if (Strings.isNullOrEmpty(attribute.getValue())) {
                template.addVariable(prepareVariableName(attribute.getKey()), "", "", true);
            }
        }
        XmlTag tag1 = hasChildren ? expandEmptyTagIfNecessary(tag) : tag;
        setAttributeValues(tag1, attributes, callback, zenCodingGenerator.isHtml(callback));
        token.setTemplateText(tag1.getContainingFile().getText(), callback);
    }
    template = zenCodingGenerator.generateTemplate(token, hasChildren, callback.getContext());
    removeVariablesWhichHasNoSegment(template);
    return template;
}
Also used : TemplateImpl(com.intellij.codeInsight.template.impl.TemplateImpl) PsiFileFactory(com.intellij.psi.PsiFileFactory) XmlZenCodingGenerator(com.intellij.codeInsight.template.emmet.generators.XmlZenCodingGenerator) ZenCodingGenerator(com.intellij.codeInsight.template.emmet.generators.ZenCodingGenerator) PsiFile(com.intellij.psi.PsiFile) HashMap(com.intellij.util.containers.HashMap)

Example 18 with PsiFileFactory

use of com.intellij.psi.PsiFileFactory in project azure-tools-for-java by Microsoft.

the class CreateFunctionAction method invokeDialog.

@Override
protected PsiElement[] invokeDialog(Project project, PsiDirectory psiDirectory) {
    final Operation operation = TelemetryManager.createOperation(TelemetryConstants.FUNCTION, TelemetryConstants.CREATE_FUNCTION_TRIGGER);
    try {
        operation.start();
        PsiPackage pkg = JavaDirectoryService.getInstance().getPackage(psiDirectory);
        // get existing package from current directory
        String hintPackageName = pkg == null ? "" : pkg.getQualifiedName();
        CreateFunctionForm form = new CreateFunctionForm(project, hintPackageName);
        List<PsiElement> psiElements = new ArrayList<>();
        if (form.showAndGet()) {
            final FunctionTemplate bindingTemplate;
            try {
                Map<String, String> parameters = form.getTemplateParameters();
                final String connectionName = parameters.get("connection");
                String triggerType = form.getTriggerType();
                String packageName = parameters.get("packageName");
                String className = parameters.get("className");
                PsiDirectory directory = ClassUtil.sourceRoot(psiDirectory);
                String newName = packageName.replace('.', '/');
                bindingTemplate = AzureFunctionsUtils.getFunctionTemplate(triggerType);
                operation.trackProperty(TelemetryConstants.TRIGGER_TYPE, triggerType);
                if (StringUtils.equalsIgnoreCase(triggerType, CreateFunctionForm.EVENT_HUB_TRIGGER)) {
                    if (StringUtils.isBlank(connectionName)) {
                        throw new AzureExecutionException(message("function.createFunction.error.connectionMissed"));
                    }
                    parameters.putIfAbsent("eventHubName", "myeventhub");
                    parameters.putIfAbsent("consumerGroup", "$Default");
                }
                final String functionClassContent = AzureFunctionsUtils.substituteParametersInTemplate(bindingTemplate, parameters);
                if (StringUtils.isNotEmpty(functionClassContent)) {
                    AzureTaskManager.getInstance().write(() -> {
                        CreateFileAction.MkDirs mkDirs = ApplicationManager.getApplication().runWriteAction((Computable<CreateFileAction.MkDirs>) () -> new CreateFileAction.MkDirs(newName + '/' + className, directory));
                        PsiFileFactory factory = PsiFileFactory.getInstance(project);
                        try {
                            mkDirs.directory.checkCreateFile(className + ".java");
                        } catch (final IncorrectOperationException e) {
                            final String dir = mkDirs.directory.getName();
                            final String error = String.format("failed to create function class[%s] in directory[%s]", className, dir);
                            throw new AzureToolkitRuntimeException(error, e);
                        }
                        CommandProcessor.getInstance().executeCommand(project, () -> {
                            PsiFile psiFile = factory.createFileFromText(className + ".java", JavaFileType.INSTANCE, functionClassContent);
                            psiElements.add(mkDirs.directory.add(psiFile));
                        }, null, null);
                        if (StringUtils.equalsIgnoreCase(triggerType, CreateFunctionForm.EVENT_HUB_TRIGGER)) {
                            try {
                                String connectionString = form.getEventHubNamespace() == null ? DEFAULT_EVENT_HUB_CONNECTION_STRING : getEventHubNamespaceConnectionString(form.getEventHubNamespace());
                                AzureFunctionsUtils.applyKeyValueToLocalSettingFile(new File(project.getBasePath(), "local.settings.json"), parameters.get("connection"), connectionString);
                            } catch (IOException e) {
                                EventUtil.logError(operation, ErrorType.systemError, e, null, null);
                                final String error = "failed to get connection string and save to local settings";
                                throw new AzureToolkitRuntimeException(error, e);
                            }
                        }
                    });
                }
            } catch (AzureExecutionException e) {
                AzureMessager.getMessager().error(e);
                EventUtil.logError(operation, ErrorType.systemError, e, null, null);
            }
        }
        if (!psiElements.isEmpty()) {
            FileEditorManager.getInstance(project).openFile(psiElements.get(0).getContainingFile().getVirtualFile(), false);
        }
        return psiElements.toArray(new PsiElement[0]);
    } finally {
        operation.complete();
    }
}
Also used : PsiFileFactory(com.intellij.psi.PsiFileFactory) ArrayList(java.util.ArrayList) PsiPackage(com.intellij.psi.PsiPackage) AzureToolkitRuntimeException(com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) IOException(java.io.IOException) FunctionTemplate(com.microsoft.azure.toolkit.lib.legacy.function.template.FunctionTemplate) PsiDirectory(com.intellij.psi.PsiDirectory) AzureExecutionException(com.microsoft.azure.toolkit.lib.common.exception.AzureExecutionException) CreateFunctionForm(com.microsoft.azure.toolkit.intellij.function.CreateFunctionForm) IncorrectOperationException(com.intellij.util.IncorrectOperationException) PsiFile(com.intellij.psi.PsiFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) PsiElement(com.intellij.psi.PsiElement) CreateFileAction(com.intellij.ide.actions.CreateFileAction)

Example 19 with PsiFileFactory

use of com.intellij.psi.PsiFileFactory in project intellij by bazelbuild.

the class ProjectViewElementGenerator method createDummyFile.

private static PsiFile createDummyFile(Project project, String contents) {
    PsiFileFactory factory = PsiFileFactory.getInstance(project);
    LightVirtualFile virtualFile = new LightVirtualFile(DUMMY_FILENAME, ProjectViewFileType.INSTANCE, contents);
    PsiFile psiFile = ((PsiFileFactoryImpl) factory).trySetupPsiForFile(virtualFile, ProjectViewLanguage.INSTANCE, false, true);
    assert psiFile != null;
    return psiFile;
}
Also used : PsiFileFactory(com.intellij.psi.PsiFileFactory) LightVirtualFile(com.intellij.testFramework.LightVirtualFile) PsiFileFactoryImpl(com.intellij.psi.impl.PsiFileFactoryImpl) PsiFile(com.intellij.psi.PsiFile)

Aggregations

PsiFileFactory (com.intellij.psi.PsiFileFactory)19 PsiFile (com.intellij.psi.PsiFile)13 ASTNode (com.intellij.lang.ASTNode)5 PsiFileFactoryImpl (com.intellij.psi.impl.PsiFileFactoryImpl)4 LightVirtualFile (com.intellij.testFramework.LightVirtualFile)4 RegExpPattern (org.intellij.lang.regexp.psi.RegExpPattern)4 IncorrectOperationException (com.intellij.util.IncorrectOperationException)3 RncFile (org.intellij.plugins.relaxNG.compact.psi.RncFile)3 NotNull (org.jetbrains.annotations.NotNull)3 Document (com.intellij.openapi.editor.Document)2 PsiElement (com.intellij.psi.PsiElement)2 Nullable (org.jetbrains.annotations.Nullable)2 ReformatCodeProcessor (com.intellij.codeInsight.actions.ReformatCodeProcessor)1 XmlZenCodingGenerator (com.intellij.codeInsight.template.emmet.generators.XmlZenCodingGenerator)1 ZenCodingGenerator (com.intellij.codeInsight.template.emmet.generators.ZenCodingGenerator)1 TemplateImpl (com.intellij.codeInsight.template.impl.TemplateImpl)1 CreateFileAction (com.intellij.ide.actions.CreateFileAction)1 FileTemplate (com.intellij.ide.fileTemplates.FileTemplate)1 FileType (com.intellij.openapi.fileTypes.FileType)1 Project (com.intellij.openapi.project.Project)1