com.intellij.psi.impl.source.tree.LeafPsiElement Java Examples

The following examples show how to use com.intellij.psi.impl.source.tree.LeafPsiElement. 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: AbstractCaseConvertingAction.java    From StringManipulation with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: JsPsiHelper.java    From idea-php-dotenv-plugin with MIT License 6 votes vote down vote up
/**
 * @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");
}
 
Example #3
Source File: DefaultASTLeafFactory.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: DartSyntax.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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();
}
 
Example #5
Source File: TemplateLineMarker.java    From idea-php-laravel-plugin with MIT License 6 votes vote down vote up
/**
 * 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)
    );
}
 
Example #6
Source File: GraphQLStructureViewModel.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@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;
}
 
Example #7
Source File: XQueryFormattingBlock.java    From intellij-xquery with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #8
Source File: DojoUnresolvedVariableInspection.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: YamlHelper.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #10
Source File: VariableInsertHandler.java    From intellij-xquery with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #11
Source File: DartSyntax.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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();
}
 
Example #12
Source File: InsertHandlerUtils.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
private static PsiElement findElementBeforeColon(InsertionContext context) {
    final PsiFile file = context.getFile();
    PsiElement element = file.findElementAt(context.getStartOffset() - 1);
    if (element instanceof LeafPsiElement
            && ((LeafPsiElement) element).getElementType() == XQueryTypes.COLON) {
        return file.findElementAt(context.getStartOffset() - 2);
    }
    return null;
}
 
Example #13
Source File: TemplateLineMarker.java    From idea-php-laravel-plugin with MIT License 5 votes vote down vote up
/**
 * Support: @slot('foobar')
 */
@NotNull
private Collection<LineMarkerInfo> collectSlotOverwrites(@NotNull LeafPsiElement psiElement, @NotNull BladePsiDirectiveParameter parameter, @NotNull String sectionName, @NotNull LazyVirtualFileTemplateResolver resolver) {
    String component = BladePsiUtil.findComponentForSlotScope(parameter);
    if(component == null) {
        return Collections.emptyList();
    }

    List<GotoRelatedItem> gotoRelatedItems = new ArrayList<>();

    for (VirtualFile virtualFile : resolver.resolveTemplateName(psiElement.getProject(), component)) {
        PsiFile file = PsiManager.getInstance(psiElement.getProject()).findFile(virtualFile);
        if(file == null) {
            continue;
        }

        gotoRelatedItems.addAll(BladePsiUtil.collectPrintBlockVariableTargets(file, sectionName).stream()
            .map((Function<PsiElement, GotoRelatedItem>) element ->
                new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(element).withIcon(LaravelIcons.LARAVEL, LaravelIcons.LARAVEL))
            .collect(Collectors.toList()
        ));
    }

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

    return Collections.singletonList(
        getRelatedPopover("Slot Overwrites", "Slot Overwrites", psiElement, gotoRelatedItems, PhpIcons.OVERRIDES)
    );
}
 
Example #14
Source File: TestRunLineMarkerProvider.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Info getInfo(PsiElement psiElement) {
    if (!this.helper.isGaugeModule(psiElement)) return null;
    List<IElementType> types = Arrays.asList(SpecTokenTypes.SPEC_HEADING, SpecTokenTypes.SCENARIO_HEADING);
    if (psiElement instanceof LeafPsiElement && types.contains(((LeafPsiElement) psiElement).getElementType()))
        return new Info(AllIcons.RunConfigurations.TestState.Run, TOOLTIP_PROVIDER, ExecutorAction.getActions(1));
    else return null;
}
 
Example #15
Source File: AbstractThriftDeclaration.java    From intellij-thrift with Apache License 2.0 5 votes vote down vote up
@Override
public PsiElement setName(@NonNls @NotNull String name) throws IncorrectOperationException {
  ThriftDefinitionName definitionName = getIdentifier();
  PsiElement id = definitionName != null ? definitionName.getFirstChild() : null;
  if (id instanceof LeafPsiElement) {
    ((LeafPsiElement)id).replaceWithText(name);
  }
  return this;
}
 
Example #16
Source File: TestXPath.java    From jetbrains-plugin-sample with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void testWildcardUnderFuncThenJustTokens() throws Exception {
	String code = loadFile("test/org/antlr/jetbrains/adaptor/test/test.sample");
	String output =
		"func\n"+
		"f\n"+
		"(\n"+
		")\n"+
		"func\n"+
		"g\n"+
		"(\n"+
		")\n"+
		"func\n"+
		"h\n"+
		"(\n"+
		")\n"+
		":";
	String xpath = "//function/*";
	myFile = createPsiFile("a", code);
	ensureParsed(myFile);
	assertEquals(code, myFile.getText());
	final StringBuilder buf = new StringBuilder();
	Collection<? extends PsiElement> nodes = XPath.findAll(SampleLanguage.INSTANCE, myFile, xpath);
	for (PsiElement n : nodes) {
		if ( n instanceof LeafPsiElement ) {
			buf.append(n.getText());
			buf.append("\n");
		}
	}
	assertEquals(output.trim(), buf.toString().trim());
}
 
Example #17
Source File: YamlKeywordsCompletionProvider.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
    PsiElement psiElement = parameters.getPosition();

    if (psiElement instanceof LeafPsiElement) {
        // Don't complete after tag (at end of line)
        // key: !my_tag <caret>\n
        if (YamlHelper.isElementAfterYamlTag(psiElement)) {
            return;
        }

        // Don't complete after End Of Line:
        // key: foo\n
        // <caret>
        if (YamlHelper.isElementAfterEol(psiElement)) {
            return;
        }

        String prefix = psiElement.getText();

        if (prefix.contains(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED)) {
            prefix = prefix.substring(0, prefix.indexOf(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED));
        }

        result = result.withPrefixMatcher(prefix);
    }

    for (Map.Entry<String, String> entry : YAML_KEYWORDS.entrySet()) {
        String yamlKeyword = entry.getKey();
        String yamlType = entry.getValue();

        LookupElementBuilder lookupElement = LookupElementBuilder.create(yamlKeyword)
                .withTypeText(yamlType);

        result.addElement(lookupElement);
    }
}
 
Example #18
Source File: ThriftColorAnnotator.java    From intellij-thrift with Apache License 2.0 5 votes vote down vote up
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
  if (element instanceof LeafPsiElement) {
    IElementType tokenType = ((LeafPsiElement)element).getElementType();
    if (tokenType == ThriftTokenTypes.IDENTIFIER && ThriftUtils.getKeywords().contains(element.getText())) {
      annotateKeyword(element, holder);
    }
  }
}
 
Example #19
Source File: ThriftPsiUtil.java    From intellij-thrift with Apache License 2.0 5 votes vote down vote up
@NotNull
public static PsiElement setName(@NotNull ThriftDefinitionName definitionName, String name) {
  PsiElement child = definitionName.getFirstChild();
  if (child instanceof LeafPsiElement) {
    ((LeafPsiElement)child).replaceWithText(name);
  }
  return definitionName;
}
 
Example #20
Source File: RunIdeConsoleAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static String getCommandText(@Nonnull Project project, @Nonnull Editor editor) {
  TextRange selectedRange = EditorUtil.getSelectionInAnyMode(editor);
  Document document = editor.getDocument();
  if (selectedRange.isEmpty()) {
    int line = document.getLineNumber(selectedRange.getStartOffset());
    selectedRange = TextRange.create(document.getLineStartOffset(line), document.getLineEndOffset(line));

    // try detect a non-trivial composite PSI element if there's a PSI file
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file != null && file.getFirstChild() != null && file.getFirstChild() != file.getLastChild()) {
      PsiElement e1 = file.findElementAt(selectedRange.getStartOffset());
      PsiElement e2 = file.findElementAt(selectedRange.getEndOffset());
      while (e1 != e2 && (e1 instanceof PsiWhiteSpace || e1 != null && StringUtil.isEmptyOrSpaces(e1.getText()))) {
        e1 = ObjectUtils.chooseNotNull(e1.getNextSibling(), PsiTreeUtil.getDeepestFirst(e1.getParent()));
      }
      while (e1 != e2 && (e2 instanceof PsiWhiteSpace || e2 != null && StringUtil.isEmptyOrSpaces(e2.getText()))) {
        e2 = ObjectUtils.chooseNotNull(e2.getPrevSibling(), PsiTreeUtil.getDeepestLast(e2.getParent()));
      }
      if (e1 instanceof LeafPsiElement) e1 = e1.getParent();
      if (e2 instanceof LeafPsiElement) e2 = e2.getParent();
      PsiElement parent = e1 == null ? e2 : e2 == null ? e1 : PsiTreeUtil.findCommonParent(e1, e2);
      if (parent != null && parent != file) {
        selectedRange = parent.getTextRange();
      }
    }
  }
  return document.getText(selectedRange);
}
 
Example #21
Source File: TemplateLineMarker.java    From idea-php-laravel-plugin with MIT License 5 votes vote down vote up
/**
 * Support: @stack('foobar')
 */
@NotNull
private Collection<LineMarkerInfo> collectStackImplements(@NotNull LeafPsiElement psiElement, @NotNull String sectionName, @NotNull LazyVirtualFileTemplateResolver resolver) {
    Collection<String> templateNames = resolver.resolveTemplateName(psiElement.getContainingFile());
    if(templateNames.size() == 0) {
        return Collections.emptyList();
    }

    List<GotoRelatedItem> gotoRelatedItems = new ArrayList<>();

    Set<VirtualFile> virtualFiles = BladeTemplateUtil.getExtendsImplementations(psiElement.getProject(), templateNames);
    if(virtualFiles.size() == 0) {
        return Collections.emptyList();
    }

    for(VirtualFile virtualFile: virtualFiles) {
        PsiFile psiFile = PsiManager.getInstance(psiElement.getProject()).findFile(virtualFile);
        if(psiFile != null) {
            BladeTemplateUtil.visit(psiFile, BladeTokenTypes.PUSH_DIRECTIVE, parameter -> {
                if (sectionName.equalsIgnoreCase(parameter.getContent())) {
                    gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(parameter.getPsiElement()).withIcon(LaravelIcons.LARAVEL, LaravelIcons.LARAVEL));
                }
            });
        }
    }

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

    return Collections.singletonList(
        getRelatedPopover("Push Implementation", "Push Implementation", psiElement, gotoRelatedItems, PhpIcons.IMPLEMENTED)
    );
}
 
Example #22
Source File: TemplateLineMarker.java    From idea-php-laravel-plugin with MIT License 5 votes vote down vote up
/**
 * Find all sub implementations of a section that are overwritten by an extends tag
 * Possible targets are: @section('sidebar')
 */
@NotNull
private Collection<LineMarkerInfo> collectImplementsSection(@NotNull LeafPsiElement psiElement, @NotNull String sectionName, @NotNull LazyVirtualFileTemplateResolver resolver) {
    Collection<String> templateNames = resolver.resolveTemplateName(psiElement.getContainingFile());
    if(templateNames.size() == 0) {
        return Collections.emptyList();
    }

    Collection<GotoRelatedItem> gotoRelatedItems = new ArrayList<>();

    Set<VirtualFile> virtualFiles = BladeTemplateUtil.getExtendsImplementations(psiElement.getProject(), templateNames);
    if(virtualFiles.size() == 0) {
        return Collections.emptyList();
    }

    for(VirtualFile virtualFile: virtualFiles) {
        PsiFile psiFile = PsiManager.getInstance(psiElement.getProject()).findFile(virtualFile);
        if(psiFile != null) {
            BladeTemplateUtil.visitSection(psiFile, parameter -> {
                if (sectionName.equalsIgnoreCase(parameter.getContent())) {
                    gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(parameter.getPsiElement()).withIcon(LaravelIcons.LARAVEL, LaravelIcons.LARAVEL));
                }
            });
        }
    }

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

    return Collections.singletonList(
        getRelatedPopover("Template", "Blade File", psiElement, gotoRelatedItems, PhpIcons.IMPLEMENTED)
    );
}
 
Example #23
Source File: TemplateLineMarker.java    From idea-php-laravel-plugin with MIT License 5 votes vote down vote up
/**
 * Like this @section('sidebar')
 */
@NotNull
private Collection<LineMarkerInfo> collectOverwrittenSection(@NotNull LeafPsiElement psiElement, @NotNull String sectionName, @NotNull LazyVirtualFileTemplateResolver resolver) {
    List<GotoRelatedItem> gotoRelatedItems = new ArrayList<>();

    for(PsiElement psiElement1 : psiElement.getContainingFile().getChildren()) {
        PsiElement extendDirective = psiElement1.getFirstChild();
        if(extendDirective != null && extendDirective.getNode().getElementType() == BladeTokenTypes.EXTENDS_DIRECTIVE) {
            PsiElement bladeParameter = extendDirective.getNextSibling();
            if(bladeParameter instanceof BladePsiDirectiveParameter) {
                String extendTemplate = BladePsiUtil.getSection(bladeParameter);
                if(extendTemplate != null) {
                    for(VirtualFile virtualFile: resolver.resolveTemplateName(psiElement.getProject(), extendTemplate)) {
                        PsiFile psiFile = PsiManager.getInstance(psiElement.getProject()).findFile(virtualFile);
                        if(psiFile != null) {
                            visitOverwrittenTemplateFile(psiFile, gotoRelatedItems, sectionName, resolver);
                        }
                    }
                }
            }
        }
    }

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

    return Collections.singletonList(
        getRelatedPopover("Parent Section", "Blade Section", psiElement, gotoRelatedItems, PhpIcons.OVERRIDES)
    );
}
 
Example #24
Source File: CSharpConstantExpressionImpl.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
@RequiredReadAction
public PsiLanguageInjectionHost updateText(@Nonnull String s)
{
	LeafPsiElement first = (LeafPsiElement) getFirstChild();
	first.replaceWithText(s);
	return this;
}
 
Example #25
Source File: BashTestUtils.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
public static PsiElement configureFixturePsiAtCaret(String fileNameInTestPath, CodeInsightTestFixture fixture) {
    fixture.configureByFile(fileNameInTestPath);

    PsiElement element = fixture.getFile().findElementAt(fixture.getCaretOffset());
    if (element instanceof LeafPsiElement) {
        return element.getParent();
    }

    return element;
}
 
Example #26
Source File: EnterInStringLiteralHandler.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
private boolean isInString(PsiElement start) {
    PsiElement parent = PsiTreeUtil.skipParentsOfType(start, LeafPsiElement.class, BashVar.class);
    if (parent != null) {
        return parent instanceof BashString;
    }
    return start instanceof BashString;
}
 
Example #27
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 #28
Source File: BashTrapCommandImpl.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@Override
public PsiElement getSignalHandlerElement() {
    //the first element after the "trap" command element
    PsiElement firstParam = BashPsiUtils.findNextSibling(getFirstChild(), BashTokenTypes.WHITESPACE);
    if (firstParam == null) {
        return null;
    }

    String text = firstParam.getText();
    if (text.startsWith("-p") || text.startsWith("-l")) {
        return null;
    }

    //the string/word container is embedded in a structure of "simple command" -> "generic command element"
    //extract it without relying too much on the defined structure
    PsiElement child = firstParam;
    while (child.getTextRange().equals(firstParam.getTextRange())) {
        PsiElement firstChild = child.getFirstChild();
        if (firstChild == null || firstChild instanceof LeafPsiElement) {
            break;
        }

        child = child.getFirstChild();
    }

    return child;
}
 
Example #29
Source File: PhpElementsUtil.java    From idea-php-toolbox with MIT License 5 votes vote down vote up
/**
 * Get array creation element and array key path:
 * ['test' => ['test2' => '<cursor>']]
 *
 * results in string path: ["test2", "test"]
 *
 *
 * @param current PsiLeaf or string array which is inside ARRAY_VALUE context
 * @param keyPath key path in reserve order
 * @return array element
 */
@Nullable
public static ArrayCreationExpression getArrayPath(final @NotNull PsiElement current, @NotNull String... keyPath) {

    // we need a php psielement like string element,
    // but we also support leaf items directly out of completion context
    PsiElement psiElement = current;
    if(current instanceof LeafPsiElement) {
        psiElement = current.getParent();
        if(psiElement == null) {
            return null;
        }
    }

    for (int i = 0; i < keyPath.length; i++) {

        // exit on invalid item
        psiElement = getArrayPathValue(psiElement, keyPath[i]);
        if(psiElement == null) {
            return null;
        }

        // last item we are done here
        if(i == keyPath.length - 1) {
            return (ArrayCreationExpression) psiElement;
        }

    }

    return null;

}
 
Example #30
Source File: JSGraphQLEndpointErrorAnnotator.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Compares the signatures of two fields, ignoring comments, whitespace, and annotations
 */
private boolean hasSameSignature(JSGraphQLEndpointFieldDefinition override, JSGraphQLEndpointFieldDefinition toImplement) {
	final StringBuilder toImplementSignature = new StringBuilder();
	final StringBuilder overrideSignature = new StringBuilder();

	final Ref<StringBuilder> sb = new Ref<>();
	final PsiElementVisitor visitor = new PsiRecursiveElementVisitor() {
		@Override
		public void visitElement(PsiElement element) {
			if (element instanceof JSGraphQLEndpointAnnotation) {
				return;
			}
			if (element instanceof PsiWhiteSpace) {
				return;
			}
			if (element instanceof PsiComment) {
				return;
			}
			if (element instanceof LeafPsiElement) {
				sb.get().append(element.getText()).append(" ");
			}
			super.visitElement(element);
		}
	};

	sb.set(overrideSignature);
	override.accept(visitor);

	sb.set(toImplementSignature);
	toImplement.accept(visitor);

	return toImplementSignature.toString().equals(overrideSignature.toString());
}