summaryrefslogtreecommitdiff
path: root/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/templates/SurroundPostfixTemplateBase.java
blob: b7fe95b96a5c57c8f42a436a9f0453734fcc2599 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.template.postfix.templates;

import com.intellij.lang.surroundWith.Surrounder;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;

public abstract class SurroundPostfixTemplateBase extends PostfixTemplateWithExpressionSelector {

  @NotNull protected final PostfixTemplatePsiInfo myPsiInfo;

  protected SurroundPostfixTemplateBase(@NotNull @NlsSafe String name,
                                        @NotNull @NlsSafe String descr,
                                        @NotNull PostfixTemplatePsiInfo psiInfo,
                                        @NotNull PostfixTemplateExpressionSelector selector) {
    super(name, descr, selector);
    myPsiInfo = psiInfo;
  }


  @Override
  public final void expandForChooseExpression(@NotNull PsiElement expression, @NotNull final Editor editor) {
    PsiElement replace = getReplacedExpression(expression);
    TextRange range = PostfixTemplatesUtils.surround(getSurrounder(), editor, replace);

    if (range != null) {
      editor.getCaretModel().moveToOffset(range.getStartOffset());
    }
  }

  protected PsiElement getReplacedExpression(@NotNull PsiElement expression) {
    PsiElement wrappedExpression = getWrappedExpression(expression);
    return expression.replace(wrappedExpression);
  }

  protected PsiElement getWrappedExpression(PsiElement expression) {
    if (StringUtil.isEmpty(getHead()) && StringUtil.isEmpty(getTail())) {
      return expression;
    }
    return createNew(expression);
  }

  protected PsiElement createNew(PsiElement expression) {
    return myPsiInfo.createExpression(expression, getHead(), getTail());
  }

  @NotNull
  protected @NlsSafe String getHead() {
    return "";
  }

  @NotNull
  protected @NlsSafe String getTail() {
    return "";
  }

  @NotNull
  protected abstract Surrounder getSurrounder();
}