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

The following examples show how to use com.intellij.openapi.util.text.StringUtil#startsWithChar() . 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: KeymapPanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void removeShortcut(Shortcut shortcut) {
  String actionId = myActionsTree.getSelectedActionId();
  if (actionId == null) {
    return;
  }

  if (!createKeymapCopyIfNeeded()) return;

  if (shortcut == null) return;

  mySelectedKeymap.removeShortcut(actionId, shortcut);
  if (StringUtil.startsWithChar(actionId, '$')) {
    mySelectedKeymap.removeShortcut(KeyMapBundle.message("editor.shortcut", actionId.substring(1)), shortcut);
  }

  repaintLists();
  processCurrentKeymapChanged(getCurrentQuickListIds());
}
 
Example 2
Source File: LocalFileSystemImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static List<String> splitPath(@Nonnull String path) {
  if (path.isEmpty()) {
    return Collections.emptyList();
  }

  if (FS_ROOT.equals(path)) {
    return Collections.singletonList(FS_ROOT);
  }

  List<String> parts = StringUtil.split(path, FS_ROOT);
  if (StringUtil.startsWithChar(path, '/')) {
    parts.add(0, FS_ROOT);
  }
  return parts;
}
 
Example 3
Source File: ArchivesBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static <T> String addParentDirectories(@Nonnull T archiveObject,
                                               @Nonnull ArchivePackageWriter<T> writer,
                                               THashSet<String> writtenPaths,
                                               String relativePath) throws IOException {
  while (StringUtil.startsWithChar(relativePath, '/')) {
    relativePath = relativePath.substring(1);
  }
  int i = relativePath.indexOf('/');
  while (i != -1) {
    String prefix = relativePath.substring(0, i + 1);
    if (!writtenPaths.contains(prefix) && prefix.length() > 1) {

      writer.addDirectory(archiveObject, prefix);

      writtenPaths.add(prefix);
    }
    i = relativePath.indexOf('/', i + 1);
  }
  return relativePath;
}
 
Example 4
Source File: LineStatusTrackerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private int[] fixRanges(@Nonnull DocumentEvent e, int line1, int line2) {
  CharSequence document = myDocument.getCharsSequence();
  int offset = e.getOffset();

  if (e.getOldLength() == 0 && e.getNewLength() != 0) {
    if (StringUtil.endsWithChar(e.getNewFragment(), '\n') && isNewline(offset - 1, document)) {
      return new int[]{line1, line2 - 1};
    }
    if (StringUtil.startsWithChar(e.getNewFragment(), '\n') && isNewline(offset + e.getNewLength(), document)) {
      return new int[]{line1 + 1, line2};
    }
  }
  if (e.getOldLength() != 0 && e.getNewLength() == 0) {
    if (StringUtil.endsWithChar(e.getOldFragment(), '\n') && isNewline(offset - 1, document)) {
      return new int[]{line1, line2 - 1};
    }
    if (StringUtil.startsWithChar(e.getOldFragment(), '\n') && isNewline(offset + e.getNewLength(), document)) {
      return new int[]{line1 + 1, line2};
    }
  }

  return new int[]{line1, line2};
}
 
Example 5
Source File: AWTIconLoaderFacade.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public SwingImageRef findIcon(@Nonnull String path, @Nonnull ClassLoader classLoader) {
  String originalPath = path;
  Pair<String, Class> patchedPath = patchPath(path);
  path = patchedPath.first;
  if (patchedPath.second != null) {
    classLoader = patchedPath.second.getClassLoader();
  }
  if (isReflectivePath(path)) return getReflectiveIcon(path, classLoader);
  if (!StringUtil.startsWithChar(path, '/')) return null;

  final URL url = classLoader.getResource(path.substring(1));
  final SwingImageRef icon = findIcon(url);
  if (icon instanceof CachedImageIcon) {
    ((CachedImageIcon)icon).myOriginalPath = originalPath;
    ((CachedImageIcon)icon).myClassLoader = classLoader;
  }
  return icon;
}
 
Example 6
Source File: CodeStyleSettings.java    From consulo with Apache License 2.0 6 votes vote down vote up
public String nameByType(String type) {
  for (int i = 0; i < myPatterns.size(); i++) {
    String pattern = myPatterns.get(i);
    if (StringUtil.startsWithChar(pattern, '*')) {
      if (type.endsWith(pattern.substring(1))) {
        return myNames.get(i);
      }
    }
    else {
      if (type.equals(pattern)) {
        return myNames.get(i);
      }
    }
  }
  return null;
}
 
Example 7
Source File: FileSetTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void runTest() throws Throwable {
  String content = FileUtil.loadFile(myTestFile);
  assertNotNull(content);

  List<String> input = new ArrayList<String>();

  int separatorIndex;

  content = StringUtil.replace(content, "\r", "");

  while ((separatorIndex = content.indexOf(getDelimiter())) >= 0) {
    input.add(content.substring(0, separatorIndex));
    content = content.substring(separatorIndex);
    while (StringUtil.startsWithChar(content, '-') || StringUtil.startsWithChar(content, '\n')) content = content.substring(1);
  }

  String result = content;

  assertTrue("No data found in source file", input.size() > 0);

  while (StringUtil.startsWithChar(result, '-') || StringUtil.startsWithChar(result, '\n') || StringUtil.startsWithChar(result, '\r')) {
    result = result.substring(1);
  }
  final String transformed;
  FileSetTestCase.this.myProject = getProject();
  String testName = myTestFile.getName();
  final int dotIdx = testName.indexOf('.');
  if (dotIdx >= 0) {
    testName = testName.substring(0, dotIdx);
  }

  transformed = StringUtil.replace(transform(testName, ArrayUtil.toStringArray(input)), "\r", "");
  result = StringUtil.replace(result, "\r", "");

  assertEquals(result.trim(),transformed.trim());
}
 
Example 8
Source File: DecodeDefaultsUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static URL getDefaultsImpl(final Object requestor, final String componentResourcePath) {
  boolean isPathAbsoulte = StringUtil.startsWithChar(componentResourcePath, '/');
  if (isPathAbsoulte) {
    return requestor.getClass().getResource(componentResourcePath + XML_EXTENSION);
  }
  else {
    return getResourceByRelativePath(requestor, componentResourcePath, XML_EXTENSION);
  }
}
 
Example 9
Source File: PhpIndexAbstractProviderAbstract.java    From idea-php-toolbox with MIT License 5 votes vote down vote up
@NotNull
@Override
public Collection<PsiElement> getPsiTargets(@NotNull PhpToolboxDeclarationHandlerParameter parameter) {
    String contents = parameter.getContents();
    if(!StringUtil.startsWithChar(contents, '\\')) {
        contents = "\\" + contents;
    }

    return new ArrayList<>(
        resolveParameter(PhpIndex.getInstance(parameter.getProject()), contents)
    );
}
 
Example 10
Source File: FileSetTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void addFileTest(File file) {
  if (!StringUtil.startsWithChar(file.getName(), '_') && !"CVS".equals(file.getName())) {
    if (myPattern != null && !myPattern.matcher(file.getPath()).matches()){
      return;
    }
    final ActualTest t = new ActualTest(file, createTestName(file));
    addTest(t);
  }
}
 
Example 11
Source File: DeploymentUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static String appendToPath(@Nonnull String basePath, @Nonnull String relativePath) {
  final boolean endsWithSlash = StringUtil.endsWithChar(basePath, '/') || StringUtil.endsWithChar(basePath, '\\');
  final boolean startsWithSlash = StringUtil.startsWithChar(relativePath, '/') || StringUtil.startsWithChar(relativePath, '\\');
  String tail;
  if (endsWithSlash && startsWithSlash) {
    tail = trimForwardSlashes(relativePath);
  }
  else if (!endsWithSlash && !startsWithSlash && basePath.length() > 0 && relativePath.length() > 0) {
    tail = "/" + relativePath;
  }
  else {
    tail = relativePath;
  }
  return basePath + tail;
}
 
Example 12
Source File: PhpIndexAbstractProviderAbstract.java    From idea-php-toolbox with MIT License 5 votes vote down vote up
@NotNull
@Override
public Collection<PsiElement> getPsiTargets(@NotNull PhpToolboxDeclarationHandlerParameter parameter) {
    String contents = parameter.getContents();
    if(!StringUtil.startsWithChar(contents, '\\')) {
        contents = "\\" + contents;
    }

    return new ArrayList<>(
        resolveParameter(PhpIndex.getInstance(parameter.getProject()), contents)
    );
}
 
Example 13
Source File: PathManager.java    From dynkt with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String trimPathQuotes(String path) {
	if ((path != null) && (path.length() >= 3) && (StringUtil.startsWithChar(path, '"'))
			&& (StringUtil.endsWithChar(path, '"'))) {
		path = path.substring(1, path.length() - 1);
	}
	return path;
}
 
Example 14
Source File: TestUtils.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
public static List<String> readInput(String filePath) throws IOException {
    String content = new String(FileUtil.loadFileText(new File(filePath)));
    Assert.assertNotNull(content);

    List<String> input = new ArrayList<String>();

    int separatorIndex;
    content = StringUtil.replace(content, "\r", ""); // for MACs

    // Adding input  before -----
    while ((separatorIndex = content.indexOf("-----")) >= 0) {
        input.add(content.substring(0, separatorIndex - 1));
        content = content.substring(separatorIndex);
        while (StringUtil.startsWithChar(content, '-')) {
            content = content.substring(1);
        }
        if (StringUtil.startsWithChar(content, '\n')) {
            content = content.substring(1);
        }
    }
    // Result - after -----
    if (content.endsWith("\n")) {
        content = content.substring(0, content.length() - 1);
    }
    input.add(content);

    Assert.assertTrue("No data found in source file", input.size() > 0);
    Assert.assertNotNull("Test output points to null", input.size() > 1);

    return input;
}
 
Example 15
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 16
Source File: KeymapImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public HashMap<String, ArrayList<KeyboardShortcut>> getConflicts(String actionId, KeyboardShortcut keyboardShortcut) {
  HashMap<String, ArrayList<KeyboardShortcut>> result = new HashMap<String, ArrayList<KeyboardShortcut>>();

  String[] actionIds = getActionIds(keyboardShortcut.getFirstKeyStroke());
  for (String id : actionIds) {
    if (id.equals(actionId)) {
      continue;
    }

    if (actionId.startsWith(EDITOR_ACTION_PREFIX) && id.equals("$" + actionId.substring(6))) {
      continue;
    }
    if (StringUtil.startsWithChar(actionId, '$') && id.equals(EDITOR_ACTION_PREFIX + actionId.substring(1))) {
      continue;
    }

    final String useShortcutOf = myKeymapManager.getActionBinding(id);
    if (useShortcutOf != null && useShortcutOf.equals(actionId)) {
      continue;
    }

    Shortcut[] shortcuts = getShortcuts(id);
    for (Shortcut shortcut1 : shortcuts) {
      if (!(shortcut1 instanceof KeyboardShortcut)) {
        continue;
      }

      KeyboardShortcut shortcut = (KeyboardShortcut)shortcut1;

      if (!shortcut.getFirstKeyStroke().equals(keyboardShortcut.getFirstKeyStroke())) {
        continue;
      }

      if (keyboardShortcut.getSecondKeyStroke() != null &&
          shortcut.getSecondKeyStroke() != null &&
          !keyboardShortcut.getSecondKeyStroke().equals(shortcut.getSecondKeyStroke())) {
        continue;
      }

      ArrayList<KeyboardShortcut> list = result.get(id);
      if (list == null) {
        list = new ArrayList<KeyboardShortcut>();
        result.put(id, list);
      }

      list.add(shortcut);
    }
  }

  return result;
}
 
Example 17
Source File: ArchiveFileSystem.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
protected String getRelativePath(@Nonnull VirtualFile file) {
  String path = file.getPath();
  String relativePath = path.substring(extractRootPath(path).length());
  return StringUtil.startsWithChar(relativePath, '/') ? relativePath.substring(1) : relativePath;
}
 
Example 18
Source File: LocalFileSystemBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
protected String extractRootPath(@Nonnull String path) {
  if (path.isEmpty()) {
    try {
      path = new File("").getCanonicalPath();
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  for (String customRootPath : ourRootPaths) {
    if (path.startsWith(customRootPath)) return customRootPath;
  }

  if (SystemInfo.isWindows) {
    if (path.length() >= 2 && path.charAt(1) == ':') {
      // Drive letter
      return StringUtil.toUpperCase(path.substring(0, 2));
    }

    if (path.startsWith("//") || path.startsWith("\\\\")) {
      // UNC. Must skip exactly two path elements like [\\ServerName\ShareName]\pathOnShare\file.txt
      // Root path is in square brackets here.

      int slashCount = 0;
      int idx;
      boolean isSlash = false;
      for (idx = 2; idx < path.length() && slashCount < 2; idx++) {
        char c = path.charAt(idx);
        isSlash = c == '\\' || c == '/';
        if (isSlash) {
          slashCount++;
          if (slashCount == 2) {
            idx--;
          }
        }
      }

      if (slashCount == 2 || slashCount == 1 && !isSlash) {
        return path.substring(0, idx);
      }
    }

    return "";
  }

  return StringUtil.startsWithChar(path, '/') ? "/" : "";
}
 
Example 19
Source File: ArchiveDestinationInfo.java    From consulo with Apache License 2.0 4 votes vote down vote up
public ArchiveDestinationInfo(final String pathInJar, final ArchivePackageInfo archivePackageInfo, DestinationInfo jarDestination) {
  super(appendPathInJar(jarDestination.getOutputPath(), pathInJar), jarDestination.getOutputFile(), jarDestination.getOutputFilePath());
  LOGGER.assertTrue(!pathInJar.startsWith(".."), pathInJar);
  myPathInJar = StringUtil.startsWithChar(pathInJar, '/') ? pathInJar : "/" + pathInJar;
  myArchivePackageInfo = archivePackageInfo;
}
 
Example 20
Source File: FileUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * @param antPattern ant-style path pattern
 * @return java regexp pattern.
 * Note that no matter whether forward or backward slashes were used in the antPattern
 * the returned regexp pattern will use forward slashes ('/') as file separators.
 * Paths containing windows-style backslashes must be converted before matching against the resulting regexp
 * @see FileUtil#toSystemIndependentName
 */
@RegExp
@Nonnull
public static String convertAntToRegexp(@Nonnull String antPattern, boolean ignoreStartingSlash) {
  final StringBuilder builder = new StringBuilder();
  int asteriskCount = 0;
  boolean recursive = true;
  final int start = ignoreStartingSlash && (StringUtil.startsWithChar(antPattern, '/') || StringUtil.startsWithChar(antPattern, '\\')) ? 1 : 0;
  for (int idx = start; idx < antPattern.length(); idx++) {
    final char ch = antPattern.charAt(idx);

    if (ch == '*') {
      asteriskCount++;
      continue;
    }

    final boolean foundRecursivePattern = recursive && asteriskCount == 2 && (ch == '/' || ch == '\\');
    final boolean asterisksFound = asteriskCount > 0;

    asteriskCount = 0;
    recursive = ch == '/' || ch == '\\';

    if (foundRecursivePattern) {
      builder.append("(?:[^/]+/)*?");
      continue;
    }

    if (asterisksFound) {
      builder.append("[^/]*?");
    }

    if (ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '^' || ch == '$' || ch == '.' || ch == '{' || ch == '}' || ch == '+' || ch == '|') {
      // quote regexp-specific symbols
      builder.append('\\').append(ch);
      continue;
    }
    if (ch == '?') {
      builder.append("[^/]{1}");
      continue;
    }
    if (ch == '\\') {
      builder.append('/');
      continue;
    }
    builder.append(ch);
  }

  // handle ant shorthand: my_package/test/ is interpreted as if it were my_package/test/**
  final boolean isTrailingSlash = builder.length() > 0 && builder.charAt(builder.length() - 1) == '/';
  if (asteriskCount == 0 && isTrailingSlash || recursive && asteriskCount == 2) {
    if (isTrailingSlash) {
      builder.setLength(builder.length() - 1);
    }
    if (builder.length() == 0) {
      builder.append(".*");
    }
    else {
      builder.append("(?:$|/.+)");
    }
  }
  else if (asteriskCount > 0) {
    builder.append("[^/]*?");
  }
  return builder.toString();
}