Java 类com.intellij.psi.PsiDocumentManager 实例源码

项目:reasonml-idea-plugin    文件:RefmtAction.java   
@Override
public void actionPerformed(AnActionEvent e) {
    RefmtManager refmt = RefmtManager.getInstance();
    if (refmt != null) {
        PsiFile file = e.getData(PSI_FILE);
        Project project = e.getProject();
        if (project != null && file != null && (file instanceof OclFile || file instanceof RmlFile)) {
            String format = file instanceof OclFile ? "ml" : "re";
            Document document = PsiDocumentManager.getInstance(project).getDocument(file);
            if (document != null) {
                //WriteCommandAction.writeCommandAction(project).run(() -> refmt.refmt(project, format, document));
                WriteCommandAction.runWriteCommandAction(project, () -> refmt.refmt(project, format, document)); // idea#143
            }
        }
    }
}
项目:bamboo-soy    文件:ClosingTagHandler.java   
public void execute(@NotNull Editor editor, char charTyped, @NotNull DataContext dataContext) {
  myOriginalHandler.execute(editor, charTyped, dataContext);
  if (isMatchForClosingTag(editor, charTyped)) {
    int offset = editor.getCaretModel().getOffset();
    PsiFile file = dataContext.getData(LangDataKeys.PSI_FILE);
    if (file == null) {
      return;
    }
    PsiElement el = file.findElementAt(offset - 1);
    TagBlockElement block = (TagBlockElement) PsiTreeUtil
        .findFirstParent(el,
            parent -> parent instanceof TagBlockElement && !(parent instanceof SoyChoiceClause));
    if (block == null) {
      return;
    }
    String closingTag = block.getOpeningTag().generateClosingTag();
    insertClosingTag(editor, offset, closingTag);
    if (editor.getProject() != null) {
      PsiDocumentManager.getInstance(editor.getProject()).commitDocument(editor.getDocument());
      CodeStyleManager.getInstance(editor.getProject()).reformat(block);
    }
  }
}
项目:intellij-csv-validator    文件:CsvValidationInspection.java   
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    try {
        PsiElement element = descriptor.getPsiElement();
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        List<Integer> quotePositions = new ArrayList<>();

        int quotePosition = CsvIntentionHelper.getOpeningQuotePosition(element);
        if (quotePosition != -1) {
            quotePositions.add(quotePosition);
        }
        PsiElement endSeparatorElement = CsvIntentionHelper.findQuotePositionsUntilSeparator(element, quotePositions);
        if (endSeparatorElement == null) {
            quotePositions.add(document.getTextLength());
        } else {
            quotePositions.add(endSeparatorElement.getTextOffset());
        }
        String text = CsvIntentionHelper.addQuotes(document.getText(), quotePositions);
        document.setText(text);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
项目:intellij-csv-validator    文件:CsvIntentionHelper.java   
public static void unquoteAll(@NotNull Project project, @NotNull PsiFile psiFile) {
    try {
        Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
        List<Integer> quotePositions = new ArrayList<>();
        Collection<PsiElement> fields = getAllFields(psiFile);
        for (PsiElement field : fields) {
            if (getChildren(field).stream().anyMatch(element -> getElementType(element) == CsvTypes.ESCAPED_TEXT)) {
                continue;
            }
            if (getElementType(field.getFirstChild()) == CsvTypes.QUOTE) {
                quotePositions.add(field.getFirstChild().getTextOffset());
            }
            if (getElementType(field.getLastChild()) == CsvTypes.QUOTE) {
                quotePositions.add(field.getLastChild().getTextOffset());
            }
        }
        String text = removeQuotes(document.getText(), quotePositions);
        document.setText(text);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
项目:intellij-csv-validator    文件:CsvIntentionHelper.java   
public static void quoteValue(@NotNull Project project, @NotNull PsiElement element) {
    try {
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        List<Integer> quotePositions = new ArrayList<>();

        element = getParentFieldElement(element);
        int quotePosition = getOpeningQuotePosition(element.getFirstChild(), element.getLastChild());
        if (quotePosition != -1) {
            quotePositions.add(quotePosition);
        }
        PsiElement endSeparatorElement = findQuotePositionsUntilSeparator(element, quotePositions);
        if (endSeparatorElement == null) {
            quotePositions.add(document.getTextLength());
        } else {
            quotePositions.add(endSeparatorElement.getTextOffset());
        }
        String text = addQuotes(document.getText(), quotePositions);
        document.setText(text);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
项目:intellij-csv-validator    文件:CsvIntentionHelper.java   
public static void unquoteValue(@NotNull Project project, @NotNull PsiElement element) {
    try {
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        List<Integer> quotePositions = new ArrayList<>();

        element = getParentFieldElement(element);
        if (getElementType(element.getFirstChild()) == CsvTypes.QUOTE) {
            quotePositions.add(element.getFirstChild().getTextOffset());
        }
        if (getElementType(element.getLastChild()) == CsvTypes.QUOTE) {
            quotePositions.add(element.getLastChild().getTextOffset());
        }
        String text = removeQuotes(document.getText(), quotePositions);
        document.setText(text);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
项目:intellij-ce-playground    文件:CopyElementAction.java   
protected void updateForEditor(DataContext dataContext, Presentation presentation) {
  Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
  if (editor == null) {
    presentation.setVisible(false);
    return;
  }

  Project project = CommonDataKeys.PROJECT.getData(dataContext);
  if (project == null) {
    return;

  }
  PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());

  PsiElement element = getTargetElement(editor, project);
  boolean result = element != null && CopyHandler.canCopy(new PsiElement[]{element});

  if (!result && file != null) {
    result = CopyHandler.canCopy(new PsiElement[]{file});
  }

  presentation.setEnabled(result);
  presentation.setVisible(true);
}
项目:intellij-ce-playground    文件:ShowReformatFileDialog.java   
@Override
public void actionPerformed(AnActionEvent event) {
  Presentation presentation = event.getPresentation();
  DataContext dataContext = event.getDataContext();
  Project project = CommonDataKeys.PROJECT.getData(dataContext);
  Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
  if (project == null || editor == null) {
    presentation.setEnabled(false);
    return;
  }

  PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  if (file == null || file.getVirtualFile() == null) {
    presentation.setEnabled(false);
    return;
  }

  boolean hasSelection = editor.getSelectionModel().hasSelection();
  LayoutCodeDialog dialog = new LayoutCodeDialog(project, file, hasSelection, HELP_ID);
  dialog.show();

  if (dialog.isOK()) {
    new FileInEditorProcessor(file, editor, dialog.getRunOptions()).processCode();
  }
}
项目:intellij-ce-playground    文件:PerFileMappingsBase.java   
private void handleMappingChange(Collection<VirtualFile> files, Collection<VirtualFile> oldFiles, boolean includeOpenFiles) {
  Project project = getProject();
  FilePropertyPusher<T> pusher = getFilePropertyPusher();
  if (project != null && pusher != null) {
    for (VirtualFile oldFile : oldFiles) {
      if (oldFile == null) continue; // project
      oldFile.putUserData(pusher.getFileDataKey(), null);
    }
    if (!project.isDefault()) {
      PushedFilePropertiesUpdater.getInstance(project).pushAll(pusher);
    }
  }
  if (shouldReparseFiles()) {
    Project[] projects = project == null ? ProjectManager.getInstance().getOpenProjects() : new Project[] { project };
    for (Project p : projects) {
      PsiDocumentManager.getInstance(p).reparseFiles(files, includeOpenFiles);
    }
  }
}
项目:cs-intellij-plugin    文件:ExecutableAnnotator.java   
private void createErrorAnnotations(PsiElement element, PsiFile file, AnnotationHolder holder, List<RuntimeException> annotationResult) {
    Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
    if (document == null) {
        return;
    }
    PsiElement psiElementWithError = element;
    for (RuntimeException exception : annotationResult) {
        if (exception instanceof LocatedRuntimeException) {
            LocatedRuntimeException locatedException = (LocatedRuntimeException) exception;
            PsiElement childAtLine = file.findElementAt(document.getLineStartOffset(locatedException.getLineNumber() - 1));
            if (childAtLine != null) {
                psiElementWithError = childAtLine;
            }
        }
        holder.createErrorAnnotation(psiElementWithError, exception.getMessage());
    }
}
项目:intellij-ce-playground    文件:PsiAwareTextEditorProvider.java   
@Override
protected void setStateImpl(final Project project, final Editor editor, final TextEditorState state) {
  super.setStateImpl(project, editor, state);
  // Folding
  final CodeFoldingState foldState = state.getFoldingState();
  if (project != null && foldState != null) {
    new WriteAction() {
      @Override
      protected void run(@NotNull Result result) throws Throwable {
        PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
        editor.getFoldingModel().runBatchFoldingOperation(
          new Runnable() {
            @Override
            public void run() {
              CodeFoldingManager.getInstance(project).restoreFoldingState(editor, foldState);
            }
          }
        );
      }
    }.execute();
  }
}
项目:intellij-ce-playground    文件:TextEditorBackgroundHighlighter.java   
@NotNull
List<TextEditorHighlightingPass> getPasses(@NotNull int[] passesToIgnore) {
  if (myProject.isDisposed()) return Collections.emptyList();
  PsiDocumentManager.getInstance(myProject).commitAllDocuments();
  renewFile();
  if (myFile == null) return Collections.emptyList();
  if (myCompiled) {
    passesToIgnore = EXCEPT_OVERRIDDEN;
  }
  else if (!DaemonCodeAnalyzer.getInstance(myProject).isHighlightingAvailable(myFile)) {
    return Collections.emptyList();
  }

  TextEditorHighlightingPassRegistrarEx passRegistrar = TextEditorHighlightingPassRegistrarEx.getInstanceEx(myProject);

  return passRegistrar.instantiatePasses(myFile, myEditor, passesToIgnore);
}
项目:intellij-ce-playground    文件:InspectionDescriptionLinkHandler.java   
@Override
public String getDescription(@NotNull final String refSuffix, @NotNull final Editor editor) {
  final Project project = editor.getProject();
  if (project == null) {
    LOG.error(editor);
    return null;
  }
  if (project.isDisposed()) return null;
  final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  if (file == null) {
    return null;
  }

  final InspectionProfile profile = (InspectionProfile)InspectionProfileManager.getInstance().getRootProfile();
  final InspectionToolWrapper toolWrapper = profile.getInspectionTool(refSuffix, file);
  if (toolWrapper == null) return null;

  String description = toolWrapper.loadDescription();
  if (description == null) {
    LOG.warn("No description for inspection '" + refSuffix + "'");
    description = InspectionsBundle.message("inspection.tool.description.under.construction.text");
  }
  return description;
}
项目:intellij-ce-playground    文件:StructuralSearchAction.java   
public static void triggerAction(Configuration config, SearchContext searchContext) {
  final Project project = searchContext.getProject();
  if (project == null) {
    return;
  }
  PsiDocumentManager.getInstance(project).commitAllDocuments();

  //StructuralSearchPlugin.getInstance(searchContext.getProject());
  final SearchDialog searchDialog = new SearchDialog(searchContext);

  if (config!=null) {
    searchDialog.setUseLastConfiguration(true);
    searchDialog.setValuesFromConfig(config);
  }

  searchDialog.show();
}
项目:MultiTypeTemplates    文件:CreateItemFilesAction.java   
private void onProcessItemViewBinder(final PsiDirectory dir, final String typeName, final PsiClass itemClass) {
    PsiFile file = itemClass.getContainingFile();
    final PsiDocumentManager manager = PsiDocumentManager.getInstance(itemClass.getProject());
    final Document document = manager.getDocument(file);
    if (document == null) {
        return;
    }

    new WriteCommandAction.Simple(itemClass.getProject()) {
        @Override
        protected void run() throws Throwable {
            manager.doPostponedOperationsAndUnblockDocument(document);
            document.setText(document.getText()
                .replace("MTI_CLASS", typeName)
                .replace("MTI_LOWER_NAME", CaseFormat.UPPER_CAMEL.to(LOWER_UNDERSCORE, typeName))
                .replace("MTI_NAME", CaseFormat.UPPER_CAMEL.to(LOWER_CAMEL, typeName)));
            CodeStyleManager.getInstance(itemClass.getProject()).reformat(itemClass);
        }
    }.execute();
}
项目:ApiDebugger    文件:ResponseBodyWidget.java   
private Editor createEditor() {
    PsiFile myFile = null;
    EditorFactory editorFactory = EditorFactory.getInstance();
    Document doc = myFile == null
            ? editorFactory.createDocument("")
            : PsiDocumentManager.getInstance(mProject).getDocument(myFile);
    Editor editor = editorFactory.createEditor(doc, mProject);
    EditorSettings editorSettings = editor.getSettings();
    editorSettings.setVirtualSpace(false);
    editorSettings.setLineMarkerAreaShown(false);
    editorSettings.setIndentGuidesShown(false);
    editorSettings.setFoldingOutlineShown(true);
    editorSettings.setAdditionalColumnsCount(3);
    editorSettings.setAdditionalLinesCount(3);
    editorSettings.setLineNumbersShown(true);
    editorSettings.setCaretRowShown(true);

    editor.getDocument().addDocumentListener(new DocumentAdapter() {
        @Override
        public void documentChanged(DocumentEvent e) {
        }
    });
    ((EditorEx) editor).setHighlighter(createHighlighter(FileTypes.PLAIN_TEXT));
    return editor;
}
项目:dimenify    文件:AbstractDimenAction.java   
protected void createDirectoriesAndFilesIfNeeded(PsiDirectory psiParent) {
    for (Dimen datum : data) {
        WriteCommandAction.runWriteCommandAction(project, () -> {
            PsiDirectory subDirectory = psiParent.findSubdirectory(datum.getDirectory());
            if (subDirectory == null) {
                subDirectory = psiParent.createSubdirectory(datum.getDirectory());
            }
            PsiFile file = subDirectory.findFile(Constants.FILE_NAME);
            if (file == null) {
                PsiFile psiFile = subDirectory.createFile(Constants.FILE_NAME);
                Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
                document.setText(Constants.RESOURCES_TEXT);
                fileCreationCompleteAndCheck();

            } else {
                fileCreationCompleteAndCheck();
            }
        });
    }
}
项目:intellij-ce-playground    文件:Psi2SaxAdapter.java   
private void setLocation(PsiElement text) {
  final PsiFile psiFile = text.getContainingFile();
  final Document document = PsiDocumentManager.getInstance(text.getProject()).getDocument(psiFile);
  if (document == null) {
    return;
  }
  final VirtualFile virtualFile = psiFile.getVirtualFile();
  if (virtualFile == null) {
    return;
  }

  final Locator2Impl locator = new Locator2Impl();
  locator.setSystemId(RngParser.reallyFixIDEAUrl(virtualFile.getUrl()));

  final int offset = text.getTextRange().getEndOffset();
  final int lineNumber = document.getLineNumber(offset);

  locator.setLineNumber(lineNumber + 1);
  locator.setColumnNumber(1 + offset - document.getLineStartOffset(lineNumber));

  myHandler.setDocumentLocator(locator);
}
项目:intellij-ce-playground    文件:UsageViewImpl.java   
private void updateLater() {
  myUpdateAlarm.cancelAllRequests();
  myUpdateAlarm.addRequest(new Runnable() {
    @Override
    public void run() {
      if (myProject.isDisposed()) return;
      PsiDocumentManagerBase documentManager = (PsiDocumentManagerBase)PsiDocumentManager.getInstance(myProject);
      documentManager.cancelAndRunWhenAllCommitted("UpdateUsageView", new Runnable() {
        @Override
        public void run() {
          updateImmediately();
        }
      });
    }
  }, 300);
}
项目:intellij-ce-playground    文件:DebuggerContextImpl.java   
public void initCaches() {
  if(myInitialized) return;

  myInitialized = true;
  if(myFrameProxy == null) {
    if(myThreadProxy != null) {
      try {
        myFrameProxy = myThreadProxy.frameCount() > 0 ? myThreadProxy.frame(0) : null;
      }
      catch (EvaluateException ignored) {
      }
    }
  }

  if (myFrameProxy != null) {
    PsiDocumentManager.getInstance(getProject()).commitAndRunReadAction(new Runnable() {
      @Override
      public void run() {
        if (mySourcePosition == null) {
          mySourcePosition = ContextUtil.getSourcePosition(DebuggerContextImpl.this);
        }
        myContextElement = ContextUtil.getContextElement(mySourcePosition);
      }
    });
  }
}
项目:intellij-ce-playground    文件:FileContentImpl.java   
public PsiFile getPsiFileForPsiDependentIndex() {
  Document document = FileDocumentManager.getInstance().getCachedDocument(getFile());
  PsiFile psi = null;
  if (document != null) {
    PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(getProject());
    if (psiDocumentManager.isUncommited(document)) {
      PsiFile existingPsi = psiDocumentManager.getPsiFile(document);
      if(existingPsi != null) {
        psi = existingPsi;
      }
    }
  }
  if (psi == null) {
    psi = getPsiFile();
  }
  return psi;
}
项目:intellij-ce-playground    文件:ReadonlyStatusHandler.java   
public static boolean ensureDocumentWritable(@NotNull Project project, @NotNull Document document) {
  final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
  boolean okWritable;
  if (psiFile == null) {
    okWritable = document.isWritable();
  }
  else {
    final VirtualFile virtualFile = psiFile.getVirtualFile();
    if (virtualFile != null) {
      okWritable = ensureFilesWritable(project, virtualFile);
    }
    else {
      okWritable = psiFile.isWritable();
    }
  }
  return okWritable;
}
项目:intellij-ce-playground    文件:LightPlatformCodeInsightTestCase.java   
/**
 * Validates that content of the editor as well as caret and selection matches one specified in data file that
 * should be formed with the same format as one used in configureByFile
 * @param message - this check specific message. Added to text, caret position, selection checking. May be null
 * @param filePath - relative path from %IDEA_INSTALLATION_HOME%/testData/
 * @param ignoreTrailingSpaces - whether trailing spaces in editor in data file should be stripped prior to comparing.
 */
protected void checkResultByFile(@Nullable String message, @TestDataFile @NotNull String filePath, final boolean ignoreTrailingSpaces) {
  bringRealEditorBack();

  getProject().getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
  if (ignoreTrailingSpaces) {
    final Editor editor = myEditor;
    TrailingSpacesStripper.stripIfNotCurrentLine(editor.getDocument(), false);
    EditorUtil.fillVirtualSpaceUntilCaret(editor);
  }

  PsiDocumentManager.getInstance(getProject()).commitAllDocuments();

  String fullPath = getTestDataPath() + filePath;

  File ioFile = new File(fullPath);

  assertTrue(getMessage("Cannot find file " + fullPath, message), ioFile.exists());
  String fileText = null;
  try {
    fileText = FileUtil.loadFile(ioFile, CharsetToolkit.UTF8_CHARSET);
  } catch (IOException e) {
    LOG.error(e);
  }
  checkResultByText(message, StringUtil.convertLineSeparators(fileText), ignoreTrailingSpaces, getTestDataPath() + "/" + filePath);
}
项目:intellij-ce-playground    文件:ExecutionWithDebuggerToolsTestCase.java   
protected void printContextWithText(final StackFrameContext context) {
  ApplicationManager.getApplication().runReadAction(new Runnable() {
    @Override
    public void run() {
      if (context.getFrameProxy() != null) {
        SourcePosition sourcePosition = PositionUtil.getSourcePosition(context);
        int offset = sourcePosition.getOffset();
        Document document = PsiDocumentManager.getInstance(myProject).getDocument(sourcePosition.getFile());
        CharSequence text = document.getImmutableCharSequence();
        String positionText = "";
        if (offset > -1) {
          positionText = StringUtil.escapeLineBreak(" [" + text.subSequence(Math.max(0, offset - 20), offset) + "<*>"
          + text.subSequence(offset, Math.min(offset + 20, text.length())) + "]");
        }

        println(sourcePosition.getFile().getVirtualFile().getName()
                + ":" + sourcePosition.getLine()
                + positionText,
                ProcessOutputTypes.SYSTEM);
      }
      else {
        println("Context thread is null", ProcessOutputTypes.SYSTEM);
      }
    }
  });
}
项目:intellij-ce-playground    文件:GroovyOptimizeImportsFix.java   
public static void invokeOnTheFlyImportOptimizer(@NotNull final Runnable runnable,
                                                 @NotNull final PsiFile file,
                                                 @NotNull final Editor editor) {
  final long stamp = editor.getDocument().getModificationStamp();
  ApplicationManager.getApplication().invokeLater(new Runnable() {
    @Override
    public void run() {
      if (file.getProject().isDisposed() || editor.isDisposed() || editor.getDocument().getModificationStamp() != stamp) return;
      //no need to optimize imports on the fly during undo/redo
      final UndoManager undoManager = UndoManager.getInstance(editor.getProject());
      if (undoManager.isUndoInProgress() || undoManager.isRedoInProgress()) return;
      PsiDocumentManager.getInstance(file.getProject()).commitAllDocuments();
      String beforeText = file.getText();
      final long oldStamp = editor.getDocument().getModificationStamp();
      DocumentUtil.writeInRunUndoTransparentAction(runnable);
      if (oldStamp != editor.getDocument().getModificationStamp()) {
        String afterText = file.getText();
        if (Comparing.strEqual(beforeText, afterText)) {
          String path = file.getViewProvider().getVirtualFile().getPath();
          LOG.error("Import optimizer  hasn't optimized any imports", new Attachment(path, afterText));
        }
      }
    }
  });
}
项目:intellij-ce-playground    文件:GroovyGotoImplementationTest.java   
public void testNoGotoImplementationOutsideSourceRoot() throws Throwable {
  final TempDirTestFixture dirFixture = new TempDirTestFixtureImpl();
  dirFixture.setUp();

  new WriteCommandAction(getProject()) {
    @Override
    protected void run(@NotNull Result result) throws Throwable {
      final VirtualFile outside = dirFixture.getFile("").createChildDirectory(this, "outside");
      PsiTestUtil.addContentRoot(myModule, outside);
      VirtualFile out = outside.createChildData(this, "Outside.groovy");
      VfsUtil.saveText(out, "class Bar {}\n class Goo extends Bar {}");
      PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
    }
  }.execute();

  try {
    PsiFile inProject = myFixture.addFileToProject("Foo.groovy", "class <caret>Foo {}\n class Bar extends Foo {}");
    myFixture.configureFromExistingVirtualFile(inProject.getVirtualFile());

    final PsiElement[] impls = new GotoImplementationHandler().getSourceAndTargetElements(myFixture.getEditor(), inProject).targets;
    assertEquals(1, impls.length);
  }
  finally {
    dirFixture.tearDown();
  }
}
项目:intellij-ce-playground    文件:GroovyResolveSnapshot.java   
public GroovyResolveSnapshot(final PsiElement scope) {
  myProject = scope.getProject();
  myDocument = PsiDocumentManager.getInstance(myProject).getDocument(scope.getContainingFile());
  final SmartPointerManager pointerManager = SmartPointerManager.getInstance(myProject);
  final Map<PsiElement, SmartPsiElementPointer> pointers = new HashMap<PsiElement, SmartPsiElementPointer>();
  scope.accept(new GroovyPsiElementVisitor(new GroovyRecursiveElementVisitor() {
    @Override
    public void visitReferenceExpression(GrReferenceExpression refExpr) {
      if (!refExpr.isQualified()) {
        PsiElement resolved = refExpr.resolve();
        if (resolved instanceof GrMember) {
          SmartPsiElementPointer key = pointerManager.createSmartPsiElementPointer(refExpr);
          SmartPsiElementPointer value = pointers.get(resolved);
          if (value == null) {
            value = pointerManager.createSmartPsiElementPointer(resolved);
            pointers.put(resolved, value);
          }
          myReferencesMap.put(key, value);
        }
      }
      super.visitReferenceExpression(refExpr);
    }
  }));
}
项目:intellij-ce-playground    文件:PyParameterTableModel.java   
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
  myCodeFragment = (PsiCodeFragment)((Pair)value).getFirst();

  myDocument = PsiDocumentManager.getInstance(myProject).getDocument(myCodeFragment);
  JPanel panel = new JPanel();
  myEditorTextField = createEditorField(myDocument);
  if (myEditorTextField != null) {
    for (DocumentListener listener : myListeners) {
      myEditorTextField.addDocumentListener(listener);
    }
    myEditorTextField.setDocument(myDocument);
    myEditorTextField.setBorder(new LineBorder(table.getSelectionBackground()));
  }

  panel.add(myEditorTextField);
  panel.add(new JCheckBox());
  return panel;
}
项目:intellij-ce-playground    文件:CodeStyleAbstractPanel.java   
/**
 * Reformats {@link #myTextToReformat target text} with the {@link #mySettings current code style settings} and returns
 * list of changes applied to the target text during that.
 *
 * @param project   project to use
 * @return          list of changes applied to the {@link #myTextToReformat target text} during reformatting. It is sorted
 *                  by change start offset in ascending order
 */
@Nullable
private Document collectChangesBeforeCurrentSettingsAppliance(Project project) {
  PsiFile psiFile = createFileFromText(project, myTextToReformat);
  prepareForReformat(psiFile);
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  if (documentManager != null) {
    Document document = documentManager.getDocument(psiFile);
    if (document != null) {
      CodeStyleSettings clone = mySettings.clone();
      clone.setRightMargin(getDefaultLanguage(), getAdjustedRightMargin());
      CodeStyleSettingsManager.getInstance(project).setTemporarySettings(clone);
      try {
        CodeStyleManager.getInstance(project).reformat(psiFile);
      }
      finally {
        CodeStyleSettingsManager.getInstance(project).dropTemporarySettings();
      }
      return document;
    }
  }
  return null;
}
项目:intellij-ce-playground    文件:ValidateXmlAction.java   
private void doRunAction(final @NotNull PsiFile psiFile) {

    CommandProcessor.getInstance().executeCommand(psiFile.getProject(), new Runnable(){
        @Override
        public void run(){
          final Runnable action = new Runnable() {
            @Override
            public void run() {
              try {
                psiFile.putUserData(runningValidationKey, "");
                PsiDocumentManager.getInstance(psiFile.getProject()).commitAllDocuments();

                getHandler(psiFile).doValidate((XmlFile)psiFile);
              }
              finally {
                psiFile.putUserData(runningValidationKey, null);
              }
            }
          };
          ApplicationManager.getApplication().runWriteAction(action);
        }
      },
      getCommandName(),
      null
    );
  }
项目:intellij-ce-playground    文件:UnusedSymbolLocalTest.java   
public void testChangeInsideCodeBlock() throws Exception {
  doTest();
  final Document document = myEditor.getDocument();
  Collection<HighlightInfo> collection = doHighlighting(HighlightSeverity.WARNING);
  assertEquals(0, collection.size());

  final int offset = myEditor.getCaretModel().getOffset();
  WriteCommandAction.runWriteCommandAction(null, new Runnable() {
    @Override
    public void run() {
      document.insertString(offset, "//");
    }
  });

  PsiDocumentManager.getInstance(getProject()).commitDocument(document);

  Collection<HighlightInfo> infos = doHighlighting(HighlightSeverity.WARNING);
  assertEquals(1, infos.size());
}
项目:intellij-ce-playground    文件:XsltBreakpointHandler.java   
@Nullable
public static PsiElement findContextElement(Project project, @Nullable XSourcePosition position) {
  if (position == null) {
    return null;
  }

  final PsiFile file = PsiManager.getInstance(project).findFile(position.getFile());
  if (file == null) {
    return null;
  }

  int offset = -1;
  final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
  if (document != null && document.getLineCount() > position.getLine() && position.getLine() >= 0) {
    offset = document.getLineStartOffset(position.getLine());
  }
  if (offset < 0) {
    offset = position.getOffset();
  }

  PsiElement contextElement = file.findElementAt(offset);
  while (contextElement != null && !(contextElement instanceof XmlElement)) {
    contextElement = PsiTreeUtil.nextLeaf(contextElement);
  }
  return contextElement;
}
项目:intellij-ce-playground    文件:StructuralReplaceAction.java   
public static void triggerAction(Configuration config, SearchContext searchContext) {
  final Project project = searchContext.getProject();
  if (project == null) {
    return;
  }
  PsiDocumentManager.getInstance(project).commitAllDocuments();

  ReplaceDialog replaceDialog = new ReplaceDialog(searchContext);

  if (config!=null) {
    replaceDialog.setUseLastConfiguration(true);
    replaceDialog.setValuesFromConfig(config);
  }

  replaceDialog.show();
}
项目:intellij-ce-playground    文件:MavenProjectModelModifier.java   
@Override
public Promise<Void> changeLanguageLevel(@NotNull Module module, @NotNull final LanguageLevel level) {
  if (!myProjectsManager.isMavenizedModule(module)) return null;

  MavenProject mavenProject = myProjectsManager.findProject(module);
  if (mavenProject == null) return null;

  final MavenDomProjectModel model = MavenDomUtil.getMavenDomProjectModel(myProject, mavenProject.getFile());
  if (model == null) return null;

  new WriteCommandAction(myProject, "Add Maven Dependency", DomUtil.getFile(model)) {
    @Override
    protected void run(@NotNull Result result) throws Throwable {
      MavenDomConfiguration configuration = getCompilerPlugin(model).getConfiguration();
      XmlTag tag = configuration.ensureTagExists();
      setChildTagValue(tag, "source", level.getCompilerComplianceDefaultOption());
      setChildTagValue(tag, "target", level.getCompilerComplianceDefaultOption());
      Document document = PsiDocumentManager.getInstance(myProject).getDocument(DomUtil.getFile(model));
      if (document != null) {
        FileDocumentManager.getInstance().saveDocument(document);
      }
    }
  }.execute();
  return myProjectsManager.forceUpdateProjects(Collections.singleton(mavenProject));
}
项目:intellij-ce-playground    文件:CompletionAutoPopupHandler.java   
public static void runLaterWithCommitted(@NotNull final Project project,
                                         @NotNull final Document document,
                                         @NotNull final Runnable runnable) {
  final long beforeStamp = document.getModificationStamp();
  PsiDocumentManager.getInstance(project).performWhenAllCommitted(new Runnable() {
    @Override
    public void run() {
      // later because we may end up in write action here if there was a synchronous commit
      ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
          if (beforeStamp != document.getModificationStamp()) {
            // no luck, will try later
            runLaterWithCommitted(project, document, runnable);
          }
          else {
            runnable.run();
          }
        }
      }, project.getDisposed());
    }
  });
}
项目:intellij-ce-playground    文件:FileFixture.java   
private boolean isOpenAndSelected() {
  FileEditorManager editorManager = FileEditorManager.getInstance(myProject);
  FileEditor selectedEditor = editorManager.getSelectedEditor(myVirtualFile);
  if (selectedEditor != null) {
    JComponent component = selectedEditor.getComponent();
    if (component.isVisible() && component.isShowing()) {
      Document document = FileDocumentManager.getInstance().getDocument(myVirtualFile);
      if (document != null) {
        PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
        if (psiFile != null) {
          DaemonCodeAnalyzerEx codeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(myProject);
          //noinspection ConstantConditions
          boolean isRunning = method("isRunning").withReturnType(boolean.class).in(codeAnalyzer).invoke();
          return !isRunning;
        }
      }
    }
  }
  return false;
}
项目:intellij-ce-playground    文件:SettingsImpl.java   
private void reinitDocumentIndentOptions() {
  if (myEditor == null) return;
  final Project project = myEditor.getProject();
  final DocumentEx document = myEditor.getDocument();

  if (project == null || project.isDisposed()) return;

  final PsiDocumentManager psiManager = PsiDocumentManager.getInstance(project);
  final PsiFile file = psiManager.getPsiFile(document);
  if (file == null) return;

  CodeStyleSettings settings = CodeStyleSettingsManager.getInstance(project).getCurrentSettings();
  CommonCodeStyleSettings.IndentOptions options = settings.getIndentOptionsByFile(file);

  if (CodeStyleSettings.isRecalculateForCommittedDocument(options)) {
    PsiDocumentManager.getInstance(project).performForCommittedDocument(document, new Runnable() {
      @Override
      public void run() {
        CodeStyleSettingsManager.updateDocumentIndentOptions(project, document);
      }
    });
  }
  else {
    CodeStyleSettingsManager.updateDocumentIndentOptions(project, document);
  }
}
项目:intellij-ce-playground    文件:IdCacheTest.java   
public void testUpdateCache2() throws Exception {
  VirtualFile child = myRootDir.findChild("1.java");
  VfsUtil.saveText(child, "xxx");

  PsiDocumentManager.getInstance(myProject).commitAllDocuments();
  FileDocumentManager.getInstance().saveAllDocuments();

  final CacheManager cache = CacheManager.SERVICE.getInstance(myProject);
  final TodoCacheManager todocache = TodoCacheManager.SERVICE.getInstance(myProject);
  final GlobalSearchScope scope = GlobalSearchScope.projectScope(myProject);
  checkResult(new String[] {"1.java"}, convert(cache.getFilesWithWord("xxx", UsageSearchContext.ANY, scope, false)));
  checkResult(new String[]{}, convert(cache.getFilesWithWord("a", UsageSearchContext.ANY, scope, false)));
  checkResult(new String[]{"2.java"}, convert(cache.getFilesWithWord("b", UsageSearchContext.ANY,scope, false)));
  checkResult(new String[]{"2.java", "3.java"}, convert(cache.getFilesWithWord("c", UsageSearchContext.ANY,scope, false)));
  checkResult(new String[]{"2.java", "3.java"}, convert(cache.getFilesWithWord("d", UsageSearchContext.ANY,scope, false)));
  checkResult(new String[]{"3.java"}, convert(cache.getFilesWithWord("e", UsageSearchContext.ANY,scope, false)));

  checkResult(new String[]{"3.java"}, convert(todocache.getFilesWithTodoItems()));
  assertEquals(0, todocache.getTodoCount(myRootDir.findChild("1.java"), TodoIndexPatternProvider.getInstance()));
  assertEquals(0, todocache.getTodoCount(myRootDir.findChild("2.java"), TodoIndexPatternProvider.getInstance()));
  assertEquals(2, todocache.getTodoCount(myRootDir.findChild("3.java"), TodoIndexPatternProvider.getInstance()));
}
项目:intellij-ce-playground    文件:IdCacheTest.java   
public void testFileCreation() throws Exception {
  final CacheManager cache = CacheManager.SERVICE.getInstance(myProject);
  final TodoCacheManager todocache = TodoCacheManager.SERVICE.getInstance(myProject);
  checkCache(cache, todocache);

  VirtualFile child = myRootDir.createChildData(null, "4.java");
  VfsUtil.saveText(child, "xxx //todo");
  PsiDocumentManager.getInstance(myProject).commitAllDocuments();

  final GlobalSearchScope scope = GlobalSearchScope.projectScope(myProject);
  checkResult(new String[]{"4.java"}, convert(cache.getFilesWithWord("xxx", UsageSearchContext.ANY, scope, false)));
  checkResult(new String[]{"1.java"}, convert(cache.getFilesWithWord("a", UsageSearchContext.ANY, scope, false)));
  checkResult(new String[]{"1.java", "2.java"}, convert(cache.getFilesWithWord("b", UsageSearchContext.ANY, scope, false)));
  checkResult(new String[]{"1.java", "2.java", "3.java"}, convert(cache.getFilesWithWord("c", UsageSearchContext.ANY, scope, false)));
  checkResult(new String[]{"2.java", "3.java"}, convert(cache.getFilesWithWord("d", UsageSearchContext.ANY, scope, false)));
  checkResult(new String[]{"3.java"}, convert(cache.getFilesWithWord("e", UsageSearchContext.ANY, scope, false)));

  checkResult(new String[]{"1.java", "3.java", "4.java"}, convert(todocache.getFilesWithTodoItems()));
  assertEquals(1, todocache.getTodoCount(myRootDir.findChild("1.java"), TodoIndexPatternProvider.getInstance()));
  assertEquals(0, todocache.getTodoCount(myRootDir.findChild("2.java"), TodoIndexPatternProvider.getInstance()));
  assertEquals(2, todocache.getTodoCount(myRootDir.findChild("3.java"), TodoIndexPatternProvider.getInstance()));
  assertEquals(1, todocache.getTodoCount(myRootDir.findChild("4.java"), TodoIndexPatternProvider.getInstance()));
}
项目:intellij-ce-playground    文件:RenameMethodMultiTest.java   
private void doAutomaticRenameMethod(final String className, final String methodSignature, final String newName) throws Exception {
  doTest((rootDir, rootAfter) -> {
    final JavaPsiFacade manager = getJavaFacade();
    final PsiClass aClass = manager.findClass(className, GlobalSearchScope.moduleScope(myModule));
    assertNotNull(aClass);
    final PsiMethod methodBySignature = aClass.findMethodBySignature(manager.getElementFactory().createMethodFromText(
      methodSignature + "{}", null), false);
    assertNotNull(methodBySignature);

    final RenameProcessor processor = new RenameProcessor(myProject, methodBySignature, newName, false, false);
    for (AutomaticRenamerFactory factory : Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME)) {
      processor.addRenamerFactory(factory);
    }
    processor.run();
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();
    FileDocumentManager.getInstance().saveAllDocuments();
  });
}