Java Code Examples for com.intellij.psi.PsiElement#getNode()

The following examples show how to use com.intellij.psi.PsiElement#getNode() . 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: GLSLForStatement.java    From glsl4idea with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Source File: BaseMoveHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 3
Source File: DustFormattingModelBuilder.java    From Intellij-Dust with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example 4
Source File: SQFDocumentationProvider.java    From arma-intellij-plugin with MIT License 6 votes vote down vote up
@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;
}
 
Example 5
Source File: CppSelectioner.java    From CppTools with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 6
Source File: XQueryXmlGtTypedHandler.java    From intellij-xquery with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 7
Source File: ASTDelegatePsiElement.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 8
Source File: LanguageFolding.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 9
Source File: ExpandLocalOpenIntention.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
@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());
    }
}
 
Example 10
Source File: TextOccurrencesUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 11
Source File: CamelDocumentationProvider.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 12
Source File: SoyDocumentationProvider.java    From bamboo-soy with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 13
Source File: FunctionDeclarationBracesBodyHandler.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 14
Source File: BuckFormattingModelBuilder.java    From Buck-IntelliJ-Plugin with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 15
Source File: XQueryFormattingModelBuilder.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 16
Source File: SimpleTemplateLanguageFormattingModelBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 17
Source File: BuckCopyPasteProcessor.java    From buck with Apache License 2.0 4 votes vote down vote up
@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;
}
 
Example 18
Source File: CppFormattingModelBuilder.java    From CppTools with Apache License 2.0 4 votes vote down vote up
public CppBlock(PsiElement psiElement) {
  myNode = psiElement.getNode();
  psiElement.getFirstChild(); // expand chameleon
}
 
Example 19
Source File: NamedFoldingDescriptor.java    From consulo with Apache License 2.0 4 votes vote down vote up
public NamedFoldingDescriptor(@Nonnull PsiElement e, int start, int end, @Nullable FoldingGroup group, @Nonnull String placeholderText) {
  this(e.getNode(), new TextRange(start, end), group, placeholderText);
}
 
Example 20
Source File: XQueryXmlSlashTypedHandler.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
private boolean isAtTheSlashOfClosingOfEmptyTag(int offset, PsiElement element) {
    return element != null && element.getNode() != null
            && element.getNode().getElementType() == XQueryTypes.XMLEMPTYELEMENTEND
            && offset == element.getTextOffset();
}