com.intellij.codeInsight.template.Template Java Examples

The following examples show how to use com.intellij.codeInsight.template.Template. 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: CreateUnresolvedMethodByLambdaTypeFix.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
@Override
public void buildTemplate(@Nonnull CreateUnresolvedElementFixContext context, CSharpContextUtil.ContextType contextType, @Nonnull PsiFile file, @Nonnull Template template)
{
	template.addTextSegment(CreateUnresolvedMethodFix.calcModifier(context).getPresentableText());
	template.addTextSegment(" ");
	if(contextType == CSharpContextUtil.ContextType.STATIC)
	{
		template.addTextSegment("static ");
	}
	template.addVariable(new TypeRefExpression(myLikeMethod.getReturnTypeRef(), file), true);
	template.addTextSegment(" ");
	template.addTextSegment(myReferenceName);

	buildParameterList(context, file, template);

	template.addTextSegment("{\n");

	template.addVariable("$RETURN_STATEMENT$", new ReturnStatementExpression(), false);
	template.addEndVariable();

	template.addTextSegment("}");
}
 
Example #2
Source File: TemplateImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public TemplateImpl copy() {
  TemplateImpl template = new TemplateImpl(myKey, myString, myGroupName);
  template.myId = myId;
  template.myDescription = myDescription;
  template.myShortcutChar = myShortcutChar;
  template.isToReformat = isToReformat;
  template.isToShortenLongNames = isToShortenLongNames;
  template.myIsInline = myIsInline;
  template.myTemplateContext = myTemplateContext.createCopy();
  template.isDeactivated = isDeactivated;
  for (Property property : Property.values()) {
    boolean value = getValue(property);
    if (value != Template.getDefaultValue(property)) {
      template.setValue(property, value);
    }
  }
  for (Variable variable : myVariables) {
    template.addVariable(variable.getName(), variable.getExpressionString(), variable.getDefaultValueString(), variable.isAlwaysStopAt());
  }
  return template;
}
 
Example #3
Source File: RulesTemplates.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static Template mandatoryAndFrequentArgumentsTemplate(RuleDefinition ruleDef) {
  TemplateImpl template = new TemplateImpl("", "");
  template.addTextSegment("(");
  ImmutableMap<String, AttributeDefinition> attributes = ruleDef.getAttributes();
  ImmutableMap<String, AttributeDefinition> requiredAttributes = ruleDef.getMandatoryAttributes();
  requiredAttributes.values().forEach(d -> addAttributeToTemplate(template, d));
  if (srcsDepsExperiment.getValue()) {
    FREQUENT_ATTRIBUTES.stream()
        .filter(a -> attributes.containsKey(a) && !requiredAttributes.containsKey(a))
        .map(attributes::get)
        .forEach(d -> addAttributeToTemplate(template, d));
  }
  template.addEndVariable();
  template.addTextSegment("\n)");
  return template;
}
 
Example #4
Source File: SnackbarTemplate.java    From android-postfix-plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected void addExprVariable(@NotNull PsiElement expr, Template template) {
    ToStringIfNeedMacro toStringIfNeedMacro = new ToStringIfNeedMacro();
    MacroCallNode macroCallNode = new MacroCallNode(toStringIfNeedMacro);
    macroCallNode.addParameter(new ConstantNode(expr.getText()));

    MacroCallNode node = new MacroCallNode(new VariableOfTypeMacro());
    node.addParameter(new ConstantNode(VIEW.toString()));
    template.addVariable("view", node, new EmptyNode(), false);

    template.addVariable("expr", macroCallNode, false);

    if (mWithAction) {
        template.addVariable("actionText", new EmptyNode(), false);
        template.addVariable("action", new EmptyNode(), false);
    }
}
 
Example #5
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 #6
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 #7
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 #8
Source File: CreateUnresolvedMethodByLambdaTypeFix.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
protected void buildParameterList(@Nonnull CreateUnresolvedElementFixContext context, @Nonnull PsiFile file, @Nonnull Template template)
{
	template.addTextSegment("(");

	CSharpSimpleParameterInfo[] parameterInfos = myLikeMethod.getParameterInfos();

	for(int i = 0; i < parameterInfos.length; i++)
	{
		if(i != 0)
		{
			template.addTextSegment(", ");
		}

		CSharpSimpleParameterInfo parameterInfo = parameterInfos[i];

		template.addVariable(new ConstantNode(CSharpTypeRefPresentationUtil.buildShortText(parameterInfo.getTypeRef(), context.getExpression())), true);
		template.addTextSegment(" ");
		template.addVariable(new ConstantNode(parameterInfo.getNotNullName()), true);

	}
	template.addTextSegment(")");
}
 
Example #9
Source File: LiveTemplateFactory.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
public static Template createInlineArgumentListTemplate(@NotNull ViewHelper viewHelper) {
    StringBuilder sb = new StringBuilder();
    List<ViewHelperArgument> requiredArguments = viewHelper.getRequiredArguments();

    sb.append("(");
    requiredArguments.forEach(a -> {
        int pos = requiredArguments.indexOf(a);
        sb.append(a.name).append(": ").append("$VAR").append(pos).append("$");

        if (requiredArguments.size() > pos + 1) {
            sb.append(", ");
        }
    });
    sb.append(")");

    TemplateImpl template = new TemplateImpl("params", sb.toString(), "Fluid");
    template.setDescription("smart viewhelper parameters completion");
    template.setToReformat(true);

    return template;
}
 
Example #10
Source File: MethodChainLookupElement.java    From litho with Apache License 2.0 6 votes vote down vote up
private static Template createTemplate(PsiElement from) {
  TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(from);
  PsiTreeUtil.processElements(
      from,
      psiElement -> {
        if (psiElement instanceof PsiIdentifier) {
          PsiIdentifier psiIdentifier = (PsiIdentifier) psiElement;
          String identifier = psiIdentifier.getText();
          if (TEMPLATE_INSERT_PLACEHOLDER.equals(identifier)) {
            templateBuilder.replaceElement(psiIdentifier, new TextExpression(""));
          } else if (TEMPLATE_INSERT_PLACEHOLDER_C.equals(identifier)) {
            templateBuilder.replaceElement(psiIdentifier, new TextExpression("c"));
          }
        }
        return true;
      });
  Template template = templateBuilder.buildTemplate();
  return template;
}
 
Example #11
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 #12
Source File: LiveTemplateFactory.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
public static Template createInlinePipeToDebugTemplate(@NotNull PsiElement source) {
    StringBuilder sb = new StringBuilder();
    sb
        .append("{ $EXPR$ -> f:debug() }")
    ;

    TemplateImpl template = new TemplateImpl("f:debug", sb.toString(), "Fluid");
    template.setDescription("f:debug the expression result");
    template.setToReformat(true);

    return template;
}
 
Example #13
Source File: TemplateSettings.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void addTemplateImpl(@Nonnull Template template) {
  TemplateImpl templateImpl = (TemplateImpl)template;
  if (getTemplate(templateImpl.getKey(), templateImpl.getGroupName()) == null) {
    myTemplates.putValue(template.getKey(), templateImpl);
  }

  myMaxKeyLength = Math.max(myMaxKeyLength, template.getKey().length());
  myState.deletedKeys.remove(TemplateKey.keyOf((TemplateImpl)template));
}
 
Example #14
Source File: TemplateSettings.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void removeTemplate(@Nonnull Template template) {
  myTemplates.remove(template.getKey(), (TemplateImpl)template);

  TemplateGroup group = mySchemesManager.findSchemeByName(((TemplateImpl)template).getGroupName());
  if (group != null) {
    group.removeElement((TemplateImpl)template);
    if (group.isEmpty()) {
      mySchemesManager.removeScheme(group);
    }
  }
}
 
Example #15
Source File: TemplateSettings.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void addTemplateById(Template template) {
  if (!myTemplatesById.containsKey(template.getId())) {
    final String id = template.getId();
    if (id != null) {
      myTemplatesById.put(id, template);
    }
  }
}
 
Example #16
Source File: LiveTemplateFactory.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
public static Template createTagModeForLoopTemplate(@NotNull PsiElement wrap) {
    StringBuilder sb = new StringBuilder();

    sb
        .append("<f:for each=\"$EACH$\" as=\"$AS$\">\n")
        .append("  $END$\n")
        .append("</f:for>\n")
    ;

    TemplateImpl template = new TemplateImpl("f:for", sb.toString(), "Fluid");
    template.setDescription("f:for loop over an expression");
    template.setToReformat(true);

    return template;
}
 
Example #17
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 #18
Source File: TemplateSettings.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void addTemplate(Template template) {
  clearPreviouslyRegistered(template);
  addTemplateImpl(template);

  TemplateImpl templateImpl = (TemplateImpl)template;
  String groupName = templateImpl.getGroupName();
  TemplateGroup group = mySchemesManager.findSchemeByName(groupName);
  if (group == null) {
    group = new TemplateGroup(groupName);
    mySchemesManager.addNewScheme(group, true);
  }
  group.addElement(templateImpl);
}
 
Example #19
Source File: FindViewByIdTemplate.java    From android-postfix-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected void addExprVariable(@NotNull PsiElement expr, Template template) {
    final FindViewByIdMacro toStringIfNeedMacro = new FindViewByIdMacro();
    MacroCallNode macroCallNode = new MacroCallNode(toStringIfNeedMacro);
    macroCallNode.addParameter(new ConstantNode(expr.getText()));
    template.addVariable("expr", macroCallNode, false);
}
 
Example #20
Source File: CreateUnresolvedPropertyFix.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Override
public void buildTemplate(@Nonnull CreateUnresolvedElementFixContext context,
		CSharpContextUtil.ContextType contextType,
		@Nonnull PsiFile file,
		@Nonnull Template template)
{
	template.addTextSegment("public ");

	if(contextType == CSharpContextUtil.ContextType.STATIC)
	{
		template.addTextSegment("static ");
	}

	// get expected from method call expression not reference
	List<ExpectedTypeInfo> expectedTypeRefs = ExpectedTypeVisitor.findExpectedTypeRefs(context.getExpression());

	if(!expectedTypeRefs.isEmpty())
	{
		template.addVariable(new TypeRefExpression(expectedTypeRefs, file), true);
	}
	else
	{
		template.addVariable(new TypeRefExpression(new CSharpTypeRefByQName(file, DotNetTypes.System.Object), file), true);
	}

	template.addTextSegment(" ");
	template.addTextSegment(myReferenceName);
	template.addTextSegment("\n{\n");
	template.addTextSegment("get;set;\n");
	template.addTextSegment("}");
	template.addEndVariable();
}
 
Example #21
Source File: LogTemplate.java    From android-postfix-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected void addExprVariable(@NotNull PsiElement expr, Template template) {
    final ToStringIfNeedMacro toStringIfNeedMacro = new ToStringIfNeedMacro();
    MacroCallNode macroCallNode = new MacroCallNode(toStringIfNeedMacro);
    macroCallNode.addParameter(new ConstantNode(expr.getText()));
    template.addVariable("expr", macroCallNode, false);
}
 
Example #22
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 #23
Source File: GenerateByPatternDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void updateDetails(final PatternDescriptor descriptor) {
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      final Template template = descriptor.getTemplate();
      if (template instanceof TemplateImpl) {
        String text = ((TemplateImpl)template).getString();
        myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), text);
        TemplateEditorUtil.setHighlighter(myEditor, ((TemplateImpl)template).getTemplateContext());
      } else {
        myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), "");
      }
    }
  });
}
 
Example #24
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 #25
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 #26
Source File: CompletionData.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static LookupElement objectToLookupItem(final @Nonnull Object object) {
  if (object instanceof LookupElement) return (LookupElement)object;

  String s = null;
  TailType tailType = TailType.NONE;
  if (object instanceof PsiElement){
    s = PsiUtilCore.getName((PsiElement)object);
  }
  else if (object instanceof PsiMetaData) {
    s = ((PsiMetaData)object).getName();
  }
  else if (object instanceof String) {
    s = (String)object;
  }
  else if (object instanceof Template) {
    s = ((Template) object).getKey();
  }
  else if (object instanceof PresentableLookupValue) {
    s = ((PresentableLookupValue)object).getPresentation();
  }
  if (s == null) {
    throw new AssertionError("Null string for object: " + object + " of class " + object.getClass());
  }

  LookupItem item = new LookupItem(object, s);

  if (object instanceof LookupValueWithUIHint && ((LookupValueWithUIHint) object).isBold()) {
    item.setBold();
  }
  item.setAttribute(LookupItem.TAIL_TYPE_ATTR, tailType);
  return item;
}
 
Example #27
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 #28
Source File: CreateUnresolvedEventFix.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Override
public void buildTemplate(@Nonnull CreateUnresolvedElementFixContext context,
		CSharpContextUtil.ContextType contextType,
		@Nonnull PsiFile file,
		@Nonnull Template template)
{
	template.addTextSegment("public ");

	if(contextType == CSharpContextUtil.ContextType.STATIC)
	{
		template.addTextSegment("static ");
	}

	template.addTextSegment("event ");

	// get expected from method call expression not reference
	List<ExpectedTypeInfo> expectedTypeRefs = ExpectedTypeVisitor.findExpectedTypeRefs(context.getExpression());

	if(!expectedTypeRefs.isEmpty())
	{
		template.addVariable(new TypeRefExpression(expectedTypeRefs, file), true);
	}
	else
	{
		template.addVariable(new TypeRefExpression(new CSharpTypeRefByQName(file, DotNetTypes.System.Object), file), true);
	}

	template.addTextSegment(" ");
	template.addTextSegment(myReferenceName);
	template.addTextSegment("\n{\n");
	template.addTextSegment("add;remove;\n");
	template.addTextSegment("}");
	template.addEndVariable();
}
 
Example #29
Source File: CreateUnresolvedConstructorFix.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Override
public void buildTemplate(@Nonnull CreateUnresolvedElementFixContext context, CSharpContextUtil.ContextType contextType, @Nonnull PsiFile file, @Nonnull Template template)
{
	template.addTextSegment("public ");
	template.addTextSegment(myReferenceName);
	buildParameterList(context, file, template);
	template.addTextSegment("{\n");
	template.addEndVariable();
	template.addTextSegment("}");
}
 
Example #30
Source File: CreateUnresolvedFieldFix.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Override
public void buildTemplate(@Nonnull CreateUnresolvedElementFixContext context, CSharpContextUtil.ContextType contextType, @Nonnull PsiFile file, @Nonnull Template template)
{
	template.addTextSegment("public ");

	if(contextType == CSharpContextUtil.ContextType.STATIC)
	{
		template.addTextSegment("static ");
	}

	// get expected from method call expression not reference
	List<ExpectedTypeInfo> expectedTypeRefs = ExpectedTypeVisitor.findExpectedTypeRefs(context.getExpression());

	if(!expectedTypeRefs.isEmpty())
	{
		template.addVariable(new TypeRefExpression(expectedTypeRefs, file), true);
	}
	else
	{
		template.addVariable(new TypeRefExpression(new CSharpTypeRefByQName(file, DotNetTypes.System.Object), file), true);
	}

	template.addTextSegment(" ");
	template.addTextSegment(myReferenceName);
	template.addTextSegment(";");
	template.addEndVariable();
}