类com.intellij.psi.impl.source.tree.LeafPsiElement源码实例Demo

下面列出了怎么用com.intellij.psi.impl.source.tree.LeafPsiElement的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: idea-php-dotenv-plugin   文件: JsPsiHelper.java
/**
 * @param psiElement checking element
 * @return true if this is process.env.*** variable
 */
static boolean checkPsiElement(@NotNull PsiElement psiElement) {
    if(!(psiElement instanceof LeafPsiElement)) {
        return false;
    }

    IElementType elementType = ((LeafPsiElement) psiElement).getElementType();
    if(!elementType.toString().equals("JS:IDENTIFIER")) {
        return false;
    }

    PsiElement parent = psiElement.getParent();
    if(!(parent instanceof JSReferenceExpression)) {
        return false;
    }

    return ((JSReferenceExpression) parent).getCanonicalText().startsWith("process.env");
}
 
源代码2 项目: flutter-intellij   文件: DartSyntax.java
/**
 * Returns the contents of a Dart string literal, provided that it doesn't do any interpolation.
 * <p>
 * Returns null if there is any string interpolation.
 */
@Nullable
public static String unquote(@NotNull DartStringLiteralExpression lit) {
  if (!lit.getShortTemplateEntryList().isEmpty() || !lit.getLongTemplateEntryList().isEmpty()) {
    return null; // is a template
  }
  // We expect a quote, string part, quote.
  if (lit.getFirstChild() == null) return null;
  final PsiElement second = lit.getFirstChild().getNextSibling();
  if (second.getNextSibling() != lit.getLastChild()) return null; // not three items
  if (!(second instanceof LeafPsiElement)) return null;
  final LeafPsiElement leaf = (LeafPsiElement)second;

  if (leaf.getElementType() != DartTokenTypes.REGULAR_STRING_PART) return null;
  return leaf.getText();
}
 
源代码3 项目: flutter-intellij   文件: DartSyntax.java
/**
 * Returns the contents of a Dart string literal, provided that it doesn't do any interpolation.
 * <p>
 * Returns null if there is any string interpolation.
 */
@Nullable
public static String unquote(@NotNull DartStringLiteralExpression lit) {
  if (!lit.getShortTemplateEntryList().isEmpty() || !lit.getLongTemplateEntryList().isEmpty()) {
    return null; // is a template
  }
  // We expect a quote, string part, quote.
  if (lit.getFirstChild() == null) return null;
  final PsiElement second = lit.getFirstChild().getNextSibling();
  if (second.getNextSibling() != lit.getLastChild()) return null; // not three items
  if (!(second instanceof LeafPsiElement)) return null;
  final LeafPsiElement leaf = (LeafPsiElement)second;

  if (leaf.getElementType() != DartTokenTypes.REGULAR_STRING_PART) return null;
  return leaf.getText();
}
 
@Override
public boolean isAlwaysLeaf(StructureViewTreeElement element) {
    if (element instanceof GraphQLStructureViewTreeElement) {
        GraphQLStructureViewTreeElement treeElement = (GraphQLStructureViewTreeElement) element;
        if (treeElement.childrenBase instanceof LeafPsiElement) {
            return true;
        }
        if (treeElement.childrenBase instanceof GraphQLField) {
            final PsiElement[] children = treeElement.childrenBase.getChildren();
            if (children.length == 0) {
                // field with no sub selections, but we have to check if there's attributes
                final PsiElement nextVisible = PsiTreeUtil.nextVisibleLeaf(treeElement.childrenBase);
                if (nextVisible != null && nextVisible.getNode().getElementType() == GraphQLElementTypes.PAREN_L) {
                    return false;
                }
                return true;
            }
            if (children.length == 1 && children[0] instanceof LeafPsiElement) {
                return true;
            }
        }
    }
    return false;
}
 
/**
 * Support: @push('foobar')
 */
@NotNull
private Collection<LineMarkerInfo> collectPushOverwrites(@NotNull LeafPsiElement psiElement, @NotNull String sectionName) {
    final List<GotoRelatedItem> gotoRelatedItems = new ArrayList<>();

    BladeTemplateUtil.visitUpPath(psiElement.getContainingFile(), 10, parameter -> {
        if(sectionName.equalsIgnoreCase(parameter.getContent())) {
            gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(parameter.getPsiElement()).withIcon(LaravelIcons.LARAVEL, LaravelIcons.LARAVEL));
        }
    }, BladeTokenTypes.STACK_DIRECTIVE);

    if(gotoRelatedItems.size() == 0) {
        return Collections.emptyList();
    }

    return Collections.singletonList(
        getRelatedPopover("Stack Section", "Stack Overwrites", psiElement, gotoRelatedItems, PhpIcons.OVERRIDES)
    );
}
 
private boolean propertiesHandling(Editor editor, DataContext dataContext, SelectionModel selectionModel,
		PsiFile psiFile) {
	PsiElement elementAtCaret = PsiUtilBase.getElementAtCaret(editor);
	if (elementAtCaret instanceof PsiWhiteSpace) {
		return false;
	} else if (elementAtCaret instanceof LeafPsiElement) {
		IElementType elementType = ((LeafPsiElement) elementAtCaret).getElementType();
		if (elementType.toString().equals("Properties:VALUE_CHARACTERS")
				|| elementType.toString().equals("Properties:KEY_CHARACTERS")) {
			TextRange textRange = elementAtCaret.getTextRange();
			if (textRange.getLength() == 0) {
				return super.selectSomethingUnderCaret(editor, dataContext, selectionModel);
			}
			selectionModel.setSelection(textRange.getStartOffset(), textRange.getEndOffset());
			return true;
		}
	}
	return false;
}
 
源代码7 项目: intellij-xquery   文件: XQueryFormattingBlock.java
@Nullable
private IElementType getIElementType(int newChildIndex) {
    Block block = getSubBlocks().get(newChildIndex - 1);
    while (block instanceof XQueryFormattingBlock && ! block.getSubBlocks().isEmpty()) {
        List<Block> subBlocks = block.getSubBlocks();
        Block childBlock = subBlocks.get(subBlocks.size() - 1);
        if (! (childBlock instanceof XQueryFormattingBlock)) break;
        else {
            ASTNode node = ((XQueryFormattingBlock) childBlock).getNode();
            PsiElement psi = node.getPsi();
            IElementType elementType = node.getElementType();
            if (elementType instanceof XQueryTokenType) break;
            if (psi instanceof LeafPsiElement || psi instanceof XQueryFunctionName || psi instanceof
                    XQueryVarName || psi instanceof XQueryNamespacePrefix)
                break;
        }
        block = childBlock;
    }
    return block instanceof XQueryFormattingBlock ? ((XQueryFormattingBlock) block).getNode().getElementType() :
            null;
}
 
源代码8 项目: intellij-xquery   文件: VariableInsertHandler.java
private PsiElement findElementBeforeNameFragment(InsertionContext context) {
    final PsiFile file = context.getFile();
    PsiElement element = file.findElementAt(context.getStartOffset() - 1);
    element = getElementInFrontOfWhitespace(file, element);
    if (element instanceof LeafPsiElement
            && ((LeafPsiElement) element).getElementType() == XQueryTypes.COLON) {
        PsiElement elementBeforeColon = file.findElementAt(context.getStartOffset() - 2);
        if (elementBeforeColon != null) {
            element = elementBeforeColon;
            PsiElement beforeElementBeforeColon = file.findElementAt(elementBeforeColon.getTextRange().getStartOffset() - 1);
            if (beforeElementBeforeColon != null) {
                element = getElementInFrontOfWhitespace(file, beforeElementBeforeColon);
            }
        }
    }
    return element;
}
 
源代码9 项目: idea-php-symfony2-plugin   文件: YamlHelper.java
/**
 * key: !my_tag <caret>
 */
public static boolean isElementAfterYamlTag(PsiElement psiElement) {
    if (!(psiElement instanceof LeafPsiElement)) {
        return false;
    }

    // key: !my_tag <caret>\n
    if (((LeafPsiElement) psiElement).getElementType() == YAMLTokenTypes.EOL) {
        PsiElement prevElement = PsiTreeUtil.getDeepestVisibleLast(psiElement);
        if (prevElement instanceof LeafPsiElement) {
            if (((LeafPsiElement) prevElement).getElementType() == YAMLTokenTypes.TAG) {
                return ((LeafPsiElement) prevElement).getText().startsWith("!");
            }
        }
    }

    return PsiTreeUtil.findSiblingBackward(psiElement, YAMLTokenTypes.TAG, null) != null;
}
 
@Override
public boolean isSuppressedFor(@NotNull PsiElement element) {
    Project project = element.getProject();
    DojoSettings settings = ServiceManager.getService(project, DojoSettings.class);
    if(!settings.isNeedsMoreDojoEnabled())
    {
        return super.isSuppressedFor(element);
    }

    if(element instanceof LeafPsiElement)
    {
        LeafPsiElement leafPsiElement = (LeafPsiElement) element;
        if(leafPsiElement.getElementType() == JSTokenTypes.IDENTIFIER &&
                leafPsiElement.getParent() != null &&
                leafPsiElement.getParent().getFirstChild() instanceof JSThisExpression)
        {
            return AttachPointResolver.getGotoDeclarationTargets(element, 0, null).length > 0 || super.isSuppressedFor(element);
        }
    }
    return super.isSuppressedFor(element);
}
 
源代码11 项目: consulo   文件: DefaultASTLeafFactory.java
@Nonnull
@Override
public LeafElement createLeaf(@Nonnull IElementType type, @Nonnull LanguageVersion languageVersion, @Nonnull CharSequence text) {
  final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(type.getLanguage());
  if(parserDefinition != null) {
    if(parserDefinition.getCommentTokens(languageVersion).contains(type)) {
      return new PsiCoreCommentImpl(type, text);
    }
  }

  // this is special case, then type is WHITE_SPACE, but no parser definition
  if(type == TokenType.WHITE_SPACE) {
    return new PsiWhiteSpaceImpl(text);
  }

  if (type instanceof ILeafElementType) {
    return (LeafElement)((ILeafElementType)type).createLeafNode(text);
  }
  return new LeafPsiElement(type, text);
}
 
源代码12 项目: Custom-Syntax-Highlighter   文件: BaseAnnotator.java
@Override
public void annotate(@NotNull final PsiElement element, @NotNull final AnnotationHolder holder) {

  if (element instanceof LeafPsiElement) {
    final TextAttributesKey kind = getKeywordKind(element);
    if (kind == null) {
      return;
    }
    final TextRange textRange = element.getTextRange();
    final TextRange range = new TextRange(textRange.getStartOffset(), textRange.getEndOffset());
    final Annotation annotation = holder.createAnnotation(HighlightSeverity.INFORMATION, range, null);

    annotation.setTextAttributes(kind);
  }
}
 
@Override
protected void addCompletions(final CompletionParameters completionParameters,
        final ProcessingContext processingContext, final CompletionResultSet resultSet) {

    final PsiElement element = completionParameters.getPosition();
    if (!LeafPsiElement.class.isInstance(element)) {
        return; // ignore comment
    }

    final Project project = element.getProject();
    final Module module = findModule(element);
    final SuggestionService service = ServiceManager.getService(project, SuggestionService.class);
    if ((module == null || !service.isSupported(completionParameters))) { // limit suggestion to Messages
        return;
    }

    if (PropertyValueImpl.class.isInstance(element)) {
        ofNullable(PropertyValueImpl.class.cast(element).getPrevSibling())
                .map(PsiElement::getPrevSibling)
                .map(PsiElement::getText)
                .ifPresent(text -> resultSet.addAllElements(service.computeValueSuggestions(text)));
    } else if (PropertyKeyImpl.class.isInstance(element)) {
        final List<String> containerElements = PropertiesFileImpl.class
                .cast(element.getContainingFile())
                .getProperties()
                .stream()
                .filter(p -> !Objects.equals(p.getKey(), element.getText()))
                .map(IProperty::getKey)
                .collect(toList());
        resultSet
                .addAllElements(service
                        .computeKeySuggestions(project, module, getPropertiesPackage(module, completionParameters),
                                containerElements, truncateIdeaDummyIdentifier(element)));
    }
}
 
源代码14 项目: flutter-intellij   文件: DartSyntaxTest.java
@Test
public void isMainFunctionDeclaration() throws Exception {
  run(() -> {
    final PsiElement mainIdentifier = setUpDartElement("main() { test('my first test', () {} ); }", "main", LeafPsiElement.class);
    final PsiElement main =
      PsiTreeUtil.findFirstParent(mainIdentifier, element -> element instanceof DartFunctionDeclarationWithBodyOrNative);
    assertTrue(DartSyntax.isMainFunctionDeclaration(main));
  });
}
 
源代码15 项目: flutter-intellij   文件: DartSyntaxTest.java
@Test
public void shouldFindEnclosingFunctionCall() throws Exception {
  run(() -> {
    final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);

    final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, "test");
    assertNotNull("findEnclosingFunctionCall() didn't find enclosing function call", call);
  });
}
 
源代码16 项目: flutter-intellij   文件: DartSyntaxTest.java
@Test
public void shouldFindEnclosingFunctionCallPattern() throws Exception {
  run(() -> {
    final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);

    final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, Pattern.compile("t.*t"));
    assertNotNull("findEnclosingFunctionCall() didn't find enclosing function call", call);
  });
}
 
源代码17 项目: flutter-intellij   文件: DartSyntaxTest.java
@Test
public void shouldNotFindEnclosingFunctionCallPattern() throws Exception {
  run(() -> {
    final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);

    final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, Pattern.compile("t.*a"));
    assertNull("findEnclosingFunctionCall() didn't find enclosing function call", call);
  });
}
 
源代码18 项目: flutter-intellij   文件: DartSyntaxTest.java
@Test
public void shouldGetFirstArgumentFromFunctionCall() throws Exception {
  run(() -> {
    final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);

    final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, "test");
    assertNotNull(call);
    final DartStringLiteralExpression lit = DartSyntax.getArgument(call, 0, DartStringLiteralExpression.class);
    assertNotNull("getSyntax() didn't return first argument", lit);
  });
}
 
private ConfigurationContext getMainContext() {
  // Set up fake source code.
  final PsiElement mainIdentifier = setUpDartElement(
    "workspace/foo/bar.dart", fileContents, "main", LeafPsiElement.class);
  final PsiElement main = PsiTreeUtil.findFirstParent(
    mainIdentifier, element -> element instanceof DartFunctionDeclarationWithBodyOrNative);
  assertThat(main, not(equalTo(null)));

  return new ConfigurationContext(main);
}
 
private ConfigurationContext getTest1Context() {
  // Set up fake source code.
  final PsiElement testIdentifier = setUpDartElement(
    TEST_FILE_PATH, fileContents, "test 1", LeafPsiElement.class);
  final PsiElement test =
    PsiTreeUtil.findFirstParent(testIdentifier, element -> element instanceof DartStringLiteralExpression);
  assertThat(test, not(equalTo(null)));
  return new ConfigurationContext(test);
}
 
/**
 * Gets a specific test or test group call.
 *
 * @param functionName The name of the function being called, eg test() or testWidgets()
 * @param testName     The name of the test desired, such as 'test 0' or 'test widgets 0'
 * @param filePath     The file containing the desired test.
 */
@NotNull
private DartCallExpression getTestCallWithName(String functionName, String testName, String filePath) {
  final PsiElement testIdentifier = setUpDartElement(filePath,
                                                     fileContents.get(filePath), testName, LeafPsiElement.class);
  assertThat(testIdentifier, not(equalTo(null)));

  final DartCallExpression result = DartSyntax.findClosestEnclosingFunctionCall(testIdentifier);
  assertThat(result, not(equalTo(null)));
  return result;
}
 
源代码22 项目: flutter-intellij   文件: DartSyntaxTest.java
@Test
public void isMainFunctionDeclaration() throws Exception {
  run(() -> {
    final PsiElement mainIdentifier = setUpDartElement("main() { test('my first test', () {} ); }", "main", LeafPsiElement.class);
    final PsiElement main =
      PsiTreeUtil.findFirstParent(mainIdentifier, element -> element instanceof DartFunctionDeclarationWithBodyOrNative);
    assertTrue(DartSyntax.isMainFunctionDeclaration(main));
  });
}
 
源代码23 项目: flutter-intellij   文件: DartSyntaxTest.java
@Test
public void shouldFindEnclosingFunctionCall() throws Exception {
  run(() -> {
    final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);

    final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, "test");
    assertNotNull("findEnclosingFunctionCall() didn't find enclosing function call", call);
  });
}
 
源代码24 项目: flutter-intellij   文件: DartSyntaxTest.java
@Test
public void shouldFindEnclosingFunctionCallPattern() throws Exception {
  run(() -> {
    final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);

    final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, Pattern.compile("t.*t"));
    assertNotNull("findEnclosingFunctionCall() didn't find enclosing function call", call);
  });
}
 
源代码25 项目: flutter-intellij   文件: DartSyntaxTest.java
@Test
public void shouldNotFindEnclosingFunctionCallPattern() throws Exception {
  run(() -> {
    final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);

    final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, Pattern.compile("t.*a"));
    assertNull("findEnclosingFunctionCall() didn't find enclosing function call", call);
  });
}
 
源代码26 项目: flutter-intellij   文件: DartSyntaxTest.java
@Test
public void shouldGetFirstArgumentFromFunctionCall() throws Exception {
  run(() -> {
    final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);

    final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, "test");
    assertNotNull(call);
    final DartStringLiteralExpression lit = DartSyntax.getArgument(call, 0, DartStringLiteralExpression.class);
    assertNotNull("getSyntax() didn't return first argument", lit);
  });
}
 
private ConfigurationContext getMainContext() {
  // Set up fake source code.
  final PsiElement mainIdentifier = setUpDartElement(
    "workspace/foo/bar.dart", fileContents, "main", LeafPsiElement.class);
  final PsiElement main = PsiTreeUtil.findFirstParent(
    mainIdentifier, element -> element instanceof DartFunctionDeclarationWithBodyOrNative);
  assertThat(main, not(equalTo(null)));

  return new ConfigurationContext(main);
}
 
private ConfigurationContext getTest1Context() {
  // Set up fake source code.
  final PsiElement testIdentifier = setUpDartElement(
    TEST_FILE_PATH, fileContents, "test 1", LeafPsiElement.class);
  final PsiElement test =
    PsiTreeUtil.findFirstParent(testIdentifier, element -> element instanceof DartStringLiteralExpression);
  assertThat(test, not(equalTo(null)));
  return new ConfigurationContext(test);
}
 
/**
 * Gets a specific test or test group call.
 *
 * @param functionName The name of the function being called, eg test() or testWidgets()
 * @param testName     The name of the test desired, such as 'test 0' or 'test widgets 0'
 * @param filePath     The file containing the desired test.
 */
@NotNull
private DartCallExpression getTestCallWithName(String functionName, String testName, String filePath) {
  final PsiElement testIdentifier = setUpDartElement(filePath,
                                                     fileContents.get(filePath), testName, LeafPsiElement.class);
  assertThat(testIdentifier, not(equalTo(null)));

  final DartCallExpression result = DartSyntax.findClosestEnclosingFunctionCall(testIdentifier);
  assertThat(result, not(equalTo(null)));
  return result;
}
 
源代码30 项目: camel-idea-plugin   文件: YamlIdeaUtils.java
@Override
public Optional<String> extractTextFromElement(PsiElement element, boolean concatString, boolean stripWhitespace) {
    // maybe its yaml
    if (element instanceof LeafPsiElement) {
        IElementType type = ((LeafPsiElement) element).getElementType();
        if (type.getLanguage().isKindOf("yaml")) {
            return Optional.ofNullable(element.getText());
        }
    }
    return Optional.empty();
}
 
 类所在包
 类方法
 同包方法