com.intellij.openapi.util.text.StringUtil Java Examples
The following examples show how to use
com.intellij.openapi.util.text.StringUtil.
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: BrowserLauncherImpl.java From consulo with Apache License 2.0 | 6 votes |
@Override protected void doShowError(@Nullable final String error, @Nullable final WebBrowser browser, @Nullable final Project project, final String title, @Nullable final Runnable launchTask) { AppUIUtil.invokeOnEdt(new Runnable() { @Override public void run() { if (Messages.showYesNoDialog(project, StringUtil.notNullize(error, "Unknown error"), title == null ? IdeBundle.message("browser" + ".error") : title, Messages.OK_BUTTON, IdeBundle.message("button.fix"), null) == Messages.NO) { final BrowserSettings browserSettings = new BrowserSettings(); AsyncResult<Void> result = ShowSettingsUtil.getInstance().editConfigurable(project, browserSettings, browser == null ? null : (Runnable)() -> browserSettings.selectBrowser(browser)); result.doWhenDone(() -> { if (launchTask != null) { launchTask.run(); } }); } } }, project == null ? null : project.getDisposed()); }
Example #2
Source File: SwitchToHeaderOrSourceSearch.java From intellij with Apache License 2.0 | 6 votes |
@Nullable private static OCFile correlateTestToHeader(OCFile file) { // Quickly check foo_test.cc -> foo.h as well. "getAssociatedFileWithSameName" only does // foo.cc <-> foo.h. However, if you do goto-related-symbol again, it will go from // foo.h -> foo.cc instead of back to foo_test.cc. PsiManager psiManager = PsiManager.getInstance(file.getProject()); String pathWithoutExtension = FileUtil.getNameWithoutExtension(file.getVirtualFile().getPath()); for (String testSuffix : PartnerFilePatterns.DEFAULT_PARTNER_SUFFIXES) { if (pathWithoutExtension.endsWith(testSuffix)) { String possibleHeaderName = StringUtil.trimEnd(pathWithoutExtension, testSuffix) + ".h"; VirtualFile virtualFile = VfsUtil.findFileByIoFile(new File(possibleHeaderName), false); if (virtualFile != null) { PsiFile psiFile = psiManager.findFile(virtualFile); if (psiFile instanceof OCFile) { return (OCFile) psiFile; } } } } return null; }
Example #3
Source File: ExportTestResultsForm.java From consulo with Apache License 2.0 | 6 votes |
@Nullable public String validate() { if (getExportFormat() == ExportTestResultsConfiguration.ExportFormat.UserTemplate) { if (StringUtil.isEmpty(myCustomTemplateField.getText())) { return ExecutionBundle.message("export.test.results.custom.template.path.empty"); } File file = new File(myCustomTemplateField.getText()); if (!file.isFile()) { return ExecutionBundle.message("export.test.results.custom.template.not.found", file.getAbsolutePath()); } } if (StringUtil.isEmpty(myFileNameField.getText())) { return ExecutionBundle.message("export.test.results.output.filename.empty"); } if (StringUtil.isEmpty(myFolderField.getText())) { return ExecutionBundle.message("export.test.results.output.path.empty"); } return null; }
Example #4
Source File: LombokConfigIndex.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 6 votes |
@NotNull @Override public KeyDescriptor<ConfigIndexKey> getKeyDescriptor() { return new KeyDescriptor<ConfigIndexKey>() { @Override public int getHashCode(ConfigIndexKey configKey) { return configKey.hashCode(); } @Override public boolean isEqual(ConfigIndexKey val1, ConfigIndexKey val2) { return val1.equals(val2); } @Override public void save(@NotNull DataOutput out, ConfigIndexKey value) throws IOException { out.writeUTF(StringUtil.notNullize(value.getDirectoryName())); out.writeUTF(StringUtil.notNullize(value.getConfigKey())); } @Override public ConfigIndexKey read(@NotNull DataInput in) throws IOException { return new ConfigIndexKey(in.readUTF(), in.readUTF()); } }; }
Example #5
Source File: YamlHelper.java From idea-php-symfony2-plugin with MIT License | 6 votes |
@Nullable public static PsiElement insertKeyIntoFile(final @NotNull YAMLFile yamlFile, final @NotNull YAMLKeyValue yamlKeyValue, @NotNull String... keys) { String keyText = yamlKeyValue.getKeyText(); return insertKeyIntoFile(yamlFile, (yamlMapping, chainedKey) -> { String text = yamlKeyValue.getText(); final String previousIndent = StringUtil.repeatSymbol(' ', YAMLUtil.getIndentInThisLine(yamlMapping)); // split content of array value object; // drop first item as getValueText() removes our key indent String[] remove = (String[]) ArrayUtils.remove(text.split("\\r?\\n"), 0); List<String> map = ContainerUtil.map(remove, s -> previousIndent + s); return "\n" + StringUtils.strip(StringUtils.join(map, "\n"), "\n"); }, (String[]) ArrayUtils.add(keys, keyText)); }
Example #6
Source File: DartElementPresentationUtil.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static void renderElement(@NotNull Element element, @NotNull OutlineTreeCellRenderer renderer, boolean nameInBold) { final SimpleTextAttributes attributes = nameInBold ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES; renderer.appendSearch(element.getName(), attributes); if (!StringUtil.isEmpty(element.getTypeParameters())) { renderer.appendSearch(element.getTypeParameters(), attributes); } if (!StringUtil.isEmpty(element.getParameters())) { renderer.appendSearch(element.getParameters(), attributes); } if (!StringUtil.isEmpty(element.getReturnType())) { renderer.append(" "); renderer.append(DartPresentableUtil.RIGHT_ARROW); renderer.append(" "); renderer.appendSearch(element.getReturnType(), SimpleTextAttributes.REGULAR_ATTRIBUTES); } }
Example #7
Source File: PersistentMapTest.java From consulo with Apache License 2.0 | 6 votes |
public void test2GLimit() throws IOException { if (!DO_SLOW_TEST) return; File file = FileUtil.createTempFile("persistent", "map"); FileUtil.createParentDirs(file); EnumeratorStringDescriptor stringDescriptor = new EnumeratorStringDescriptor(); PersistentHashMap<String, String> map = new PersistentHashMap<String, String>(file, stringDescriptor, stringDescriptor); for (int i = 0; i < 12000; i++) { map.put("abc" + i, StringUtil.repeat("0123456789", 10000)); } map.close(); map = new PersistentHashMap<String, String>(file, stringDescriptor, stringDescriptor); long len = 0; for (String key : map.getAllKeysWithExistingMapping()) { len += map.get(key).length(); } map.close(); assertEquals(1200000000L, len); }
Example #8
Source File: ConsoleViewImpl.java From consulo with Apache License 2.0 | 6 votes |
private static int evaluateBackspacesInTokens(@Nonnull List<? extends TokenBuffer.TokenInfo> source, int sourceStartIndex, @Nonnull List<? super TokenBuffer.TokenInfo> dest) { int backspacesFromNextToken = 0; for (int i = source.size() - 1; i >= sourceStartIndex; i--) { TokenBuffer.TokenInfo token = source.get(i); final TokenBuffer.TokenInfo newToken; if (StringUtil.containsChar(token.getText(), BACKSPACE) || backspacesFromNextToken > 0) { StringBuilder tokenTextBuilder = new StringBuilder(token.getText().length() + backspacesFromNextToken); tokenTextBuilder.append(token.getText()); for (int j = 0; j < backspacesFromNextToken; j++) { tokenTextBuilder.append(BACKSPACE); } normalizeBackspaceCharacters(tokenTextBuilder); backspacesFromNextToken = getBackspacePrefixLength(tokenTextBuilder); String newText = tokenTextBuilder.substring(backspacesFromNextToken); newToken = new TokenBuffer.TokenInfo(token.contentType, newText, token.getHyperlinkInfo()); } else { newToken = token; } dest.add(newToken); } Collections.reverse(dest); return backspacesFromNextToken; }
Example #9
Source File: OptionTagBinding.java From consulo with Apache License 2.0 | 6 votes |
public OptionTagBinding(@Nonnull MutableAccessor accessor, @Nullable OptionTag optionTag) { super(accessor, optionTag == null ? null : optionTag.value(), optionTag == null ? null : optionTag.converter()); if (optionTag == null) { myTagName = Constants.OPTION; myNameAttribute = Constants.NAME; myValueAttribute = Constants.VALUE; } else { myNameAttribute = optionTag.nameAttribute(); myValueAttribute = optionTag.valueAttribute(); String tagName = optionTag.tag(); if (StringUtil.isEmpty(myNameAttribute) && Constants.OPTION.equals(tagName)) { tagName = myAccessor.getName(); } myTagName = tagName; } }
Example #10
Source File: WSLDistribution.java From consulo with Apache License 2.0 | 6 votes |
/** * Attempts to resolve symlink with a given timeout * * @param path path in question * @param timeoutInMilliseconds timeout for execution * @return actual file name */ @Nonnull public String resolveSymlink(@Nonnull String path, int timeoutInMilliseconds) { try { final ProcessOutput output = executeOnWsl(timeoutInMilliseconds, "readlink", "-f", path); if (output.getExitCode() == 0) { String stdout = output.getStdout().trim(); if (output.getExitCode() == 0 && StringUtil.isNotEmpty(stdout)) { return stdout; } } } catch (ExecutionException e) { LOG.debug("Error while resolving symlink: " + path, e); } return path; }
Example #11
Source File: TreeState.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull private static String calcId(@Nullable Object userObject) { if (userObject == null) return ""; Object value = userObject instanceof NodeDescriptorProvidingKey ? ((NodeDescriptorProvidingKey)userObject).getKey() : userObject instanceof AbstractTreeNode ? ((AbstractTreeNode)userObject).getValue() : userObject; if (value instanceof NavigationItem) { try { String name = ((NavigationItem)value).getName(); return name != null ? name : StringUtil.notNullize(value.toString()); } catch (Exception ignored) { } } return StringUtil.notNullize(userObject.toString()); }
Example #12
Source File: BeanBinding.java From consulo with Apache License 2.0 | 6 votes |
@Nullable private static Pair<String, Boolean> getPropertyData(@Nonnull String methodName) { String part = ""; boolean isSetter = false; if (methodName.startsWith("get")) { part = methodName.substring(3, methodName.length()); } else if (methodName.startsWith("is")) { part = methodName.substring(2, methodName.length()); } else if (methodName.startsWith("set")) { part = methodName.substring(3, methodName.length()); isSetter = true; } return part.isEmpty() ? null : Pair.create(StringUtil.decapitalize(part), isSetter); }
Example #13
Source File: XValueContainerNode.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull public XDebuggerTreeNode addTemporaryEditorNode(@Nullable Image icon, @Nullable String text) { if (isLeaf()) { setLeaf(false); } myTree.expandPath(getPath()); MessageTreeNode node = new MessageTreeNode(myTree, this, true); node.setIcon(icon); if (!StringUtil.isEmpty(text)) { node.getText().append(text, SimpleTextAttributes.REGULAR_ATTRIBUTES); } myTemporaryEditorNode = node; myCachedAllChildren = null; fireNodesInserted(Collections.singleton(node)); return node; }
Example #14
Source File: CSharpTypeStubElementType.java From consulo-csharp with Apache License 2.0 | 6 votes |
@Override @RequiredReadAction public void indexStub(@Nonnull CSharpTypeDeclStub stub, @Nonnull IndexSink indexSink) { String name = getName(stub); if(!StringUtil.isEmpty(name)) { indexSink.occurrence(CSharpIndexKeys.TYPE_INDEX, name); String parentQName = stub.getParentQName(); if(!stub.isNested()) { DotNetNamespaceStubUtil.indexStub(indexSink, CSharpIndexKeys.MEMBER_BY_NAMESPACE_QNAME_INDEX, CSharpIndexKeys.MEMBER_BY_ALL_NAMESPACE_QNAME_INDEX, parentQName, name); if(BitUtil.isSet(stub.getOtherModifierMask(), CSharpTypeDeclStub.HAVE_EXTENSIONS)) { indexSink.occurrence(CSharpIndexKeys.TYPE_WITH_EXTENSION_METHODS_INDEX, DotNetNamespaceStubUtil.getIndexableNamespace(parentQName)); } } indexSink.occurrence(CSharpIndexKeys.TYPE_BY_VMQNAME_INDEX, stub.getVmQName().hashCode()); } }
Example #15
Source File: FileLookupData.java From intellij with Apache License 2.0 | 6 votes |
@Nullable public static FileLookupData nonLocalFileLookup( String originalLabel, @Nullable BuildFile containingFile, QuoteType quoteType, PathFormat pathFormat) { if (originalLabel.indexOf(':') != -1) { // it's a package-local reference return null; } // handle the single '/' case by calling twice. String relativePath = StringUtil.trimStart(StringUtil.trimStart(originalLabel, "/"), "/"); if (relativePath.startsWith("/")) { return null; } boolean onlyDirectories = pathFormat != PathFormat.NonLocalWithoutInitialBackslashes; VirtualFileFilter filter = vf -> !onlyDirectories || vf.isDirectory(); return new FileLookupData( originalLabel, containingFile, null, relativePath, pathFormat, quoteType, filter); }
Example #16
Source File: ShowUsagesAction.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull private static List<UsageNode> collectData(@Nonnull List<Usage> usages, @Nonnull Collection<UsageNode> visibleNodes, @Nonnull UsageViewImpl usageView, @Nonnull UsageViewPresentation presentation) { @Nonnull List<UsageNode> data = new ArrayList<>(); int filtered = filtered(usages, usageView); if (filtered != 0) { data.add(createStringNode(UsageViewBundle.message("usages.were.filtered.out", filtered))); } data.addAll(visibleNodes); if (data.isEmpty()) { String progressText = StringUtil.escapeXml(UsageViewManagerImpl.getProgressTitle(presentation)); data.add(createStringNode(progressText)); } Collections.sort(data, USAGE_NODE_COMPARATOR); return data; }
Example #17
Source File: PatternCompilerImpl.java From consulo with Apache License 2.0 | 6 votes |
private StringBuilder toString(final Node node, final StringBuilder sb) { if (node.target == ERROR_NODE) { return sb.append(node.method); } if (node.target != null) { toString(node.target, sb); sb.append('.'); } sb.append(node.method).append('('); boolean first = true; for (Object arg : node.args) { if (first) first = false; else sb.append(',').append(' '); if (arg instanceof Node) { toString((Node)arg, sb); } else if (arg instanceof String) { sb.append('\"').append(StringUtil.escapeStringCharacters((String)arg)).append('\"'); } else if (arg instanceof Number) { sb.append(arg); } } sb.append(')'); return sb; }
Example #18
Source File: TestSuiteStack.java From consulo with Apache License 2.0 | 5 votes |
protected String getSuitePathPresentation() { final String[] names = getSuitePath(); if (names.length == 0) { return EMPTY; } return StringUtil.join(names, new Function<String, String>() { @Override public String fun(String s) { return "[" + s + "]"; } }, "->"); }
Example #19
Source File: DocumentCommitThread.java From consulo with Apache License 2.0 | 5 votes |
@NonNls @Override public String toString() { Document document = getDocument(); String indicatorInfo = isCanceled() ? " (Canceled: " + ((UserDataHolder)indicator).getUserData(CANCEL_REASON) + ")" : ""; String removedInfo = dead ? " (dead)" : ""; String reasonInfo = " task reason: " + StringUtil.first(String.valueOf(reason), 180, true) + (isStillValid() ? "" : "; changed: old seq=" + modificationSequence + ", new seq=" + ((DocumentEx)document).getModificationSequence()); String contextInfo = " Context: " + myCreationContext; return System.identityHashCode(this) + "; " + indicatorInfo + removedInfo + contextInfo + reasonInfo; }
Example #20
Source File: RemoteCredentialsHolder.java From consulo with Apache License 2.0 | 5 votes |
public void setSerializedUserName(String userName) { if (StringUtil.isEmpty(userName)) { myUserName = null; } else { myUserName = userName; } }
Example #21
Source File: AbstractCreateFormAction.java From react-templates-plugin with MIT License | 5 votes |
protected String createFormBody(@Nullable String fqn, @NonNls String formName, String layoutManager) throws IncorrectOperationException { String s = ""; try { s = FileUtil.loadTextAndClose(getClass().getResourceAsStream(formName)); } catch (IOException e) { // throw new IncorrectOperationException(RTBundle.message("error.cannot.read", formName), (Throwable)e); } s = fqn == null ? StringUtil.replace(s, "bind-to-class=\"$CLASS$\"", "") : StringUtil.replace(s, "$CLASS$", fqn); s = StringUtil.replace(s, "$LAYOUT$", layoutManager); return StringUtil.convertLineSeparators(s); }
Example #22
Source File: DumpLookupElementWeights.java From consulo with Apache License 2.0 | 5 votes |
public static List<String> getLookupElementWeights(LookupImpl lookup, boolean hideSingleValued) { final Map<LookupElement, List<Pair<String, Object>>> weights = lookup.getRelevanceObjects(lookup.getItems(), hideSingleValued); return ContainerUtil.map(weights.entrySet(), new Function<Map.Entry<LookupElement, List<Pair<String, Object>>>, String>() { @Override public String fun(Map.Entry<LookupElement, List<Pair<String, Object>>> entry) { return entry.getKey().getLookupString() + "\t" + StringUtil.join(entry.getValue(), new Function<Pair<String, Object>, String>() { @Override public String fun(Pair<String, Object> pair) { return pair.first + "=" + pair.second; } }, ", "); } }); }
Example #23
Source File: FSRecords.java From consulo with Apache License 2.0 | 5 votes |
static void storeSymlinkTarget(int id, @Nullable String symlinkTarget) { writeAndHandleErrors(() -> { DbConnection.markDirty(); try (DataOutputStream stream = writeAttribute(id, ourSymlinkTargetAttr)) { IOUtil.writeUTF(stream, StringUtil.notNullize(symlinkTarget)); } }); }
Example #24
Source File: LoadTextUtil.java From consulo with Apache License 2.0 | 5 votes |
public static void changeLineSeparators(@Nullable Project project, @Nonnull VirtualFile file, @Nonnull String newSeparator, @Nonnull Object requestor) throws IOException { CharSequence currentText = getTextByBinaryPresentation(file.contentsToByteArray(), file, true, false); String currentSeparator = detectLineSeparator(file, false); if (newSeparator.equals(currentSeparator)) { return; } String newText = StringUtil.convertLineSeparators(currentText.toString(), newSeparator); file.setDetectedLineSeparator(newSeparator); write(project, file, requestor, newText, -1); }
Example #25
Source File: JsonReferenceInspection.java From intellij-swagger with MIT License | 5 votes |
@NotNull @Override public PsiElementVisitor buildVisitor( @NotNull final ProblemsHolder holder, final boolean isOnTheFly, @NotNull final LocalInspectionToolSession session) { final PsiFile file = holder.getFile(); final VirtualFile virtualFile = file.getVirtualFile(); final Project project = holder.getProject(); boolean checkRefs = indexFacade.isMainSpecFile(virtualFile, project) || indexFacade.isPartialSpecFile(virtualFile, project); return new JsonElementVisitor() { @Override public void visitProperty(@NotNull JsonProperty o) { if (!checkRefs) { return; } if ("$ref".equals(o.getName())) { JsonValue value = o.getValue(); if (!(value instanceof JsonStringLiteral)) { return; } final String unquotedValue = StringUtil.unquoteString(value.getText()); if (!unquotedValue.startsWith("http")) { doCheck(holder, value, new CreateJsonReferenceIntentionAction(unquotedValue)); } } super.visitProperty(o); } }; }
Example #26
Source File: ConflictsDialog.java From consulo with Apache License 2.0 | 5 votes |
private UsagePresentation getPresentation(final UsagePresentation usagePresentation, PsiElement element) { final Collection<String> elementConflicts = new LinkedHashSet<String>(myElementConflictDescription.get(element)); final String conflictDescription = " (" + Pattern.compile("<[^<>]*>").matcher(StringUtil.join(elementConflicts, "\n")).replaceAll("") + ")"; return new UsagePresentation() { @Override @Nonnull public TextChunk[] getText() { final TextChunk[] chunks = usagePresentation.getText(); return ArrayUtil .append(chunks, new TextChunk(SimpleTextAttributes.GRAY_ITALIC_ATTRIBUTES.toTextAttributes(), conflictDescription)); } @Override @Nonnull public String getPlainText() { return usagePresentation.getPlainText() + conflictDescription; } @Override public Image getIcon() { return usagePresentation.getIcon(); } @Override public String getTooltipText() { return usagePresentation.getTooltipText(); } }; }
Example #27
Source File: ModuleExtensionProviderEP.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull @Override protected Image compute() { if (StringUtil.isEmpty(icon)) { return AllIcons.Toolbar.Unknown; } Image temp = IconLoader.findIcon(icon, getLoaderForClass()); return temp == null ? AllIcons.Toolbar.Unknown : temp; }
Example #28
Source File: StubProvidedIndexExtension.java From consulo with Apache License 2.0 | 5 votes |
@Nullable public <K> ProvidedIndexExtension<K, Void> findProvidedStubIndex(@Nonnull StubIndexExtension<K, ?> extension) { String name = extension.getKey().getName(); File path = getIndexPath(); File indexPath = new File(path, StringUtil.toLowerCase(name)); if (!indexPath.exists()) return null; return new ProvidedIndexExtension<K, Void>() { @Nonnull @Override public File getIndexPath() { return myIndexFile; } @Nonnull @Override public ID<K, Void> getIndexId() { return (ID)extension.getKey(); } @Nonnull @Override public KeyDescriptor<K> createKeyDescriptor() { return extension.getKeyDescriptor(); } @Nonnull @Override public DataExternalizer<Void> createValueExternalizer() { return VoidDataExternalizer.INSTANCE; } }; }
Example #29
Source File: PsiElement2UsageTargetAdapter.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull @Override public String getLongDescriptiveName() { SearchScope searchScope = myOptions.searchScope; String scopeString = searchScope.getDisplayName(); PsiElement psiElement = getElement(); return psiElement == null ? UsageViewBundle.message("node.invalid") : FindBundle.message("recent.find.usages.action.popup", StringUtil.capitalize(UsageViewUtil.getType(psiElement)), DescriptiveNameUtil.getDescriptiveName(psiElement), scopeString); }
Example #30
Source File: ProjectInfo.java From intellij-pants-plugin with Apache License 2.0 | 5 votes |
private static <T> List<Map.Entry<String, T>> getSortedEntries(Map<String, T> map) { return ContainerUtil.sorted( map.entrySet(), new Comparator<Map.Entry<String, T>>() { @Override public int compare(Map.Entry<String, T> o1, Map.Entry<String, T> o2) { return StringUtil.naturalCompare(o1.getKey(), o2.getKey()); } } ); }