com.intellij.psi.PsiComment Java Examples

The following examples show how to use com.intellij.psi.PsiComment. 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: OnEventGenerateUtils.java    From litho with Apache License 2.0 6 votes vote down vote up
/**
 * Adds comment to the given method "// An event handler ContextClassName.methodName(c,
 * parameterName)
 */
public static void addComment(PsiClass contextClass, PsiMethod method) {
  final Project project = contextClass.getProject();
  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);

  final StringBuilder builder =
      new StringBuilder("// An event handler ")
          .append(LithoPluginUtils.getLithoComponentNameFromSpec(contextClass.getName()))
          .append(".")
          .append(method.getName())
          .append("(")
          .append(CONTEXT_PARAMETER_NAME);
  for (PsiParameter parameter : method.getParameterList().getParameters()) {
    if (LithoPluginUtils.isParam(parameter)) {
      builder.append(", ").append(parameter.getName());
    }
  }

  builder.append(")");
  final PsiComment comment = factory.createCommentFromText(builder.toString(), method);
  method.addBefore(comment, method.getModifierList());
}
 
Example #2
Source File: SQFStatement.java    From arma-intellij-plugin with MIT License 6 votes vote down vote up
/**
 * Used for debugging. Will return the statement the given element is contained in.
 * If the element is a PsiComment, <PsiComment> will be returned. Otherwise, the element's ancestor statement
 * text will be returned with all newlines replaced with spaces.
 * <p>
 * If the element has no parent or no {@link SQFStatement} parent, &lt;No Statement Parent&gt; will be returned
 *
 * @return the text, or &lt;PsiComment&gt; if element is a PsiComment
 */
@NotNull
public static String debug_getStatementTextForElement(@NotNull PsiElement element) {
	if (element instanceof PsiComment) {
		return "<PsiComment>";
	}
	if (element.getContainingFile() == null || !(element.getContainingFile() instanceof SQFFile)) {
		throw new IllegalArgumentException("element isn't in an SQFFile");
	}
	while (!(element instanceof SQFStatement)) {
		element = element.getParent();
		if (element == null) {
			return "<No Statement Parent>";
		}
	}
	return element.getText().replaceAll("\n", " ");
}
 
Example #3
Source File: SQFStatement.java    From arma-intellij-plugin with MIT License 6 votes vote down vote up
/**
 * @return the nearest ancestor {@link SQFStatement} that contains the given element, or null if not in a {@link SQFStatement}
 * @throws IllegalArgumentException when element is a PsiComment or when it is not in an SQFFile
 */
@Nullable
public static SQFStatement getStatementForElement(@NotNull PsiElement element) {
	if (element instanceof PsiComment) {
		throw new IllegalArgumentException("element is a comment");
	}
	if (element.getContainingFile() == null || !(element.getContainingFile() instanceof SQFFile)) {
		throw new IllegalArgumentException("element isn't in an SQFFile");
	}
	while (!(element instanceof SQFStatement)) {
		element = element.getParent();
		if (element == null) {
			return null;
		}
	}
	return (SQFStatement) element;
}
 
Example #4
Source File: EnterHandler.java    From bamboo-soy with Apache License 2.0 6 votes vote down vote up
@Override
public Result postProcessEnter(
    @NotNull PsiFile file, @NotNull Editor editor, @NotNull DataContext dataContext) {
  if (file.getFileType() != SoyFileType.INSTANCE) {
    return Result.Continue;
  }

  int caretOffset = editor.getCaretModel().getOffset();
  PsiElement element = file.findElementAt(caretOffset);
  Document document = editor.getDocument();

  int lineNumber = document.getLineNumber(caretOffset) - 1;
  int lineStartOffset = document.getLineStartOffset(lineNumber);
  String lineTextBeforeCaret = document.getText(new TextRange(lineStartOffset, caretOffset));

  if (element instanceof PsiComment && element.getTextOffset() < caretOffset) {
    handleEnterInComment(element, file, editor);
  } else if (lineTextBeforeCaret.startsWith("/*")) {
    insertText(file, editor, " * \n ", 3);
  }

  return Result.Continue;
}
 
Example #5
Source File: UnterminatedCommentAnnotator.java    From bamboo-soy with Apache License 2.0 6 votes vote down vote up
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder annotationHolder) {
  if (element instanceof PsiComment) {
    IElementType commentTokenType = ((PsiComment) element).getTokenType();
    if (commentTokenType != SoyTypes.DOC_COMMENT_BLOCK
        && commentTokenType != SoyTypes.COMMENT_BLOCK) {
      return;
    }
    if (!element.getText().endsWith("*/")) {
      int start = element.getTextRange().getEndOffset() - 1;
      int end = start + 1;
      annotationHolder
          .createErrorAnnotation(TextRange.create(start, end), "Unterminated comment");
    }
  }
}
 
Example #6
Source File: SQFStatement.java    From arma-intellij-plugin with MIT License 6 votes vote down vote up
/**
 * Used for debugging. Will return the statement the given element is contained in.
 * If the element is a PsiComment, &lt;PsiComment&gt; will be returned. Otherwise, the element's ancestor statement
 * text will be returned with all newlines replaced with spaces.
 * <p>
 * If the element has no parent or no {@link SQFStatement} parent, &lt;No Statement Parent&gt; will be returned
 *
 * @return the text, or &lt;PsiComment&gt; if element is a PsiComment
 */
@NotNull
public static String debug_getStatementTextForElement(@NotNull PsiElement element) {
	if (element instanceof PsiComment) {
		return "<PsiComment>";
	}
	if (element.getContainingFile() == null || !(element.getContainingFile() instanceof SQFFile)) {
		throw new IllegalArgumentException("element isn't in an SQFFile");
	}
	while (!(element instanceof SQFStatement)) {
		element = element.getParent();
		if (element == null) {
			return "<No Statement Parent>";
		}
	}
	return element.getText().replaceAll("\n", " ");
}
 
Example #7
Source File: ExtJsGoToDeclarationHandler.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
@Nullable
@Override
public PsiElement[] getGotoDeclarationTargets(PsiElement sourceElement, int offset, Editor editor) {

    if(!ShopwareProjectComponent.isValidForProject(sourceElement)) {
        return new PsiElement[0];
    }

    final List<PsiElement> targets = new ArrayList<>();

    if(ExtJsUtil.getStringLiteralPattern().accepts(sourceElement)) {
        // {link file='frontend/_resources/styles/framework.css'}
        attachControllerActionNameGoto(sourceElement, targets);

        // {s name='foobar' namespace='foobar/ns'}
        attachSnippets(sourceElement, targets);
    }

    if(PlatformPatterns.psiElement(PsiComment.class).accepts(sourceElement)) {
        attachSnippetAsComment(sourceElement, targets);
    }

    return targets.toArray(new PsiElement[0]);
}
 
Example #8
Source File: BuildFileRunLineMarkerContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static FuncallExpression getRuleFuncallExpression(PsiElement element) {
  PsiFile parentFile = element.getContainingFile();
  if (!(parentFile instanceof BuildFile)
      || ((BuildFile) parentFile).getBlazeFileType() != BlazeFileType.BuildPackage) {
    return null;
  }
  if (!(element instanceof LeafElement)
      || element instanceof PsiWhiteSpace
      || element instanceof PsiComment) {
    return null;
  }
  if (!(element.getParent() instanceof ReferenceExpression)) {
    return null;
  }
  PsiElement grandParent = element.getParent().getParent();
  return grandParent instanceof FuncallExpression
          && ((FuncallExpression) grandParent).isTopLevel()
      ? (FuncallExpression) grandParent
      : null;
}
 
Example #9
Source File: FormatterBasedLineIndentInfoBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private List<Block> getBlocksStartingNewLine() {
  NewLineBlocksIterator newLineBlocksIterator = new NewLineBlocksIterator(myRootBlock, myDocument);

  List<Block> newLineBlocks = new ArrayList<Block>();
  int currentLine = 0;
  while (newLineBlocksIterator.hasNext() && currentLine < MAX_NEW_LINE_BLOCKS_TO_PROCESS) {
    Block next = newLineBlocksIterator.next();
    if (next instanceof ASTBlock && ((ASTBlock)next).getNode() instanceof PsiComment) {
      continue;
    }
    newLineBlocks.add(next);
    currentLine++;
  }

  return newLineBlocks;
}
 
Example #10
Source File: Trees.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Get all non-WS, non-Comment children of t */
@NotNull
public static PsiElement[] getChildren(PsiElement t) {
	if ( t==null ) return PsiElement.EMPTY_ARRAY;

	PsiElement psiChild = t.getFirstChild();
	if (psiChild == null) return PsiElement.EMPTY_ARRAY;

	List<PsiElement> result = new ArrayList<>();
	while (psiChild != null) {
		if ( !(psiChild instanceof PsiComment) &&
			 !(psiChild instanceof PsiWhiteSpace) )
		{
			result.add(psiChild);
		}
		psiChild = psiChild.getNextSibling();
	}
	return PsiUtilCore.toPsiElementArray(result);
}
 
Example #11
Source File: SimpleDuplicatesFinder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
protected SimpleMatch isDuplicateFragment(@Nonnull final PsiElement candidate) {
  if (!canReplace(myReplacement, candidate)) return null;
  for (PsiElement pattern : myPattern) {
    if (PsiTreeUtil.isAncestor(pattern, candidate, false)) return null;
  }
  PsiElement sibling = candidate;
  final ArrayList<PsiElement> candidates = new ArrayList<>();
  for (int i = 0; i != myPattern.size(); ++i) {
    if (sibling == null) return null;

    candidates.add(sibling);
    sibling = PsiTreeUtil.skipSiblingsForward(sibling, PsiWhiteSpace.class, PsiComment.class);
  }
  if (myPattern.size() != candidates.size()) return null;
  if (candidates.size() <= 0) return null;
  final SimpleMatch match = new SimpleMatch(candidates.get(0), candidates.get(candidates.size() - 1));
  for (int i = 0; i < myPattern.size(); i++) {
    if (!matchPattern(myPattern.get(i), candidates.get(i), match)) return null;
  }
  return match;
}
 
Example #12
Source File: JSGraphQLEndpointDocPsiUtil.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
/**
 * Gets whether the specified comment is considered documentation, i.e. that it's placed directly above a type or field definition
 */
public static boolean isDocumentationComment(PsiElement element) {
	if (element instanceof PsiComment) {
		PsiElement next = element.getNextSibling();
		while (next != null) {
			final boolean isWhiteSpace = next instanceof PsiWhiteSpace;
			if (next instanceof PsiComment || isWhiteSpace) {
				if (isWhiteSpace && StringUtils.countMatches(next.getText(), "\n") > 1) {
					// a blank line before the next element, so this comment is not directly above it
					break;
				}
				next = next.getNextSibling();
			} else {
				break;
			}
		}
		if (next instanceof JSGraphQLEndpointFieldDefinition || next instanceof JSGraphQLEndpointNamedTypeDefinition) {
			return true;
		}
	}
	return false;
}
 
Example #13
Source File: JSGraphQLEndpointDocPsiUtil.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
/**
 * Gets the text of the continuous comments placed directly above the specified element
 * @param element element whose previous siblings are enumerated and included if they're documentation comments
 * @return the combined text of the documentation comments, preserving line breaks, or <code>null</code> if no documentation is available
 */
public static String getDocumentation(PsiElement element) {
	final PsiComment comment = PsiTreeUtil.getPrevSiblingOfType(element, PsiComment.class);
	final PsiElement previousElement =PsiTreeUtil.getPrevSiblingOfType(element, element.getClass());
	if(isDocumentationComment(comment)) {
		if(previousElement != null && previousElement.getTextOffset() > comment.getTextOffset()) {
			// the comment is for another element of same type so no docs for this element
			return null;
		}
		final List<PsiComment> siblings = Lists.newArrayList(comment);
		getDocumentationCommentSiblings(comment, siblings, PsiElement::getPrevSibling);
		Collections.reverse(siblings);
		return siblings.stream().map(c -> StringUtils.stripStart(c.getText(), "# ")).collect(Collectors.joining("\n"));
	}
	return null;
}
 
Example #14
Source File: JSGraphQLEndpointSpellcheckingStrategy.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public Tokenizer getTokenizer(PsiElement element) {
    if (element instanceof PsiWhiteSpace) {
        return EMPTY_TOKENIZER;
    }
    if (element instanceof PsiNameIdentifierOwner) {
        return new PsiIdentifierOwnerTokenizer();
    }
    if (element.getParent() instanceof PsiNameIdentifierOwner) {
        return EMPTY_TOKENIZER;
    }
    if (element.getNode().getElementType() == JSGraphQLEndpointTokenTypes.IDENTIFIER) {
        return IDENTIFIER_TOKENIZER;
    }
    if (element instanceof PsiComment) {
        if (SuppressionUtil.isSuppressionComment(element)) {
            return EMPTY_TOKENIZER;
        }
        return myCommentTokenizer;
    }
    return EMPTY_TOKENIZER;
}
 
Example #15
Source File: CommonMacroCompletionContributor.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the element before which a new load statement should be placed, or null if it belongs
 * at the top of the file.
 */
@Nullable
private static PsiElement findAnchorElement(BuildFile file) {
  for (PsiElement child : file.getChildren()) {
    if (child instanceof LoadStatement || child instanceof PsiComment || isWhiteSpace(child)) {
      continue;
    }
    return child;
  }
  return null;
}
 
Example #16
Source File: FormatterTagHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void visitComment(PsiComment comment) {
  FormatterTag tag = getFormatterTag(comment);
  //noinspection EnumSwitchStatementWhichMissesCases
  switch (tag) {
    case OFF:
      myTagInfoList.add(new FormatterTagInfo(comment.getTextRange().getEndOffset(), FormatterTag.OFF));
      break;
    case ON:
      myTagInfoList.add(new FormatterTagInfo(comment.getTextRange().getEndOffset(), FormatterTag.ON));
      break;
  }
}
 
Example #17
Source File: PantsIntegrationTestCase.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
protected void modify(@NonNls @NotNull String qualifiedName) {
  final PsiClass psiClass = findClassAndAssert(qualifiedName);
  final PsiFile psiFile = psiClass.getContainingFile();
  final PsiParserFacade parserFacade = PsiParserFacade.SERVICE.getInstance(myProject);
  final PsiComment comment = parserFacade.createBlockCommentFromText(psiFile.getLanguage(), "Foo");
  WriteCommandAction.runWriteCommandAction(
    myProject,
    ((Runnable) () -> psiFile.add(comment))
  );
  FileDocumentManager manager = FileDocumentManager.getInstance();
  manager.saveAllDocuments();
}
 
Example #18
Source File: AtElementSingle.java    From bamboo-soy with Apache License 2.0 5 votes vote down vote up
@Nullable
default PsiComment getDocComment() {
  PsiElement firstChild = getFirstChild();
  return firstChild instanceof PsiComment
          && firstChild.getNode().getElementType() == SoyTypes.DOC_COMMENT_BLOCK
      ? (PsiComment) firstChild
      : null;
}
 
Example #19
Source File: JSGraphQLEndpointDocInjector.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Override
public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host, @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) {
	if(ApplicationManager.getApplication().isUnitTestMode()) {
		// intellij unit test env doesn't properly support language injection in combination with formatter tests, so skip injection in that case
		return;
	}
	if (host instanceof PsiComment && host.getLanguage() == JSGraphQLEndpointLanguage.INSTANCE) {
		injectionPlacesRegistrar.addPlace(JSGraphQLEndpointDocLanguage.INSTANCE, TextRange.create(0, host.getTextLength()), "", "");
	}
}
 
Example #20
Source File: SQFDocumentationProvider.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
@Nullable
@Override
public String generateDoc(PsiElement element, @Nullable PsiElement originalElement) {
	if (element == null) {
		return null;
	}
	if (element.getNode() == null) {
		return null;
	}
	if (element instanceof XmlTag) {
		return StringTableKey.getKeyDoc((XmlTag) element);
	}
	if (SQFParserDefinition.isCommand(element.getNode().getElementType())) {
		return generateCommandDoc(element.getText());
	}
	if (SQFStatic.isBisFunction(element.getText())) {
		return generateFunctionDoc(element.getText());
	}
	if (PsiUtil.isOfElementType(element, SQFParserDefinition.INLINE_COMMENT) || PsiUtil.isOfElementType(element, SQFParserDefinition.BLOCK_COMMENT)) {
		PsiComment comment = (PsiComment) element;
		return DocumentationUtil.purtify(DocumentationUtil.getCommentContent(comment));
	}
	if (element instanceof PsiFile) {
		PsiElement[] children = element.getChildren();
		for (PsiElement child : children) {
			if (child instanceof SQFScope) {
				break;
			}
			if (child instanceof PsiComment) {
				return DocumentationUtil.purtify(DocumentationUtil.getCommentContent((PsiComment) child));
			}
		}
		return null;
	}
	return null;
}
 
Example #21
Source File: ElmAddImportHelper.java    From elm-plugin with MIT License 5 votes vote down vote up
private static PsiElement skipOverDocComments(PsiElement startElement) {
    PsiElement elt = startElement.getNextSibling();
    if (elt == null) {
        return startElement;
    } else if (elt instanceof PsiComment) {
        IElementType commentType = ((PsiComment) elt).getTokenType();
        if (commentType == START_DOC_COMMENT) {
            return PsiTreeUtil.skipSiblingsForward(elt, PsiComment.class);
        }
    }

    return elt;
}
 
Example #22
Source File: DocumentationUtil.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
@NotNull
public static String getCommentContent(@NotNull PsiComment comment) {
	if (comment.getNode().getElementType() == SQFParserDefinition.INLINE_COMMENT) {
		if (comment.getText().length() <= 2) {
			return "";
		}
		return comment.getText().substring(2);
	}
	return comment.getText().substring(2, comment.getTextLength() - 2).replaceAll("\t([^\r\n])", "$1"); //shift comments left 1 tab if tabbed
}
 
Example #23
Source File: BuildSpellcheckingStrategy.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isMyContext(PsiElement element) {
  if (element instanceof PsiComment) {
    return true;
  }
  if (element instanceof StringLiteral) {
    // as a rough heuristic, only spell-check triple-quoted strings, which are more likely to be
    // english sentences rather than keywords
    QuoteType q = ((StringLiteral) element).getQuoteType();
    return q == QuoteType.TripleDouble || q == QuoteType.TripleSingle;
  }
  return false;
}
 
Example #24
Source File: TwigPattern.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
public static ElementPattern<PsiComment> getTwigTypeDocBlockPattern() {
    Collection<ElementPattern> patterns = new ArrayList<>();

    for (String s : TwigTypeResolveUtil.DOC_TYPE_PATTERN_SINGLE) {
        patterns.add(PlatformPatterns.psiComment().withText(PlatformPatterns.string().matches(s)).withLanguage(TwigLanguage.INSTANCE));
    }

    return PlatformPatterns.or(patterns.toArray(new ElementPattern[patterns.size()]));
}
 
Example #25
Source File: DocumentationUtil.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Annotates the given comment so that tags like @command, @bis, and @fnc (Arma Intellij Plugin specific tags) are properly annotated
 *
 * @param annotator the annotator
 * @param comment   the comment
 */
public static void annotateDocumentationWithArmaPluginTags(@NotNull AnnotationHolder annotator, @NotNull PsiComment comment) {
	List<String> allowedTags = new ArrayList<>(3);
	allowedTags.add("command");
	allowedTags.add("bis");
	allowedTags.add("fnc");
	Pattern patternTag = Pattern.compile("@([a-zA-Z]+) ([a-zA-Z_0-9]+)");
	Matcher matcher = patternTag.matcher(comment.getText());
	String tag;
	Annotation annotation;
	int startTag, endTag, startArg, endArg;
	while (matcher.find()) {
		if (matcher.groupCount() < 2) {
			continue;
		}
		tag = matcher.group(1);
		if (!allowedTags.contains(tag)) {
			continue;
		}
		startTag = matcher.start(1);
		endTag = matcher.end(1);
		startArg = matcher.start(2);
		endArg = matcher.end(2);
		annotation = annotator.createAnnotation(HighlightSeverity.INFORMATION, TextRange.create(comment.getTextOffset() + startTag - 1, comment.getTextOffset() + endTag), null);
		annotation.setTextAttributes(DefaultLanguageHighlighterColors.DOC_COMMENT_TAG);
		annotation = annotator.createAnnotation(HighlightSeverity.INFORMATION, TextRange.create(comment.getTextOffset() + startArg, comment.getTextOffset() + endArg), null);
		annotation.setTextAttributes(DefaultLanguageHighlighterColors.DOC_COMMENT_TAG_VALUE);
	}
}
 
Example #26
Source File: BashKeywordCompletionProvider.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@Override
public boolean accepts(@Nullable Object o, ProcessingContext context) {
    if (o instanceof LeafPsiElement && rejectedTokens.contains(((LeafPsiElement) o).getElementType())) {
        return false;
    }

    if (o instanceof PsiElement) {
        if (BashPsiUtils.hasParentOfType((PsiElement) o, BashString.class, 5)) {
            return false;
        }

        if (BashPsiUtils.hasParentOfType((PsiElement) o, PsiComment.class, 3)) {
            return false;
        }

        if (BashPsiUtils.hasParentOfType((PsiElement) o, BashShebang.class, 3)) {
            return false;
        }

        if (BashPsiUtils.hasParentOfType((PsiElement) o, BashHereDoc.class, 1)) {
            return false;
        }

        if (BashPsiUtils.hasParentOfType((PsiElement) o, BashParameterExpansion.class, 2)) {
            return false;
        }

        if (BashPsiUtils.isCommandParameterWord((PsiElement) o)) {
            return false;
        }

        return true;

    }

    return false;
}
 
Example #27
Source File: AbstractSuppressByNoInspectionCommentFix.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@Nonnull final Project project, @Nullable Editor editor, @Nonnull final PsiElement element) throws IncorrectOperationException {
  PsiElement container = getContainer(element);
  if (container == null) return;

  if (!FileModificationService.getInstance().preparePsiElementForWrite(container)) return;

  final List<? extends PsiElement> comments = getCommentsFor(container);
  if (comments != null) {
    for (PsiElement comment : comments) {
      if (comment instanceof PsiComment && SuppressionUtil.isSuppressionComment(comment)) {
        replaceSuppressionComment(comment);
        return;
      }
    }
  }

  boolean caretWasBeforeStatement = editor != null && editor.getCaretModel().getOffset() == container.getTextRange().getStartOffset();
  try {
    createSuppression(project, element, container);
  }
  catch (IncorrectOperationException e) {
    if (!ApplicationManager.getApplication().isUnitTestMode() && editor != null) {
      Messages.showErrorDialog(editor.getComponent(),
                               InspectionsBundle.message("suppress.inspection.annotation.syntax.error", e.getMessage()));
    }
  }

  if (caretWasBeforeStatement) {
    editor.getCaretModel().moveToOffset(container.getTextRange().getStartOffset());
  }
  UndoUtil.markPsiFileForUndo(element.getContainingFile());
}
 
Example #28
Source File: JSGraphQLEndpointDocPsiUtil.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Gets the values of other documentation tags that are immediate siblings
 *
 * @param comment the comment to use as a staring point
 */
public static List<String> getOtherDocTagValues(PsiComment comment) {


	final Project project = comment.getProject();
	final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(project);

	final List<PsiComment> siblings = Lists.newArrayList();
	getDocumentationCommentSiblings(comment, siblings, PsiElement::getPrevSibling);
	getDocumentationCommentSiblings(comment, siblings, PsiElement::getNextSibling);

	final List<String> values = Lists.newArrayList();

	for (PsiComment sibling : siblings) {
		if (sibling instanceof PsiLanguageInjectionHost) {
			List<Pair<PsiElement, TextRange>> injected = injectedLanguageManager.getInjectedPsiFiles(sibling);
			if (injected != null) {
				for (Pair<PsiElement, TextRange> pair : injected) {
					PsiFile injectedFile = pair.first.getContainingFile();
					final JSGraphQLEndpointDocTag tag = PsiTreeUtil.findChildOfType(injectedFile, JSGraphQLEndpointDocTag.class);
					if (tag != null && tag.getDocValue() != null) {
						values.add(tag.getDocValue().getText());
					}
				}
			}
		}
	}
	return values;
}
 
Example #29
Source File: LineCommentSelectioner.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public List<TextRange> select(PsiElement element, CharSequence editorText, int cursorOffset, Editor editor) {
  List<TextRange> result = super.select(element, editorText, cursorOffset, editor);


  PsiElement firstComment = element;
  PsiElement e = element;

  while (e.getPrevSibling() != null) {
    if (e instanceof PsiComment) {
      firstComment = e;
    }
    else if (!(e instanceof PsiWhiteSpace)) {
      break;
    }
    e = e.getPrevSibling();
  }

  PsiElement lastComment = element;
  e = element;
  while (e.getNextSibling() != null) {
    if (e instanceof PsiComment) {
      lastComment = e;
    }
    else if (!(e instanceof PsiWhiteSpace)) {
      break;
    }
    e = e.getNextSibling();
  }


  result.addAll(expandToWholeLine(editorText, new TextRange(firstComment.getTextRange().getStartOffset(),
                                                            lastComment.getTextRange().getEndOffset())));

  return result;
}
 
Example #30
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);
}