com.intellij.codeInsight.template.TemplateManager Java Examples

The following examples show how to use com.intellij.codeInsight.template.TemplateManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CreateFromTemplateActionBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void startLiveTemplate(@Nonnull PsiFile file, @Nonnull Map<String, String> defaultValues) {
  Editor editor = EditorHelper.openInEditor(file);
  if (editor == null) return;

  TemplateImpl template = new TemplateImpl("", file.getText(), "");
  template.setInline(true);
  int count = template.getSegmentsCount();
  if (count == 0) return;

  Set<String> variables = new HashSet<>();
  for (int i = 0; i < count; i++) {
    variables.add(template.getSegmentName(i));
  }
  variables.removeAll(TemplateImpl.INTERNAL_VARS_SET);
  for (String variable : variables) {
    String defaultValue = defaultValues.getOrDefault(variable, variable);
    template.addVariable(variable, null, '"' + defaultValue + '"', true);
  }

  Project project = file.getProject();
  WriteCommandAction.runWriteCommandAction(project, () -> editor.getDocument().setText(template.getTemplateText()));

  editor.getCaretModel().moveToOffset(0);  // ensures caret at the start of the template
  TemplateManager.getInstance(project).startTemplate(editor, template);
}
 
Example #2
Source File: ForEachPostfixTemplate.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@Override
public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
    FluidInlineStatement expression = (FluidInlineStatement) PsiTreeUtil.findFirstParent(context, psiElement -> psiElement instanceof FluidInlineStatement);
    if (expression == null) {
        return;
    }

    Template tagTemplate = LiveTemplateFactory.createTagModeForLoopTemplate(expression);
    tagTemplate.addVariable("EACH", new TextExpression(expression.getText()), true);
    tagTemplate.addVariable("AS", new TextExpression("myVar"), true);

    int textOffset = expression.getTextOffset();
    editor.getCaretModel().moveToOffset(textOffset);

    TemplateManager.getInstance(context.getProject()).startTemplate(editor, tagTemplate);
    PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());

    expression.delete();
}
 
Example #3
Source File: DebugInlinePostfixTemplate.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@Override
public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
    FluidInlineStatement expression = (FluidInlineStatement) PsiTreeUtil.findFirstParent(context, psiElement -> psiElement instanceof FluidInlineStatement);
    if (expression == null) {
        return;
    }

    Template tagTemplate = LiveTemplateFactory.createInlinePipeToDebugTemplate(expression);
    tagTemplate.addVariable("EXPR", new TextExpression(expression.getInlineChain().getText()), true);

    int textOffset = expression.getTextOffset() + expression.getTextLength();
    editor.getCaretModel().moveToOffset(textOffset);

    TemplateManager.getInstance(context.getProject()).startTemplate(editor, tagTemplate);
    PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());

    expression.delete();
}
 
Example #4
Source File: AliasPostfixTemplate.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@Override
public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
    FluidInlineStatement expression = (FluidInlineStatement) PsiTreeUtil.findFirstParent(context, psiElement -> psiElement instanceof FluidInlineStatement);
    if (expression == null) {
        return;
    }

    Template tagTemplate = LiveTemplateFactory.createTagModeAliasTemplate(expression);
    tagTemplate.addVariable("ALIAS", new TextExpression("myVar"), true);
    tagTemplate.addVariable("EXPR", new TextExpression("'" + expression.getText() + "'"), true);

    int textOffset = expression.getTextOffset() + expression.getTextLength();
    editor.getCaretModel().moveToOffset(textOffset);

    TemplateManager.getInstance(context.getProject()).startTemplate(editor, tagTemplate);
    PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());

    expression.delete();
}
 
Example #5
Source File: FindViewByIdVariableTemplate.java    From android-postfix-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected void onTemplateFinished(final TemplateManager manager, final Editor editor, Template template) {
    final ActionManager actionManager = ActionManagerImpl.getInstance();
    final String editorCompleteStatementText = "IntroduceVariable";
    final AnAction action = actionManager.getAction(editorCompleteStatementText);
    actionManager.tryToExecute(action, ActionCommand.getInputEvent(editorCompleteStatementText), null, ActionPlaces.UNKNOWN, true);
}
 
Example #6
Source File: InvokeTemplateAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void perform() {
  final Document document = myEditor.getDocument();
  final VirtualFile file = FileDocumentManager.getInstance().getFile(document);
  if (file != null) {
    ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(file);
  }

  CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
    @Override
    public void run() {
      myEditor.getCaretModel().runForEachCaret(new CaretAction() {
        @Override
        public void perform(Caret caret) {
          // adjust the selection so that it starts with a non-whitespace character (to make sure that the template is inserted
          // at a meaningful position rather than at indent 0)
          if (myEditor.getSelectionModel().hasSelection() && myTemplate.isToReformat()) {
            int offset = myEditor.getSelectionModel().getSelectionStart();
            int selectionEnd = myEditor.getSelectionModel().getSelectionEnd();
            int lineEnd = document.getLineEndOffset(document.getLineNumber(offset));
            while (offset < lineEnd && offset < selectionEnd &&
                   (document.getCharsSequence().charAt(offset) == ' ' || document.getCharsSequence().charAt(offset) == '\t')) {
              offset++;
            }
            // avoid extra line break after $SELECTION$ in case when selection ends with a complete line
            if (selectionEnd == document.getLineStartOffset(document.getLineNumber(selectionEnd))) {
              selectionEnd--;
            }
            if (offset < lineEnd && offset < selectionEnd) {  // found non-WS character in first line of selection
              myEditor.getSelectionModel().setSelection(offset, selectionEnd);
            }
          }
          String selectionString = myEditor.getSelectionModel().getSelectedText();
          TemplateManager.getInstance(myProject).startTemplate(myEditor, selectionString, myTemplate);
        }
      });
    }
  }, "Wrap with template", "Wrap with template " + myTemplate.getKey());
}
 
Example #7
Source File: EnterHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
  final Project project = editor.getProject();
  if (project != null && TemplateManager.getInstance(project).startTemplate(editor, TemplateSettings.ENTER_CHAR)) {
    return;
  }

  if (myOriginalHandler != null) {
    myOriginalHandler.execute(editor, caret, dataContext);
  }
}
 
Example #8
Source File: SpaceHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Result beforeCharTyped(char charTyped, Project project, Editor editor, PsiFile file, FileType fileType) {
  if (charTyped == TemplateSettings.SPACE_CHAR && TemplateManager.getInstance(project).startTemplate(editor, TemplateSettings.SPACE_CHAR)) {
    return Result.STOP;
  }

  return super.beforeCharTyped(charTyped, project, editor, file, fileType);
}
 
Example #9
Source File: SurroundWithHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
static void doSurround(final Project project, final Editor editor, final Surrounder surrounder, final PsiElement[] elements) {
  if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
    return;
  }

  try {
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    int col = editor.getCaretModel().getLogicalPosition().column;
    int line = editor.getCaretModel().getLogicalPosition().line;
    if (!editor.getCaretModel().supportsMultipleCarets()) {
      LogicalPosition pos = new LogicalPosition(0, 0);
      editor.getCaretModel().moveToLogicalPosition(pos);
    }
    TextRange range = surrounder.surroundElements(project, editor, elements);
    if (range != CARET_IS_OK) {
      if (TemplateManager.getInstance(project).getActiveTemplate(editor) == null &&
          InplaceRefactoring.getActiveInplaceRenamer(editor) == null) {
        LogicalPosition pos1 = new LogicalPosition(line, col);
        editor.getCaretModel().moveToLogicalPosition(pos1);
      }
      if (range != null) {
        int offset = range.getStartOffset();
        editor.getCaretModel().removeSecondaryCarets();
        editor.getCaretModel().moveToOffset(offset);
        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
        editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
      }
    }
  }
  catch (IncorrectOperationException e) {
    LOG.error(e);
  }
}
 
Example #10
Source File: CreateRuleFix.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
	String ruleName = editor.getDocument().getText(textRange);

	prepareEditor(project, editor, file);

	Template template = TemplateManager.getInstance(project).createTemplate("", "");
	template.addTextSegment(ruleName + ": ");
	template.addVariable("CONTENT", new TextExpression("' '"), true);
	template.addTextSegment(";");

	TemplateManager.getInstance(project).startTemplate(editor, template);
}
 
Example #11
Source File: AsposeMavenUtil.java    From Aspose.OCR-for-Java with MIT License 5 votes vote down vote up
private static void runOrApplyFileTemplate(Project project,
                                           VirtualFile file,
                                           String templateName,
                                           Properties properties) throws IOException {
    FileTemplateManager manager = FileTemplateManager.getInstance();
    FileTemplate fileTemplate = manager.getJ2eeTemplate(templateName);
    Properties allProperties = manager.getDefaultProperties(project);
    allProperties.putAll(properties);
    String text = fileTemplate.getText(allProperties);
    Pattern pattern = Pattern.compile("\\$\\{(.*)\\}");
    Matcher matcher = pattern.matcher(text);
    StringBuffer builder = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(builder, "\\$" + matcher.group(1).toUpperCase() + "\\$");
    }
    matcher.appendTail(builder);
    text = builder.toString();

    TemplateImpl template = (TemplateImpl) TemplateManager.getInstance(project).createTemplate("", "", text);
    for (int i = 0; i < template.getSegmentsCount(); i++) {
        if (i == template.getEndSegmentNumber()) continue;
        String name = template.getSegmentName(i);
        String value = "\"" + properties.getProperty(name, "") + "\"";
        template.addVariable(name, value, value, true);
    }

    VfsUtil.saveText(file, template.getTemplateText());

    PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
    if (psiFile != null) {
        new ReformatCodeProcessor(project, psiFile, null, false).run();
    }

}
 
Example #12
Source File: AbstractRichStringBasedPostfixTemplate.java    From android-postfix-plugin with Apache License 2.0 5 votes vote down vote up
protected void onTemplateFinished(TemplateManager manager, Editor editor, Template template) {
    // format and add ;
    final ActionManager actionManager = ActionManagerImpl.getInstance();
    final String editorCompleteStatementText = "EditorCompleteStatement";
    final AnAction action = actionManager.getAction(editorCompleteStatementText);
    actionManager.tryToExecute(action, ActionCommand.getInputEvent(editorCompleteStatementText), null, ActionPlaces.UNKNOWN, true);
}
 
Example #13
Source File: EditorEventManager.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("WeakerAccess")
public void prepareAndRunSnippet(String insertText) {

    List<SnippetVariable> variables = new ArrayList<>();
    // Extracts variables using placeholder REGEX pattern.
    Matcher varMatcher = Pattern.compile(SNIPPET_PLACEHOLDER_REGEX).matcher(insertText);
    while (varMatcher.find()) {
        variables.add(new SnippetVariable(varMatcher.group(), varMatcher.start(), varMatcher.end()));
    }

    variables.sort(Comparator.comparingInt(o -> o.startIndex));
    final String[] finalInsertText = {insertText};
    variables.forEach(var -> finalInsertText[0] = finalInsertText[0].replace(var.lspSnippetText, "$"));

    String[] splitInsertText = finalInsertText[0].split("\\$");
    finalInsertText[0] = String.join("", splitInsertText);

    TemplateImpl template = (TemplateImpl) TemplateManager.getInstance(getProject()).createTemplate(finalInsertText[0],
            "lsp4intellij");
    template.parseSegments();

    final int[] varIndex = {0};
    variables.forEach(var -> {
        template.addTextSegment(splitInsertText[varIndex[0]]);
        template.addVariable(varIndex[0] + "_" + var.variableValue, new TextExpression(var.variableValue),
                new TextExpression(var.variableValue), true, false);
        varIndex[0]++;
    });
    // If the snippet text ends with a placeholder, there will be no string segment left to append after the last
    // variable.
    if (splitInsertText.length != variables.size()) {
        template.addTextSegment(splitInsertText[splitInsertText.length - 1]);
    }
    template.setInline(true);
    EditorModificationUtil.moveCaretRelatively(editor, -template.getTemplateText().length());
    TemplateManager.getInstance(getProject()).startTemplate(editor, template);
}
 
Example #14
Source File: FindViewByIdFieldTemplate.java    From android-postfix-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected void onTemplateFinished(final TemplateManager manager, final Editor editor, Template template) {
    final ActionManager actionManager = ActionManagerImpl.getInstance();
    final String editorCompleteStatementText = "IntroduceField";
    final AnAction action = actionManager.getAction(editorCompleteStatementText);
    actionManager.tryToExecute(action, ActionCommand.getInputEvent(editorCompleteStatementText), null, ActionPlaces.UNKNOWN, true);
}
 
Example #15
Source File: AbstractRichStringBasedPostfixTemplate.java    From HakunaMatataIntelliJPlugin with Apache License 2.0 5 votes vote down vote up
protected void onTemplateFinished(TemplateManager manager, Editor editor, Template template) {
    // format and add ;
    final ActionManager actionManager = ActionManagerImpl.getInstance();
    final String editorCompleteStatementText = "EditorCompleteStatement";
    final AnAction action = actionManager.getAction(editorCompleteStatementText);
    actionManager.tryToExecute(action, ActionCommand.getInputEvent(editorCompleteStatementText), null, ActionPlaces.UNKNOWN, true);
}
 
Example #16
Source File: FluidViewHelperReferenceInsertHandler.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@Override
public void handleInsert(InsertionContext context, LookupElement item) {
    Editor editor = context.getEditor();
    if (context.getCompletionChar() == '(') {
        context.setAddCompletionChar(false);
    }

    ViewHelper viewHelper = null;
    PsiElement completionParent = item.getPsiElement().getParent();
    if (completionParent instanceof FluidViewHelperReference) {
        viewHelper = findViewHelperByReference((FluidViewHelperReference) completionParent, item);
    } else if(completionParent instanceof FluidBoundNamespace) {
        // find viewhelper
    } else if (completionParent instanceof FluidFieldChain) {
        viewHelper = findViewHelperByFieldPosition((FluidFieldChain) completionParent, item);
    }

    if (viewHelper == null) {
        editor.getDocument().insertString(context.getTailOffset(), "()");

        return;
    }

    if (viewHelper.arguments.size() == 0) {
        editor.getDocument().insertString(context.getTailOffset(), "()");

        return;
    }

    Template t = LiveTemplateFactory.createInlineArgumentListTemplate(viewHelper);
    List<ViewHelperArgument> requiredArguments = viewHelper.getRequiredArguments();
    requiredArguments.forEach(a -> {
        int pos = requiredArguments.indexOf(a);
        t.addVariable("VAR" + pos, new TextExpression(""), true);
    });

    TemplateManager.getInstance(context.getProject()).startTemplate(context.getEditor(), t);
}
 
Example #17
Source File: MethodChainLookupElement.java    From litho with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void handleInsertInternal(
    Editor editor, Document document, int startOffset, int tailOffset, Project project) {
  // Copied from LiveTemplateLookupElementImpl
  final int offsetAfterDot =
      document.getText(TextRange.create(startOffset, tailOffset)).indexOf('.') + 1 + startOffset;
  document.deleteString(offsetAfterDot, tailOffset);
  TemplateManager.getInstance(project).startTemplate(editor, fromTemplate);
}
 
Example #18
Source File: TextUtilsIsEmptyTemplate.java    From android-postfix-plugin with Apache License 2.0 4 votes vote down vote up
@Override
protected void onTemplateFinished(TemplateManager manager, Editor editor, Template template) {
    // nothing
    // Prevent complete statement
}
 
Example #19
Source File: AddTokenDefinitionFix.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void runTemplate(@NotNull Editor editor, Project project, String tokenDefLeftSide, String tokenDefinitionExpression, PsiFile psiFile, int newLastLineStart) {
    PsiElement elementAt = Objects.requireNonNull(psiFile.findElementAt(newLastLineStart), "Unable to find element at position " + newLastLineStart).getParent();
    Template template = buildTemplate(tokenDefinitionExpression, elementAt, tokenDefLeftSide.length());
    TemplateManager.getInstance(project).startTemplate(editor, template);
}
 
Example #20
Source File: BuiltInFunctionCompletionContributor.java    From intellij with Apache License 2.0 4 votes vote down vote up
private static InsertHandler<LookupElement> createTemplateInsertHandler(Template t) {
  return (context, item) ->
      TemplateManager.getInstance(context.getProject()).startTemplate(context.getEditor(), t);
}
 
Example #21
Source File: MockitoBasePostfixTemplate.java    From HakunaMatataIntelliJPlugin with Apache License 2.0 4 votes vote down vote up
@Override
public Template createTemplate(TemplateManager manager, String templateString) {
    final Template template = super.createTemplate(manager, templateString);
    template.setValue(Template.Property.USE_STATIC_IMPORT_IF_POSSIBLE, true);
    return template;
}
 
Example #22
Source File: LiveTemplateLookupElementImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void handleInsert(InsertionContext context) {
  context.getDocument().deleteString(context.getStartOffset(), context.getTailOffset());
  context.setAddCompletionChar(false);
  TemplateManager.getInstance(context.getProject()).startTemplate(context.getEditor(), myTemplate);
}
 
Example #23
Source File: AbstractRichStringBasedPostfixTemplate.java    From android-postfix-plugin with Apache License 2.0 3 votes vote down vote up
/**
 * Create a new instance of a code template for the current postfix template.
 *
 * @param project        The current project
 * @param manager        The template manager
 * @param templateString The template string
 */
protected Template createTemplate(Project project, TemplateManager manager, String templateString) {
    Template template = manager.createTemplate("", "", templateString);
    template.setToReformat(shouldReformat());
    template.setValue(Template.Property.USE_STATIC_IMPORT_IF_POSSIBLE, false);
    return template;
}
 
Example #24
Source File: AbstractRichStringBasedPostfixTemplate.java    From HakunaMatataIntelliJPlugin with Apache License 2.0 3 votes vote down vote up
/**
 * Create a new instance of a code template for the current postfix template.
 *
 * @param project        The current project
 * @param manager        The template manager
 * @param templateString The template string
 */
protected Template createTemplate(Project project, TemplateManager manager, String templateString) {
    Template template = manager.createTemplate("", "", templateString);
    template.setToReformat(shouldReformat());
    template.setValue(Template.Property.USE_STATIC_IMPORT_IF_POSSIBLE, false);
    return template;
}