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

The following examples show how to use com.intellij.openapi.util.text.StringUtil#endsWithChar() . 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: ZipHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private EntryInfo getOrCreate(@Nonnull ArchiveEntry entry, @Nonnull Map<String, EntryInfo> map, @Nonnull ArchiveFile zip) {
  boolean isDirectory = entry.isDirectory();
  String entryName = entry.getName();
  if (StringUtil.endsWithChar(entryName, '/')) {
    entryName = entryName.substring(0, entryName.length() - 1);
    isDirectory = true;
  }

  EntryInfo info = map.get(entryName);
  if (info != null) return info;

  Pair<String, String> path = splitPath(entryName);
  EntryInfo parentInfo = getOrCreate(path.first, map, zip);
  if (".".equals(path.second)) {
    return parentInfo;
  }
  info = store(map, parentInfo, path.second, isDirectory, entry.getSize(), myFileStamp, entryName);
  return info;
}
 
Example 2
Source File: JavaIdeaUtils.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Code from com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl#getInnerText()
 */
@Nullable
private String getInnerText(String text) {
    if (text == null) {
        return null;
    }
    if (StringUtil.endsWithChar(text, '\"') && text.length() == 1) {
        return "";
    }
    // Remove any newline feed + whitespaces + single + double quot to concat a split string
    return StringUtil.unquoteString(text.replace(QUOT, "\"")).replaceAll("(^\\n\\s+|\\n\\s+$|\\n\\s+)|(\"\\s*\\+\\s*\")|(\"\\s*\\+\\s*\\n\\s*\"*)", "");
}
 
Example 3
Source File: IdeaUtils.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Code from com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl#getInnerText()
 */
@Nullable
public String getInnerText(String text) {
    if (text == null) {
        return null;
    }
    if (StringUtil.endsWithChar(text, '\"') && text.length() == 1) {
        return "";
    }
    // Remove any newline feed + whitespaces + single + double quot to concat a split string
    return StringUtil.unquoteString(text.replace(QUOT, "\"")).replaceAll("(^\\n\\s+|\\n\\s+$|\\n\\s+)|(\"\\s*\\+\\s*\")|(\"\\s*\\+\\s*\\n\\s*\"*)", "");
}
 
Example 4
Source File: Util.java    From DarkyenusTimeTracker with The Unlicense 5 votes vote down vote up
@Nullable
public static Path convertToIOFile(@Nullable VirtualFile file) {
	if (file == null || !file.isInLocalFileSystem()) {
		return null;
	}

	// Based on LocalFileSystemBase.java
	String path = file.getPath();
	if (StringUtil.endsWithChar(path, ':') && path.length() == 2 && SystemInfo.isWindows) {
		path += "/";
	}

	return Paths.get(path);
}
 
Example 5
Source File: XmlIdeaUtils.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Code from com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl#getInnerText()
 */
@Nullable
public static String getInnerText(String text) {
    if (text == null) {
        return null;
    }
    if (StringUtil.endsWithChar(text, '\"') && text.length() == 1) {
        return "";
    }
    // Remove any newline feed + whitespaces + single + double quot to concat a split string
    return StringUtil.unquoteString(text.replace(QUOT, "\"")).replaceAll("(^\\n\\s+|\\n\\s+$|\\n\\s+)|(\"\\s*\\+\\s*\")|(\"\\s*\\+\\s*\\n\\s*\"*)", "");
}
 
Example 6
Source File: SemicolonFixer.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private static boolean fixReturn(@NotNull Editor editor, @Nullable PsiElement psiElement) {
  if (!(psiElement instanceof HaxeReturnStatement)) {
    return false;
  }

  HaxeReturnStatement haxeReturnStatement = (HaxeReturnStatement)psiElement;

  if (StringUtil.endsWithChar(haxeReturnStatement.getText(), ';')) {
    return false;
  }

  HaxeMethodDeclaration haxeFunctionDeclarationWithAttributes =
    PsiTreeUtil.getParentOfType(haxeReturnStatement, HaxeMethodDeclaration.class);

  if (haxeFunctionDeclarationWithAttributes != null) {
    HaxeTypeTag typeTag = haxeFunctionDeclarationWithAttributes.getTypeTag();
    if (typeTag != null) {
      HaxeTypeOrAnonymous typeOrAnonymous = typeTag.getTypeOrAnonymous();
      if (typeOrAnonymous != null) {
        if (typeOrAnonymous.getText().equals(SpecificTypeReference.VOID)) {
          return false;
        }
      }
    }
  }

  HaxeExpression haxeReturnStatementExpression = haxeReturnStatement.getExpression();
  if (haxeReturnStatementExpression != null) {
    Document doc = editor.getDocument();
    int offset = haxeReturnStatementExpression.getTextRange().getEndOffset();
    doc.insertString(offset, ";");
    editor.getCaretModel().moveToOffset(offset + 1);
    return true;
  }

  return false;
}
 
Example 7
Source File: VfsUtilCore.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean isEqualOrAncestor(@Nonnull String ancestorUrl, @Nonnull String fileUrl) {
  if (ancestorUrl.equals(fileUrl)) return true;
  if (StringUtil.endsWithChar(ancestorUrl, '/')) {
    return fileUrl.startsWith(ancestorUrl);
  }
  else {
    return StringUtil.startsWithConcatenation(fileUrl, ancestorUrl, "/");
  }
}
 
Example 8
Source File: DesktopContainerPathManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static String trimPathQuotes(String path) {
  if (!(path != null && !(path.length() < 3))) {
    return path;
  }
  if (StringUtil.startsWithChar(path, '\"') && StringUtil.endsWithChar(path, '\"')) {
    return path.substring(1, path.length() - 1);
  }
  return path;
}
 
Example 9
Source File: VFileCreateEvent.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
protected String computePath() {
  String parentPath = myParent.getPath();
  // jar file returns "x.jar!/"
  return StringUtil.endsWithChar(parentPath, '/') ? parentPath + getChildName() : parentPath + "/" + getChildName();
}
 
Example 10
Source File: LocalFileSystemBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static File convertToIOFile(@Nonnull VirtualFile file) {
  String path = file.getPath();
  if (StringUtil.endsWithChar(path, ':') && path.length() == 2 && SystemInfo.isWindows) {
    path += '/';  // makes 'C:' resolve to a root directory of the drive C:, not the current directory on that drive
  }
  return new File(path);
}
 
Example 11
Source File: DiffCorrection.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void process(@Nonnull DiffFragment fragment, @Nonnull FragmentBuffer buffer) {
  if (fragment.isEqual()) buffer.add(fragment);
  else if (fragment.isOneSide()) {
    DiffString text = FragmentSide.chooseSide(fragment).getText(fragment);
    if (StringUtil.endsWithChar(text, '\n'))
      buffer.add(fragment);
    else
      buffer.markIfNone(CHANGE);
  } else buffer.markIfNone(CHANGE);
}
 
Example 12
Source File: Messages.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Shows dialog with text area to edit long strings that don't fit in text field.
 */
public static void showTextAreaDialog(final JTextField textField,
                                      final String title,
                                      @NonNls final String dimensionServiceKey,
                                      final Function<String, List<String>> parser,
                                      final Function<List<String>, String> lineJoiner) {
  if (isApplicationInUnitTestOrHeadless()) {
    ourTestImplementation.show(title);
  }
  else {
    final JTextArea textArea = new JTextArea(10, 50);
    textArea.setWrapStyleWord(true);
    textArea.setLineWrap(true);
    List<String> lines = parser.fun(textField.getText());
    textArea.setText(StringUtil.join(lines, "\n"));
    InsertPathAction.copyFromTo(textField, textArea);
    final DialogBuilder builder = new DialogBuilder(textField);
    builder.setDimensionServiceKey(dimensionServiceKey);
    builder.setCenterPanel(ScrollPaneFactory.createScrollPane(textArea));
    builder.setPreferredFocusComponent(textArea);
    String rawText = title;
    if (StringUtil.endsWithChar(rawText, ':')) {
      rawText = rawText.substring(0, rawText.length() - 1);
    }
    builder.setTitle(rawText);
    builder.addOkAction();
    builder.addCancelAction();
    builder.setOkOperation(new Runnable() {
      @Override
      public void run() {
        textField.setText(lineJoiner.fun(Arrays.asList(StringUtil.splitByLines(textArea.getText()))));
        builder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE);
      }
    });
    builder.addDisposable(new TextComponentUndoProvider(textArea));
    builder.show();
  }
}
 
Example 13
Source File: PsiFormatUtilBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected static void appendSpaceIfNeeded(StringBuilder buffer) {
  if (buffer.length() != 0 && !StringUtil.endsWithChar(buffer, ' ')) {
    buffer.append(' ');
  }
}
 
Example 14
Source File: NameUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static String compoundSuggestion(@Nonnull String prefix, boolean upperCaseStyle, @Nonnull String[] words, int wordCount, @Nonnull String startWord, char c, boolean isArray, boolean skip_) {
  StringBuilder buffer = new StringBuilder();

  buffer.append(prefix);

  if (upperCaseStyle) {
    startWord = StringUtil.toUpperCase(startWord);
  }
  else {
    if (prefix.isEmpty() || StringUtil.endsWithChar(prefix, '_')) {
      startWord = StringUtil.toLowerCase(startWord);
    }
    else {
      startWord = Character.toUpperCase(c) + startWord.substring(1);
    }
  }
  buffer.append(startWord);

  for (int i = words.length - wordCount + 1; i < words.length; i++) {
    String word = words[i];
    String prevWord = words[i - 1];
    if (upperCaseStyle) {
      word = StringUtil.toUpperCase(word);
      if (prevWord.charAt(prevWord.length() - 1) != '_' && word.charAt(0) != '_') {
        word = "_" + word;
      }
    }
    else {
      if (prevWord.charAt(prevWord.length() - 1) == '_') {
        word = StringUtil.toLowerCase(word);
      }

      if (skip_) {
        if (word.equals("_")) continue;
        if (prevWord.equals("_")) {
          word = StringUtil.capitalize(word);
        }
      }
    }
    buffer.append(word);
  }

  String suggestion = buffer.toString();
  if (isArray) {
    suggestion = StringUtil.pluralize(suggestion);
    if (upperCaseStyle) {
      suggestion = StringUtil.toUpperCase(suggestion);
    }
  }
  return suggestion;
}
 
Example 15
Source File: ZipUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean addFileToZip(@Nonnull ZipOutputStream zos,
                                   @Nonnull File file,
                                   @Nonnull String relativeName,
                                   @Nullable Set<String> writtenItemRelativePaths,
                                   @Nullable FileFilter fileFilter,
                                   @Nonnull FileContentProcessor contentProcessor) throws IOException {
  while (relativeName.length() != 0 && relativeName.charAt(0) == '/') {
    relativeName = relativeName.substring(1);
  }

  boolean isDir = file.isDirectory();
  if (isDir && !StringUtil.endsWithChar(relativeName, '/')) {
    relativeName += "/";
  }
  if (fileFilter != null && !FileUtil.isFilePathAcceptable(file, fileFilter)) return false;
  if (writtenItemRelativePaths != null && !writtenItemRelativePaths.add(relativeName)) return false;

  if (LOG.isDebugEnabled()) {
    LOG.debug("Add " + file + " as " + relativeName);
  }

  long size = isDir ? 0 : file.length();
  ZipEntry e = new ZipEntry(relativeName);
  e.setTime(file.lastModified());
  if (size == 0) {
    e.setMethod(ZipEntry.STORED);
    e.setSize(0);
    e.setCrc(0);
  }
  zos.putNextEntry(e);
  if (!isDir) {
    InputStream is = null;
    try {
      is = contentProcessor.getContent(file);
      FileUtil.copy(is, zos);
    }
    finally {
      StreamUtil.closeStream(is);
    }
  }
  zos.closeEntry();
  return true;
}
 
Example 16
Source File: LabeledComponent.java    From consulo with Apache License 2.0 4 votes vote down vote up
public String getText() {
  String text = TextWithMnemonic.fromLabel(myLabel).getTextWithMnemonic();
  if (StringUtil.endsWithChar(text, ':')) return text.substring(0, text.length() - 1);
  return text;
}
 
Example 17
Source File: DirectoryUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Creates the directory with the given path via PSI, including any
 * necessary but nonexistent parent directories. Must be run in write action.
 * @param path directory path in the local file system; separators must be '/'
 * @return true if path exists or has been created as the result of this method call; false otherwise
 */
public static PsiDirectory mkdirs(PsiManager manager, String path) throws IncorrectOperationException{
  if (File.separatorChar != '/') {
    if (path.indexOf(File.separatorChar) != -1) {
      throw new IllegalArgumentException("separators must be '/'; path is " + path);
    }
  }

  String existingPath = path;

  PsiDirectory directory = null;

  // find longest existing path
  while (existingPath.length() > 0) {
    VirtualFile file = LocalFileSystem.getInstance().findFileByPath(existingPath);
    if (file != null) {
      directory = manager.findDirectory(file);
      if (directory == null) {
        return null;
      }
      break;
    }

    if (StringUtil.endsWithChar(existingPath, '/')) {
      existingPath = existingPath.substring(0, existingPath.length() - 1);
      if (SystemInfo.isWindows && existingPath.length() == 2 && existingPath.charAt(1) == ':') {
        return null;
      }
    }

    int index = existingPath.lastIndexOf('/');
    if (index == -1) {
      // nothing to do more
      return null;
    }

    existingPath = existingPath.substring(0, index);
  }

  if (directory == null) {
    return null;
  }

  if (existingPath.equals(path)) {
    return directory;
  }

  String postfix = path.substring(existingPath.length() + 1, path.length());
  StringTokenizer tokenizer = new StringTokenizer(postfix, "/");
  while (tokenizer.hasMoreTokens()) {
    String name = tokenizer.nextToken();

    PsiDirectory subdirectory = directory.createSubdirectory(name);
    if (subdirectory == null) {
      return null;
    }

    directory = subdirectory;
  }

  return directory;
}
 
Example 18
Source File: FindUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static TextRange doReplace(final Project project,
                                  final Document document,
                                  final FindModel model,
                                  FindResult result,
                                  @Nonnull String stringToReplace,
                                  boolean reallyReplace,
                                  List<Pair<TextRange, String>> rangesToChange) {
  final int startOffset = result.getStartOffset();
  final int endOffset = result.getEndOffset();

  int newOffset;
  if (reallyReplace) {
    newOffset = doReplace(project, document, startOffset, endOffset, stringToReplace);
  }
  else {
    final String converted = StringUtil.convertLineSeparators(stringToReplace);
    TextRange textRange = new TextRange(startOffset, endOffset);
    rangesToChange.add(Pair.create(textRange, converted));

    newOffset = endOffset;
  }

  int start = startOffset;
  int end = newOffset;
  if (model.isRegularExpressions()) {
    String toFind = model.getStringToFind();
    if (model.isForward()) {
      if (StringUtil.endsWithChar(toFind, '$')) {
        int i = 0;
        int length = toFind.length();
        while (i + 2 <= length && toFind.charAt(length - i - 2) == '\\') i++;
        if (i % 2 == 0) end++; //This $ is a special symbol in regexp syntax
      }
      else if (StringUtil.startsWithChar(toFind, '^')) {
        while (end < document.getTextLength() && document.getCharsSequence().charAt(end) != '\n') end++;
      }
    }
    else {
      if (StringUtil.startsWithChar(toFind, '^')) {
        start--;
      }
      else if (StringUtil.endsWithChar(toFind, '$')) {
        while (start >= 0 && document.getCharsSequence().charAt(start) != '\n') start--;
      }
    }
  }
  return new TextRange(start, end);
}
 
Example 19
Source File: TokenBuffer.java    From consulo with Apache License 2.0 4 votes vote down vote up
private boolean hasTrailingCR() {
  return !tokens.isEmpty() && tokens.peekLast() != CR_TOKEN && StringUtil.endsWithChar(tokens.peekLast().getText(), '\r');
}
 
Example 20
Source File: FakeVirtualFile.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public String getPath() {
  final String basePath = myParent.getPath();
  return StringUtil.endsWithChar(basePath, '/') ? basePath + myName : basePath + '/' + myName;
}