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

The following examples show how to use com.intellij.openapi.util.text.StringUtil#trimStart() . 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: InvokableInformation.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 6 votes vote down vote up
public InvokableInformation(String fullSignature, String name) {
    String signatureWithoutName = StringUtil.trimStart(fullSignature, name);
    Matcher m = CypherElementWithSignature.FULL_SIGNATURE_REGEXP.matcher(signatureWithoutName);
    if (m.find()) {
        signature = m.group(1);
        returnTypeString = m.group(2);
    } else {
        // should never happen, unless Neo4j changes signature syntax
        signature = fullSignature;
        returnTypeString = "ANY?";
    }

    returnType = CypherType.parse(returnTypeString);

    this.name = name;
    this.hasParameters = !this.signature.startsWith("()");

    this.arguments = parseArguments();
    this.arity = calculateArity();
}
 
Example 3
Source File: PutIntoDefaultLocationActionBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected static String getTargetLocationText(Set<String> paths) {
  String target;
  if (paths.size() == 1) {
    final String path = StringUtil.trimStart(StringUtil.trimEnd(paths.iterator().next(), "/"), "/");
    if (path.length() > 0) {
      target = "/" + path;
    }
    else {
      target = "Output Root";
    }
  }
  else {
    target = "Default Locations";
  }
  return target;
}
 
Example 4
Source File: ProjectViewLabelReference.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
private PsiFileSystemItem resolveFile(String path) {
  if (path.startsWith("/") || path.contains(":")) {
    return null;
  }
  BuildReferenceManager manager = BuildReferenceManager.getInstance(getProject());
  path = StringUtil.trimStart(path, "-");
  File file = manager.resolvePackage(WorkspacePath.createIfValid(path));
  if (file == null) {
    return null;
  }
  VirtualFile vf =
      VirtualFileSystemProvider.getInstance().getSystem().findFileByPath(file.getPath());
  if (vf == null) {
    return null;
  }
  PsiManager psiManager = PsiManager.getInstance(getProject());
  return vf.isDirectory() ? psiManager.findDirectory(vf) : psiManager.findFile(vf);
}
 
Example 5
Source File: ProjectFileTargetLocator.java    From idea-php-toolbox with MIT License 6 votes vote down vote up
@NotNull
@Override
public Collection<PsiElement> getTargets(@NotNull TargetLocatorParameter parameter) {
    if(!parameter.getTarget().startsWith("file://")) {
        return Collections.emptyList();
    }

    String projectFile = parameter.getTarget().substring("file://".length());
    projectFile = StringUtil.trimStart(projectFile.replaceAll("\\\\+", "/").replaceAll("/+", "/"), "/");

    VirtualFile relativeFile = VfsUtil.findRelativeFile(parameter.getProject().getBaseDir(), projectFile.split("/"));
    if(relativeFile == null) {
        return Collections.emptyList();
    }

    PsiFile file = PsiManager.getInstance(parameter.getProject()).findFile(relativeFile);
    if(file == null) {
        return Collections.emptyList();
    }

    Collection<PsiElement> targets = new ArrayList<>();
    targets.add(file);

    return targets;
}
 
Example 6
Source File: PackagingElementFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public List<? extends PackagingElement<?>> createParentDirectories(@Nonnull String relativeOutputPath, @Nonnull List<? extends PackagingElement<?>> elements) {
  relativeOutputPath = StringUtil.trimStart(relativeOutputPath, "/");
  if (relativeOutputPath.length() == 0) {
    return elements;
  }
  int slash = relativeOutputPath.indexOf('/');
  if (slash == -1) slash = relativeOutputPath.length();
  String rootName = relativeOutputPath.substring(0, slash);
  String pathTail = relativeOutputPath.substring(slash);
  final DirectoryPackagingElement root = createDirectory(rootName);
  final CompositePackagingElement<?> last = getOrCreateDirectory(root, pathTail);
  last.addOrFindChildren(elements);
  return Collections.singletonList(root);
}
 
Example 7
Source File: IndexPattern.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void compilePattern() {
  try {
    int flags = 0;
    if (!myCaseSensitive) {
      flags = Pattern.CASE_INSENSITIVE;
    }
    myPattern = Pattern.compile(myPatternString, flags);
    String optimizedPattern = myPatternString;
    optimizedPattern = StringUtil.trimStart(optimizedPattern, ".*");
    myOptimizedIndexingPattern = Pattern.compile(optimizedPattern, flags);
  }
  catch (PatternSyntaxException e) {
    myPattern = null;
    myOptimizedIndexingPattern = null;
  }
}
 
Example 8
Source File: FileLookupData.java    From intellij with Apache License 2.0 6 votes vote down vote up
@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 9
Source File: ProjectFileTargetLocator.java    From idea-php-toolbox with MIT License 6 votes vote down vote up
@NotNull
@Override
public Collection<PsiElement> getTargets(@NotNull TargetLocatorParameter parameter) {
    if(!parameter.getTarget().startsWith("file://")) {
        return Collections.emptyList();
    }

    String projectFile = parameter.getTarget().substring("file://".length());
    projectFile = StringUtil.trimStart(projectFile.replaceAll("\\\\+", "/").replaceAll("/+", "/"), "/");

    VirtualFile relativeFile = VfsUtil.findRelativeFile(parameter.getProject().getBaseDir(), projectFile.split("/"));
    if(relativeFile == null) {
        return Collections.emptyList();
    }

    PsiFile file = PsiManager.getInstance(parameter.getProject()).findFile(relativeFile);
    if(file == null) {
        return Collections.emptyList();
    }

    Collection<PsiElement> targets = new ArrayList<>();
    targets.add(file);

    return targets;
}
 
Example 10
Source File: BlazePythonTestLocator.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Override
public List<Location> getLocation(
    String protocol, String path, Project project, GlobalSearchScope scope) {
  if (protocol.equals(SmRunnerUtils.GENERIC_SUITE_PROTOCOL)) {
    return findTestClass(project, scope, path);
  }
  if (protocol.equals(SmRunnerUtils.GENERIC_TEST_PROTOCOL)) {
    path = StringUtil.trimStart(path, PY_TESTCASE_PREFIX);
    String[] components = path.split("\\.|::");
    if (components.length < 2) {
      return ImmutableList.of();
    }
    return findTestMethod(
        project, scope, components[components.length - 2], components[components.length - 1]);
  }
  return ImmutableList.of();
}
 
Example 11
Source File: IdeaGateway.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void doCreateChildrenForPathOnly(@Nonnull DirectoryEntry parent,
                                         @Nonnull String path,
                                         @Nonnull Iterable<VirtualFile> children) {
  for (VirtualFile child : children) {
    String name = StringUtil.trimStart(child.getName(), "/"); // on Mac FS root name is "/"
    if (!path.startsWith(name)) continue;
    String rest = path.substring(name.length());
    if (!rest.isEmpty() && rest.charAt(0) != '/') continue;
    if (!rest.isEmpty() && rest.charAt(0) == '/') {
      rest = rest.substring(1);
    }
    Entry e = doCreateEntryForPathOnly(child, rest);
    if (e == null) continue;
    parent.addChild(e);
  }
}
 
Example 12
Source File: VirtualFile.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Finds file by path relative to this file.
 *
 * @param relPath the relative path with / used as separators
 * @return the file if found any, <code>null</code> otherwise
 */
@Nullable
public VirtualFile findFileByRelativePath(@Nonnull String relPath) {
  if (relPath.isEmpty()) return this;
  relPath = StringUtil.trimStart(relPath, "/");

  int index = relPath.indexOf('/');
  if (index < 0) index = relPath.length();
  String name = relPath.substring(0, index);

  VirtualFile child;
  if (name.equals(".")) {
    child = this;
  }
  else if (name.equals("..")) {
    if (is(VFileProperty.SYMLINK)) {
      final VirtualFile canonicalFile = getCanonicalFile();
      child = canonicalFile != null ? canonicalFile.getParent() : null;
    }
    else {
      child = getParent();
    }
  }
  else {
    child = findChild(name);
  }

  if (child == null) return null;

  if (index < relPath.length()) {
    return child.findFileByRelativePath(relPath.substring(index + 1));
  }
  return child;
}
 
Example 13
Source File: IwyuPragmas.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public void visitComment(PsiComment comment) {
  String text = trimCommentContent(comment.getText());
  if (text.startsWith(IWYU_PREFIX)) {
    String pragmaContent = StringUtil.trimStart(text, IWYU_PREFIX);
    for (StandalonePragmaParser parser : STANDALONE_PARSERS) {
      if (parser.tryParse(this, pragmaContent)) {
        break;
      }
    }
  }
  super.visitComment(comment);
}
 
Example 14
Source File: PostfixTemplateLookupElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
public PostfixTemplateLookupElement(@Nonnull PostfixLiveTemplate liveTemplate,
                                    @Nonnull PostfixTemplate postfixTemplate,
                                    @Nonnull String templateKey,
                                    @Nonnull PostfixTemplateProvider provider,
                                    boolean sudden) {
  super(liveTemplate, templateKey, StringUtil.trimStart(templateKey, "."), postfixTemplate.getDescription(), sudden, true);
  myTemplate = postfixTemplate;
  myProvider = provider;
}
 
Example 15
Source File: CreateElementActionBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static String filterMessage(String message) {
  if (message == null) return null;
  @NonNls final String ioExceptionPrefix = "java.io.IOException:";
  message = StringUtil.trimStart(message, ioExceptionPrefix);
  return message;
}
 
Example 16
Source File: VfsUtilCore.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
public static VirtualFile findRelativeFile(@Nonnull String uri, @Nullable VirtualFile base) {
  if (base != null) {
    if (!base.isValid()) {
      LOG.error("Invalid file name: " + base.getName() + ", url: " + uri);
    }
  }

  uri = uri.replace('\\', '/');

  if (uri.startsWith("file:///")) {
    uri = uri.substring("file:///".length());
    if (!SystemInfo.isWindows) uri = "/" + uri;
  }
  else if (uri.startsWith("file:/")) {
    uri = uri.substring("file:/".length());
    if (!SystemInfo.isWindows) uri = "/" + uri;
  }
  else {
    uri = StringUtil.trimStart(uri, "file:");
  }

  VirtualFile file = null;

  if (uri.startsWith("jar:file:/")) {
    uri = uri.substring("jar:file:/".length());
    if (!SystemInfo.isWindows) uri = "/" + uri;
    file = VirtualFileManager.getInstance().findFileByUrl(StandardFileSystems.ZIP_PROTOCOL_PREFIX + uri);
  }
  else if (!SystemInfo.isWindows && StringUtil.startsWithChar(uri, '/') || SystemInfo.isWindows && uri.length() >= 2 && Character.isLetter(uri.charAt(0)) && uri.charAt(1) == ':') {
    file = StandardFileSystems.local().findFileByPath(uri);
  }

  if (file == null && uri.contains(URLUtil.ARCHIVE_SEPARATOR)) {
    file = StandardFileSystems.zip().findFileByPath(uri);
    if (file == null && base == null) {
      file = VirtualFileManager.getInstance().findFileByUrl(uri);
    }
  }

  if (file == null) {
    if (base == null) return StandardFileSystems.local().findFileByPath(uri);
    if (!base.isDirectory()) base = base.getParent();
    if (base == null) return StandardFileSystems.local().findFileByPath(uri);
    file = VirtualFileManager.getInstance().findFileByUrl(base.getUrl() + "/" + uri);
    if (file == null) return null;
  }

  return file;
}
 
Example 17
Source File: BuildReferenceManager.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Nullable
public BuildFile resolveBlazePackage(String workspaceRelativePath) {
  workspaceRelativePath = StringUtil.trimStart(workspaceRelativePath, "//");
  return resolveBlazePackage(WorkspacePath.createIfValid(workspaceRelativePath));
}
 
Example 18
Source File: BuildReferenceManager.java    From intellij with Apache License 2.0 4 votes vote down vote up
/**
 * Finds all child directories. If exactly one is found, continue traversing (and appending to
 * LookupElement string) until there are multiple options. Stops traversing at BUILD packages.
 *
 * <p>Used for package path completion suggestions.
 */
public BuildLookupElement[] resolvePackageLookupElements(FileLookupData lookupData) {
  String relativePath = lookupData.filePathFragment;
  if (!relativePath.equals(FileUtil.toCanonicalUriPath(relativePath))) {
    // ignore invalid labels containing './', '../', etc.
    return BuildLookupElement.EMPTY_ARRAY;
  }
  File file = resolveWorkspaceRelativePath(relativePath);

  FileOperationProvider provider = FileOperationProvider.getInstance();
  String pathFragment = "";
  if (file == null || (!provider.isDirectory(file) && !relativePath.endsWith("/"))) {
    // we might be partway through a file name. Try the parent directory
    relativePath = PathUtil.getParentPath(relativePath);
    file = resolveWorkspaceRelativePath(relativePath);
    pathFragment =
        StringUtil.trimStart(lookupData.filePathFragment.substring(relativePath.length()), "/");
  }
  if (file == null || !provider.isDirectory(file)) {
    return BuildLookupElement.EMPTY_ARRAY;
  }
  VirtualFile vf =
      VirtualFileSystemProvider.getInstance().getSystem().findFileByPath(file.getPath());
  if (vf == null || !vf.isDirectory()) {
    return BuildLookupElement.EMPTY_ARRAY;
  }
  BuildLookupElement[] uniqueLookup = new BuildLookupElement[1];
  while (true) {
    VirtualFile[] children = vf.getChildren();
    if (children == null || children.length == 0) {
      return uniqueLookup[0] != null ? uniqueLookup : BuildLookupElement.EMPTY_ARRAY;
    }
    List<VirtualFile> validChildren = Lists.newArrayListWithCapacity(children.length);
    for (VirtualFile child : children) {
      ProgressManager.checkCanceled();
      if (child.getName().startsWith(pathFragment) && lookupData.acceptFile(project, child)) {
        validChildren.add(child);
      }
    }
    if (validChildren.isEmpty()) {
      return uniqueLookup[0] != null ? uniqueLookup : BuildLookupElement.EMPTY_ARRAY;
    }
    if (validChildren.size() > 1) {
      return uniqueLookup[0] != null ? uniqueLookup : lookupsForFiles(validChildren, lookupData);
    }
    // if we've already traversed a directory and this is a BUILD package, stop here
    if (uniqueLookup[0] != null && hasBuildFile(children)) {
      return uniqueLookup;
    }
    // otherwise continue traversing while there's only one option
    uniqueLookup[0] = lookupForFile(validChildren.get(0), lookupData);
    pathFragment = "";
    vf = validChildren.get(0);
  }
}
 
Example 19
Source File: WildcardTargetPattern.java    From intellij with Apache License 2.0 4 votes vote down vote up
/** Returns null if the target is not a valid wildcard target pattern. */
@Nullable
public static WildcardTargetPattern fromExpression(TargetExpression target) {
  String pattern = target.toString();
  int colonIndex = pattern.lastIndexOf(':');
  String packagePart = colonIndex < 0 ? pattern : pattern.substring(0, colonIndex);
  String targetPart = colonIndex < 0 ? "" : pattern.substring(colonIndex + 1);

  if (packagePart.startsWith("-")) {
    packagePart = packagePart.substring(1);
  }
  packagePart = StringUtil.trimStart(packagePart, "//");

  if (packagePart.endsWith(ALL_PACKAGES_RECURSIVE_SUFFIX)) {
    WorkspacePath basePackageDir =
        WorkspacePath.createIfValid(
            StringUtil.trimEnd(packagePart, ALL_PACKAGES_RECURSIVE_SUFFIX));
    if (basePackageDir == null) {
      return null;
    }
    if (targetPart.isEmpty() || targetPart.equals(ALL_RULES_IN_SUFFIX)) {
      return new WildcardTargetPattern(target, basePackageDir, true, true);
    }
    if (ALL_TARGETS_IN_SUFFIXES.contains(targetPart)) {
      return new WildcardTargetPattern(target, basePackageDir, true, false);
    }
    return null; // ignore invalid patterns -- blaze will give us a better error later.
  }

  WorkspacePath packageDir = WorkspacePath.createIfValid(packagePart);
  if (packageDir == null) {
    return null;
  }
  if (targetPart.equals(ALL_RULES_IN_SUFFIX)) {
    return new WildcardTargetPattern(target, packageDir, false, true);
  }
  if (ALL_TARGETS_IN_SUFFIXES.contains(targetPart)) {
    return new WildcardTargetPattern(target, packageDir, false, false);
  }
  // not a wildcard target pattern
  return null;
}
 
Example 20
Source File: TestsPresentationUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static String getPresentableName(final SMTestProxy testProxy) {
  final SMTestProxy parent = testProxy.getParent();
  final String name = testProxy.getName();

  if (name == null) {
    return NO_NAME_TEST;
  }

  String presentationCandidate = name;
  if (parent != null) {
    String parentName = parent.getName();
    if (parentName != null) {
      boolean parentStartsWith = name.startsWith(parentName);
      if (!parentStartsWith && parent instanceof SMTestProxy.SMRootTestProxy) {
        final String presentation = ((SMTestProxy.SMRootTestProxy)parent).getPresentation();
        if (presentation != null) {
          parentName = presentation;
          parentStartsWith = name.startsWith(parentName);
        }
      }
      if (parentStartsWith) {
        presentationCandidate = name.substring(parentName.length());

        // remove "." separator
        presentationCandidate = StringUtil.trimStart(presentationCandidate, ".");
      }
    }
  }

  // trim
  presentationCandidate = presentationCandidate.trim();

  // remove extra spaces
  presentationCandidate = presentationCandidate.replaceAll("\\s+", " ");

  if (StringUtil.isEmpty(presentationCandidate)) {
    return NO_NAME_TEST;
  }

  return presentationCandidate;
}