public static void removeVariable(GrVariable variable) { final GrVariableDeclaration varDecl = (GrVariableDeclaration) variable.getParent(); final List<GrVariable> variables = Arrays.asList(varDecl.getVariables()); if (!variables.contains(variable)) { throw new IllegalArgumentException(); } final PsiElement parent = varDecl.getParent(); final ASTNode owner = parent.getNode(); if (variables.size() == 1 && owner != null) { PsiElement next = varDecl.getNextSibling(); // remove redundant semicolons //noinspection ConstantConditions while (next != null && next.getNode() != null && next.getNode().getElementType() == mSEMI) { PsiElement tmpNext = next.getNextSibling(); //noinspection ConstantConditions next.delete(); next = tmpNext; } removeNewLineAfter(varDecl); varDecl.delete(); return; } variable.delete(); }
public static void deleteStatementTail(PsiElement container, @NotNull PsiElement statement) { PsiElement next = statement.getNextSibling(); while (next != null) { final ASTNode node = next.getNode(); final IElementType type = node.getElementType(); if (type == mSEMI) { final PsiElement nnext = next.getNextSibling(); container.deleteChildRange(next, next); next = nnext; } else if (type == mNLS || type == TokenType.WHITE_SPACE && next.getText().contains("\n")) { final String text = next.getText(); final int first = text.indexOf("\n"); final int second = text.indexOf("\n", first + 1); if (second < 0) { container.deleteChildRange(next, next); return; } final String substring = text.substring(second); container .getNode() .replaceChild( node, createSingleLeafElement( type, substring, 0, substring.length(), null, container.getManager())); return; } else { break; } } }
public static PsiElement getChild( final PsiElement parent, int position, boolean ignoreWhiteSpaces, boolean ignoreComments, boolean ignoreErrors) { PsiElement curChild = parent.getFirstChild(); int i = 0; while (i <= position && curChild != null) { if (WHITE_SPACES.contains(curChild.getNode().getElementType())) { if (!ignoreWhiteSpaces) i++; curChild = curChild.getNextSibling(); } else if (COMMENTS.contains(curChild.getNode().getElementType())) { if (!ignoreComments) i++; curChild = curChild.getNextSibling(); } else if (curChild instanceof PsiErrorElement) { if (!ignoreErrors) { return null; } i++; curChild = curChild.getNextSibling(); } else { if (i == position) return curChild; i++; curChild = curChild.getNextSibling(); } } return null; }
@Nullable @Override protected Indent getChildIndent(@Nullable PsiElement prevChild, @Nullable PsiElement child) { if (prevChild != null && child != null && !inTheSameLine(prevChild.getNode(), child.getNode())) return Indent.getNormalIndent(); return super.getChildIndent(prevChild, child); }
public void replaceDotToken(PsiElement newDot) { if (newDot == null) return; if (!TokenSets.DOTS.contains(newDot.getNode().getElementType())) return; final PsiElement oldDot = getDotToken(); if (oldDot == null) return; getNode().replaceChild(oldDot.getNode(), newDot.getNode()); }
public boolean isFunctionCall() { PsiElement commandElement = commandElement(); if (commandElement == null || commandElement.getNode() == null) { return false; } return commandElement.getNode().getElementType() == BashElementTypes.GENERIC_COMMAND_ELEMENT && internalResolve() != null; }
@Nullable public static PsiElement searchNonSpaceNonCommentBack(PsiElement element) { if (element == null || element.getNode() == null) return null; ASTNode leftNeibour = TreeUtil.prevLeaf(element.getNode()); while (leftNeibour != null && (leftNeibour.getElementType() == TokenType.WHITE_SPACE || leftNeibour.getPsi() instanceof PsiComment)) { leftNeibour = TreeUtil.prevLeaf(leftNeibour); } return leftNeibour != null ? leftNeibour.getPsi() : null; }
public PsiElement handleElementRename(String newName) throws IncorrectOperationException { if (StringUtil.isEmpty(newName)) { return null; } final PsiElement original = commandElement(); final PsiElement replacement = BashChangeUtil.createWord(getProject(), newName); getNode().replaceChild(original.getNode(), replacement.getNode()); return this; }
private int computeIndentCount(IDocument document, int offset) { try { if (offset == document.getLength()) { return 0; } IFile file = EditorUtil.getFile(editor); if (file == null) { KotlinLogger.logError("Failed to retrieve IFile from editor " + editor, null); return 0; } if (document.get().contains(LineEndUtil.CARRIAGE_RETURN_STRING)) { offset -= document.getLineOfOffset(offset); } PsiFile parsedDocument = KotlinPsiManager.getKotlinFileIfExist(file, document.get()); if (parsedDocument == null) { return 0; } PsiElement leaf = parsedDocument.findElementAt(offset); if (leaf == null) { return 0; } if (leaf.getNode().getElementType() != JetTokens.WHITE_SPACE) { leaf = parsedDocument.findElementAt(offset - 1); } int indent = 0; ASTNode node = null; if (leaf != null) { node = leaf.getNode(); } while (node != null) { indent = AlignmentStrategy.updateIndent(node, indent); node = node.getTreeParent(); } return indent; } catch (BadLocationException e) { KotlinLogger.logAndThrow(e); } return 0; }
public static GrDocComment setDocComment( @NotNull GrDocCommentOwner owner, @Nullable GrDocComment comment) { GrDocComment docComment = owner.getDocComment(); if (docComment != null) { if (comment == null) { docComment.delete(); return null; } else { PsiElement added = docComment.replace(comment); assert added instanceof GrDocComment; return (GrDocComment) added; } } else { if (comment == null) return null; PsiElement parent = owner.getParent(); ASTNode node = owner.getNode(); parent.getNode().addLeaf(GroovyTokenTypes.mNLS, "\n ", node); PsiElement added = parent.addBefore(comment, owner); assert added instanceof GrDocComment; return (GrDocComment) added; } }
/** * Adds all children of specified element to given list * * @param elem * @param list * @param indent * @param aligner */ private void addBinaryChildrenRecursively( PsiElement elem, List<Block> list, Indent indent, @Nullable AlignmentProvider.Aligner aligner) { if (elem == null) return; // For binary expressions if ((elem instanceof GrBinaryExpression)) { GrBinaryExpression myExpr = ((GrBinaryExpression) elem); if (myExpr.getLeftOperand() instanceof GrBinaryExpression) { addBinaryChildrenRecursively( myExpr.getLeftOperand(), list, Indent.getContinuationWithoutFirstIndent(), aligner); } PsiElement op = ((GrBinaryExpression) elem).getOperationToken(); for (ASTNode childNode : visibleChildren(elem.getNode())) { PsiElement psi = childNode.getPsi(); if (!(psi instanceof GrBinaryExpression)) { if (op != psi && aligner != null) { aligner.append(psi); } list.add( new GroovyBlock( childNode, indent, myWrap, mySettings, myGroovySettings, myAlignmentProvider)); } } if (myExpr.getRightOperand() instanceof GrBinaryExpression) { addBinaryChildrenRecursively( myExpr.getRightOperand(), list, Indent.getContinuationWithoutFirstIndent(), aligner); } } }
public static UsageGroup getUsageGroupingRule(PsiElement element) { final PsiElement[] etype = {null}; ASTTreeProcessor treeProcessor = new ASTTreeProcessor(); treeProcessor.add( new ASTNodeHandler() { @NotNull public TokenSet getTokenSet() { return TokenSet.create( PlSqlElementTypes.FUNCTION_BODY, PlSqlElementTypes.PROCEDURE_BODY); } public boolean handleNode(@NotNull ASTNode node) { etype[0] = node.getPsi(); return true; } }); treeProcessor.process(element.getNode(), true /* break on first hit*/); if (etype[0] == null || etype[0].getNode() == null) { return null; } if (etype[0].getNode().getElementType() == PlSqlElementTypes.FUNCTION_BODY) { return new FunctionBodyUsageGroup((Function) etype[0]); } else if (etype[0].getNode().getElementType() == PlSqlElementTypes.PROCEDURE_BODY) { return new ProcedureBodyUsageGroup((Procedure) etype[0]); } return null; }
@Override public void checkFile( @NotNull PsiFile originalFile, @NotNull final InspectionManager manager, @NotNull ProblemsHolder problemsHolder, @NotNull final GlobalInspectionContext globalContext, @NotNull final ProblemDescriptionsProcessor problemDescriptionsProcessor) { for (Pair<PsiFile, HighlightInfo> pair : runGeneralHighlighting(originalFile, highlightErrorElements, runAnnotators)) { PsiFile file = pair.first; HighlightInfo info = pair.second; TextRange range = new TextRange(info.startOffset, info.endOffset); PsiElement element = file.findElementAt(info.startOffset); while (element != null && !element.getTextRange().contains(range)) { element = element.getParent(); } if (element == null) { element = file; } GlobalInspectionUtil.createProblem( element, info, range.shiftRight(-element.getNode().getStartOffset()), info.getProblemGroup(), manager, problemDescriptionsProcessor, globalContext); } }
/** * Adds all children of specified element to given list * * @param elem * @param list * @param indent * @param alignment */ private void addBinaryChildrenRecursively( PsiElement elem, List<Block> list, Indent indent, Alignment alignment) { if (elem == null) return; // For binary expressions if ((elem instanceof GrBinaryExpression)) { GrBinaryExpression myExpr = ((GrBinaryExpression) elem); if (myExpr.getLeftOperand() instanceof GrBinaryExpression) { addBinaryChildrenRecursively( myExpr.getLeftOperand(), list, Indent.getContinuationWithoutFirstIndent(), alignment); } PsiElement op = ((GrBinaryExpression) elem).getOperationToken(); for (ASTNode childNode : visibleChildren(elem.getNode())) { PsiElement psi = childNode.getPsi(); if (!(psi instanceof GrBinaryExpression)) { Alignment alignmentToUse = op == psi ? myInnerAlignments.get(op) : alignment; list.add( new GroovyBlock( childNode, alignmentToUse, indent, myWrap, mySettings, myGroovySettings, myInnerAlignments)); } } if (myExpr.getRightOperand() instanceof GrBinaryExpression) { addBinaryChildrenRecursively( myExpr.getRightOperand(), list, Indent.getContinuationWithoutFirstIndent(), alignment); } } }
@NotNull public GrAnnotation addAnnotation(@NotNull @NonNls String qualifiedName) { final PsiClass psiClass = JavaPsiFacade.getInstance(getProject()).findClass(qualifiedName, getResolveScope()); final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(getProject()); GrAnnotation annotation; if (psiClass != null && psiClass.isAnnotationType()) { annotation = (GrAnnotation) addAfter(factory.createModifierFromText("@xxx"), null); annotation.getClassReference().bindToElement(psiClass); } else { annotation = (GrAnnotation) addAfter(factory.createModifierFromText("@" + qualifiedName), null); } final PsiElement parent = getParent(); if (!(parent instanceof GrParameter)) { final ASTNode node = annotation.getNode(); final ASTNode treeNext = node.getTreeNext(); if (treeNext != null) { getNode().addLeaf(TokenType.WHITE_SPACE, "\n", treeNext); } else { parent.getNode().addLeaf(TokenType.WHITE_SPACE, "\n", getNode().getTreeNext()); } } return annotation; }
@Override public boolean value(PsiElement element) { if (element.getNode().getElementType() == RegExpTT.CHARACTER || element instanceof RegExpChar) { return false; } return true; }
private int getPrevOrNextParameterOffset(boolean isNext) { if (!(myHandler instanceof ParameterInfoHandlerWithTabActionSupport)) return -1; ParameterInfoHandlerWithTabActionSupport handler = (ParameterInfoHandlerWithTabActionSupport) myHandler; boolean noDelimiter = handler.getActualParameterDelimiterType() == TokenType.WHITE_SPACE; int caretOffset = myEditor.getCaretModel().getOffset(); int offset = noDelimiter ? caretOffset : CharArrayUtil.shiftBackward( myEditor.getDocument().getCharsSequence(), caretOffset - 1, " \t") + 1; int lbraceOffset = myLbraceMarker.getStartOffset(); PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument()); PsiElement argList = lbraceOffset < offset ? findArgumentList(file, offset, lbraceOffset) : null; if (argList == null) return -1; @SuppressWarnings("unchecked") PsiElement[] parameters = handler.getActualParameters(argList); int currentParameterIndex = noDelimiter ? JBIterable.of(parameters).indexOf((o) -> o.getTextRange().containsOffset(offset)) : ParameterInfoUtils.getCurrentParameterIndex( argList.getNode(), offset, handler.getActualParameterDelimiterType()); int prevOrNextParameterIndex = isNext && currentParameterIndex < parameters.length - 1 ? currentParameterIndex + 1 : !isNext && currentParameterIndex > 0 ? currentParameterIndex - 1 : -1; return prevOrNextParameterIndex != -1 ? parameters[prevOrNextParameterIndex].getTextRange().getStartOffset() : -1; }
private static void appendInferredType( PsiElement originalElement, GrVariable variable, StringBuilder buffer) { PsiType inferredType = null; if (PsiImplUtil.isWhiteSpaceOrNls(originalElement)) { originalElement = PsiTreeUtil.prevLeaf(originalElement); } if (originalElement != null && originalElement.getNode().getElementType() == GroovyTokenTypes.mIDENT) { originalElement = originalElement.getParent(); } if (originalElement instanceof GrReferenceExpression) { inferredType = ((GrReferenceExpression) originalElement).getType(); } else if (originalElement instanceof GrVariableDeclaration) { inferredType = variable.getTypeGroovy(); } else if (originalElement instanceof GrVariable) { inferredType = ((GrVariable) originalElement).getTypeGroovy(); } if (inferredType != null) { buffer.append("[inferred type] "); appendTypeString(buffer, inferredType, originalElement); } else { buffer.append("[cannot infer type]"); } }
private void calculateAlignments(List<ASTNode> children, boolean classLevel) { List<GrStatement> currentGroup = null; boolean spock = true; for (ASTNode child : children) { PsiElement psi = child.getPsi(); if (psi instanceof GrLabeledStatement) { alignGroup(currentGroup, spock, classLevel); currentGroup = ContainerUtil.newArrayList((GrStatement) psi); spock = true; } else if (currentGroup != null && spock && isTablePart(psi)) { currentGroup.add((GrStatement) psi); } else if (psi instanceof GrVariableDeclaration) { GrVariable[] variables = ((GrVariableDeclaration) psi).getVariables(); if (variables.length > 0) { if (!classLevel || currentGroup == null || fieldGroupEnded(psi) || spock) { alignGroup(currentGroup, spock, classLevel); currentGroup = ContainerUtil.newArrayList(); spock = false; } currentGroup.add((GrStatement) psi); } } else { if (psi instanceof PsiComment) { PsiElement prev = psi.getPrevSibling(); if (prev != null && prev.getNode().getElementType() != mNLS || classLevel && !fieldGroupEnded(psi)) { continue; } } alignGroup(currentGroup, spock, classLevel); currentGroup = null; } } }
@Override public void collect(PsiElement psiElement, @NotNull Collection<LineMarkerInfo> lineMarkerInfos) { PsiElement parent = psiElement.getParent(); IElementType elementType = psiElement.getNode().getElementType(); if ((elementType == CSharpTokens.IDENTIFIER || elementType == CSharpTokens.THIS_KEYWORD) && OverrideUtil.isAllowForOverride(parent)) { DotNetVirtualImplementOwner virtualImplementOwner = (DotNetVirtualImplementOwner) parent; Collection<DotNetVirtualImplementOwner> overrideElements = OverrideUtil.collectOverridenMembers(virtualImplementOwner); if (overrideElements.isEmpty()) { return; } Icon icon = CSharpIcons.Gutter.HidedMethod; for (DotNetVirtualImplementOwner overrideElement : overrideElements) { if (overrideElement.getTypeForImplement() == null) { icon = null; break; } } if (icon == null) { boolean allAbstract = true; for (DotNetVirtualImplementOwner overrideElement : overrideElements) { if (!(overrideElement instanceof DotNetModifierListOwner && ((DotNetModifierListOwner) overrideElement) .hasModifier(DotNetModifier.ABSTRACT))) { allAbstract = false; break; } } boolean abstractMe = virtualImplementOwner instanceof DotNetModifierListOwner && ((DotNetModifierListOwner) virtualImplementOwner) .hasModifier(DotNetModifier.ABSTRACT); if (allAbstract && abstractMe) { icon = AllIcons.Gutter.OverridenMethod; } else if (abstractMe) { icon = AllIcons.Gutter.ImplementedMethod; } else { icon = AllIcons.Gutter.OverridenMethod; } } val lineMarkerInfo = new LineMarkerInfo<PsiElement>( psiElement, psiElement.getTextRange(), icon, Pass.UPDATE_OVERRIDEN_MARKERS, new ConstantFunction<PsiElement, String>("Searching for overrided"), OurHandler.INSTANCE, GutterIconRenderer.Alignment.LEFT); lineMarkerInfos.add(lineMarkerInfo); } }
@NotNull private static String getMultilineDocCommentText(final @NotNull DartDocComment docComment) { final StringBuilder buf = new StringBuilder(); boolean afterAsterisk = false; for (PsiElement child = docComment.getFirstChild(); child != null; child = child.getNextSibling()) { final IElementType elementType = child.getNode().getElementType(); final String text = child.getText(); if (elementType != DartTokenTypesSets.MULTI_LINE_DOC_COMMENT_START && elementType != DartTokenTypesSets.DOC_COMMENT_LEADING_ASTERISK && elementType != DartTokenTypesSets.MULTI_LINE_COMMENT_END) { int newLinesCount; if (child instanceof PsiWhiteSpace && (newLinesCount = StringUtil.countNewLines(text)) > 0) { buf.append(StringUtil.repeatSymbol('\n', newLinesCount)); } else { if (afterAsterisk && text.startsWith(" ")) { buf.append(text.substring(1)); } else { buf.append(text); } } } afterAsterisk = elementType == DartTokenTypesSets.DOC_COMMENT_LEADING_ASTERISK; } return buf.toString(); }
@NotNull public IElementType getOperationTokenType() { PsiElement opElement = getOperationToken(); ASTNode node = opElement.getNode(); assert node != null; return node.getElementType(); }
public static PsiElement findTailingSemicolon(@NotNull GrStatement statement) { final PsiElement nextNonSpace = PsiUtil.skipWhitespaces(statement.getNextSibling(), true); if (nextNonSpace != null && nextNonSpace.getNode().getElementType() == mSEMI) { return nextNonSpace; } return null; }
public static void changeModifier( PsiElement element, @Nullable JetModifierList modifierList, @Nullable PsiElement insertAnchor, JetToken[] modifiersThatCanBeReplaced, Project project, boolean toBeginning, JetModifierList listWithModifier) { PsiElement whiteSpace = JetPsiFactory.createWhiteSpace(project); if (modifierList == null) { if (listWithModifier != null) { if (insertAnchor != null) { listWithModifier = (JetModifierList) element.addBefore(listWithModifier, insertAnchor); element.addBefore(whiteSpace, insertAnchor); element.addBefore(whiteSpace, listWithModifier); } else { PsiElement firstChild = element.getFirstChild(); element.addBefore(listWithModifier, firstChild); element.addBefore(whiteSpace, firstChild); } } } else { boolean replaced = false; if (modifiersThatCanBeReplaced != null) { PsiElement toBeReplaced = null; PsiElement toReplace = null; for (JetToken modifierThatCanBeReplaced : modifiersThatCanBeReplaced) { if (modifierList.hasModifier(modifierThatCanBeReplaced)) { PsiElement modifierElement = modifierList.getModifierNode(modifierThatCanBeReplaced).getPsi(); assert modifierElement != null; if (!replaced && listWithModifier != null) { toBeReplaced = modifierElement; toReplace = listWithModifier.getFirstChild(); // modifierElement.replace(listWithModifier.getFirstChild()); replaced = true; } else { modifierList.deleteChildInternal(modifierElement.getNode()); } } } if (toBeReplaced != null && toReplace != null) { toBeReplaced.replace(toReplace); } } if (!replaced && listWithModifier != null) { if (toBeginning) { PsiElement firstChild = modifierList.getFirstChild(); modifierList.addBefore(listWithModifier.getFirstChild(), firstChild); modifierList.addBefore(whiteSpace, firstChild); } else { PsiElement lastChild = modifierList.getLastChild(); modifierList.addAfter(listWithModifier.getFirstChild(), lastChild); modifierList.addAfter(whiteSpace, lastChild); } } } }
@Nullable public static PsiElement prevLeafIgnoringWhitespaceAndComments(@NotNull PsiElement element) { PsiElement prev = PsiTreeUtil.prevLeaf(element, true); while (prev != null && KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET.contains(prev.getNode().getElementType())) { prev = PsiTreeUtil.prevLeaf(prev, true); } return prev; }
private static boolean isTagStartOrEnd(@Nullable PsiElement element) { if (element == null) return false; final IElementType type = element.getNode().getElementType(); if (type == XmlTokenType.XML_NAME) return isTagStartOrEnd(element.getNextSibling()) || isTagStartOrEnd(element.getPrevSibling()); return type == XmlTokenType.XML_START_TAG_START || type == XmlTokenType.XML_END_TAG_START || type == XmlTokenType.XML_TAG_END; }
@Nullable private static LineRange getWhenEntryTargetRange( @NotNull Editor editor, @NotNull PsiElement sibling, boolean down) { if (sibling.getNode().getElementType() == (down ? JetTokens.RBRACE : JetTokens.LBRACE) && PsiTreeUtil.getParentOfType(sibling, JetWhenEntry.class) == null) { return null; } return new LineRange(sibling, sibling, editor.getDocument()); }
@Override public PsiElement qualifyClassReferences(@NotNull PsiElement element) { final ReferenceAdjuster adjuster = ReferenceAdjuster.Extension.getReferenceAdjuster(element.getLanguage()); if (adjuster != null) { final ASTNode reference = adjuster.process(element.getNode(), false, false, true, true); return SourceTreeToPsiMap.treeToPsiNotNull(reference); } return element; }
public static ASTNode createNameIdentifier(Project project, String name) throws IncorrectOperationException { final PsiFile dummyFile = PsiFileFactory.getInstance(project) .createFileFromText( DUMMY + ParserFileType.PARSER_FILE_TYPE.getDefaultExtension(), name); final PsiElement expressionStatement = dummyFile.getFirstChild(); assert expressionStatement != null; return expressionStatement.getNode(); }
public void checkParameterHasNoValOrVar( @NotNull JetParameter parameter, @NotNull DiagnosticFactory1<PsiElement, JetKeywordToken> diagnosticFactory) { PsiElement valOrVar = parameter.getValOrVarKeyword(); if (valOrVar != null) { trace.report( diagnosticFactory.on( valOrVar, ((JetKeywordToken) valOrVar.getNode().getElementType()))); } }