@Nullable private String findNameGroup(@Nullable final String name) { if (name == null) { return null; } String[] words = NameUtil.splitNameIntoWords(name); String result = null; for(String word: words) { String group = myWordToGroupMap.get(word.toLowerCase()); if (group != null) { if (result == null) { result = group; } else if (!result.equals(group)) { result = null; break; } } } return result; }
private static int calcMatch(final String expectedName, final List<String> words, int max) { if (expectedName == null) return max; String[] expectedWords = NameUtil.nameToWords(expectedName); int limit = Math.min(words.size(), expectedWords.length); for (int i = 0; i < limit; i++) { String word = words.get(words.size() - i - 1); String expectedWord = expectedWords[expectedWords.length - i - 1]; if (word.equalsIgnoreCase(expectedWord)) { max = Math.max(max, i + 1); } else { break; } } return max; }
@NotNull @Override public Comparable weigh(@NotNull LookupElement element) { final Object object = element.getObject(); final String name = getLookupObjectName(object); if (name != null) { int max = 0; final List<String> wordsNoDigits = NameUtil.nameToWordsLowerCase(truncDigits(name)); for (ExpectedTypeInfo myExpectedInfo : myExpectedTypes) { String expectedName = ((ExpectedTypeInfoImpl)myExpectedInfo).getExpectedName(); if (expectedName != null) { final THashSet<String> set = new THashSet<String>(NameUtil.nameToWordsLowerCase(truncDigits(expectedName))); set.retainAll(wordsNoDigits); max = Math.max(max, set.size()); } } return -max; } return 0; }
private static Condition<PsiMember> getQualifiedNameMatcher(String completePattern) { final Condition<PsiMember> qualifiedMatcher; if (completePattern.contains(".")) { final MinusculeMatcher matcher = new MinusculeMatcher("*" + StringUtil.replace(completePattern, ".", ".*"), NameUtil.MatchingCaseSensitivity.NONE); qualifiedMatcher = new Condition<PsiMember>() { @Override public boolean value(PsiMember member) { String qualifiedName = PsiUtil.getMemberQualifiedName(member); return qualifiedName != null && matcher.matches(qualifiedName); } }; } else { //noinspection unchecked qualifiedMatcher = Condition.TRUE; } return qualifiedMatcher; }
@Override public final void consumeTopHits(@NonNls String pattern, Consumer<Object> collector, Project project) { if (!pattern.startsWith("#")) return; pattern = pattern.substring(1); final List<String> parts = StringUtil.split(pattern, " "); if (parts.size() == 0) { return; } String id = parts.get(0); if (getId().startsWith(id) || pattern.startsWith(" ")) { if (pattern.startsWith(" ")) { pattern = pattern.trim(); } else { pattern = pattern.substring(id.length()).trim().toLowerCase(); } final MinusculeMatcher matcher = NameUtil.buildMatcher("*" + pattern, NameUtil.MatchingCaseSensitivity.NONE); for (BooleanOptionDescription option : getOptions(project)) { if (matcher.matches(option.getOption())) { collector.consume(option); } } } }
private MinusculeMatcher createMatcher(final boolean caseSensitive) { String prefix = applyMiddleMatching(myPrefix); if (!caseSensitive) { return NameUtil.buildMatcher(prefix, NameUtil.MatchingCaseSensitivity.NONE); } switch (CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE) { case CodeInsightSettings.NONE: return NameUtil.buildMatcher(prefix, NameUtil.MatchingCaseSensitivity.NONE); case CodeInsightSettings.FIRST_LETTER: return NameUtil.buildMatcher(prefix, NameUtil.MatchingCaseSensitivity.FIRST_LETTER); default: return NameUtil.buildMatcher(prefix, NameUtil.MatchingCaseSensitivity.ALL); } }
@VisibleForTesting public String convertString(String text) { final String[] words = NameUtil.nameToWords(text); boolean insertUnderscore = false; final StringBuilder buf = new StringBuilder(); for (String word : words) { if (!Character.isLetterOrDigit(word.charAt(0))) { buf.append("_"); insertUnderscore = false; continue; } if (insertUnderscore) { buf.append("_"); } else { insertUnderscore = true; } buf.append(convertCase(word)); } return buf.toString(); }
private synchronized void buildStructure(final String pattern) { if (!Registry.is("search.everywhere.structure") || myStructureModel == null) return; final List<StructureViewTreeElement> elements = new ArrayList<StructureViewTreeElement>(); final MinusculeMatcher matcher = new MinusculeMatcher("*" + pattern, NameUtil.MatchingCaseSensitivity.NONE); fillStructure(myStructureModel.getRoot(), elements, matcher); if (elements.size() > 0) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (isCanceled()) return; myListModel.titleIndex.structure = myListModel.size(); for (Object element : elements) { myListModel.addElement(element); } myListModel.moreIndex.files = -1; } }); } }
private static void processNamesByPattern(@NotNull final ChooseByNameBase base, @NotNull final String[] names, @NotNull final String pattern, final ProgressIndicator indicator, @NotNull final Consumer<MatchResult> consumer) { final MinusculeMatcher matcher = buildPatternMatcher(pattern, NameUtil.MatchingCaseSensitivity.NONE); Processor<String> processor = new Processor<String>() { @Override public boolean process(String name) { ProgressManager.checkCanceled(); MatchResult result = matches(base, pattern, matcher, name); if (result != null) { consumer.consume(result); } return true; } }; if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(Arrays.asList(names), indicator, false, true, processor)) { throw new ProcessCanceledException(); } }
@Nullable private Pattern getTaskPattern(String pattern) { if (!Comparing.strEqual(pattern, myPattern)) { myCompiledPattern = null; myPattern = pattern; } if (myCompiledPattern == null) { final String regex = "^.*" + NameUtil.buildRegexp(pattern, 0, true, true); final Perl5Compiler compiler = new Perl5Compiler(); try { myCompiledPattern = compiler.compile(regex); } catch (MalformedPatternException ignored) { } } return myCompiledPattern; }
@Override public void processElementsWithName(@NotNull String name, @NotNull final Processor<NavigationItem> processor, @NotNull FindSymbolParameters parameters) { final MinusculeMatcher matcher = NameUtil.buildMatcher(parameters.getCompletePattern(), NameUtil.MatchingCaseSensitivity.FIRST_LETTER); if (!matcher.isStartMatch(name.substring(0, name.lastIndexOf(':')))) return; String[] names = name.split(":"); MavenId mavenId = new MavenId(names[0], names[1], names[2]); projectsManager = MavenProjectsManager.getInstance(project); MavenProject p = projectsManager.findProject(mavenId); PsiFileSystemItem pomFile = null; if (p != null) { pomFile = PsiManager.getInstance(project).findFile(p.getFile()); } else if (parameters.isSearchInLibraries()) { Map<MavenId, PsiFile> notImportPoms = getNotImportPoms(projectsManager.getRootProjects().get(0)); pomFile = notImportPoms.get(mavenId); } if (pomFile != null) { PomWrapper pomWrapper = new PomWrapper(pomFile, mavenId, project.getBasePath(), showPomLocation); processor.process(pomWrapper); } }
@NotNull @Override public Comparable weigh(@NotNull LookupElement element) { final Object object = element.getObject(); final String name = getLookupObjectName(object); if (name != null) { int max = 0; final List<String> wordsNoDigits = NameUtil.nameToWordsLowerCase(truncDigits(name)); for (ExpectedTypeInfo myExpectedInfo : myExpectedTypes) { String expectedName = ((ExpectedTypeInfoImpl)myExpectedInfo).expectedName.compute(); if (expectedName != null) { final THashSet<String> set = new THashSet<String>(NameUtil.nameToWordsLowerCase(truncDigits(expectedName))); set.retainAll(wordsNoDigits); max = Math.max(max, set.size()); } } return -max; } return 0; }
@Override protected Result calculateResult(@NotNull Expression[] params, ExpressionContext context, boolean quick) { String text = getTextResult(params, context, true); if (text != null && text.length() > 0) { final String[] words = NameUtil.nameToWords(text); boolean insertUnderscore = false; final StringBuffer buf = new StringBuffer(); for (String word : words) { if (insertUnderscore) { buf.append("_"); } else { insertUnderscore = true; } buf.append(StringUtil.toUpperCase(word)); } return new TextResult(buf.toString()); } return null; }
private static void processNamesByPattern(@NotNull final ChooseByNameBase base, @NotNull final String[] names, @NotNull final String pattern, final ProgressIndicator indicator, @NotNull final Consumer<MatchResult> consumer) { final MinusculeMatcher matcher = buildPatternMatcher(pattern, NameUtil.MatchingCaseSensitivity.NONE); Processor<String> processor = new Processor<String>() { @Override public boolean process(String name) { ProgressManager.checkCanceled(); MatchResult result = matches(base, pattern, matcher, name); if (result != null) { consumer.consume(result); } return true; } }; JobLauncher.getInstance().invokeConcurrentlyUnderProgress(Arrays.asList(names), indicator, false, false, processor); }
@Nullable @Override @RequiredReadAction public Comparable weigh(@NotNull LookupElement element) { if(myExpectedNames.isEmpty()) { return null; } String targetName = getName(element); if(targetName != null) { int max = 0; final List<String> wordsNoDigits = NameUtil.nameToWordsLowerCase(truncDigits(targetName)); for(String expectedName : myExpectedNames) { final THashSet<String> set = new THashSet<>(NameUtil.nameToWordsLowerCase(truncDigits(expectedName))); set.retainAll(wordsNoDigits); max = Math.max(max, set.size()); } return -max; } return 0; }
private static int calcMatch(final String expectedName, final List<String> words, int max) { if(expectedName == null) { return max; } String[] expectedWords = NameUtil.nameToWords(expectedName); int limit = Math.min(words.size(), expectedWords.length); for(int i = 0; i < limit; i++) { String word = words.get(words.size() - i - 1); String expectedWord = expectedWords[expectedWords.length - i - 1]; if(word.equalsIgnoreCase(expectedWord)) { max = Math.max(max, i + 1); } else { break; } } return max; }
@Override public final void consumeTopHits(@NonNls String pattern, Consumer<Object> collector, Project project) { if (!pattern.startsWith("#")) return; pattern = pattern.substring(1); final List<String> parts = StringUtil.split(pattern, " "); if (parts.size() == 0) return; String id = parts.get(0); if (getId().startsWith(id)) { pattern = pattern.substring(id.length()).trim().toLowerCase(); final MinusculeMatcher matcher = NameUtil.buildMatcher("*" + pattern, NameUtil.MatchingCaseSensitivity.NONE); for (BooleanOptionDescription option : getOptions(project)) { if (matcher.matches(option.getOption())) { collector.consume(option); } } } }
@Override protected Result calculateResult(@Nonnull Expression[] params, ExpressionContext context, boolean quick) { String text = getTextResult(params, context, true); if (text != null && text.length() > 0) { final String[] words = NameUtil.nameToWords(text); boolean insertUnderscore = false; final StringBuffer buf = new StringBuffer(); for (String word : words) { if (insertUnderscore) { buf.append("_"); } else { insertUnderscore = true; } buf.append(StringUtil.toUpperCase(word)); } return new TextResult(buf.toString()); } return null; }
private synchronized void buildStructure(final String pattern) { if (!Registry.is("search.everywhere.structure") || myStructureModel == null) return; final List<StructureViewTreeElement> elements = new ArrayList<>(); final MinusculeMatcher matcher = new MinusculeMatcher("*" + pattern, NameUtil.MatchingCaseSensitivity.NONE); fillStructure(myStructureModel.getRoot(), elements, matcher); if (elements.size() > 0) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (isCanceled()) return; myListModel.titleIndex.structure = myListModel.size(); for (Object element : elements) { myListModel.addElement(element); } myListModel.moreIndex.files = -1; } }); } }
private SearchResult getConfigurations(String pattern, int max) { SearchResult configurations = new SearchResult(); if (!Registry.is("search.everywhere.configurations")) { return configurations; } MinusculeMatcher matcher = new MinusculeMatcher(pattern, NameUtil.MatchingCaseSensitivity.NONE); final ChooseRunConfigurationPopup.ItemWrapper[] wrappers = ChooseRunConfigurationPopup.createSettingsList(project, new ExecutorProvider() { @Override public Executor getExecutor() { return ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG); } }, false); check(); for (ChooseRunConfigurationPopup.ItemWrapper wrapper : wrappers) { if (matcher.matches(wrapper.getText()) && !myListModel.contains(wrapper)) { if (configurations.size() == max) { configurations.needMore = true; break; } configurations.add(wrapper); } check(); } return configurations; }
private static void processNamesByPattern(@Nonnull final ChooseByNameBase base, @Nonnull final String[] names, @Nonnull final String pattern, final ProgressIndicator indicator, @Nonnull final Consumer<MatchResult> consumer) { final MinusculeMatcher matcher = buildPatternMatcher(pattern, NameUtil.MatchingCaseSensitivity.NONE); Processor<String> processor = new Processor<String>() { @Override public boolean process(String name) { ProgressManager.checkCanceled(); MatchResult result = matches(base, pattern, matcher, name); if (result != null) { consumer.consume(result); } return true; } }; if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(Arrays.asList(names), indicator, false, true, processor)) { throw new ProcessCanceledException(); } }
@NotNull @Override public Comparable weigh(@NotNull LookupElement element) { final Object object = element.getObject(); final String name = getLookupObjectName(object); if(name != null) { int max = 0; final List<String> wordsNoDigits = NameUtil.nameToWordsLowerCase(truncDigits(name)); for(ExpectedTypeInfo myExpectedInfo : myExpectedTypes) { String expectedName = ((ExpectedTypeInfoImpl) myExpectedInfo).getExpectedName(); if(expectedName != null) { final THashSet<String> set = new THashSet<>(NameUtil.nameToWordsLowerCase(truncDigits(expectedName))); set.retainAll(wordsNoDigits); max = Math.max(max, set.size()); } } return -max; } return 0; }
@NotNull private String[] getSuggestionsByName(@NotNull String name, @NotNull VariableKind variableKind, boolean isArray, boolean correctKeywords) { boolean upperCaseStyle = variableKind == VariableKind.STATIC_FINAL_FIELD; boolean preferLongerNames = getSettings().PREFER_LONGER_NAMES; String prefix = getPrefixByVariableKind(variableKind); String suffix = getSuffixByVariableKind(variableKind); List<String> answer = new ArrayList<String>(); for(String suggestion : NameUtil.getSuggestionsByName(name, prefix, suffix, upperCaseStyle, preferLongerNames, isArray)) { answer.add(correctKeywords ? changeIfNotIdentifier(suggestion) : suggestion); } return ArrayUtil.toStringArray(answer); }
private static int getNameEndMatchingDegree(final String name, ExpectedTypeInfo[] expectedInfos) { int res = 0; if (name != null && expectedInfos != null) { final List<String> words = NameUtil.nameToWordsLowerCase(name); final List<String> wordsNoDigits = NameUtil.nameToWordsLowerCase(truncDigits(name)); int max1 = calcMatch(words, 0, expectedInfos); max1 = calcMatch(wordsNoDigits, max1, expectedInfos); res = max1; } return res; }
@NotNull @Override public Comparable weigh(@NotNull LookupElement element) { final Object object = element.getObject(); final String name = getLookupObjectName(object); if (name != null && getNameEndMatchingDegree(name, myExpectedTypes) != 0) { return NameUtil.nameToWords(name).length - 1000; } return 0; }
@Override public void processElementsWithName(@NotNull String name, @NotNull final Processor<NavigationItem> processor, @NotNull final FindSymbolParameters parameters) { String namePattern = StringUtil.getShortName(parameters.getCompletePattern()); boolean hasDollar = namePattern.contains("$"); if (hasDollar) { Matcher matcher = ChooseByNamePopup.patternToDetectAnonymousClasses.matcher(namePattern); if (matcher.matches()) { namePattern = matcher.group(1); hasDollar = namePattern.contains("$"); } } final MinusculeMatcher innerMatcher = hasDollar ? new MinusculeMatcher("*" + namePattern, NameUtil.MatchingCaseSensitivity.NONE) : null; PsiShortNamesCache.getInstance(parameters.getProject()).processClassesWithName(name, new Processor<PsiClass>() { final boolean isAnnotation = parameters.getLocalPatternName().startsWith("@"); @Override public boolean process(PsiClass aClass) { if (aClass.getContainingFile().getVirtualFile() == null || !aClass.isPhysical()) return true; if (isAnnotation && !aClass.isAnnotationType()) return true; if (innerMatcher != null) { if (aClass.getContainingClass() == null) return true; String jvmQName = ClassUtil.getJVMClassName(aClass); if (jvmQName == null || !innerMatcher.matches(StringUtil.getShortName(jvmQName))) return true; } return processor.process(aClass); } }, parameters.getSearchScope(), parameters.getIdFilter()); }
@Nullable private static String[] suggestProperlyCasedName(PsiElement psiElement) { if (!(psiElement instanceof PsiNamedElement)) return null; if (psiElement instanceof PsiFile) return null; String name = ((PsiNamedElement)psiElement).getName(); if (name == null) return null; String prefix = ""; if (psiElement instanceof PsiVariable) { final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(psiElement.getProject()); final VariableKind kind = codeStyleManager.getVariableKind((PsiVariable)psiElement); prefix = codeStyleManager.getPrefixByVariableKind(kind); if (kind == VariableKind.STATIC_FINAL_FIELD) { final String[] words = NameUtil.splitNameIntoWords(name); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < words.length; i++) { String word = words[i]; if (i > 0) buffer.append('_'); buffer.append(StringUtil.toUpperCase(word)); } return new String[] {buffer.toString()}; } } final List<String> result = new ArrayList<String>(); result.add(suggestProperlyCasedName(prefix, NameUtil.splitNameIntoWords(name))); if (name.startsWith(prefix)) { name = name.substring(prefix.length()); result.add(suggestProperlyCasedName(prefix, NameUtil.splitNameIntoWords(name))); } result.add(suggestProperlyCasedName(prefix, NameUtil.splitNameIntoWords(name.toLowerCase()))); return ArrayUtil.toStringArray(result); }
public void updatePattern(final String string) { myString = string; try { myMatcher = NameUtil.buildMatcher("*" + string, 0, true, false); } catch (Exception e) { myMatcher = null; } }
public static String getDefaultTypeName(final Class aClass) { String simpleName = aClass.getSimpleName(); final int i = simpleName.indexOf('$'); if (i >= 0) { simpleName = simpleName.substring(i + 1); } return StringUtil.capitalizeWords(StringUtil.join(NameUtil.nameToWords(simpleName), " "), true); }
@Nullable private String computeClassName(final File file) { String absPath = file.getAbsolutePath(); if (!includeUnconventionallyNamedTests) { if (absPath.endsWith("Test.class")) { return StringUtil.trimEnd(absPath.substring(startPackageName), ".class").replace(File.separatorChar, '.'); } } else { String className = file.getName(); if (className.endsWith(".class")) { int dollar = className.lastIndexOf("$"); if (dollar != -1) { className = className.substring(dollar + 1); // most likely something like RecursionManagerTest$_testMayCache_closure5 or other anonymous class // may cause https://issues.apache.org/jira/browse/GROOVY-5351 if (!Character.isUpperCase(className.charAt(0))) return null; } // A test may be named Test*, *Test, *Tests*, *TestCase, *TestSuite, *Suite, etc List<String> words = Arrays.asList(NameUtil.nameToWords(className)); if (words.contains("Test") || words.contains("Tests") || words.contains("Suite")) { String fqn = StringUtil.trimEnd(absPath.substring(startPackageName), ".class").replace(File.separatorChar, '.'); if (!Arrays.asList("com.intellij.tests.BootstrapTests", "com.intellij.AllTests").contains(fqn)) { return fqn; } } } } return null; }
private MinusculeMatcher obtainMatcher(@NotNull String pattern) { if (myRecentSearchText == null || !myRecentSearchText.equals(pattern)) { myRecentSearchText = pattern; if (myShouldMatchCamelCase) { pattern = StringUtil.join(NameUtil.nameToWords(pattern), "*"); } if (!myShouldMatchFromTheBeginning && !pattern.startsWith("*")) { pattern = "*" + pattern; } myMinusculeMatcher = createMatcher(pattern); } return myMinusculeMatcher; }
public static List<Pair<String, Integer>> collectPossibleClassNamesWithWeights(String testName) { String[] words = NameUtil.splitNameIntoWords(testName); List<Pair<String, Integer>> result = new ArrayList<Pair<String, Integer>>(); for (int from = 0; from < words.length; from++) { for (int to = from; to < words.length; to++) { result.add(new Pair<String, Integer>(StringUtil.join(words, from, to + 1, ""), words.length - from + to)); } } return result; }