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);
  }
예제 #2
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) {}
          });
    }
예제 #3
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());
  }
예제 #4
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);
                  }
                }
              });
    }
  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);
    }
  }
    @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;
    }
  protected void doTest(final String extension) throws Exception {
    CommandProcessor.getInstance()
        .executeCommand(
            getProject(),
            () ->
                WriteCommandAction.runWriteCommandAction(
                    null,
                    () -> {
                      String fileName = getTestName(false) + extension;
                      try {
                        String text = loadFile(fileName);
                        PsiFile file = createFile(fileName, text);

                        JavaCodeStyleManager.getInstance(myProject).optimizeImports(file);
                        PostprocessReformattingAspect.getInstance(getProject())
                            .doPostponedFormatting();
                        PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
                        String textAfter = loadFile(getTestName(false) + "_after" + extension);
                        String fileText = file.getText();
                        assertEquals(textAfter, fileText);
                      } catch (Exception e) {
                        LOG.error(e);
                      }
                    }),
            "",
            "");
  }
  private Collection<AbstractTreeNode> createGeneralList() {
    ArrayList<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>();

    PsiFile psiFile = getValue();
    final TodoItem[] items =
        findAllTodos(psiFile, myBuilder.getTodoTreeStructure().getSearchHelper());
    final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(psiFile);

    if (document != null) {
      for (final TodoItem todoItem : items) {
        if (todoItem.getTextRange().getEndOffset() < document.getTextLength() + 1) {
          final SmartTodoItemPointer pointer = new SmartTodoItemPointer(todoItem, document);
          TodoFilter todoFilter = getToDoFilter();
          if (todoFilter != null) {
            if (todoFilter.contains(todoItem.getPattern())) {
              children.add(new TodoItemNode(getProject(), pointer, myBuilder));
            }
          } else {
            children.add(new TodoItemNode(getProject(), pointer, myBuilder));
          }
        }
      }
    }
    Collections.sort(children, SmartTodoItemPointerComparator.ourInstance);
    return children;
  }
예제 #9
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
  public PsiElement getSubstituted() {
    if (mySubstituted != null && mySubstituted.isValid()) {
      if (mySubstituted instanceof PsiNameIdentifierOwner) {
        if (Comparing.strEqual(myOldName, ((PsiNameIdentifierOwner) mySubstituted).getName()))
          return mySubstituted;

        final RangeMarker rangeMarker =
            mySubstitutedRange != null ? mySubstitutedRange : myRenameOffset;
        if (rangeMarker != null)
          return PsiTreeUtil.getParentOfType(
              mySubstituted.getContainingFile().findElementAt(rangeMarker.getStartOffset()),
              PsiNameIdentifierOwner.class);
      }
      return mySubstituted;
    }
    if (mySubstitutedRange != null) {
      final PsiFile psiFile =
          PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
      if (psiFile != null) {
        return PsiTreeUtil.getParentOfType(
            psiFile.findElementAt(mySubstitutedRange.getStartOffset()),
            PsiNameIdentifierOwner.class);
      }
    }
    return getVariable();
  }
  public void testAddSourceRoot() throws Exception {
    File dir = createTempDirectory();

    final VirtualFile root =
        LocalFileSystem.getInstance()
            .refreshAndFindFileByPath(dir.getCanonicalPath().replace(File.separatorChar, '/'));

    new WriteCommandAction.Simple(getProject()) {
      @Override
      protected void run() throws Throwable {
        PsiTestUtil.addContentRoot(myModule, root);

        VirtualFile newFile = createChildData(root, "New.java");
        setFileText(newFile, "class A{ Exception e;} //todo");
      }
    }.execute().throwException();

    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiTodoSearchHelper.SERVICE
        .getInstance(myProject)
        .findFilesWithTodoItems(); // to initialize caches

    PsiTestUtil.addSourceRoot(myModule, root);

    PsiClass exceptionClass =
        myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject()));
    assertNotNull(exceptionClass);
    checkUsages(exceptionClass, new String[] {"1.java", "2.java", "New.java"});
    checkTodos(new String[] {"2.java", "New.java"});
  }
  public void testSCR6066() throws Exception {
    ProjectRootManagerEx rootManager =
        (ProjectRootManagerEx) ProjectRootManager.getInstance(myProject);
    final VirtualFile root = rootManager.getContentRoots()[0];

    PsiTodoSearchHelper.SERVICE
        .getInstance(myProject)
        .findFilesWithTodoItems(); // to initialize caches

    new WriteCommandAction.Simple(getProject()) {
      @Override
      protected void run() throws Throwable {
        VirtualFile newFile = createChildData(root, "New.java");
        setFileText(newFile, "class A{ Exception e;} //todo");
      }
    }.execute().throwException();

    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiTodoSearchHelper.SERVICE.getInstance(myProject).findFilesWithTodoItems(); // to update caches

    PsiTestUtil.addExcludedRoot(myModule, root);

    PsiClass exceptionClass =
        myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject()));
    assertNotNull(exceptionClass);
    checkUsages(exceptionClass, new String[] {});
    checkTodos(new String[] {});
  }
  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);
        }
      }
    }
  }
예제 #14
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;
  }
예제 #15
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);
    }
  }
  private static PsiDirectory[] suggestMostAppropriateDirectories(PsiPackage psiPackage) {
    final Project project = psiPackage.getProject();
    PsiDirectory[] directories = null;
    final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
    if (editor != null) {
      final Document document = editor.getDocument();
      final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
      if (psiFile != null) {
        final Module module = ModuleUtil.findModuleForPsiElement(psiFile);
        if (module != null) {
          directories =
              psiPackage.getDirectories(GlobalSearchScope.moduleWithDependenciesScope(module));
        } else {
          directories =
              psiPackage.getDirectories(
                  GlobalSearchScope.notScope(GlobalSearchScope.projectScope(project)));
        }
      }
    }

    if (directories == null || directories.length == 0) {
      directories = psiPackage.getDirectories();
    }
    return directories;
  }
  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));
    }
  }
예제 #18
0
 @NotNull
 @Override
 public PsiFile getContext() {
   final PsiFile psiFile =
       PsiDocumentManager.getInstance(getProject()).getPsiFile(myFilePanel.getDocument());
   return psiFile != null ? psiFile : super.getOriginalFile();
 }
  public void testRemoveSourceRoot() {
    final VirtualFile root = ModuleRootManager.getInstance(myModule).getContentRoots()[0];

    PsiTodoSearchHelper.SERVICE
        .getInstance(myProject)
        .findFilesWithTodoItems(); // to initialize caches

    new WriteCommandAction.Simple(getProject()) {
      @Override
      protected void run() throws Throwable {
        VirtualFile newFile = createChildData(root, "New.java");
        setFileText(newFile, "class A{ Exception e;} //todo");
      }
    }.execute().throwException();

    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiTodoSearchHelper.SERVICE.getInstance(myProject).findFilesWithTodoItems(); // to update caches

    VirtualFile[] sourceRoots = ModuleRootManager.getInstance(myModule).getSourceRoots();
    LOG.assertTrue(sourceRoots.length == 1);
    PsiTestUtil.removeSourceRoot(myModule, sourceRoots[0]);

    PsiClass exceptionClass =
        myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject()));
    assertNotNull(exceptionClass);
    // currently it actually finds usages by FQN due to Java PSI enabled for out-of-source java
    // files
    // so the following check is disabled
    // checkUsages(exceptionClass, new String[]{});
    checkTodos(new String[] {"2.java", "New.java"});
  }
 public void invoke(Project project, PsiExpression[] expressions) {
   for (PsiExpression expression : expressions) {
     final PsiFile file = expression.getContainingFile();
     if (!CommonRefactoringUtil.checkReadOnlyStatus(project, file)) return;
   }
   PsiDocumentManager.getInstance(project).commitAllDocuments();
   super.invoke(project, expressions, null);
 }
 @Override
 protected SearchScope getReferencesSearchScope(VirtualFile file) {
   PsiFile currentFile =
       PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
   return currentFile != null
       ? new LocalSearchScope(currentFile)
       : ProjectScope.getProjectScope(myProject);
 }
 public boolean canMoveTo(SourcePosition position) {
   if (!super.canMoveTo(position)) {
     return false;
   }
   final Document document =
       PsiDocumentManager.getInstance(getProject()).getDocument(position.getFile());
   return canAddLineBreakpoint(myProject, document, position.getLine());
 }
  public void invoke(
      @NotNull final Project project, final Editor editor, PsiFile file, DataContext dataContext) {
    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, file)) return;

    PsiDocumentManager.getInstance(project).commitAllDocuments();
    ElementToWorkOn.processElementToWorkOn(
        editor, file, REFACTORING_NAME, getHelpID(), project, getElementProcessor(project, editor));
  }
  public static void renameNonCodeUsages(
      @NotNull Project project, @NotNull NonCodeUsageInfo[] usages) {
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    Map<Document, List<UsageOffset>> docsToOffsetsMap = new HashMap<Document, List<UsageOffset>>();
    final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    for (NonCodeUsageInfo usage : usages) {
      PsiElement element = usage.getElement();

      if (element == null) continue;
      element = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(element, true);
      if (element == null) continue;

      final ProperTextRange rangeInElement = usage.getRangeInElement();
      if (rangeInElement == null) continue;

      final PsiFile containingFile = element.getContainingFile();
      final Document document = psiDocumentManager.getDocument(containingFile);

      final Segment segment = usage.getSegment();
      LOG.assertTrue(segment != null);
      int fileOffset = segment.getStartOffset();

      List<UsageOffset> list = docsToOffsetsMap.get(document);
      if (list == null) {
        list = new ArrayList<UsageOffset>();
        docsToOffsetsMap.put(document, list);
      }

      list.add(new UsageOffset(fileOffset, fileOffset + rangeInElement.getLength(), usage.newText));
    }

    for (Document document : docsToOffsetsMap.keySet()) {
      List<UsageOffset> list = docsToOffsetsMap.get(document);
      LOG.assertTrue(list != null, document);
      UsageOffset[] offsets = list.toArray(new UsageOffset[list.size()]);
      Arrays.sort(offsets);

      for (int i = offsets.length - 1; i >= 0; i--) {
        UsageOffset usageOffset = offsets[i];
        document.replaceString(usageOffset.startOffset, usageOffset.endOffset, usageOffset.newText);
      }
      PsiDocumentManager.getInstance(project).commitDocument(document);
    }
    PsiDocumentManager.getInstance(project).commitAllDocuments();
  }
  @Override
  public void invoke(
      @NotNull final Project project, @NotNull Editor editor, @NotNull PsiFile file) {
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    DumbService.getInstance(project).setAlternativeResolveEnabled(true);
    try {
      int offset = editor.getCaretModel().getOffset();
      PsiElement[] elements =
          underModalProgress(
              project,
              "Resolving Reference...",
              () -> findAllTargetElements(project, editor, offset));
      FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.goto.declaration");

      if (elements.length != 1) {
        if (elements.length == 0
            && suggestCandidates(TargetElementUtil.findReference(editor, offset)).isEmpty()) {
          PsiElement element =
              findElementToShowUsagesOf(editor, editor.getCaretModel().getOffset());
          if (startFindUsages(editor, element)) {
            return;
          }

          // disable 'no declaration found' notification for keywords
          final PsiElement elementAtCaret = file.findElementAt(offset);
          if (elementAtCaret != null) {
            final NamesValidator namesValidator =
                LanguageNamesValidation.INSTANCE.forLanguage(elementAtCaret.getLanguage());
            if (namesValidator != null
                && namesValidator.isKeyword(elementAtCaret.getText(), project)) {
              return;
            }
          }
        }
        chooseAmbiguousTarget(editor, offset, elements, file);
        return;
      }

      PsiElement element = elements[0];
      if (element == findElementToShowUsagesOf(editor, editor.getCaretModel().getOffset())
          && startFindUsages(editor, element)) {
        return;
      }

      PsiElement navElement = element.getNavigationElement();
      navElement = TargetElementUtil.getInstance().getGotoDeclarationTarget(element, navElement);
      if (navElement != null) {
        gotoTargetElement(navElement, editor, file);
      }
    } catch (IndexNotReadyException e) {
      DumbService.getInstance(project)
          .showDumbModeNotification("Navigation is not available here during index update");
    } finally {
      DumbService.getInstance(project).setAlternativeResolveEnabled(false);
    }
  }
 @Override
 protected boolean notSameFile(@Nullable VirtualFile file, @NotNull PsiFile containingFile) {
   final PsiFile currentFile =
       PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
   if (currentFile == null) return true;
   InjectedLanguageManager manager =
       InjectedLanguageManager.getInstance(containingFile.getProject());
   return manager.getTopLevelFile(containingFile) != manager.getTopLevelFile(currentFile);
 }
 @Override
 protected PsiElement checkLocalScope() {
   PsiFile currentFile =
       PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
   if (currentFile != null) {
     return currentFile;
   }
   return super.checkLocalScope();
 }
  final boolean isValidBase() {
    if (PsiDocumentManager.getInstance(myProject).getUncommittedDocuments().length > 0) {
      return myCachedIsValidBase;
    }

    final PsiElement element = mySmartPsiElementPointer.getElement();
    myCachedIsValidBase = element != null && isApplicableElement(element) && element.isValid();
    return myCachedIsValidBase;
  }
 @Override
 public int injectedToHost(@NotNull PsiElement element, int offset) {
   PsiFile file = element.getContainingFile();
   if (file == null) return offset;
   Document document = PsiDocumentManager.getInstance(file.getProject()).getCachedDocument(file);
   if (!(document instanceof DocumentWindowImpl)) return offset;
   DocumentWindowImpl documentWindow = (DocumentWindowImpl) document;
   return documentWindow.injectedToHost(offset);
 }
 @Override
 public void reparseRange(PsiFile file, int startOffset, int endOffset, CharSequence newTextS)
     throws IncorrectOperationException {
   LOG.assertTrue(file.isValid());
   final PsiFileImpl psiFile = (PsiFileImpl) file;
   final Document document = psiFile.getViewProvider().getDocument();
   assert document != null;
   document.replaceString(startOffset, endOffset, newTextS);
   PsiDocumentManager.getInstance(psiFile.getProject()).commitDocument(document);
 }