Пример #1
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);
    }
  }
  void loadFromEditor(@NotNull Editor editor) {
    assertDispatchThread();
    LOG.assertTrue(!editor.isDisposed());
    clear();

    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
    documentManager.commitDocument(editor.getDocument());
    PsiFile file = documentManager.getPsiFile(editor.getDocument());

    SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(myProject);
    EditorFoldingInfo info = EditorFoldingInfo.get(editor);
    FoldRegion[] foldRegions = editor.getFoldingModel().getAllFoldRegions();
    for (FoldRegion region : foldRegions) {
      if (!region.isValid()) continue;
      PsiElement element = info.getPsiElement(region);
      boolean expanded = region.isExpanded();
      boolean collapseByDefault =
          element != null
              && FoldingPolicy.isCollapseByDefault(element)
              && !FoldingUtil.caretInsideRange(editor, TextRange.create(region));
      if (collapseByDefault == expanded || element == null) {
        FoldingInfo fi = new FoldingInfo(region.getPlaceholderText(), expanded);
        if (element != null) {
          myPsiElements.add(smartPointerManager.createSmartPsiElementPointer(element, file));
          element.putUserData(FOLDING_INFO_KEY, fi);
        } else if (region.isValid()) {
          myRangeMarkers.add(region);
          region.putUserData(FOLDING_INFO_KEY, fi);
        }
      }
    }
  }
 private static void commit(@NotNull PsiFile file) {
   PsiDocumentManager manager = PsiDocumentManager.getInstance(file.getProject());
   Document document = manager.getDocument(file);
   if (document != null) {
     manager.commitDocument(document);
   }
 }
Пример #4
0
  public void testTypingDoesNotInterfereWithDuplicates() throws Exception {
    SliceTreeStructure treeStructure = configureTree("DupSlice");
    SliceNode root = (SliceNode) treeStructure.getRootElement();
    List<SliceNode> nodes = new ArrayList<SliceNode>();
    expandNodesTo(root, nodes);

    for (int i = 0; i < nodes.size() - 1; i++) {
      SliceNode node = nodes.get(i);
      assertNull(node.getDuplicate());
    }
    SliceNode last = nodes.get(nodes.size() - 1);
    assertNotNull(last.getDuplicate());

    type("   xx");
    PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
    backspace();
    backspace();
    PsiDocumentManager.getInstance(getProject()).commitAllDocuments();

    nodes.clear();
    expandNodesTo(root, nodes);
    for (int i = 0; i < nodes.size() - 1; i++) {
      SliceNode node = nodes.get(i);
      assertNull(node.getDuplicate());
    }
    assertNotNull(last.getDuplicate());
  }
  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);
  }
  private void createNameAndReturnTypeEditors() {
    myNameCodeFragment = new GroovyCodeFragment(myProject, "");
    myNameField =
        new EditorTextField(
            PsiDocumentManager.getInstance(myProject).getDocument(myNameCodeFragment),
            myProject,
            myNameCodeFragment.getFileType());

    final JavaCodeFragmentFactory factory = JavaCodeFragmentFactory.getInstance(myProject);
    myReturnTypeCodeFragment =
        factory.createTypeCodeFragment("", myMethod, true, JavaCodeFragmentFactory.ALLOW_VOID);
    final Document document =
        PsiDocumentManager.getInstance(myProject).getDocument(myReturnTypeCodeFragment);
    myReturnTypeField =
        new EditorTextField(document, myProject, myReturnTypeCodeFragment.getFileType());

    myNameField.setText(myMethod.getName());
    final GrTypeElement element = myMethod.getReturnTypeElementGroovy();
    if (element != null) {
      myReturnTypeField.setText(element.getText());
    }

    myReturnTypeLabel = new JLabel();
    myReturnTypeLabel.setLabelFor(myReturnTypeField);

    myNameLabel = new JLabel();
    myNameLabel.setLabelFor(myNameField);
  }
Пример #7
0
    void execute(BrowseMode browseMode) {
      myBrowseMode = browseMode;

      Document document = myEditor.getDocument();
      final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
      if (file == null) return;
      PsiDocumentManager.getInstance(myProject).commitAllDocuments();

      if (EditorUtil.inVirtualSpace(myEditor, myPosition)) {
        return;
      }

      final int offset = myEditor.logicalPositionToOffset(myPosition);

      int selStart = myEditor.getSelectionModel().getSelectionStart();
      int selEnd = myEditor.getSelectionModel().getSelectionEnd();

      if (offset >= selStart && offset < selEnd) return;

      ProgressIndicatorUtils.scheduleWithWriteActionPriority(
          myProgress,
          new ReadTask() {
            @Override
            public void computeInReadAction(@NotNull ProgressIndicator indicator) {
              doExecute(file, offset);
            }

            @Override
            public void onCanceled(@NotNull ProgressIndicator indicator) {}
          });
    }
  private void altCommitToOriginal(@NotNull DocumentEvent e) {
    final PsiFile origPsiFile =
        PsiDocumentManager.getInstance(myProject).getPsiFile(myOrigDocument);
    String newText = myNewDocument.getText();
    // prepare guarded blocks
    LinkedHashMap<String, String> replacementMap = new LinkedHashMap<String, String>();
    int count = 0;
    for (RangeMarker o : ContainerUtil.reverse(((DocumentEx) myNewDocument).getGuardedBlocks())) {
      String replacement = o.getUserData(REPLACEMENT_KEY);
      String tempText = "REPLACE" + (count++) + Long.toHexString(StringHash.calc(replacement));
      newText =
          newText.substring(0, o.getStartOffset()) + tempText + newText.substring(o.getEndOffset());
      replacementMap.put(tempText, replacement);
    }
    // run preformat processors
    final int hostStartOffset = myAltFullRange.getStartOffset();
    myEditor.getCaretModel().moveToOffset(hostStartOffset);
    for (CopyPastePreProcessor preProcessor :
        Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
      newText = preProcessor.preprocessOnPaste(myProject, origPsiFile, myEditor, newText, null);
    }
    myOrigDocument.replaceString(hostStartOffset, myAltFullRange.getEndOffset(), newText);
    // replace temp strings for guarded blocks
    for (String tempText : replacementMap.keySet()) {
      int idx =
          CharArrayUtil.indexOf(
              myOrigDocument.getCharsSequence(),
              tempText,
              hostStartOffset,
              myAltFullRange.getEndOffset());
      myOrigDocument.replaceString(idx, idx + tempText.length(), replacementMap.get(tempText));
    }
    // JAVA: fix occasional char literal concatenation
    fixDocumentQuotes(myOrigDocument, hostStartOffset - 1);
    fixDocumentQuotes(myOrigDocument, myAltFullRange.getEndOffset());

    // reformat
    PsiDocumentManager.getInstance(myProject).commitDocument(myOrigDocument);
    Runnable task =
        () -> {
          try {
            CodeStyleManager.getInstance(myProject)
                .reformatRange(origPsiFile, hostStartOffset, myAltFullRange.getEndOffset(), true);
          } catch (IncorrectOperationException e1) {
            // LOG.error(e);
          }
        };
    DocumentUtil.executeInBulk(myOrigDocument, true, task);

    PsiElement newInjected =
        InjectedLanguageManager.getInstance(myProject)
            .findInjectedElementAt(origPsiFile, hostStartOffset);
    DocumentWindow documentWindow =
        newInjected == null ? null : InjectedLanguageUtil.getDocumentWindow(newInjected);
    if (documentWindow != null) {
      myEditor.getCaretModel().moveToOffset(documentWindow.injectedToHost(e.getOffset()));
      myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    }
  }
Пример #9
0
    public void execute(BrowseMode browseMode) {
      myBrowseMode = browseMode;

      Document document = myEditor.getDocument();
      final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
      if (file == null) return;
      PsiDocumentManager.getInstance(myProject).commitAllDocuments();

      if (TargetElementUtilBase.inVirtualSpace(myEditor, myPosition)) {
        return;
      }

      final int offset = myEditor.logicalPositionToOffset(myPosition);

      int selStart = myEditor.getSelectionModel().getSelectionStart();
      int selEnd = myEditor.getSelectionModel().getSelectionEnd();

      if (offset >= selStart && offset < selEnd) return;

      ApplicationManager.getApplication()
          .executeOnPooledThread(
              new Runnable() {
                public void run() {
                  final ProgressIndicator progressIndicator = new ProgressIndicatorBase();
                  final ApplicationAdapter listener =
                      new ApplicationAdapter() {
                        @Override
                        public void beforeWriteActionStart(Object action) {
                          progressIndicator.cancel();
                        }
                      };
                  final Application application = ApplicationManager.getApplication();
                  try {
                    application.addApplicationListener(listener);
                    ProgressManager.getInstance()
                        .runProcess(
                            new Runnable() {
                              @Override
                              public void run() {
                                // This read action can possibe last for a long time, we want it to
                                // stop immediately on the first write access.
                                // For this purpose we launch it under empty progress and invoke
                                // progressIndicator#cancel on write access to avoid possible write
                                // lock delays.
                                application.runReadAction(
                                    new Runnable() {
                                      public void run() {
                                        doExecute(file, offset);
                                      }
                                    });
                              }
                            },
                            progressIndicator);
                  } finally {
                    application.removeApplicationListener(listener);
                  }
                }
              });
    }
Пример #10
0
  @Nullable
  private KtNamedDeclaration[] getVariables(Expression[] params, ExpressionContext context) {
    if (params.length != 0) return null;

    Project project = context.getProject();
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    PsiFile psiFile =
        PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument());
    if (!(psiFile instanceof KtFile)) return null;

    KtExpression contextExpression = findContextExpression(psiFile, context.getStartOffset());
    if (contextExpression == null) return null;

    ResolutionFacade resolutionFacade = ResolutionUtils.getResolutionFacade(contextExpression);

    BindingContext bindingContext =
        resolutionFacade.analyze(contextExpression, BodyResolveMode.FULL);
    LexicalScope scope =
        ScopeUtils.getResolutionScope(contextExpression, bindingContext, resolutionFacade);

    IterableTypesDetector detector =
        resolutionFacade.getIdeService(IterableTypesDetection.class).createDetector(scope);

    DataFlowInfo dataFlowInfo =
        BindingContextUtilsKt.getDataFlowInfo(bindingContext, contextExpression);

    List<VariableDescriptor> filteredDescriptors = new ArrayList<VariableDescriptor>();
    for (DeclarationDescriptor declarationDescriptor : getAllVariables(scope)) {
      if (declarationDescriptor instanceof VariableDescriptor) {
        VariableDescriptor variableDescriptor = (VariableDescriptor) declarationDescriptor;

        if (variableDescriptor.getExtensionReceiverParameter() != null
            && ExtensionUtils.substituteExtensionIfCallableWithImplicitReceiver(
                    variableDescriptor, scope, bindingContext, dataFlowInfo)
                .isEmpty()) {
          continue;
        }

        if (isSuitable(variableDescriptor, project, detector)) {
          filteredDescriptors.add(variableDescriptor);
        }
      }
    }

    List<KtNamedDeclaration> declarations = new ArrayList<KtNamedDeclaration>();
    for (DeclarationDescriptor declarationDescriptor : filteredDescriptors) {
      PsiElement declaration =
          DescriptorToSourceUtils.descriptorToDeclaration(declarationDescriptor);
      assert declaration == null || declaration instanceof PsiNamedElement;

      if (declaration instanceof KtProperty || declaration instanceof KtParameter) {
        declarations.add((KtNamedDeclaration) declaration);
      }
    }

    return declarations.toArray(new KtNamedDeclaration[declarations.size()]);
  }
  @Override
  protected void processIntention(@NotNull PsiElement element, Project project, Editor editor)
      throws IncorrectOperationException {
    final GrMethodCallExpression expression = (GrMethodCallExpression) element;
    final GrClosableBlock block = expression.getClosureArguments()[0];
    final GrParameterList parameterList = block.getParameterList();
    final GrParameter[] parameters = parameterList.getParameters();

    String var;
    if (parameters.length == 1) {
      var = parameters[0].getText();
      var = StringUtil.replace(var, GrModifier.DEF, "");
    } else {
      var = "it";
    }

    final GrExpression invokedExpression = expression.getInvokedExpression();
    GrExpression qualifier = ((GrReferenceExpression) invokedExpression).getQualifierExpression();
    final GroovyPsiElementFactory elementFactory =
        GroovyPsiElementFactory.getInstance(element.getProject());
    if (qualifier == null) {
      qualifier = elementFactory.createExpressionFromText("this");
    }

    StringBuilder builder = new StringBuilder();
    builder.append("for (").append(var).append(" in ").append(qualifier.getText()).append(") {\n");
    String text = block.getText();
    final PsiElement blockArrow = block.getArrow();
    int index;
    if (blockArrow != null) {
      index = blockArrow.getStartOffsetInParent() + blockArrow.getTextLength();
    } else {
      index = 1;
    }
    while (index < text.length() && Character.isWhitespace(text.charAt(index))) index++;
    text = text.substring(index, text.length() - 1);
    builder.append(text);
    builder.append("}");

    final GrStatement statement = elementFactory.createStatementFromText(builder.toString());
    GrForStatement forStatement = (GrForStatement) expression.replaceWithStatement(statement);
    final GrForClause clause = forStatement.getClause();
    GrVariable variable = clause.getDeclaredVariable();

    forStatement = updateReturnStatements(forStatement);

    if (variable == null) return;

    if (ApplicationManager.getApplication().isUnitTestMode()) return;

    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    final Document doc = documentManager.getDocument(element.getContainingFile());
    if (doc == null) return;

    documentManager.doPostponedOperationsAndUnblockDocument(doc);
    editor.getCaretModel().moveToOffset(variable.getTextOffset());
    new VariableInplaceRenamer(variable, editor).performInplaceRename();
  }
 protected static void bringRealEditorBack() {
   PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
   if (myEditor instanceof EditorWindow) {
     Document document = ((DocumentWindow) myEditor.getDocument()).getDelegate();
     myFile = PsiDocumentManager.getInstance(getProject()).getPsiFile(document);
     myEditor = ((EditorWindow) myEditor).getDelegate();
     myVFile = myFile.getVirtualFile();
   }
 }
 public static void scheduleIndentAdjustment(
     @NotNull Project myProject, @NotNull Document myDocument, int myOffset) {
   IndentAdjusterRunnable fixer = new IndentAdjusterRunnable(myProject, myDocument, myOffset);
   PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
   if (ApplicationManager.getApplication().isUnitTestMode()) {
     documentManager.commitDocument(myDocument);
     fixer.run();
   } else {
     documentManager.performLaterWhenAllCommitted(fixer);
   }
 }
  private CodeFormatterFacade getFormatterFacade(final FileViewProvider viewProvider) {
    final CodeStyleSettings styleSettings =
        CodeStyleSettingsManager.getSettings(myPsiManager.getProject());
    final PsiDocumentManager documentManager =
        PsiDocumentManager.getInstance(myPsiManager.getProject());
    final Document document = viewProvider.getDocument();
    final CodeFormatterFacade codeFormatter = new CodeFormatterFacade(styleSettings);

    documentManager.commitDocument(document);
    return codeFormatter;
  }
 private void commitToOriginalInner() {
   final String text = myNewDocument.getText();
   final Map<
           PsiLanguageInjectionHost,
           Set<Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer>>>
       map =
           ContainerUtil.classify(
               myMarkers.iterator(),
               new Convertor<
                   Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer>,
                   PsiLanguageInjectionHost>() {
                 @Override
                 public PsiLanguageInjectionHost convert(
                     final Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer> o) {
                   final PsiElement element = o.third.getElement();
                   return (PsiLanguageInjectionHost) element;
                 }
               });
   PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
   documentManager.commitDocument(myOrigDocument); // commit here and after each manipulator update
   int localInsideFileCursor = 0;
   for (PsiLanguageInjectionHost host : map.keySet()) {
     if (host == null) continue;
     String hostText = host.getText();
     ProperTextRange insideHost = null;
     StringBuilder sb = new StringBuilder();
     for (Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer> entry : map.get(host)) {
       RangeMarker origMarker = entry.first; // check for validity?
       int hostOffset = host.getTextRange().getStartOffset();
       ProperTextRange localInsideHost =
           new ProperTextRange(
               origMarker.getStartOffset() - hostOffset, origMarker.getEndOffset() - hostOffset);
       RangeMarker rangeMarker = entry.second;
       ProperTextRange localInsideFile =
           new ProperTextRange(
               Math.max(localInsideFileCursor, rangeMarker.getStartOffset()),
               rangeMarker.getEndOffset());
       if (insideHost != null) {
         // append unchanged inter-markers fragment
         sb.append(
             hostText.substring(insideHost.getEndOffset(), localInsideHost.getStartOffset()));
       }
       sb.append(
           localInsideFile.getEndOffset() <= text.length() && !localInsideFile.isEmpty()
               ? localInsideFile.substring(text)
               : "");
       localInsideFileCursor = localInsideFile.getEndOffset();
       insideHost = insideHost == null ? localInsideHost : insideHost.union(localInsideHost);
     }
     assert insideHost != null;
     ElementManipulators.getManipulator(host).handleContentChange(host, insideHost, sb.toString());
     documentManager.commitDocument(myOrigDocument);
   }
 }
 public void formatEveryoneAndCheckIfResultEqual(@NotNull final String... before) {
   assert before.length > 1;
   final PsiFile file = createFile("A.java", "");
   final PsiDocumentManager manager = PsiDocumentManager.getInstance(getProject());
   final Document document = manager.getDocument(file);
   String afterFirst = replaceAndProcessDocument(Action.REFORMAT, before[0], file, document);
   for (String nextBefore : before) {
     assertEquals(
         afterFirst, replaceAndProcessDocument(Action.REFORMAT, nextBefore, file, document));
   }
 }
  @Override
  public void executeWriteAction(Editor editor, DataContext dataContext) {
    final Project project = editor.getProject();
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    final Document document = editor.getDocument();
    PsiFile file = getRoot(documentManager.getPsiFile(document), editor);

    final MoverWrapper mover = getSuitableMover(editor, file);
    if (mover != null) {
      mover.move(editor, file);
    }
  }
  @Nullable
  public static Document getDocumentToBeUsedFor(final PsiFile file) {
    final Project project = file.getProject();
    final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
    if (document == null) return null;
    if (PsiDocumentManager.getInstance(project).isUncommited(document)) return null;
    PsiToDocumentSynchronizer synchronizer =
        ((PsiDocumentManagerImpl) PsiDocumentManager.getInstance(project)).getSynchronizer();
    if (synchronizer.isDocumentAffectedByTransactions(document)) return null;

    return document;
  }
    @Nullable
    private PsiComment createComment(final CharSequence buffer, final CodeInsightSettings settings)
        throws IncorrectOperationException {
      myDocument.insertString(myOffset, buffer);

      PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
      CodeStyleManager.getInstance(getProject())
          .adjustLineIndent(myFile, myOffset + buffer.length() - 2);

      PsiComment comment =
          PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class);

      comment = createJavaDocStub(settings, comment, getProject());
      if (comment == null) {
        return null;
      }

      CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(getProject());
      CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject());
      boolean old = codeStyleSettings.ENABLE_JAVADOC_FORMATTING;
      codeStyleSettings.ENABLE_JAVADOC_FORMATTING = false;

      try {
        comment = (PsiComment) codeStyleManager.reformat(comment);
      } finally {
        codeStyleSettings.ENABLE_JAVADOC_FORMATTING = old;
      }
      PsiElement next = comment.getNextSibling();
      if (next == null && comment.getParent().getClass() == comment.getClass()) {
        next =
            comment
                .getParent()
                .getNextSibling(); // expanding chameleon comment produces comment under comment
      }
      if (next != null) {
        next =
            myFile.findElementAt(
                next.getTextRange().getStartOffset()); // maybe switch to another tree
      }
      if (next != null
          && (!FormatterUtil.containsWhiteSpacesOnly(next.getNode())
              || !next.getText().contains(LINE_SEPARATOR))) {
        int lineBreakOffset = comment.getTextRange().getEndOffset();
        myDocument.insertString(lineBreakOffset, LINE_SEPARATOR);
        PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
        codeStyleManager.adjustLineIndent(myFile, lineBreakOffset + 1);
        comment =
            PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class);
      }
      return comment;
    }
 public static void updateDocumentIndentOptions(
     @NotNull Project project, @NotNull Document document) {
   if (!project.isDisposed()) {
     PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
     if (documentManager != null) {
       PsiFile file = documentManager.getPsiFile(document);
       if (file != null) {
         CommonCodeStyleSettings.IndentOptions indentOptions =
             getSettings(project).getIndentOptionsByFile(file, true);
         indentOptions.associateWithDocument(document);
       }
     }
   }
 }
 public void doTextTest(
     @NotNull final Action action, @NotNull String text, @NotNull String textAfter)
     throws IncorrectOperationException {
   final PsiFile file = createFile("A.java", text);
   final PsiDocumentManager manager = PsiDocumentManager.getInstance(getProject());
   final Document document = manager.getDocument(file);
   if (document == null) {
     fail("Document is null");
     return;
   }
   replaceAndProcessDocument(action, text, file, document);
   assertEquals(textAfter, document.getText());
   manager.commitDocument(document);
   assertEquals(textAfter, file.getText());
 }
 @Nullable
 private static PsiFile getPsiFile(@Nullable Project project, @NotNull Document document) {
   if (project != null) {
     PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
     if (documentManager.isCommitted(document)) {
       return documentManager.getCachedPsiFile(document);
     }
   } else {
     VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
     LOG.warn(
         "No current project is given, trailing spaces will be stripped later (postponed). File: "
             + (virtualFile != null ? virtualFile.getCanonicalPath() : "undefined"));
   }
   return null;
 }
  private void queueElement(
      @NotNull PsiElement child,
      final boolean whitespaceOptimizationAllowed,
      @NotNull PsiTreeChangeEvent event) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    PsiFile file = event.getFile();
    if (file == null) file = child.getContainingFile();
    if (file == null) {
      myFileStatusMap.markAllFilesDirty(child);
      return;
    }

    if (!child.isValid()) return;

    PsiDocumentManagerImpl pdm = (PsiDocumentManagerImpl) PsiDocumentManager.getInstance(myProject);
    Document document = pdm.getCachedDocument(file);
    if (document != null) {
      if (pdm.getSynchronizer().getTransaction(document) == null) {
        // content reload, language level change or some other big change
        myFileStatusMap.markAllFilesDirty(child);
        return;
      }

      List<Pair<PsiElement, Boolean>> toUpdate = changedElements.get(document);
      if (toUpdate == null) {
        toUpdate = new SmartList<>();
        changedElements.put(document, toUpdate);
      }
      toUpdate.add(Pair.create(child, whitespaceOptimizationAllowed));
    }
  }
Пример #24
0
 private static LineRange expandLineRangeToCoverPsiElements(
     final LineRange range, Editor editor, final PsiFile file) {
   Pair<PsiElement, PsiElement> psiRange = getElementRange(editor, file, range);
   if (psiRange == null) return null;
   final PsiElement parent =
       PsiTreeUtil.findCommonParent(psiRange.getFirst(), psiRange.getSecond());
   Pair<PsiElement, PsiElement> elementRange =
       getElementRange(parent, psiRange.getFirst(), psiRange.getSecond());
   if (elementRange == null) return null;
   int endOffset = elementRange.getSecond().getTextRange().getEndOffset();
   Document document = editor.getDocument();
   if (endOffset > document.getTextLength()) {
     LOG.assertTrue(!PsiDocumentManager.getInstance(file.getProject()).isUncommited(document));
     LOG.assertTrue(PsiDocumentManagerImpl.checkConsistency(file, document));
   }
   int endLine;
   if (endOffset == document.getTextLength()) {
     endLine = document.getLineCount();
   } else {
     endLine = editor.offsetToLogicalPosition(endOffset).line + 1;
     endLine = Math.min(endLine, document.getLineCount());
   }
   int startLine =
       Math.min(
           range.startLine,
           editor.offsetToLogicalPosition(elementRange.getFirst().getTextOffset()).line);
   endLine = Math.max(endLine, range.endLine);
   return new LineRange(startLine, endLine);
 }
 @Nullable
 private static PsiElement getSelectedPsiElement(
     final DataContext dataContext, final Project project) {
   PsiElement element = null;
   final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
   if (editor != null) {
     final PsiFile psiFile =
         PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
     if (psiFile != null) {
       final int offset = editor.getCaretModel().getOffset();
       element = psiFile.findElementAt(offset);
       if (element == null && offset > 0 && offset == psiFile.getTextLength()) {
         element = psiFile.findElementAt(offset - 1);
       }
     }
   }
   if (element == null) {
     final PsiElement[] elements = LangDataKeys.PSI_ELEMENT_ARRAY.getData(dataContext);
     element = elements != null && elements.length > 0 ? elements[0] : null;
   }
   if (element == null) {
     final VirtualFile[] files = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext);
     if (files != null && files.length > 0) {
       element = PsiManager.getInstance(project).findFile(files[0]);
     }
   }
   return element;
 }
  public void invoke(
      @NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    final LookupEx lookup = LookupManagerImpl.getActiveLookup(editor);
    if (lookup != null) {
      lookup.showElementActions();
      return;
    }

    if (HintManagerImpl.getInstanceImpl().performCurrentQuestionAction()) return;

    // intentions check isWritable before modification: if (!file.isWritable()) return;
    if (file instanceof PsiCodeFragment) return;

    TemplateState state = TemplateManagerImpl.getTemplateState(editor);
    if (state != null && !state.isFinished()) {
      return;
    }

    final DaemonCodeAnalyzerImpl codeAnalyzer =
        (DaemonCodeAnalyzerImpl) DaemonCodeAnalyzer.getInstance(project);
    codeAnalyzer.autoImportReferenceAtCursor(editor, file); // let autoimport complete

    ShowIntentionsPass.IntentionsInfo intentions = new ShowIntentionsPass.IntentionsInfo();
    ShowIntentionsPass.getActionsToShow(editor, file, intentions, -1);

    if (!intentions.isEmpty()) {
      IntentionHintComponent.showIntentionHint(project, file, editor, intentions, true);
    }
  }
Пример #27
0
  public static TextWithImports getEditorText(final Editor editor) {
    if (editor == null) {
      return null;
    }
    final Project project = editor.getProject();
    if (project == null) return null;

    String defaultExpression = editor.getSelectionModel().getSelectedText();
    if (defaultExpression == null) {
      int offset = editor.getCaretModel().getOffset();
      PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      if (psiFile != null) {
        PsiElement elementAtCursor = psiFile.findElementAt(offset);
        if (elementAtCursor != null) {
          final EditorTextProvider textProvider =
              EditorTextProvider.EP.forLanguage(elementAtCursor.getLanguage());
          if (textProvider != null) {
            final TextWithImports editorText = textProvider.getEditorText(elementAtCursor);
            if (editorText != null) return editorText;
          }
        }
      }
    } else {
      return new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, defaultExpression);
    }
    return null;
  }
  private boolean getStringToReplace(
      int textOffset,
      int textEndOffset,
      Document document,
      FindModel findModel,
      Ref<String> stringToReplace)
      throws FindManager.MalformedReplacementStringException {
    if (textOffset < 0 || textOffset >= document.getTextLength()) {
      return false;
    }
    if (textEndOffset < 0 || textOffset > document.getTextLength()) {
      return false;
    }
    FindManager findManager = FindManager.getInstance(myProject);
    final CharSequence foundString =
        document.getCharsSequence().subSequence(textOffset, textEndOffset);
    PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
    FindResult findResult =
        findManager.findString(
            document.getCharsSequence(),
            textOffset,
            findModel,
            file != null ? file.getVirtualFile() : null);
    if (!findResult.isStringFound()) {
      return false;
    }

    stringToReplace.set(
        FindManager.getInstance(myProject)
            .getStringToReplace(foundString.toString(), findModel, textOffset, document.getText()));

    return true;
  }
  protected void doTest(final PerformAction performAction, final String testName) throws Exception {
    String path = getTestDataPath() + getTestRoot() + testName;

    String pathBefore = path + "/before";
    final VirtualFile rootDir =
        PsiTestUtil.createTestProjectStructure(
            myProject, myModule, pathBefore, myFilesToDelete, false);
    prepareProject(rootDir);
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    String pathAfter = path + "/after";
    final VirtualFile rootAfter =
        LocalFileSystem.getInstance().findFileByPath(pathAfter.replace(File.separatorChar, '/'));

    performAction.performAction(rootDir, rootAfter);
    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
              }
            });

    FileDocumentManager.getInstance().saveAllDocuments();

    if (myDoCompare) {
      PlatformTestUtil.assertDirectoriesEqual(rootAfter, rootDir);
    }
  }
  private CompletionInitializationContext runContributorsBeforeCompletion(
      Editor editor, PsiFile psiFile, int invocationCount, Caret caret) {
    final Ref<CompletionContributor> current = Ref.create(null);
    CompletionInitializationContext context =
        new CompletionInitializationContext(
            editor, caret, psiFile, myCompletionType, invocationCount) {
          CompletionContributor dummyIdentifierChanger;

          @Override
          public void setDummyIdentifier(@NotNull String dummyIdentifier) {
            super.setDummyIdentifier(dummyIdentifier);

            if (dummyIdentifierChanger != null) {
              LOG.error(
                  "Changing the dummy identifier twice, already changed by "
                      + dummyIdentifierChanger);
            }
            dummyIdentifierChanger = current.get();
          }
        };
    List<CompletionContributor> contributors =
        CompletionContributor.forLanguage(context.getPositionLanguage());
    Project project = psiFile.getProject();
    List<CompletionContributor> filteredContributors =
        DumbService.getInstance(project).filterByDumbAwareness(contributors);
    for (final CompletionContributor contributor : filteredContributors) {
      current.set(contributor);
      contributor.beforeCompletion(context);
      CompletionAssertions.checkEditorValid(editor);
      assert !PsiDocumentManager.getInstance(project).isUncommited(editor.getDocument())
          : "Contributor " + contributor + " left the document uncommitted";
    }
    return context;
  }