summaryrefslogtreecommitdiff
path: root/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateCompletionContributor.java
blob: 9b3e29783b42cfec8e64f8cd70f0d4ce06b940c6 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.codeInsight.template.impl;

import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.template.CustomLiveTemplate;
import com.intellij.codeInsight.template.CustomTemplateCallback;
import com.intellij.codeInsight.template.TemplateContextType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiFile;
import com.intellij.util.Consumer;
import com.intellij.util.ProcessingContext;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

import static com.intellij.codeInsight.template.impl.ListTemplatesHandler.listApplicableCustomTemplates;

/**
 * @author peter
 */
public class LiveTemplateCompletionContributor extends CompletionContributor {
  public static boolean ourShowTemplatesInTests = false;

  public static boolean shouldShowAllTemplates() {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      return ourShowTemplatesInTests;
    }
    return Registry.is("show.live.templates.in.completion");
  }
  
  public LiveTemplateCompletionContributor() {
    extend(CompletionType.BASIC, PlatformPatterns.psiElement(), new CompletionProvider<CompletionParameters>() {
      @Override
      protected void addCompletions(@NotNull final CompletionParameters parameters,
                                    ProcessingContext context,
                                    @NotNull CompletionResultSet result) {
        final PsiFile file = parameters.getPosition().getContainingFile();
        final int offset = parameters.getOffset();
        final List<TemplateImpl> templates = listApplicableTemplates(file, offset);
        Editor editor = parameters.getEditor();
        if (showAllTemplates()) {
          final MultiMap<String, CustomLiveTemplateLookupElement> customTemplates = listApplicableCustomTemplates(editor, file, offset);
          final Ref<Boolean> templatesShown = Ref.create(false);
          final CompletionResultSet finalResult = result;
          result.runRemainingContributors(parameters, new Consumer<CompletionResult>() {
            @Override
            public void consume(CompletionResult completionResult) {
              finalResult.passResult(completionResult);
              ensureTemplatesShown(templatesShown, templates, customTemplates, finalResult);
            }
          });

          ensureTemplatesShown(templatesShown, templates, customTemplates, result);
          return;
        }

        if (parameters.getInvocationCount() > 0) return; //only in autopopups for now

        String templatePrefix = findLiveTemplatePrefix(file, editor, result.getPrefixMatcher().getPrefix());
        final TemplateImpl template = findApplicableTemplate(file, offset, templatePrefix);
        if (template != null) {
          result = result.withPrefixMatcher(template.getKey());
          result.addElement(new LiveTemplateLookupElementImpl(template, true));
        }
        for (final TemplateImpl possible : templates) {
          result.restartCompletionOnPrefixChange(possible.getKey());
        }
      }
    });
  }

  @SuppressWarnings("MethodMayBeStatic") //for Kotlin
  protected boolean showAllTemplates() {
    return shouldShowAllTemplates();
  }

  private static void ensureTemplatesShown(Ref<Boolean> templatesShown,
                                           List<TemplateImpl> templates,
                                           MultiMap<String, CustomLiveTemplateLookupElement> customTemplates,
                                           CompletionResultSet result) {
    if (!templatesShown.get()) {
      templatesShown.set(true);
      for (final TemplateImpl possible : templates) {
        result.addElement(new LiveTemplateLookupElementImpl(possible, false));
      }

      for (Map.Entry<String, Collection<CustomLiveTemplateLookupElement>> entry : customTemplates.entrySet()) {
        Collection<CustomLiveTemplateLookupElement> value = entry.getValue();
        if (!value.isEmpty()) {
          result.withPrefixMatcher(entry.getKey()).addAllElements(value);
        }
      }
    }
  }

  private static List<TemplateImpl> listApplicableTemplates(PsiFile file, int offset) {
    Set<TemplateContextType> contextTypes = TemplateManagerImpl.getApplicableContextTypes(file, offset);

    final ArrayList<TemplateImpl> result = ContainerUtil.newArrayList();
    for (final TemplateImpl template : TemplateSettings.getInstance().getTemplates()) {
      if (!template.isDeactivated() && TemplateManagerImpl.isApplicable(template, contextTypes)) {
        result.add(template);
      }
    }
    return result;
  }

  @Nullable
  public static TemplateImpl findApplicableTemplate(final PsiFile file, int offset, @NotNull final String possiblePrefix) {
    return ContainerUtil.find(listApplicableTemplates(file, offset), new Condition<TemplateImpl>() {
      @Override
      public boolean value(TemplateImpl template) {
        return possiblePrefix.equals(template.getKey());
      }
    });
  }

  @NotNull
  public static String findLiveTemplatePrefix(@NotNull PsiFile file, @NotNull Editor editor, @NotNull String defaultValue) {
    final CustomTemplateCallback callback = new CustomTemplateCallback(editor, file, false);
    for (CustomLiveTemplate customLiveTemplate : CustomLiveTemplate.EP_NAME.getExtensions()) {
      final String customKey = customLiveTemplate.computeTemplateKey(callback);
      if (customKey != null) {
        return customKey;
      }
    }
    return defaultValue;
  }

  public static class Skipper extends CompletionPreselectSkipper {

    @Override
    public boolean skipElement(LookupElement element, CompletionLocation location) {
      return element instanceof LiveTemplateLookupElement && ((LiveTemplateLookupElement)element).sudden && !Registry.is("ide.completion.autopopup.select.live.templates");
    }
  }

}