Java Code Examples for com.intellij.openapi.util.text.StringUtil#trimEnd()

The following examples show how to use com.intellij.openapi.util.text.StringUtil#trimEnd() . 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: DartVmServiceStackFrame.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void customizePresentation(@NotNull final ColoredTextContainer component) {
  final String unoptimizedPrefix = "[Unoptimized] ";

  String name = StringUtil.trimEnd(myVmFrame.getCode().getName(), "="); // trim setter postfix
  name = StringUtil.trimStart(name, unoptimizedPrefix);

  final boolean causal = myVmFrame.getKind() == FrameKind.AsyncCausal;
  component.append(name, causal ? SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES);

  if (mySourcePosition != null) {
    final String text = " (" + mySourcePosition.getFile().getName() + ":" + (mySourcePosition.getLine() + 1) + ")";
    component.append(text, SimpleTextAttributes.GRAY_ATTRIBUTES);
  }

  component.setIcon(AllIcons.Debugger.Frame);
}
 
Example 2
Source File: GitWorkingSetProvider.java    From intellij with Apache License 2.0 6 votes vote down vote up
/** @return the console output, in string form, or null if there was a non-zero exit code. */
@Nullable
private static String getConsoleOutput(WorkspaceRoot workspaceRoot, String... commands) {
  ByteArrayOutputStream stdout = new ByteArrayOutputStream();
  ByteArrayOutputStream stderr = new ByteArrayOutputStream();

  int retVal =
      ExternalTask.builder(workspaceRoot)
          .args(commands)
          .stdout(stdout)
          .stderr(stderr)
          .build()
          .run();
  if (retVal != 0) {
    logger.error(stderr);
    return null;
  }
  return StringUtil.trimEnd(stdout.toString(), "\n");
}
 
Example 3
Source File: GitStatusLineProcessor.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Override
public boolean processLine(String line) {
  Matcher matcher = REGEX.matcher(line);
  if (matcher.find()) {
    String type = matcher.group(1);
    String file = matcher.group(2);
    file = StringUtil.trimEnd(file, '/');

    WorkspacePath workspacePath = getWorkspacePath(file);
    if (workspacePath == null) {
      return true;
    }
    switch (type) {
      case "A":
        addedFiles.add(workspacePath);
        break;
      case "M":
        modifiedFiles.add(workspacePath);
        break;
      case "D":
        deletedFiles.add(workspacePath);
        break;
    }
  }
  return true;
}
 
Example 4
Source File: IncludePath.java    From intellij with Apache License 2.0 6 votes vote down vote up
static IncludePath create(String rawHeaderPath) {
  if (rawHeaderPath.startsWith(Delimiters.QUOTES.getBeforeText())
      && rawHeaderPath.endsWith(Delimiters.QUOTES.getAfterText())) {
    return new AutoValue_IncludePath(
        StringUtil.trimEnd(
            StringUtil.trimStart(rawHeaderPath, Delimiters.QUOTES.getBeforeText()),
            Delimiters.QUOTES.getAfterText()),
        Delimiters.QUOTES);
  }
  if (rawHeaderPath.startsWith(Delimiters.ANGLE_BRACKETS.getBeforeText())
      && rawHeaderPath.endsWith(Delimiters.ANGLE_BRACKETS.getAfterText())) {
    return new AutoValue_IncludePath(
        StringUtil.trimEnd(
            StringUtil.trimStart(rawHeaderPath, Delimiters.ANGLE_BRACKETS.getBeforeText()),
            Delimiters.ANGLE_BRACKETS.getAfterText()),
        Delimiters.ANGLE_BRACKETS);
  }
  return new AutoValue_IncludePath(rawHeaderPath, Delimiters.NONE);
}
 
Example 5
Source File: ScratchFileServiceImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public VirtualFile findFile(@Nonnull RootType rootType, @Nonnull String pathName, @Nonnull Option option) throws IOException {
  ApplicationManager.getApplication().assertReadAccessAllowed();

  String fullPath = getRootPath(rootType) + "/" + pathName;
  if (option != Option.create_new_always) {
    VirtualFile file = LocalFileSystem.getInstance().findFileByPath(fullPath);
    if (file != null && !file.isDirectory()) return file;
    if (option == Option.existing_only) return null;
  }
  String ext = PathUtil.getFileExtension(pathName);
  String fileNameExt = PathUtil.getFileName(pathName);
  String fileName = StringUtil.trimEnd(fileNameExt, ext == null ? "" : "." + ext);
  AccessToken token = ApplicationManager.getApplication().acquireWriteActionLock(getClass());
  try {
    VirtualFile dir = VfsUtil.createDirectories(PathUtil.getParentPath(fullPath));
    if (option == Option.create_new_always) {
      return VfsUtil.createChildSequent(LocalFileSystem.getInstance(), dir, fileName, StringUtil.notNullize(ext));
    }
    else {
      return dir.createChildData(LocalFileSystem.getInstance(), fileNameExt);
    }
  }
  finally {
    token.finish();
  }
}
 
Example 6
Source File: ZipUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static String createRelativeExtractPath(ZipEntry zipEntry) {
  String name = zipEntry.getName();
  int ind = name.indexOf('/');
  if (ind >= 0) {
    name = name.substring(ind + 1);
  }
  return StringUtil.trimEnd(name, "/");
}
 
Example 7
Source File: WildcardTargetPattern.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Strip any wildcard suffix from the given target pattern, returning a non-wildcard pattern. This
 * is used to validate general target expressions.
 */
public static String stripWildcardSuffix(String pattern) {
  if (pattern.endsWith(":all")) {
    pattern = pattern.substring(0, pattern.length() - ":all".length());
  } else if (pattern.endsWith(":*")) {
    pattern = pattern.substring(0, pattern.length() - ":*".length());
  } else if (pattern.endsWith(":all-targets")) {
    pattern = pattern.substring(0, pattern.length() - ":all-targets".length());
  }
  return pattern.equals("//...")
      ? ""
      : StringUtil.trimEnd(pattern, ALL_PACKAGES_RECURSIVE_SUFFIX);
}
 
Example 8
Source File: ResourceCompilerConfiguration.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static CompiledPattern convertToRegexp(String wildcardPattern) throws MalformedPatternException{
  if (isPatternNegated(wildcardPattern)) {
    wildcardPattern = wildcardPattern.substring(1);
  }

  wildcardPattern = FileUtil.toSystemIndependentName(wildcardPattern);

  String srcRoot = null;
  int colon = wildcardPattern.indexOf(":");
  if (colon > 0) {
    srcRoot = wildcardPattern.substring(0, colon);
    wildcardPattern = wildcardPattern.substring(colon + 1);
  }

  String dirPattern = null;
  int slash = wildcardPattern.lastIndexOf('/');
  if (slash >= 0) {
    dirPattern = wildcardPattern.substring(0, slash + 1);
    wildcardPattern = wildcardPattern.substring(slash + 1);
    if (!dirPattern.startsWith("/")) {
      dirPattern = "/" + dirPattern;
    }
    //now dirPattern starts and ends with '/'

    dirPattern = normalizeWildcards(dirPattern);

    dirPattern = StringUtil.replace(dirPattern, "/.*.*/", "(/.*)?/");
    dirPattern = StringUtil.trimEnd(dirPattern, "/");

    dirPattern = optimize(dirPattern);
  }

  wildcardPattern = normalizeWildcards(wildcardPattern);
  wildcardPattern = optimize(wildcardPattern);

  final Pattern dirCompiled = dirPattern == null ? null : compilePattern(dirPattern);
  final Pattern srcCompiled = srcRoot == null ? null : compilePattern(optimize(normalizeWildcards(srcRoot)));
  return new CompiledPattern(compilePattern(wildcardPattern), dirCompiled, srcCompiled);
}
 
Example 9
Source File: XmlStringUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static String stripHtml(@Nonnull String toolTip) {
  toolTip = StringUtil.trimStart(toolTip, HTML_START);
  toolTip = StringUtil.trimStart(toolTip, BODY_START);
  toolTip = StringUtil.trimEnd(toolTip, HTML_END);
  toolTip = StringUtil.trimEnd(toolTip, BODY_END);
  return toolTip;
}
 
Example 10
Source File: EnvironmentUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
protected static Map<String, String> runProcessAndReadEnvs(@Nonnull List<String> command, @Nonnull File envFile, String lineSeparator) throws Exception {
  ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true);
  builder.environment().put(DISABLE_OMZ_AUTO_UPDATE, "true");
  Process process = builder.start();
  StreamGobbler gobbler = new StreamGobbler(process.getInputStream());
  int rv = waitAndTerminateAfter(process, SHELL_ENV_READING_TIMEOUT);
  gobbler.stop();

  String lines = FileUtil.loadFile(envFile);
  if (rv != 0 || lines.isEmpty()) {
    throw new Exception("rv:" + rv + " text:" + lines.length() + " out:" + StringUtil.trimEnd(gobbler.getText(), '\n'));
  }
  return parseEnv(lines.split(lineSeparator));
}
 
Example 11
Source File: GotoClassAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
static void invokeGoToFile(@Nonnull Project project, @Nonnull AnActionEvent e) {
  String actionTitle = StringUtil.trimEnd(ObjectUtils.notNull(e.getPresentation().getText(), GotoClassPresentationUpdater.getActionTitle()), "...");
  String message = IdeBundle.message("go.to.class.dumb.mode.message", actionTitle);
  DumbService.getInstance(project).showDumbModeNotification(message);
  AnAction action = ActionManager.getInstance().getAction(GotoFileAction.ID);
  InputEvent event = ActionCommand.getInputEvent(GotoFileAction.ID);
  Component component = e.getData(PlatformDataKeys.CONTEXT_COMPONENT);
  ActionManager.getInstance().tryToExecute(action, event, component, e.getPlace(), true);
}
 
Example 12
Source File: PathManager.java    From dynkt with GNU Affero General Public License v3.0 5 votes vote down vote up
@Nullable
private static String extractRoot(URL resourceURL, String resourcePath) {
	if ((!StringUtil.startsWithChar(resourcePath, '/')) && (!StringUtil.startsWithChar(resourcePath, '\\'))) {
		log("precondition failed: " + resourcePath);
		return null;
	}
	String resultPath = null;
	String protocol = resourceURL.getProtocol();
	if ("file".equals(protocol)) {
		String path = resourceURL.getFile();
		String testPath = path.replace('\\', '/');
		String testResourcePath = resourcePath.replace('\\', '/');
		if (StringUtil.endsWithIgnoreCase(testPath, testResourcePath)) {
			resultPath = path.substring(0, path.length() - resourcePath.length());
		}
	} else if ("jar".equals(protocol)) {
		Pair<String, String> paths = URLUtil.splitJarUrl(resourceURL.getFile());
		if (paths != null) {
			resultPath = paths.first;
		}
	} else if ("bundle".equals(protocol)) {
		resultPath = (new File(
				(PathManager.class.getProtectionDomain().getCodeSource().getLocation() + "").replace("file:/", "")))
						.getAbsolutePath().replace('\\', '/');
	} else {
		throw new UnsupportedOperationException(
				"No '" + protocol + "' known! (" + resourceURL + ", " + resourcePath + ")");
	}
	if (resultPath == null) {
		log("cannot extract: " + resourcePath + " from " + resourceURL);
		return null;
	}
	if ((SystemInfo.isWindows) && (resultPath.startsWith("/"))) {
		resultPath = resultPath.substring(1);
	}
	resultPath = StringUtil.trimEnd(resultPath, File.separator);
	resultPath = URLUtil.unescapePercentSequences(resultPath);

	return resultPath;
}
 
Example 13
Source File: FluidElementImpl.java    From idea-php-typo3-plugin with MIT License 4 votes vote down vote up
@Override
public String toString() {
  final String className = getClass().getSimpleName();
  return StringUtil.trimEnd(className, "Impl");
}
 
Example 14
Source File: ParagraphFillHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected void performOnElement(@Nonnull final PsiElement element, @Nonnull final Editor editor) {
  final Document document = editor.getDocument();

  final TextRange textRange = getTextRange(element, editor);
  if (textRange.isEmpty()) return;
  final String text = textRange.substring(element.getContainingFile().getText());

  final List<String> subStrings = StringUtil.split(text, "\n", true);
  final String prefix = getPrefix(element);
  final String postfix = getPostfix(element);

  final StringBuilder stringBuilder = new StringBuilder();
  appendPrefix(element, text, stringBuilder);

  for (String string : subStrings) {
    final String startTrimmed = StringUtil.trimStart(string.trim(), prefix.trim());
    final String str = StringUtil.trimEnd(startTrimmed, postfix.trim());
    final String finalString = str.trim();
    if (!StringUtil.isEmptyOrSpaces(finalString))
      stringBuilder.append(finalString).append(" ");
  }
  appendPostfix(element, text, stringBuilder);

  final String replacementText = stringBuilder.toString();

  CommandProcessor.getInstance().executeCommand(element.getProject(), () -> {
    document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(),
                           replacementText);
    final CodeFormatterFacade codeFormatter = new CodeFormatterFacade(
            CodeStyleSettingsManager.getSettings(element.getProject()), element.getLanguage());

    final PsiFile file = element.getContainingFile();
    FormatterTagHandler formatterTagHandler = new FormatterTagHandler(CodeStyleSettingsManager.getSettings(file.getProject()));
    List<TextRange> enabledRanges = formatterTagHandler.getEnabledRanges(file.getNode(), TextRange.create(0, document.getTextLength()));

    codeFormatter.doWrapLongLinesIfNecessary(editor, element.getProject(), document,
                                             textRange.getStartOffset(),
                                             textRange.getStartOffset() + replacementText.length() + 1,
                                             enabledRanges);
  }, null, document);

}
 
Example 15
Source File: IgnoreReferenceSet.java    From idea-gitignore with MIT License 4 votes vote down vote up
/**
 * Parses entry, searches for file references and stores them in {@link #myReferences}.
 */
@Override
protected void reparse() {
    ProgressManager.checkCanceled();
    String str = StringUtil.trimEnd(getPathString(), getSeparatorString());
    final List<FileReference> referencesList = new ArrayList<>();

    String separatorString = getSeparatorString(); // separator's length can be more then 1 char
    int sepLen = separatorString.length();
    int currentSlash = -sepLen;
    int startInElement = getStartInElement();

    // skip white space
    while (currentSlash + sepLen < str.length() && Character.isWhitespace(str.charAt(currentSlash + sepLen))) {
        currentSlash++;
    }

    if (currentSlash + sepLen + sepLen < str.length() && str.substring(currentSlash + sepLen,
            currentSlash + sepLen + sepLen).equals(separatorString)) {
        currentSlash += sepLen;
    }
    int index = 0;

    if (str.equals(separatorString)) {
        final FileReference fileReference = createFileReference(
                new TextRange(startInElement, startInElement + sepLen),
                index++,
                separatorString
        );
        referencesList.add(fileReference);
    }

    while (true) {
        ProgressManager.checkCanceled();
        final int nextSlash = str.indexOf(separatorString, currentSlash + sepLen);
        final String subReferenceText = nextSlash > 0 ? str.substring(0, nextSlash) : str;
        TextRange range = new TextRange(startInElement + currentSlash + sepLen, startInElement +
                (nextSlash > 0 ? nextSlash : str.length()));
        final FileReference ref = createFileReference(range, index++, subReferenceText);
        referencesList.add(ref);
        if ((currentSlash = nextSlash) < 0) {
            break;
        }
    }

    myReferences = referencesList.toArray(new FileReference[0]);
}
 
Example 16
Source File: ArchiveFileSystemBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public String extractPresentableUrl(@Nonnull String path) {
  return super.extractPresentableUrl(StringUtil.trimEnd(path, URLUtil.ARCHIVE_SEPARATOR));
}
 
Example 17
Source File: AbstractPyImportResolverStrategy.java    From intellij with Apache License 2.0 4 votes vote down vote up
static QualifiedName fromRelativePath(String relativePath) {
  relativePath = StringUtil.trimEnd(relativePath, File.separator + PyNames.INIT_DOT_PY);
  relativePath = StringUtil.trimExtensions(relativePath);
  return QualifiedName.fromComponents(StringUtil.split(relativePath, File.separator));
}
 
Example 18
Source File: UnifiedDiffWriter.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void write(@Nullable Project project,
                         @Nullable String basePath,
                         Collection<FilePatch> patches,
                         Writer writer,
                         final String lineSeparator,
                         @Nonnull final PatchEP[] extensions,
                         final CommitContext commitContext) throws IOException {
  for(FilePatch filePatch: patches) {
    if (!(filePatch instanceof TextFilePatch)) continue;
    TextFilePatch patch = (TextFilePatch)filePatch;
    String path = ObjectUtils.assertNotNull(patch.getBeforeName() == null ? patch.getAfterName() : patch.getBeforeName());
    String pathRelatedToProjectDir =
            project == null ? path : getPathRelatedToDir(ObjectUtils.assertNotNull(project.getBasePath()), basePath, path);
    final Map<String, CharSequence> additionalMap = new HashMap<>();
    for (PatchEP extension : extensions) {
      final CharSequence charSequence = extension.provideContent(pathRelatedToProjectDir, commitContext);
      if (! StringUtil.isEmpty(charSequence)) {
        additionalMap.put(extension.getName(), charSequence);
      }
    }
    writeFileHeading(patch, writer, lineSeparator, additionalMap);
    for(PatchHunk hunk: patch.getHunks()) {
      writeHunkStart(writer, hunk.getStartLineBefore(), hunk.getEndLineBefore(), hunk.getStartLineAfter(), hunk.getEndLineAfter(),
                     lineSeparator);
      for(PatchLine line: hunk.getLines()) {
        char prefixChar = ' ';
        switch (line.getType()) {
          case ADD:
            prefixChar = '+';
            break;
          case REMOVE:
            prefixChar = '-';
            break;
          case CONTEXT:
            prefixChar = ' ';
            break;
        }
        String text = line.getText();
        text = StringUtil.trimEnd(text, "\n");
        writeLine(writer, text, prefixChar);
        if (line.isSuppressNewLine()) {
          writer.write(lineSeparator + NO_NEWLINE_SIGNATURE + lineSeparator);
        }
        else {
          writer.write(lineSeparator);
        }
      }
    }
  }
}
 
Example 19
Source File: InspectionProfileEntry.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static String getShortName(@Nonnull String className) {
  return StringUtil.trimEnd(StringUtil.trimEnd(className, "Inspection"),"InspectionBase");
}
 
Example 20
Source File: SourceTestConfig.java    From intellij with Apache License 2.0 3 votes vote down vote up
/**
 * We modify the glob patterns provided by the user, so that their behavior more closely matches
 * what is expected.
 *
 * <p>Rules:
 * <li>path/ => path*
 * <li>path/* => path*
 * <li>path => path*
 */
@VisibleForTesting
static String modifyPattern(String pattern) {
  pattern = StringUtil.trimEnd(pattern, '*');
  pattern = StringUtil.trimEnd(pattern, File.separatorChar);
  return pattern + "*";
}