Java Code Examples for com.intellij.psi.PsiDocumentManager#getInstance()

The following examples show how to use com.intellij.psi.PsiDocumentManager#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: YamlCreateServiceArgumentsCallback.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Override
public void insert(List<String> items) {
    PsiDocumentManager manager = PsiDocumentManager.getInstance(serviceKeyValue.getProject());
    Document document = manager.getDocument(serviceKeyValue.getContainingFile());
    if (document == null) {
        return;
    }

    List<String> arrayList = new ArrayList<>();
    for (String item : items) {
        arrayList.add("'@" + (StringUtils.isNotBlank(item) ? item : "?") + "'");
    }

    YamlHelper.putKeyValue(serviceKeyValue, "arguments", "[" + StringUtils.join(arrayList, ", ") + "]");

    manager.doPostponedOperationsAndUnblockDocument(document);
    manager.commitDocument(document);
}
 
Example 2
Source File: PasteHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
static void indentBlock(Project project, Editor editor, final int startOffset, final int endOffset, int originalCaretCol) {
  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  documentManager.commitAllDocuments();
  final Document document = editor.getDocument();
  PsiFile file = documentManager.getPsiFile(document);
  if (file == null) {
    return;
  }

  if (LanguageFormatting.INSTANCE.forContext(file) != null) {
    indentBlockWithFormatter(project, document, startOffset, endOffset, file);
  }
  else {
    indentPlainTextBlock(document, startOffset, endOffset, originalCaretCol);
  }
}
 
Example 3
Source File: FormatterImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void validateModel(FormattingModel model) throws FormattingModelInconsistencyException {
  FormattingDocumentModel documentModel = model.getDocumentModel();
  Document document = documentModel.getDocument();
  Block rootBlock = model.getRootBlock();
  if (rootBlock instanceof ASTBlock) {
    PsiElement rootElement = ((ASTBlock)rootBlock).getNode().getPsi();
    if (!rootElement.isValid()) {
      throw new FormattingModelInconsistencyException("Invalid root block PSI element");
    }
    PsiFile file = rootElement.getContainingFile();
    Project project = file.getProject();
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    if (documentManager.isUncommited(document)) {
      throw new FormattingModelInconsistencyException("Uncommitted document");
    }
    if (document.getTextLength() != file.getTextLength()) {
      throw new FormattingModelInconsistencyException("Document length " + document.getTextLength() + " doesn't match PSI file length " + file.getTextLength() + ", language: " + file.getLanguage());
    }
  }
}
 
Example 4
Source File: GotoCustomRegionDialog.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
private Collection<FoldingDescriptor> getCustomFoldingDescriptors() {
  Set<FoldingDescriptor> foldingDescriptors = new HashSet<FoldingDescriptor>();
  final Document document = myEditor.getDocument();
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
  PsiFile file = documentManager != null ? documentManager.getPsiFile(document) : null;
  if (file != null) {
    final FileViewProvider viewProvider = file.getViewProvider();
    for (final Language language : viewProvider.getLanguages()) {
      final PsiFile psi = viewProvider.getPsi(language);
      final FoldingBuilder foldingBuilder = LanguageFolding.INSTANCE.forLanguage(language);
      if (psi != null) {
        for (FoldingDescriptor descriptor : LanguageFolding.buildFoldingDescriptors(foldingBuilder, psi, document, false)) {
          CustomFoldingBuilder customFoldingBuilder = getCustomFoldingBuilder(foldingBuilder, descriptor);
          if (customFoldingBuilder != null) {
            if (customFoldingBuilder.isCustomRegionStart(descriptor.getElement())) {
              foldingDescriptors.add(descriptor);
            }
          }
        }
      }
    }
  }
  return foldingDescriptors;
}
 
Example 5
Source File: CustomizableLanguageCodeStylePanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected PsiFile doReformat(final Project project, final PsiFile psiFile) {
  final String text = psiFile.getText();
  final PsiDocumentManager manager = PsiDocumentManager.getInstance(project);
  final Document doc = manager.getDocument(psiFile);
  CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
    if (doc != null) {
      doc.replaceString(0, doc.getTextLength(), text);
      manager.commitDocument(doc);
    }
    try {
      CodeStyleManager.getInstance(project).reformat(psiFile);
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }), "", "");
  if (doc != null) {
    manager.commitDocument(doc);
  }
  return psiFile;
}
 
Example 6
Source File: ExternalFormatterCodeStyleManager.java    From intellij with Apache License 2.0 6 votes vote down vote up
private void formatInternal(PsiFile file, Collection<TextRange> ranges) {
  ApplicationManager.getApplication().assertWriteAccessAllowed();
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
  documentManager.commitAllDocuments();
  CheckUtil.checkWritable(file);

  Document document = documentManager.getDocument(file);

  if (document == null) {
    return;
  }
  // If there are postponed PSI changes (e.g., during a refactoring), just abort.
  // If we apply them now, then the incoming text ranges may no longer be valid.
  if (documentManager.isDocumentBlockedByPsi(document)) {
    return;
  }

  format(file, document, ranges);
}
 
Example 7
Source File: JSGraphQLQueryContextCaretListener.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@Override
public void runActivity(@NotNull Project project) {
    if (!ApplicationManager.getApplication().isHeadlessEnvironment()) {
        final EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();
        final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
        eventMulticaster.addCaretListener(new CaretListener() {
            @Override
            public void caretPositionChanged(CaretEvent e) {
                final PsiFile psiFile = psiDocumentManager.getPsiFile(e.getEditor().getDocument());
                if (psiFile instanceof GraphQLFile) {
                    int offset = e.getEditor().logicalPositionToOffset(e.getNewPosition());
                    psiFile.putUserData(CARET_OFFSET, offset);
                }
            }
        }, project);
    }
}
 
Example 8
Source File: PerformFixesModalTask.java    From consulo with Apache License 2.0 5 votes vote down vote up
public PerformFixesModalTask(@Nonnull Project project,
                             @Nonnull CommonProblemDescriptor[] descriptors,
                             @Nonnull SequentialModalProgressTask task) {
  myProject = project;
  myDescriptors = descriptors;
  myTask = task;
  myDocumentManager = PsiDocumentManager.getInstance(myProject);
}
 
Example 9
Source File: PsiDocumentUtils.java    From markdown-image-kit with MIT License 5 votes vote down vote up
/**
 * 全文替换
 *
 * @param project  the project
 * @param document the document
 * @param string   the string
 */
public static void commitAndSaveDocument(Project project, Document document, String string) {
    if (document != null) {
        PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
        WriteCommandAction.runWriteCommandAction(project, () -> {
            document.setText(string);
            psiDocumentManager.doPostponedOperationsAndUnblockDocument(document);
            psiDocumentManager.commitDocument(document);
            FileDocumentManager.getInstance().saveDocument(document);
        });
    }
}
 
Example 10
Source File: ConcatenationInjectorManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static InjectionResult doCompute(@Nonnull PsiFile containingFile, @Nonnull Project project, @Nonnull PsiElement anchor, @Nonnull PsiElement[] operands) {
  PsiDocumentManager docManager = PsiDocumentManager.getInstance(project);
  InjectionRegistrarImpl registrar = new InjectionRegistrarImpl(project, containingFile, anchor, docManager);
  InjectionResult result = null;
  ConcatenationInjectorManager concatenationInjectorManager = getInstance(project);
  for (ConcatenationAwareInjector concatenationInjector : concatenationInjectorManager.myConcatenationInjectors) {
    concatenationInjector.inject(registrar, operands);
    result = registrar.getInjectedResult();
    if (result != null) break;
  }

  return result;
}
 
Example 11
Source File: AppendFileCommandAction.java    From idea-gitignore with MIT License 5 votes vote down vote up
/**
 * Builds a new instance of {@link AppendFileCommandAction}.
 * Takes a {@link Set} of the rules to add.
 *
 * @param project          current project
 * @param file             working file
 * @param content          rule
 * @param ignoreDuplicates ignore duplicated entries
 * @param ignoreComments   ignore comments and empty lines
 */
public AppendFileCommandAction(@NotNull Project project, @NotNull PsiFile file, @NotNull Set<String> content,
                               boolean ignoreDuplicates, boolean ignoreComments) {
    super(project);
    this.project = project;
    this.file = file;
    this.content = content;
    this.manager = PsiDocumentManager.getInstance(project);
    this.ignoreDuplicates = ignoreDuplicates;
    this.ignoreComments = ignoreComments;
    this.insertAtCursor = IgnoreSettings.getInstance().isInsertAtCursor();
}
 
Example 12
Source File: BaseCodeInsightAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
public static Editor getInjectedEditor(@Nonnull Project project, final Editor editor, boolean commit) {
  Editor injectedEditor = editor;
  if (editor != null) {
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    PsiFile psiFile = documentManager.getCachedPsiFile(editor.getDocument());
    if (psiFile != null) {
      if (commit) documentManager.commitAllDocuments();
      injectedEditor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(editor, psiFile);
    }
  }
  return injectedEditor;
}
 
Example 13
Source File: RangeMarkerTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
protected void setUp() throws Exception {
  super.setUp();
  documentManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(getProject());
  synchronizer = documentManager.getSynchronizer();
}
 
Example 14
Source File: RearrangeCodeAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  final Project project = e.getProject();
  if (project == null) {
    return;
  }

  final Editor editor = e.getData(CommonDataKeys.EDITOR);
  if (editor == null) {
    return;
  }

  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  Document document = editor.getDocument();
  documentManager.commitDocument(document);

  final PsiFile file = documentManager.getPsiFile(document);
  if (file == null) {
    return;
  }

  SelectionModel model = editor.getSelectionModel();
  if (model.hasSelection()) {
    new RearrangeCodeProcessor(file, model).run();
  }
  else {
    new RearrangeCodeProcessor(file).run();
  }
}
 
Example 15
Source File: FormatterBasedIndentAdjuster.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void scheduleIndentAdjustment(@Nonnull Project myProject, @Nonnull Document myDocument, int myOffset) {
  IndentAdjusterRunnable fixer = new IndentAdjusterRunnable(myProject, myDocument, myOffset);
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
  if (isSynchronousAdjustment(myDocument)) {
    documentManager.commitDocument(myDocument);
    fixer.run();
  }
  else {
    documentManager.performLaterWhenAllCommitted(fixer);
  }
}
 
Example 16
Source File: InnerBuilderHandler.java    From innerbuilder with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
    final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    final Document currentDocument = psiDocumentManager.getDocument(file);
    if (currentDocument == null) {
        return;
    }

    psiDocumentManager.commitDocument(currentDocument);

    if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) {
        return;
    }

    if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
        return;
    }

    final List<PsiFieldMember> existingFields = collectFields(file, editor);
    if (existingFields != null) {
        final List<PsiFieldMember> selectedFields = selectFieldsAndOptions(existingFields, project);

        if (selectedFields == null || selectedFields.isEmpty()) {
            return;
        }

        InnerBuilderGenerator.generate(project, editor, file, selectedFields);
    }
}
 
Example 17
Source File: SettingsImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void reinitDocumentIndentOptions() {
  if (myEditor == null || myEditor.isViewer()) 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;

  CodeStyleSettingsManager.updateDocumentIndentOptions(project, document);
}
 
Example 18
Source File: AbstractDelombokAction.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
  final Project project = event.getProject();
  if (project == null) {
    return;
  }

  PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
  if (psiDocumentManager.hasUncommitedDocuments()) {
    psiDocumentManager.commitAllDocuments();
  }

  final DataContext dataContext = event.getDataContext();
  final Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);

  if (null != editor) {
    final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
    if (null != psiFile) {
      final PsiClass targetClass = getTargetClass(editor, psiFile);
      if (null != targetClass) {
        process(project, psiFile, targetClass);
      }
    }
  } else {
    final VirtualFile[] files = PlatformDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext);
    if (null != files) {
      for (VirtualFile file : files) {
        if (file.isDirectory()) {
          processDirectory(project, file);
        } else {
          processFile(project, file);
        }
      }
    }
  }
}
 
Example 19
Source File: FormattingDocumentModelImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean canUseDocumentModel(@Nonnull Document document, @Nonnull PsiFile file) {
  PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(file.getProject());
  return !psiDocumentManager.isUncommited(document) &&
         !psiDocumentManager.isDocumentBlockedByPsi(document) &&
         file.getText().equals(document.getText());
}
 
Example 20
Source File: CompletionAssertions.java    From consulo with Apache License 2.0 4 votes vote down vote up
static void assertCommitSuccessful(Editor editor, PsiFile psiFile) {
  Document document = editor.getDocument();
  int docLength = document.getTextLength();
  int psiLength = psiFile.getTextLength();
  PsiDocumentManager manager = PsiDocumentManager.getInstance(psiFile.getProject());
  boolean committed = !manager.isUncommited(document);
  if (docLength == psiLength && committed) {
    return;
  }

  FileViewProvider viewProvider = psiFile.getViewProvider();

  String message = "unsuccessful commit:";
  message += "\nmatching=" + (psiFile == manager.getPsiFile(document));
  message += "\ninjectedEditor=" + (editor instanceof EditorWindow);
  message += "\ninjectedFile=" + InjectedLanguageManager.getInstance(psiFile.getProject()).isInjectedFragment(psiFile);
  message += "\ncommitted=" + committed;
  message += "\nfile=" + psiFile.getName();
  message += "\nfile class=" + psiFile.getClass();
  message += "\nfile.valid=" + psiFile.isValid();
  message += "\nfile.physical=" + psiFile.isPhysical();
  message += "\nfile.eventSystemEnabled=" + viewProvider.isEventSystemEnabled();
  message += "\nlanguage=" + psiFile.getLanguage();
  message += "\ndoc.length=" + docLength;
  message += "\npsiFile.length=" + psiLength;
  String fileText = psiFile.getText();
  if (fileText != null) {
    message += "\npsiFile.text.length=" + fileText.length();
  }
  FileASTNode node = psiFile.getNode();
  if (node != null) {
    message += "\nnode.length=" + node.getTextLength();
    String nodeText = node.getText();
    message += "\nnode.text.length=" + nodeText.length();
  }
  VirtualFile virtualFile = viewProvider.getVirtualFile();
  message += "\nvirtualFile=" + virtualFile;
  message += "\nvirtualFile.class=" + virtualFile.getClass();
  message += "\n" + DebugUtil.currentStackTrace();

  throw new RuntimeExceptionWithAttachments("Commit unsuccessful", message, new Attachment(virtualFile.getPath() + "_file.txt", StringUtil.notNullize(fileText)), createAstAttachment(psiFile, psiFile),
                                            new Attachment("docText.txt", document.getText()));
}