Exemplo n.º 1
1
  @Override
  protected void updateTitle(@Nullable final PsiVariable variable, final String value) {
    final PsiElement declarationScope =
        variable != null ? ((PsiParameter) variable).getDeclarationScope() : null;
    if (declarationScope instanceof PsiMethod) {
      final PsiMethod psiMethod = (PsiMethod) declarationScope;
      final StringBuilder buf = new StringBuilder();
      buf.append(psiMethod.getName()).append(" (");
      boolean frst = true;
      final List<TextRange> ranges2Remove = new ArrayList<>();
      TextRange addedRange = null;
      for (PsiParameter parameter : psiMethod.getParameterList().getParameters()) {
        if (frst) {
          frst = false;
        } else {
          buf.append(", ");
        }
        int startOffset = buf.length();
        if (myMustBeFinal || myPanel.isGenerateFinal()) {
          buf.append("final ");
        }
        buf.append(parameter.getType().getPresentableText())
            .append(" ")
            .append(variable == parameter ? value : parameter.getName());
        int endOffset = buf.length();
        if (variable == parameter) {
          addedRange = new TextRange(startOffset, endOffset);
        } else if (myPanel.isParamToRemove(parameter)) {
          ranges2Remove.add(new TextRange(startOffset, endOffset));
        }
      }

      buf.append(")");
      setPreviewText(buf.toString());
      final MarkupModel markupModel =
          DocumentMarkupModel.forDocument(getPreviewEditor().getDocument(), myProject, true);
      markupModel.removeAllHighlighters();
      for (TextRange textRange : ranges2Remove) {
        markupModel.addRangeHighlighter(
            textRange.getStartOffset(),
            textRange.getEndOffset(),
            0,
            getTestAttributesForRemoval(),
            HighlighterTargetArea.EXACT_RANGE);
      }
      markupModel.addRangeHighlighter(
          addedRange.getStartOffset(),
          addedRange.getEndOffset(),
          0,
          getTextAttributesForAdd(),
          HighlighterTargetArea.EXACT_RANGE);
      revalidate();
    }
  }
 @Override
 public int compare(TextRange range1, TextRange range2) {
   int startOffsetDiff = range1.getStartOffset() - range2.getStartOffset();
   return startOffsetDiff != 0
       ? startOffsetDiff
       : range1.getEndOffset() - range2.getEndOffset();
 }
  @Nullable
  private static PsiElement findParent(
      int syncStartOffset, int syncEndOffset, @NotNull AnchorTypeInfo type, PsiElement anchor) {
    TextRange range = anchor.getTextRange();

    if (range.getStartOffset() != syncStartOffset) return null;
    while (range.getEndOffset() < syncEndOffset) {
      anchor = anchor.getParent();
      if (anchor == null || anchor.getTextRange() == null) {
        return null;
      }
      range = anchor.getTextRange();
    }

    while (range.getEndOffset() == syncEndOffset) {
      if (type.isAcceptable(anchor)) {
        return anchor;
      }
      anchor = anchor.getParent();
      if (anchor == null || anchor.getTextRange() == null) break;
      range = anchor.getTextRange();
    }

    return null;
  }
    private void updateFragments(int start, int end, @NotNull String replace) {
      int docStart = psiToDocumentOffset(start);
      int docEnd = psiToDocumentOffset(end);

      TextRange startRange = findFragment(docStart);
      TextRange endRange = findFragment(docEnd);

      myPsiText = myPsiText.delete(start, end).insert(start, replace);

      TextRange newFragment =
          new TextRange(
              startRange != null ? startRange.getStartOffset() : docStart,
              endRange != null ? endRange.getEndOffset() : docEnd);
      CharSequence newReplacement =
          myPsiText.subSequence(
              documentToPsiOffset(newFragment.getStartOffset(), false),
              documentToPsiOffset(newFragment.getEndOffset(), true)
                  + replace.length()
                  - (end - start));

      for (Iterator<TextRange> iterator = myAffectedFragments.keySet().iterator();
          iterator.hasNext(); ) {
        if (iterator.next().intersects(newFragment)) {
          iterator.remove();
        }
      }
      myAffectedFragments.put(newFragment, newReplacement);
    }
 @NotNull
 private static Collection<PsiLanguageInjectionHost> collectInjectionHosts(
     @NotNull PsiFile file, @NotNull TextRange range) {
   Stack<PsiElement> toProcess = new Stack<PsiElement>();
   for (PsiElement e = file.findElementAt(range.getStartOffset());
       e != null;
       e = e.getNextSibling()) {
     if (e.getTextRange().getStartOffset() >= range.getEndOffset()) {
       break;
     }
     toProcess.push(e);
   }
   if (toProcess.isEmpty()) {
     return Collections.emptySet();
   }
   Set<PsiLanguageInjectionHost> result = null;
   while (!toProcess.isEmpty()) {
     PsiElement e = toProcess.pop();
     if (e instanceof PsiLanguageInjectionHost) {
       if (result == null) {
         result = ContainerUtilRt.newHashSet();
       }
       result.add((PsiLanguageInjectionHost) e);
     } else {
       for (PsiElement child = e.getFirstChild(); child != null; child = child.getNextSibling()) {
         if (e.getTextRange().getStartOffset() >= range.getEndOffset()) {
           break;
         }
         toProcess.push(child);
       }
     }
   }
   return result == null ? Collections.<PsiLanguageInjectionHost>emptySet() : result;
 }
Exemplo n.º 6
0
  public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    PsiElement element = descriptor.getPsiElement();
    PsiStatement anchorStatement = PsiTreeUtil.getParentOfType(element, PsiStatement.class);
    LOG.assertTrue(anchorStatement != null);
    Editor editor = getEditor(project, element);
    if (editor == null) return;
    PsiFile file = element.getContainingFile();
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    Document document = documentManager.getDocument(file);
    if (!CodeInsightUtilBase.prepareFileForWrite(file)) return;
    PsiElement[] elements = {anchorStatement};
    PsiElement prev = PsiTreeUtil.skipSiblingsBackward(anchorStatement, PsiWhiteSpace.class);
    if (prev instanceof PsiComment
        && SuppressManager.getInstance().getSuppressedInspectionIdsIn(prev) != null) {
      elements = new PsiElement[] {prev, anchorStatement};
    }
    try {
      TextRange textRange = new JavaWithIfSurrounder().surroundElements(project, editor, elements);
      if (textRange == null) return;

      @NonNls String newText = myText + " != null";
      document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), newText);
      editor.getCaretModel().moveToOffset(textRange.getEndOffset() + newText.length());
      editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);

    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
 @Override
 public int compare(TextRange o1, TextRange o2) {
   if (o1.getStartOffset() == o2.getStartOffset()) {
     return o2.getEndOffset() - o1.getEndOffset(); // longer is better
   }
   return o1.getStartOffset() - o2.getStartOffset();
 }
  public void commentRange(
      int startOffset,
      int endOffset,
      String commentPrefix,
      String commentSuffix,
      Commenter commenter) {
    final CharSequence chars = myDocument.getCharsSequence();
    LogicalPosition caretPosition = myCaret.getLogicalPosition();

    if (startOffset == 0 || chars.charAt(startOffset - 1) == '\n') {
      if (endOffset == myDocument.getTextLength()
          || endOffset > 0 && chars.charAt(endOffset - 1) == '\n') {
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject);
        CommonCodeStyleSettings settings =
            CodeStyleSettingsManager.getSettings(myProject).getCommonSettings(myFile.getLanguage());
        String space;
        if (!settings.BLOCK_COMMENT_AT_FIRST_COLUMN) {
          final FileType fileType = myFile.getFileType();
          int line1 = myEditor.offsetToLogicalPosition(startOffset).line;
          int line2 = myEditor.offsetToLogicalPosition(endOffset - 1).line;
          Indent minIndent =
              CommentUtil.getMinLineIndent(myProject, myDocument, line1, line2, fileType);
          if (minIndent == null) {
            minIndent = codeStyleManager.zeroIndent();
          }
          space = codeStyleManager.fillIndent(minIndent, fileType);
        } else {
          space = "";
        }
        final StringBuilder nestingPrefix = new StringBuilder(space).append(commentPrefix);
        if (!commentPrefix.endsWith("\n")) {
          nestingPrefix.append("\n");
        }
        final StringBuilder nestingSuffix = new StringBuilder(space);
        nestingSuffix.append(
            commentSuffix.startsWith("\n") ? commentSuffix.substring(1) : commentSuffix);
        nestingSuffix.append("\n");
        TextRange range =
            insertNestedComments(
                startOffset,
                endOffset,
                nestingPrefix.toString(),
                nestingSuffix.toString(),
                commenter);
        myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
        LogicalPosition pos = new LogicalPosition(caretPosition.line + 1, caretPosition.column);
        myCaret.moveToLogicalPosition(pos);
        return;
      }
    }

    TextRange range =
        insertNestedComments(startOffset, endOffset, commentPrefix, commentSuffix, commenter);
    myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
    LogicalPosition pos =
        new LogicalPosition(caretPosition.line, caretPosition.column + commentPrefix.length());
    myCaret.moveToLogicalPosition(pos);
  }
 @Override
 public int compare(TextRange o1, TextRange o2) {
   if (o1.getStartOffset() == o2.getStartOffset()) {
     return o1.getEndOffset() > o2.getEndOffset() ? 1 : -1;
   }
   if (o1.getStartOffset() > o2.getStartOffset()) return 1;
   if (o1.getEndOffset() > o2.getEndOffset()) return 1;
   return -1;
 }
 @Override
 @NotNull
 public ProperTextRange injectedToHost(@NotNull TextRange injected) {
   int start = injectedToHost(injected.getStartOffset(), false);
   int end = injectedToHost(injected.getEndOffset(), true);
   if (end < start) {
     end = injectedToHost(injected.getEndOffset(), false);
   }
   return new ProperTextRange(start, end);
 }
Exemplo n.º 11
0
  private void doCheckRefs(final PsiElement value, final PsiReference[] references, int start) {
    for (int i = start; i < references.length; ++i) {
      PsiReference reference = references[i];
      ProgressManager.checkCanceled();
      if (reference == null) {
        continue;
      }
      if (!hasBadResolve(reference, false)) {
        continue;
      }
      String description = getErrorDescription(reference);

      final int startOffset = reference.getElement().getTextRange().getStartOffset();
      final TextRange referenceRange = reference.getRangeInElement();

      // logging for IDEADEV-29655
      if (referenceRange.getStartOffset() > referenceRange.getEndOffset()) {
        LOG.error(
            "Reference range start offset > end offset:  "
                + reference
                + ", start offset: "
                + referenceRange.getStartOffset()
                + ", end offset: "
                + referenceRange.getEndOffset());
      }

      HighlightInfoType type =
          getTagProblemInfoType(PsiTreeUtil.getParentOfType(value, XmlTag.class));
      if (value instanceof XmlAttributeValue) {
        PsiElement parent = value.getParent();
        if (parent instanceof XmlAttribute) {
          String name = ((XmlAttribute) parent).getName().toLowerCase();
          if (type.getSeverity(null).compareTo(HighlightInfoType.WARNING.getSeverity(null)) > 0
              && name.endsWith("stylename")) {
            type = HighlightInfoType.WARNING;
          } else if (name.equals("href")
              && type.getSeverity(null) == HighlightInfoType.WARNING.getSeverity(null)) {
            continue;
          }
        }
      }
      HighlightInfo info =
          HighlightInfo.createHighlightInfo(
              type,
              startOffset + referenceRange.getStartOffset(),
              startOffset + referenceRange.getEndOffset(),
              description);
      addToResults(info);
      if (reference instanceof QuickFixProvider)
        ((QuickFixProvider) reference).registerQuickfix(info, reference);
      UnresolvedReferenceQuickFixProvider.registerReferenceFixes(
          reference, new QuickFixActionRegistrarImpl(info));
    }
  }
Exemplo n.º 12
0
  @Override
  protected LineRange getElementSourceLineRange(
      @NotNull PsiElement element, @NotNull Editor editor, @NotNull LineRange oldRange) {
    TextRange textRange = element.getTextRange();
    if (editor.getDocument().getTextLength() < textRange.getEndOffset()) return null;

    int startLine = editor.offsetToLogicalPosition(textRange.getStartOffset()).line;
    int endLine = editor.offsetToLogicalPosition(textRange.getEndOffset()).line + 1;

    return new LineRange(startLine, endLine);
  }
 @Override
 public CharSequence getText(final TextRange textRange) {
   if (textRange.getStartOffset() < 0 || textRange.getEndOffset() > myDocument.getTextLength()) {
     LOG.error(
         String.format(
             "Please submit a ticket to the tracker and attach current source file to it!%nInvalid processing detected: given text "
                 + "range (%s) targets non-existing regions (the boundaries are [0; %d)). File's language: %s",
             textRange, myDocument.getTextLength(), myFile.getLanguage()));
   }
   return myDocument
       .getCharsSequence()
       .subSequence(textRange.getStartOffset(), textRange.getEndOffset());
 }
 @Override
 public TextRange getRangeInElement() {
   final TextRange rangeInElement = super.getRangeInElement();
   final XmlTag tagElement = getTagElement();
   if (tagElement != null) {
     final String tagElementName = tagElement.getName();
     final int dotIdx = tagElementName.indexOf(".");
     if (dotIdx > -1 && dotIdx + 2 < rangeInElement.getEndOffset()) {
       return new TextRange(
           rangeInElement.getStartOffset() + dotIdx + 1, rangeInElement.getEndOffset());
     }
   }
   return rangeInElement;
 }
  private void doReplaceString(int startOffset, int endOffset, CharSequence s) {
    assert intersectWithEditable(new TextRange(startOffset, startOffset)) != null;
    assert intersectWithEditable(new TextRange(endOffset, endOffset)) != null;

    List<Pair<TextRange, CharSequence>> hostRangesToModify;
    synchronized (myLock) {
      hostRangesToModify = new ArrayList<Pair<TextRange, CharSequence>>(myShreds.size());

      int offset = startOffset;
      int curRangeStart = 0;
      for (int i = 0; i < myShreds.size(); i++) {
        PsiLanguageInjectionHost.Shred shred = myShreds.get(i);
        curRangeStart += shred.getPrefix().length();
        if (offset < curRangeStart) offset = curRangeStart;
        Segment hostRange = shred.getHostRangeMarker();
        if (hostRange == null) continue;
        int hostRangeLength = hostRange.getEndOffset() - hostRange.getStartOffset();
        TextRange range = TextRange.from(curRangeStart, hostRangeLength);
        if (range.contains(offset)
            || range.getEndOffset() == offset /* in case of inserting at the end*/) {
          TextRange rangeToModify =
              new TextRange(offset, Math.min(range.getEndOffset(), endOffset));
          TextRange hostRangeToModify =
              rangeToModify.shiftRight(hostRange.getStartOffset() - curRangeStart);
          CharSequence toReplace =
              i == myShreds.size() - 1
                      || range.getEndOffset() + shred.getSuffix().length() >= endOffset
                  ? s
                  : s.subSequence(0, Math.min(hostRangeToModify.getLength(), s.length()));
          s = toReplace == s ? "" : s.subSequence(toReplace.length(), s.length());
          hostRangesToModify.add(Pair.create(hostRangeToModify, toReplace));
          offset = rangeToModify.getEndOffset();
        }
        curRangeStart += hostRangeLength;
        curRangeStart += shred.getSuffix().length();
        if (curRangeStart > endOffset) break;
      }
    }

    int delta = 0;
    for (Pair<TextRange, CharSequence> pair : hostRangesToModify) {
      TextRange hostRange = pair.getFirst();
      CharSequence replace = pair.getSecond();

      myDelegate.replaceString(
          hostRange.getStartOffset() + delta, hostRange.getEndOffset() + delta, replace);
      delta -= hostRange.getLength() - replace.length();
    }
  }
Exemplo n.º 16
0
 @NotNull
 private static List<DiagnosticDescriptor> getSortedDiagnosticDescriptors(
     @NotNull Collection<Diagnostic> diagnostics) {
   LinkedListMultimap<TextRange, Diagnostic> diagnosticsGroupedByRanges =
       LinkedListMultimap.create();
   for (Diagnostic diagnostic : diagnostics) {
     if (!diagnostic.isValid()) continue;
     for (TextRange textRange : diagnostic.getTextRanges()) {
       diagnosticsGroupedByRanges.put(textRange, diagnostic);
     }
   }
   List<DiagnosticDescriptor> diagnosticDescriptors = Lists.newArrayList();
   for (TextRange range : diagnosticsGroupedByRanges.keySet()) {
     diagnosticDescriptors.add(
         new DiagnosticDescriptor(
             range.getStartOffset(), range.getEndOffset(), diagnosticsGroupedByRanges.get(range)));
   }
   Collections.sort(
       diagnosticDescriptors,
       new Comparator<DiagnosticDescriptor>() {
         @Override
         public int compare(@NotNull DiagnosticDescriptor d1, @NotNull DiagnosticDescriptor d2) {
           // Start early -- go first; start at the same offset, the one who end later is the
           // outer, i.e. goes first
           return (d1.start != d2.start) ? d1.start - d2.start : d2.end - d1.end;
         }
       });
   return diagnosticDescriptors;
 }
Exemplo n.º 17
0
 /**
  * @deprecated To be removed in idea 13. Use {@link
  *     HighlightInfo#newHighlightInfo(HighlightInfoType)} instead.
  */
 @Deprecated
 @Nullable
 public static HighlightInfo createHighlightInfo(
     @NotNull HighlightInfoType type, @NotNull TextRange textRange, @Nullable String description) {
   return createHighlightInfo(
       type, textRange.getStartOffset(), textRange.getEndOffset(), description);
 }
  protected void invokeImpl(final PsiClass targetClass) {
    final Project project = myConstructorCall.getProject();
    PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();

    try {
      PsiMethod constructor = (PsiMethod) targetClass.add(elementFactory.createConstructor());

      final PsiFile file = targetClass.getContainingFile();
      TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(constructor);
      CreateFromUsageUtils.setupMethodParameters(
          constructor,
          templateBuilder,
          myConstructorCall.getArgumentList(),
          getTargetSubstitutor(myConstructorCall));
      final PsiMethod superConstructor =
          CreateClassFromNewFix.setupSuperCall(targetClass, constructor, templateBuilder);

      constructor = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(constructor);
      Template template = templateBuilder.buildTemplate();
      if (targetClass == null) return;
      final Editor editor = positionCursor(project, targetClass.getContainingFile(), targetClass);
      final TextRange textRange = constructor.getTextRange();
      editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
      editor.getCaretModel().moveToOffset(textRange.getStartOffset());

      startTemplate(
          editor,
          template,
          project,
          new TemplateEditingAdapter() {
            public void templateFinished(Template template, boolean brokenOff) {
              ApplicationManager.getApplication()
                  .runWriteAction(
                      new Runnable() {
                        public void run() {
                          try {
                            PsiDocumentManager.getInstance(project)
                                .commitDocument(editor.getDocument());
                            final int offset = editor.getCaretModel().getOffset();
                            PsiMethod constructor =
                                PsiTreeUtil.findElementOfClassAtOffset(
                                    file, offset, PsiMethod.class, false);
                            if (superConstructor == null) {
                              CreateFromUsageUtils.setupMethodBody(constructor);
                            } else {
                              OverrideImplementUtil.setupMethodBody(
                                  constructor, superConstructor, targetClass);
                            }
                            CreateFromUsageUtils.setupEditor(constructor, editor);
                          } catch (IncorrectOperationException e) {
                            LOG.error(e);
                          }
                        }
                      });
            }
          });
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
Exemplo n.º 19
0
  @Override
  @Nullable
  public PsiElement restoreElement() {
    long typeAndId = myStubElementTypeAndId;
    int stubId = (int) typeAndId;
    if (stubId != -1) {
      PsiFile file = restoreFile();
      if (!(file instanceof PsiFileWithStubSupport)) return null;
      short index = (short) (typeAndId >> 32);
      IStubElementType stubElementType = (IStubElementType) IElementType.find(index);
      return PsiAnchor.restoreFromStubIndex(
          (PsiFileWithStubSupport) file, stubId, stubElementType, false);
    }

    Segment psiRange = getPsiRange();
    if (psiRange == null) return null;

    PsiFile file = restoreFile();
    if (file == null) return null;
    PsiElement anchor = file.findElementAt(psiRange.getStartOffset());
    if (anchor == null) return null;

    TextRange range = anchor.getTextRange();
    if (range.getStartOffset() != psiRange.getStartOffset()
        || range.getEndOffset() != psiRange.getEndOffset()) return null;

    for (SmartPointerAnchorProvider provider : SmartPointerAnchorProvider.EP_NAME.getExtensions()) {
      final PsiElement element = provider.restoreElement(anchor);
      if (element != null) return element;
    }
    return null;
  }
  public GrLiteralImpl handleContentChange(GrLiteral expr, TextRange range, String newContent)
      throws IncorrectOperationException {
    if (!(expr.getValue() instanceof String))
      throw new IncorrectOperationException("cannot handle content change");

    LOG.assertTrue(expr instanceof GrLiteralImpl);

    String oldText = expr.getText();
    final String quote = GrStringUtil.getStartQuote(oldText);

    if (quote.startsWith("'")) {
      newContent = GrStringUtil.escapeSymbolsForString(newContent, !quote.equals("'''"), false);
    } else if (quote.startsWith("\"")) {
      newContent = GrStringUtil.escapeSymbolsForGString(newContent, !quote.equals("\"\"\""), true);
    } else if ("/".equals(quote)) {
      newContent = GrStringUtil.escapeSymbolsForSlashyStrings(newContent);
    } else if ("$/".equals(quote)) {
      newContent = GrStringUtil.escapeSymbolsForDollarSlashyStrings(newContent);
    }

    String newText =
        oldText.substring(0, range.getStartOffset())
            + newContent
            + oldText.substring(range.getEndOffset());
    return ((GrLiteralImpl) expr).updateText(newText);
  }
Exemplo n.º 21
0
 /** Patches attributes to be visible under debugger active line */
 @SuppressWarnings("UseJBColor")
 public static TextAttributes patchAttributesColor(
     TextAttributes attributes, @NotNull TextRange range, @NotNull Editor editor) {
   if (attributes.getForegroundColor() == null && attributes.getEffectColor() == null)
     return attributes;
   MarkupModel model =
       DocumentMarkupModel.forDocument(editor.getDocument(), editor.getProject(), false);
   if (model != null) {
     if (!((MarkupModelEx) model)
         .processRangeHighlightersOverlappingWith(
             range.getStartOffset(),
             range.getEndOffset(),
             highlighter -> {
               if (highlighter.isValid()
                   && highlighter.getTargetArea() == HighlighterTargetArea.LINES_IN_RANGE) {
                 TextAttributes textAttributes = highlighter.getTextAttributes();
                 if (textAttributes != null) {
                   Color color = textAttributes.getBackgroundColor();
                   return !(color != null
                       && color.getBlue() > 128
                       && color.getRed() < 128
                       && color.getGreen() < 128);
                 }
               }
               return true;
             })) {
       TextAttributes clone = attributes.clone();
       clone.setForegroundColor(Color.orange);
       clone.setEffectColor(Color.orange);
       return clone;
     }
   }
   return attributes;
 }
 public TextRange surroundExpression(
     final Project project, final Editor editor, PsiExpression expr)
     throws IncorrectOperationException {
   assert expr.isValid();
   PsiType[] types = GuessManager.getInstance(project).guessTypeToCast(expr);
   final boolean parenthesesNeeded =
       expr instanceof PsiPolyadicExpression
           || expr instanceof PsiConditionalExpression
           || expr instanceof PsiAssignmentExpression;
   String exprText = parenthesesNeeded ? "(" + expr.getText() + ")" : expr.getText();
   final Template template = generateTemplate(project, exprText, types);
   TextRange range;
   if (expr.isPhysical()) {
     range = expr.getTextRange();
   } else {
     final RangeMarker rangeMarker = expr.getUserData(ElementToWorkOn.TEXT_RANGE);
     if (rangeMarker == null) return null;
     range = new TextRange(rangeMarker.getStartOffset(), rangeMarker.getEndOffset());
   }
   editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
   editor.getCaretModel().moveToOffset(range.getStartOffset());
   editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
   TemplateManager.getInstance(project).startTemplate(editor, template);
   return null;
 }
  private static void replaceByTagContent(Project project, XmlTag tagToReplace, XmlTag tagToInline)
      throws AndroidRefactoringErrorException {
    final ASTNode node = tagToInline.getNode();

    if (node == null) {
      throw new AndroidRefactoringErrorException();
    }
    final ASTNode startTagEnd = XmlChildRole.START_TAG_END_FINDER.findChild(node);
    final ASTNode closingTagStart = XmlChildRole.CLOSING_TAG_START_FINDER.findChild(node);

    if (startTagEnd == null || closingTagStart == null) {
      throw new AndroidRefactoringErrorException();
    }
    final int contentStart = startTagEnd.getTextRange().getEndOffset();
    final int contentEnd = closingTagStart.getTextRange().getStartOffset();

    if (contentStart < 0 || contentEnd < 0 || contentStart >= contentEnd) {
      throw new AndroidRefactoringErrorException();
    }
    final PsiFile file = tagToInline.getContainingFile();

    if (file == null) {
      throw new AndroidRefactoringErrorException();
    }
    final String textToInline = file.getText().substring(contentStart, contentEnd).trim();
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    final Document document = documentManager.getDocument(tagToReplace.getContainingFile());

    if (document == null) {
      throw new AndroidRefactoringErrorException();
    }
    final TextRange range = tagToReplace.getTextRange();
    document.replaceString(range.getStartOffset(), range.getEndOffset(), textToInline);
    documentManager.commitDocument(document);
  }
  @Override
  public void addOccurrenceHighlights(
      @NotNull Editor editor,
      @NotNull PsiElement[] elements,
      @NotNull TextAttributes attributes,
      boolean hideByTextChange,
      Collection<RangeHighlighter> outHighlighters) {
    if (elements.length == 0) return;
    int flags = HIDE_BY_ESCAPE;
    if (hideByTextChange) {
      flags |= HIDE_BY_TEXT_CHANGE;
    }

    Color scrollmarkColor = getScrollMarkColor(attributes);
    if (editor instanceof EditorWindow) {
      editor = ((EditorWindow) editor).getDelegate();
    }

    for (PsiElement element : elements) {
      TextRange range = element.getTextRange();
      range = InjectedLanguageManager.getInstance(myProject).injectedToHost(element, range);
      addOccurrenceHighlight(
          editor,
          trimOffsetToDocumentSize(editor, range.getStartOffset()),
          trimOffsetToDocumentSize(editor, range.getEndOffset()),
          attributes,
          flags,
          outHighlighters,
          scrollmarkColor);
    }
  }
 private static void duplicateHighlighters(
     MarkupModel to, MarkupModel from, int offset, TextRange textRange) {
   for (RangeHighlighter rangeHighlighter : from.getAllHighlighters()) {
     if (!rangeHighlighter.isValid()) continue;
     Object tooltip = rangeHighlighter.getErrorStripeTooltip();
     HighlightInfo highlightInfo =
         tooltip instanceof HighlightInfo ? (HighlightInfo) tooltip : null;
     if (highlightInfo != null) {
       if (highlightInfo.getSeverity() != HighlightSeverity.INFORMATION) continue;
       if (highlightInfo.type.getAttributesKey() == EditorColors.IDENTIFIER_UNDER_CARET_ATTRIBUTES)
         continue;
     }
     final int localOffset = textRange.getStartOffset();
     final int start = Math.max(rangeHighlighter.getStartOffset(), localOffset) - localOffset;
     final int end =
         Math.min(rangeHighlighter.getEndOffset(), textRange.getEndOffset()) - localOffset;
     if (start > end) continue;
     final RangeHighlighter h =
         to.addRangeHighlighter(
             start + offset,
             end + offset,
             rangeHighlighter.getLayer(),
             rangeHighlighter.getTextAttributes(),
             rangeHighlighter.getTargetArea());
     ((RangeHighlighterEx) h)
         .setAfterEndOfLine(((RangeHighlighterEx) rangeHighlighter).isAfterEndOfLine());
   }
 }
Exemplo n.º 26
0
  private HighlightersSet installHighlighterSet(Info info, Editor editor) {
    final JComponent internalComponent = editor.getContentComponent();
    internalComponent.addKeyListener(myEditorKeyListener);
    editor.getScrollingModel().addVisibleAreaListener(myVisibleAreaListener);
    final Cursor cursor = internalComponent.getCursor();
    internalComponent.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    myFileEditorManager.addFileEditorManagerListener(myFileEditorManagerListener);

    List<RangeHighlighter> highlighters = new ArrayList<RangeHighlighter>();
    TextAttributes attributes =
        myEditorColorsManager
            .getGlobalScheme()
            .getAttributes(EditorColors.REFERENCE_HYPERLINK_COLOR);
    for (TextRange range : info.getRanges()) {
      TextAttributes attr = patchAttributesColor(attributes, range, editor);
      final RangeHighlighter highlighter =
          editor
              .getMarkupModel()
              .addRangeHighlighter(
                  range.getStartOffset(),
                  range.getEndOffset(),
                  HighlighterLayer.SELECTION + 1,
                  attr,
                  HighlighterTargetArea.EXACT_RANGE);
      highlighters.add(highlighter);
    }

    return new HighlightersSet(highlighters, editor, cursor, info);
  }
  private static void highlightTodos(
      @NotNull PsiFile file,
      @NotNull CharSequence text,
      int startOffset,
      int endOffset,
      @NotNull ProgressIndicator progress,
      @NotNull ProperTextRange priorityRange,
      @NotNull Collection<HighlightInfo> result,
      @NotNull Collection<HighlightInfo> outsideResult) {
    PsiSearchHelper helper = PsiSearchHelper.SERVICE.getInstance(file.getProject());
    TodoItem[] todoItems = helper.findTodoItems(file, startOffset, endOffset);
    if (todoItems.length == 0) return;

    for (TodoItem todoItem : todoItems) {
      progress.checkCanceled();
      TextRange range = todoItem.getTextRange();
      String description =
          text.subSequence(range.getStartOffset(), range.getEndOffset()).toString();
      TextAttributes attributes = todoItem.getPattern().getAttributes().getTextAttributes();
      HighlightInfo info =
          HighlightInfo.createHighlightInfo(
              HighlightInfoType.TODO, range, description, description, attributes);
      assert info != null;
      if (priorityRange.containsRange(info.getStartOffset(), info.getEndOffset())) {
        result.add(info);
      } else {
        outsideResult.add(info);
      }
    }
  }
  private static Condition<PsiElement> findFieldUsages(
      final PsiField psiField,
      final List<UsageInfo> usages,
      final PsiElement[] allElementsToDelete) {
    final Condition<PsiElement> isInsideDeleted = getUsageInsideDeletedFilter(allElementsToDelete);
    ReferencesSearch.search(psiField)
        .forEach(
            reference -> {
              if (!isInsideDeleted.value(reference.getElement())) {
                final PsiElement element = reference.getElement();
                final PsiElement parent = element.getParent();
                if (parent instanceof PsiAssignmentExpression
                    && element == ((PsiAssignmentExpression) parent).getLExpression()) {
                  usages.add(
                      new SafeDeleteFieldWriteReference(
                          (PsiAssignmentExpression) parent, psiField));
                } else {
                  TextRange range = reference.getRangeInElement();
                  usages.add(
                      new SafeDeleteReferenceJavaDeleteUsageInfo(
                          reference.getElement(),
                          psiField,
                          range.getStartOffset(),
                          range.getEndOffset(),
                          false,
                          PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class)
                              != null));
                }
              }

              return true;
            });

    return isInsideDeleted;
  }
 @Override
 @Deprecated
 @Nullable
 public TextRange intersectWithEditable(@NotNull TextRange rangeToEdit) {
   int startOffset = -1;
   int endOffset = -1;
   synchronized (myLock) {
     int offset = 0;
     for (PsiLanguageInjectionHost.Shred shred : myShreds) {
       Segment hostRange = shred.getHostRangeMarker();
       if (hostRange == null) continue;
       offset += shred.getPrefix().length();
       int length = hostRange.getEndOffset() - hostRange.getStartOffset();
       TextRange intersection =
           new ProperTextRange(offset, offset + length).intersection(rangeToEdit);
       if (intersection != null) {
         if (startOffset == -1) {
           startOffset = intersection.getStartOffset();
         }
         endOffset = intersection.getEndOffset();
       }
       offset += length;
       offset += shred.getSuffix().length();
     }
   }
   if (startOffset == -1) return null;
   return new ProperTextRange(startOffset, endOffset);
 }
Exemplo n.º 30
0
  @NotNull
  public static HighlightInfo fromAnnotation(
      @NotNull Annotation annotation, @Nullable TextRange fixedRange, boolean batchMode) {
    final TextAttributes forcedAttributes = annotation.getEnforcedTextAttributes();
    final TextAttributesKey forcedAttributesKey =
        forcedAttributes == null ? annotation.getTextAttributes() : null;

    HighlightInfo info =
        new HighlightInfo(
            forcedAttributes,
            forcedAttributesKey,
            convertType(annotation),
            fixedRange != null ? fixedRange.getStartOffset() : annotation.getStartOffset(),
            fixedRange != null ? fixedRange.getEndOffset() : annotation.getEndOffset(),
            annotation.getMessage(),
            annotation.getTooltip(),
            annotation.getSeverity(),
            annotation.isAfterEndOfLine(),
            annotation.needsUpdateOnTyping(),
            annotation.isFileLevelAnnotation(),
            0,
            annotation.getProblemGroup(),
            annotation.getGutterIconRenderer());
    appendFixes(
        fixedRange, info, batchMode ? annotation.getBatchFixes() : annotation.getQuickFixes());
    return info;
  }