com.intellij.psi.PsiElement#getNode ( )源码实例Demo

下面列出了com.intellij.psi.PsiElement#getNode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: consulo   文件: TextOccurrencesUtil.java
private static boolean processStringLiteralsContainingIdentifier(@Nonnull String identifier,
                                                                 @Nonnull SearchScope searchScope,
                                                                 PsiSearchHelper helper,
                                                                 final Processor<PsiElement> processor) {
  TextOccurenceProcessor occurenceProcessor = new TextOccurenceProcessor() {
    @Override
    public boolean execute(PsiElement element, int offsetInElement) {
      final ParserDefinition definition = LanguageParserDefinitions.INSTANCE.forLanguage(element.getLanguage());
      final ASTNode node = element.getNode();
      if (definition != null &&
          node != null &&
          definition.getStringLiteralElements(element.getLanguageVersion()).contains(node.getElementType())) {
        return processor.process(element);
      }
      return true;
    }
  };

  return helper.processElementsWithWord(occurenceProcessor, searchScope, identifier, UsageSearchContext.IN_STRINGS, true);
}
 
@Override
void runInvoke(@NotNull Project project, @NotNull PsiLocalOpen parentElement) {
    // parentElement is the scope: Module.Module «( ... )»
    RmlTypes types = RmlTypes.INSTANCE;
    PsiElement grandParentElement = parentElement.getParent();

    // Extract the module path (and remove path nodes)
    String modulePath = "";
    PsiElement sibling = PsiTreeUtil.prevVisibleLeaf(parentElement);
    while (sibling != null && (sibling.getNode().getElementType() == types.UIDENT || sibling.getNode().getElementType() == types.DOT)) {
        ASTNode currentNode = sibling.getNode();
        if (!modulePath.isEmpty() || currentNode.getElementType() != types.DOT) {
            modulePath = sibling.getText() + modulePath;
        }
        sibling = PsiTreeUtil.prevVisibleLeaf(sibling);
        grandParentElement.getNode().removeChild(currentNode);
    }

    String text = parentElement.getText();
    PsiElement newOpen = ORCodeFactory.createExpression(project, "{ open " + modulePath + "; " + text.substring(1, text.length() - 1) + "; }");
    if (newOpen != null) {
        grandParentElement.getNode().replaceChild(parentElement.getNode(), newOpen.getNode());
    }
}
 
源代码3 项目: consulo   文件: LanguageFolding.java
@RequiredReadAction
public static FoldingDescriptor[] buildFoldingDescriptors(FoldingBuilder builder, PsiElement root, Document document, boolean quick) {
  if (!DumbService.isDumbAware(builder) && DumbService.getInstance(root.getProject()).isDumb()) {
    return FoldingDescriptor.EMPTY;
  }

  if (builder instanceof FoldingBuilderEx) {
    return ((FoldingBuilderEx)builder).buildFoldRegions(root, document, quick);
  }
  final ASTNode astNode = root.getNode();
  if (astNode == null || builder == null) {
    return FoldingDescriptor.EMPTY;
  }

  return builder.buildFoldRegions(astNode, document);
}
 
源代码4 项目: glsl4idea   文件: GLSLForStatement.java
/**
 * Fetches the initialization, the condition and the counter elements and places them in an array.
 * The array will always have length 3 and the elements are always placed in their respective places.
 * They will be null if missing.
 *
 * @return an array containing the loop elements.
 */
@NotNull
private GLSLElement[] getForElements() {
    GLSLElement[] result = new GLSLElement[3];
    int numberOfSemicolonsPassed = 0;
    PsiElement current = getFirstChild();
    while (current != null) {
        ASTNode node = current.getNode();
        if (current instanceof GLSLExpression || current instanceof GLSLDeclaration) {
            result[numberOfSemicolonsPassed] = (GLSLElement) current;
        } else if (node != null) {
            if (node.getElementType() == GLSLTokenTypes.SEMICOLON) {
                numberOfSemicolonsPassed++;
            }
            if (node.getElementType() == GLSLTokenTypes.RIGHT_PAREN) {
                break;
            }
        }

        current = current.getNextSibling();
    }
    return result;
}
 
源代码5 项目: consulo   文件: ASTDelegatePsiElement.java
@Override
@Nonnull
@RequiredReadAction
public PsiElement[] getChildren() {
  PsiElement psiChild = getFirstChild();
  if (psiChild == null) return PsiElement.EMPTY_ARRAY;

  List<PsiElement> result = new ArrayList<PsiElement>();
  while (psiChild != null) {
    if (psiChild.getNode() instanceof CompositeElement) {
      result.add(psiChild);
    }
    psiChild = psiChild.getNextSibling();
  }
  return PsiUtilCore.toPsiElementArray(result);
}
 
源代码6 项目: intellij-xquery   文件: XQueryXmlGtTypedHandler.java
@Override
public Result beforeCharTyped(final char c, final Project project, final Editor editor, final PsiFile editedFile, final FileType fileType) {
    if ((editedFile.getLanguage() instanceof XQueryLanguage) && c == '>') {
        PsiDocumentManager.getInstance(project).commitAllDocuments();
        PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
        if (file == null) return Result.CONTINUE;
        final int offset = editor.getCaretModel().getOffset();
        FileViewProvider provider = file.getViewProvider();
        PsiElement element = provider.findElementAt(offset, XQueryLanguage.class);

        if (element != null && element.getNode() != null && (
                element.getNode().getElementType() == XQueryTypes.XMLTAGEND ||
                        element.getNode().getElementType() == XQueryTypes.XMLEMPTYELEMENTEND)) {
            EditorModificationUtil.moveCaretRelatively(editor, 1);
            editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
            return Result.STOP;
        }
    }
    return Result.CONTINUE;
}
 
源代码7 项目: CppTools   文件: CppSelectioner.java
public List<TextRange> select(PsiElement psiElement, CharSequence charSequence, int i, Editor editor) {
  final PsiFile psiFile = psiElement.getContainingFile();
  final SelectWordCommand command = new SelectWordCommand(psiFile.getVirtualFile().getPath(),editor);
  command.post(psiFile.getProject());

  List<TextRange> result = new ArrayList<TextRange>();
  ASTNode node = psiElement.getNode();
  if (node != null && node.getElementType() == CppTokenTypes.STRING_LITERAL) {
    int textOffset = psiElement.getTextOffset();
    result.add(new TextRange(textOffset + 1, textOffset + psiElement.getTextLength() - 1));
  }
  if (!command.hasReadyResult()) {
    WindowManager.getInstance().getStatusBar(psiFile.getProject()).setInfo("Command was cancelled");
    return result;
  }

  final int start = command.getSelectionStart();
  int selectionEnd = command.getSelectionEnd();

  if (selectionEnd >= editor.getDocument().getTextLength()) {
    selectionEnd = editor.getDocument().getTextLength();
  }
  result.add(new TextRange(start, selectionEnd));

  return result;
}
 
@Nullable
@Override
public List<String> getUrlFor(PsiElement element, PsiElement originalElement) {
	if (element == null) {
		return null;
	}
	if (element.getNode() == null) {
		return null;
	}
	List<String> lst = new ArrayList<>();
	if (SQFParserDefinition.isCommand(element.getNode().getElementType()) || SQFStatic.isBisFunction(element.getText())) {
		lst.add(SQFStatic.BIS_WIKI_URL_PREFIX + element.getText());
		return lst;
	}
	return null;
}
 
/**
 * We have to override {@link com.intellij.formatting.templateLanguages.TemplateLanguageFormattingModelBuilder#createModel}
 * since after we delegate to some templated languages, those languages (xml/html for sure, potentially others)
 * delegate right back to us to format the DustTypes.OUTER_TYPE token we tell them to ignore,
 * causing an stack-overflowing loop.
 */
@NotNull
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {

  final PsiFile file = element.getContainingFile();
  Block rootBlock;

  ASTNode node = element.getNode();

  if (node.getElementType() == DustFileViewProvider.OUTER_TYPE) {
    // If we're looking at a DustTypes.HTML element, then we've been invoked by our templated
    // language.  Make a dummy block to allow that formatter to continue
    return new SimpleTemplateLanguageFormattingModelBuilder().createModel(element, settings);
  } else {
    rootBlock = getRootBlock(file, file.getViewProvider(), settings);
  }

  return new DocumentBasedFormattingModel(rootBlock, element.getProject(), settings, file.getFileType(), file);
}
 
源代码10 项目: consulo   文件: BaseMoveHandler.java
@Nullable
private static PsiFile getRoot(final PsiFile file, final Editor editor) {
  if (file == null) return null;
  int offset = editor.getCaretModel().getOffset();
  if (offset == editor.getDocument().getTextLength()) offset--;
  if (offset<0) return null;
  PsiElement leafElement = file.findElementAt(offset);
  if (leafElement == null) return null;
  if (leafElement.getLanguage() instanceof DependentLanguage) {
    leafElement = file.getViewProvider().findElementAt(offset, file.getViewProvider().getBaseLanguage());
    if (leafElement == null) return null;
  }
  ASTNode node = leafElement.getNode();
  if (node == null) return null;
  return (PsiFile)PsiUtilBase.getRoot(node).getPsi();
}
 
@Override
@Nonnull
public FormattingModel createModel(final PsiElement element, final CodeStyleSettings settings) {
  if (element instanceof PsiFile) {
    final FileViewProvider viewProvider = ((PsiFile)element).getViewProvider();
    if (viewProvider instanceof TemplateLanguageFileViewProvider) {
      final Language language = ((TemplateLanguageFileViewProvider)viewProvider).getTemplateDataLanguage();
      FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forLanguage(language);
      if (builder != null) {
        return builder.createModel(viewProvider.getPsi(language), settings);
      }
    }
  }

  final PsiFile file = element.getContainingFile();
  return new DocumentBasedFormattingModel(new AbstractBlock(element.getNode(), Wrap.createWrap(WrapType.NONE, false), Alignment.createAlignment()) {
    @Override
    protected List<Block> buildChildren() {
      return Collections.emptyList();
    }

    @Override
    public Spacing getSpacing(final Block child1, @Nonnull final Block child2) {
      return Spacing.getReadOnlySpacing();
    }

    @Override
    public boolean isLeaf() {
      return true;
    }
  }, element.getProject(), settings, file.getFileType(), file);
}
 
@NotNull
@Override
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
    CommonCodeStyleSettings commonSettings = settings.getCommonSettings(XQueryLanguage.INSTANCE);
    XQueryCodeStyleSettings xQuerySettings = settings.getCustomSettings(XQueryCodeStyleSettings.class);
    final XQueryFormattingBlock block = new XQueryFormattingBlock(element.getNode(), null, null, commonSettings,
            createSpacingBuilder(commonSettings, xQuerySettings, settings));
    FormattingModel result = createFormattingModelForPsiFile(element.getContainingFile(), block, settings);
    return result;
}
 
源代码13 项目: bamboo-soy   文件: SoyDocumentationProvider.java
@Nullable
@Override
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) {
  if (element.getNode() == null) {
    // Happens for a fake PSI element containing a URL ("Open in browser").
    return null;
  }

  Document document =
      FileDocumentManager.getInstance().getDocument(element.getContainingFile().getVirtualFile());
  if (document == null) {
    return null;
  }

  int lineNum = document.getLineNumber(element.getTextOffset()) + 1 /* count starts at zero */;
  String path = element.getContainingFile().getVirtualFile().getName();
  StringBuilder navigateInfo = new StringBuilder("Defined at ");
  navigateInfo.append(path);
  navigateInfo.append(":");
  navigateInfo.append(lineNum);
  String optDoc = getDocCommentForEnclosingTag(element);
  if (optDoc != null) {
    navigateInfo.append("\n");
    navigateInfo.append(produceCommentPreview(optDoc));
  }
  return navigateInfo.toString();
}
 
@Nullable
@Override
public PsiElement getCustomDocumentationElement(@NotNull Editor editor, @NotNull PsiFile file, @Nullable PsiElement contextElement) {
    // documentation from properties file will cause IDEA to call this method where we can tell IDEA we can provide
    // documentation for the element if we can detect its a Camel component

    if (contextElement != null) {
        ASTNode node = contextElement.getNode();
        if (node != null && node instanceof XmlToken) {
            //there is an &amp; in the route that splits the route in separated PsiElements
            if (node.getElementType() == XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN
                //the caret is at the end of the route next to the " character
                || node.getElementType() == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER
                //the caret is placed on an &amp; element
                || contextElement.getText().equals("&amp;")) {
                if (hasDocumentationForCamelComponent(contextElement.getParent())) {
                    return contextElement.getParent();
                }
            }
        }
        if (hasDocumentationForCamelComponent(contextElement)) {
            return contextElement;
        }
    }

    return null;
}
 
@Override
public Result charTyped(char c, Project project, @NotNull Editor editor, @NotNull PsiFile editedFile) {
    if ((editedFile.getLanguage() instanceof XQueryLanguage) && (c == '{' || c == '}')) {
        PsiDocumentManager.getInstance(project).commitAllDocuments();
        PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
        if (file == null) return Result.CONTINUE;
        FileViewProvider provider = file.getViewProvider();
        final int offset = editor.getCaretModel().getOffset();
        PsiElement element = provider.findElementAt(offset - 1, XQueryLanguage.class);
        if (element == null) return Result.CONTINUE;
        if (!(element.getLanguage() instanceof XQueryLanguage)) return Result.CONTINUE;
        ASTNode prevLeaf = element.getNode();
        if (prevLeaf == null) return Result.CONTINUE;
        final String prevLeafText = prevLeaf.getText();

        if (isInFunctionBodyAfterInsertionOfMatchingRightBrace(element, prevLeafText)) {
            if (c == '{') {
                editor.getDocument().insertString(offset + 1, ";");
            } else {
                EditorModificationUtil.insertStringAtCaret(editor, ";", false);
            }
        }

    }

    return Result.CONTINUE;
}
 
@NotNull
@Override
public FormattingModel createModel(@NotNull PsiElement element,
                                   @NotNull CodeStyleSettings settings,
                                   @NotNull FormattingMode mode) {
  final BuckBlock block =
      new BuckBlock(null, element.getNode(), settings, null, Indent.getNoneIndent(), null);
  return FormattingModelProvider.createFormattingModelForPsiFile(
      element.getContainingFile(),
      block,
      settings);
}
 
源代码17 项目: CppTools   文件: CppFormattingModelBuilder.java
public CppBlock(PsiElement psiElement) {
  myNode = psiElement.getNode();
  psiElement.getFirstChild(); // expand chameleon
}
 
源代码18 项目: consulo   文件: NamedFoldingDescriptor.java
public NamedFoldingDescriptor(@Nonnull PsiElement e, int start, int end, @Nullable FoldingGroup group, @Nonnull String placeholderText) {
  this(e.getNode(), new TextRange(start, end), group, placeholderText);
}
 
源代码19 项目: buck   文件: BuckCopyPasteProcessor.java
@Override
public String preprocessOnPaste(
    Project project, PsiFile psiFile, Editor editor, String text, RawText rawText) {
  if (!(psiFile instanceof BuckFile)) {
    return text;
  }
  final Document document = editor.getDocument();
  PsiDocumentManager.getInstance(project).commitDocument(document);
  final SelectionModel selectionModel = editor.getSelectionModel();

  // Pastes in block selection mode (column mode) are not handled by a CopyPasteProcessor.
  final int selectionStart = selectionModel.getSelectionStart();
  final PsiElement element = psiFile.findElementAt(selectionStart);
  if (element == null) {
    return text;
  }

  ASTNode elementNode = element.getNode();
  // A simple test of the element type
  boolean isQuotedString =
      BuckPsiUtils.hasElementType(
          elementNode, BuckTypes.QUOTED_STRING, BuckTypes.APOSTROPHED_STRING);
  // isQuotedString will be true if the caret is under the left quote, the right quote,
  // or anywhere in between. But pasting with caret under the left quote acts differently than
  // pasting in other isQuotedString positions: Text will be inserted before the quotes, not
  // inside them
  boolean inQuotedString = false;
  if (isQuotedString) {
    inQuotedString =
        element instanceof TreeElement
            && ((TreeElement) element).getStartOffset() < selectionStart;
  }
  if (isQuotedString || BuckPsiUtils.hasElementType(elementNode, TokenType.WHITE_SPACE)) {
    if (inQuotedString) {
      // We want to impose the additional requirement that the string is currently empty. That is,
      // if you are pasting into an existing target, we don't want to process the paste text.
      String elementText = elementNode.getText().trim();
      if (!(elementText.equals("''") || elementText.equals("\"\""))) {
        return text;
      }
    }

    BuckArgument buckArgument = PsiTreeUtil.getParentOfType(element, BuckArgument.class);
    if (checkArgumentName(buckArgument)) {
      return formatPasteText(text, element, project, inQuotedString);
    }
  }
  return text;
}
 
private boolean isAtTheSlashOfClosingOfEmptyTag(int offset, PsiElement element) {
    return element != null && element.getNode() != null
            && element.getNode().getElementType() == XQueryTypes.XMLEMPTYELEMENTEND
            && offset == element.getTextOffset();
}