Java Code Examples for com.intellij.psi.PsiDocumentManager

The following examples show how to use com.intellij.psi.PsiDocumentManager. These examples are extracted from open source projects. 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 Project: intellij-latte   Source File: AttrMacroInsertHandler.java    License: MIT License 6 votes vote down vote up
public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	if (element != null && element.getLanguage() == LatteLanguage.INSTANCE && element.getNode().getElementType() == LatteTypes.T_HTML_TAG_NATTR_NAME) {
		Editor editor = context.getEditor();
		CaretModel caretModel = editor.getCaretModel();
		int offset = caretModel.getOffset();
		if (LatteUtil.isStringAtCaret(editor, "=")) {
			caretModel.moveToOffset(offset + 2);
			return;
		}

		String attrName = LatteUtil.normalizeNAttrNameModifier(element.getText());
		LatteTagSettings macro = LatteConfiguration.getInstance(element.getProject()).getTag(attrName);
		if (macro != null && !macro.hasParameters()) {
			return;
		}

		editor.getDocument().insertString(offset, "=\"\"");
		caretModel.moveToOffset(offset + 2);

		PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
	}
}
 
Example 2
Source Project: lsp4intellij   Source File: EditorEventManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Applies the given edits to the document
 *
 * @param version    The version of the edits (will be discarded if older than current version)
 * @param edits      The edits to apply
 * @param name       The name of the edits (Rename, for example)
 * @param closeAfter will close the file after edits if set to true
 * @return True if the edits were applied, false otherwise
 */
boolean applyEdit(int version, List<TextEdit> edits, String name, boolean closeAfter, boolean setCaret) {
    Runnable runnable = getEditsRunnable(version, edits, name, setCaret);
    writeAction(() -> {
        if (runnable != null) {
            CommandProcessor.getInstance()
                    .executeCommand(project, runnable, name, "LSPPlugin", editor.getDocument());
        }
        if (closeAfter) {
            PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
            if (file != null) {
                FileEditorManager.getInstance(project).closeFile(file.getVirtualFile());
            }
        }
    });
    return runnable != null;
}
 
Example 3
Source Project: markdown-image-kit   Source File: AbstractUploadCloudActionTest.java    License: MIT License 6 votes vote down vote up
/**
 * 获取 document 的几种方式
 *
 * @param e the e
 */
private void getDocument(AnActionEvent e) {
    // 从当前编辑器中获取
    Document documentFromEditor = Objects.requireNonNull(e.getData(PlatformDataKeys.EDITOR)).getDocument();
    // 从 VirtualFile 获取 (如果之前未加载文档内容,则此调用会强制从磁盘加载文档内容)
    VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
    if (virtualFile != null) {
        Document documentFromVirtualFile = FileDocumentManager.getInstance().getDocument(virtualFile);
        // 从缓存中获取
        Document documentFromVirtualFileCache = FileDocumentManager.getInstance().getCachedDocument(virtualFile);

        // 从 PSI 中获取
        Project project = e.getProject();
        if (project != null) {
            // 获取 PSI (一)
            PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
            // 获取 PSI (二)
            psiFile = e.getData(CommonDataKeys.PSI_FILE);
            if (psiFile != null) {
                Document documentFromPsi = PsiDocumentManager.getInstance(project).getDocument(psiFile);
                // 从缓存中获取
                Document documentFromPsiCache = PsiDocumentManager.getInstance(project).getCachedDocument(psiFile);
            }
        }
    }
}
 
Example 4
private void performReplacements(
    final Document document, final Map<TextRange, String> replacements) {

  if (replacements.isEmpty()) {
    return;
  }

  TreeMap<TextRange, String> sorted = new TreeMap<>(comparing(TextRange::getStartOffset));
  sorted.putAll(replacements);
  WriteCommandAction.runWriteCommandAction(
      getProject(),
      () -> {
        for (Entry<TextRange, String> entry : sorted.descendingMap().entrySet()) {
          document.replaceString(
              entry.getKey().getStartOffset(), entry.getKey().getEndOffset(), entry.getValue());
        }
        PsiDocumentManager.getInstance(getProject()).commitDocument(document);
      });
}
 
Example 5
Source Project: consulo   Source File: PerFileMappingsBase.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
  }
}
 
Example 6
Source Project: consulo   Source File: FileContentUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void setFileText(@javax.annotation.Nullable Project project, final VirtualFile virtualFile, final String text) throws IOException {
  if (project == null) {
    project = ProjectUtil.guessProjectForFile(virtualFile);
  }
  if (project != null) {
    final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
    final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    final Document document = psiFile == null? null : psiDocumentManager.getDocument(psiFile);
    if (document != null) {
      document.setText(text != null ? text : "");
      psiDocumentManager.commitDocument(document);
      FileDocumentManager.getInstance().saveDocument(document);
      return;
    }
  }
  VfsUtil.saveText(virtualFile, text != null ? text : "");
  virtualFile.refresh(false, false);
}
 
Example 7
Source Project: consulo   Source File: TextEditorBackgroundHighlighter.java    License: Apache License 2.0 6 votes vote down vote up
private void renewFile() {
  if (myFile == null || !myFile.isValid()) {
    myFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myDocument);
    myCompiled = myFile instanceof PsiCompiledFile;
    if (myCompiled) {
      myFile = ((PsiCompiledFile)myFile).getDecompiledPsiFile();
    }
    if (myFile != null && !myFile.isValid()) {
      myFile = null;
    }
  }

  if (myFile != null) {
    myFile.putUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING, Boolean.TRUE);
  }
}
 
Example 8
private void doTestCompletion(String sourceFile, List<String> expectedCompletions) {
    for (PsiFile file : this.files) {
        if (file.getVirtualFile().getPath().endsWith(sourceFile)) {
            myFixture.configureFromExistingVirtualFile(file.getVirtualFile());
            break;
        }
    }
    final Lock readLock = GraphQLConfigManager.getService(getProject()).getReadLock();
    try {
        readLock.lock();
        myFixture.complete(CompletionType.BASIC, 1);
        final List<String> completions = myFixture.getLookupElementStrings();
        assertEquals("Wrong completions", expectedCompletions, completions);
    } finally {
        readLock.unlock();
    }
    ApplicationManager.getApplication().runWriteAction(() -> {
        myFixture.getEditor().getDocument().setText(""); // blank out the file so it doesn't affect other tests
        PsiDocumentManager.getInstance(myFixture.getProject()).commitAllDocuments();
    });
}
 
Example 9
protected void formatAsync(FileContentsProvider fileContents, ListenableFuture<String> future) {
  future.addListener(
      () -> {
        String text = fileContents.getFileContentsIfUnchanged();
        if (text == null) {
          return;
        }
        Document document = getDocument(fileContents.file);
        if (!FormatUtils.canApplyChanges(getProject(), document)) {
          return;
        }
        String formattedFile = getFormattingFuture(future);
        if (formattedFile == null || formattedFile.equals(text)) {
          return;
        }
        FormatUtils.runWriteActionIfUnchanged(
            getProject(),
            document,
            text,
            () -> {
              document.setText(formattedFile);
              PsiDocumentManager.getInstance(getProject()).commitDocument(document);
            });
      },
      MoreExecutors.directExecutor());
}
 
Example 10
Source Project: reasonml-idea-plugin   Source File: ReformatAction.java    License: MIT License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
    PsiFile file = e.getData(PSI_FILE);
    Project project = e.getProject();
    if (project != null && file != null) {
        String format = ReformatUtil.getFormat(file);
        if (format != null) {
            Document document = PsiDocumentManager.getInstance(project).getCachedDocument(file);
            if (document != null) {
                ServiceManager.
                        getService(project, BsCompiler.class).
                        refmt(file.getVirtualFile(), FileHelper.isInterface(file.getFileType()), format, document);
            }
        }
    }
}
 
Example 11
Source Project: idea-php-typo3-plugin   Source File: DebugInlinePostfixTemplate.java    License: MIT License 6 votes vote down vote up
@Override
public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
    FluidInlineStatement expression = (FluidInlineStatement) PsiTreeUtil.findFirstParent(context, psiElement -> psiElement instanceof FluidInlineStatement);
    if (expression == null) {
        return;
    }

    Template tagTemplate = LiveTemplateFactory.createInlinePipeToDebugTemplate(expression);
    tagTemplate.addVariable("EXPR", new TextExpression(expression.getInlineChain().getText()), true);

    int textOffset = expression.getTextOffset() + expression.getTextLength();
    editor.getCaretModel().moveToOffset(textOffset);

    TemplateManager.getInstance(context.getProject()).startTemplate(editor, tagTemplate);
    PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());

    expression.delete();
}
 
Example 12
Source Project: KodeBeagle   Source File: JavaImportsUtil.java    License: Apache License 2.0 6 votes vote down vote up
public final Map<String, Set<String>> getImportInLines(final Editor projectEditor,
                                                       final Pair<Integer, Integer> pair) {
    PsiDocumentManager psiInstance =
            PsiDocumentManager.getInstance(windowObjects.getProject());
    PsiJavaFile psiJavaFile =
            (PsiJavaFile) psiInstance.getPsiFile(projectEditor.getDocument());
    PsiJavaElementVisitor psiJavaElementVisitor =
            new PsiJavaElementVisitor(pair.getFirst(), pair.getSecond());
    Map<String, Set<String>> finalImports = new HashMap<>();
    if (psiJavaFile != null && psiJavaFile.findElementAt(pair.getFirst()) != null) {
        PsiElement psiElement = psiJavaFile.findElementAt(pair.getFirst());
        final PsiElement psiMethod = PsiTreeUtil.getParentOfType(psiElement, PsiMethod.class);
        if (psiMethod != null) {
            psiMethod.accept(psiJavaElementVisitor);
        } else {
            final PsiClass psiClass = PsiTreeUtil.getParentOfType(psiElement, PsiClass.class);
            if (psiClass != null) {
                psiClass.accept(psiJavaElementVisitor);
            }
        }
        Map<String, Set<String>> importVsMethods = psiJavaElementVisitor.getImportVsMethods();
        finalImports = getImportsAndMethodsAfterValidation(psiJavaFile, importVsMethods);
    }
    return removeImplicitImports(finalImports);
}
 
Example 13
@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 14
Source Project: consulo   Source File: PasteHandler.java    License: Apache License 2.0 6 votes vote down vote up
private static void reformatBlock(final Project project, final Editor editor, final int startOffset, final int endOffset) {
  PsiDocumentManager.getInstance(project).commitAllDocuments();
  Runnable task = new Runnable() {
    @Override
    public void run() {
      PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      try {
        CodeStyleManager.getInstance(project).reformatRange(file, startOffset, endOffset, true);
      }
      catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }
  };

  if (endOffset - startOffset > 1000) {
    DocumentUtil.executeInBulk(editor.getDocument(), true, task);
  }
  else {
    task.run();
  }
}
 
Example 15
Source Project: consulo   Source File: FindUsagesInFileAction.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean isEnabled(DataContext dataContext) {
  Project project = dataContext.getData(CommonDataKeys.PROJECT);
  if (project == null) {
    return false;
  }

  Editor editor = dataContext.getData(PlatformDataKeys.EDITOR);
  if (editor == null) {
    UsageTarget[] target = dataContext.getData(UsageView.USAGE_TARGETS_KEY);
    return target != null && target.length > 0;
  }
  else {
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null) {
      return false;
    }

    Language language = PsiUtilBase.getLanguageInEditor(editor, project);
    if (language == null) {
      language = file.getLanguage();
    }
    return !(LanguageFindUsages.INSTANCE.forLanguage(language) instanceof EmptyFindUsagesProvider);
  }
}
 
Example 16
Source Project: consulo   Source File: DiffContentFactoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private static Document createPsiDocument(@Nonnull Project project,
                                          @Nonnull String content,
                                          @Nonnull FileType fileType,
                                          @Nonnull String fileName,
                                          boolean readOnly) {
  ThrowableComputable<Document,RuntimeException> action = () -> {
    LightVirtualFile file = new LightVirtualFile(fileName, fileType, content);
    file.setWritable(!readOnly);

    file.putUserData(DiffPsiFileSupport.KEY, true);

    Document document = FileDocumentManager.getInstance().getDocument(file);
    if (document == null) return null;

    PsiDocumentManager.getInstance(project).getPsiFile(document);

    return document;
  };
  return AccessRule.read(action);
}
 
Example 17
Source Project: consulo   Source File: DefaultHighlightInfoProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void highlightsOutsideVisiblePartAreProduced(@Nonnull final HighlightingSession session,
                                                    @Nullable Editor editor,
                                                    @Nonnull final List<? extends HighlightInfo> infos,
                                                    @Nonnull final TextRange priorityRange,
                                                    @Nonnull final TextRange restrictedRange, final int groupId) {
  final PsiFile psiFile = session.getPsiFile();
  final Project project = psiFile.getProject();
  final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
  if (document == null) return;
  final long modificationStamp = document.getModificationStamp();
  ((HighlightingSessionImpl)session).applyInEDT(() -> {
    if (project.isDisposed() || modificationStamp != document.getModificationStamp()) return;

    EditorColorsScheme scheme = session.getColorsScheme();

    UpdateHighlightersUtil
            .setHighlightersOutsideRange(project, document, psiFile, infos, scheme, restrictedRange.getStartOffset(), restrictedRange.getEndOffset(), ProperTextRange.create(priorityRange), groupId);
    if (editor != null) {
      repaintErrorStripeAndIcon(editor, project);
    }
  });
}
 
Example 18
Source Project: consulo   Source File: EditorHighlighterCache.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
public static Lexer getLexerBasedOnLexerHighlighter(CharSequence text, VirtualFile virtualFile, Project project) {
  EditorHighlighter highlighter = null;

  PsiFile psiFile = virtualFile != null ? PsiManager.getInstance(project).findFile(virtualFile) : null;
  final Document document = psiFile != null ? PsiDocumentManager.getInstance(project).getDocument(psiFile) : null;
  final EditorHighlighter cachedEditorHighlighter;
  boolean alreadyInitializedHighlighter = false;

  if (document != null &&
      (cachedEditorHighlighter = getEditorHighlighterForCachesBuilding(document)) != null &&
      PlatformIdTableBuilding.checkCanUseCachedEditorHighlighter(text, cachedEditorHighlighter)) {
    highlighter = cachedEditorHighlighter;
    alreadyInitializedHighlighter = true;
  }
  else if (virtualFile != null) {
    highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(project, virtualFile);
  }

  if (highlighter != null) {
    return new LexerEditorHighlighterLexer(highlighter, alreadyInitializedHighlighter);
  }
  return null;
}
 
Example 19
Source Project: consulo   Source File: PasteHandler.java    License: 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 20
Source Project: Intellij-Plugin   Source File: GaugeConsoleProperties.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public SMTestLocator getTestLocator() {
    return (protocol, path, project, globalSearchScope) -> {
        try {
            String[] fileInfo = path.split(Constants.SPEC_SCENARIO_DELIMITER);
            VirtualFile file = LocalFileSystem.getInstance().findFileByPath(fileInfo[0]);
            if (file == null) return new ArrayList<>();
            PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
            if (psiFile == null) return new ArrayList<>();
            Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
            if (document == null) return new ArrayList<>();
            int line = Integer.parseInt(fileInfo[1]);
            PsiElement element = psiFile.findElementAt(document.getLineStartOffset(line));
            if (element == null) return new ArrayList<>();
            return Collections.singletonList(new PsiLocation<>(element));
        } catch (Exception e) {
            return new ArrayList<>();
        }
    };
}
 
Example 21
Source Project: consulo   Source File: FormatterTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"UNUSED_SYMBOL"})
private void restoreFileContent(final PsiFile file, final String text) {
  CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
    @Override
    public void run() {
      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(file);
          document.replaceString(0, document.getTextLength(), text);
          PsiDocumentManager.getInstance(getProject()).commitDocument(document);
        }
      });

    }
  }, "test", null);
}
 
Example 22
Source Project: consulo-csharp   Source File: AddUsingAction.java    License: Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
private void execute0(final NamespaceReference namespaceReference)
{
	PsiDocumentManager.getInstance(myProject).commitAllDocuments();

	WriteCommandAction.runWriteCommandAction(myProject, () ->
	{
		addUsing(namespaceReference.getNamespace());

		String libraryName = namespaceReference.getLibraryName();
		if(libraryName != null)
		{
			Module moduleForFile = ModuleUtilCore.findModuleForPsiElement(myFile);
			if(moduleForFile != null)
			{
				ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(moduleForFile);

				final ModifiableRootModel modifiableModel = moduleRootManager.getModifiableModel();

				modifiableModel.addOrderEntry(new DotNetLibraryOrderEntryImpl((ModuleRootLayerImpl) moduleRootManager.getCurrentLayer(), libraryName));

				WriteAction.run(modifiableModel::commit);
			}
		}
	});
}
 
Example 23
Source Project: consulo   Source File: IndentSelectionAction.java    License: Apache License 2.0 6 votes vote down vote up
private static void indentSelection(Editor editor, Project project) {
  int oldSelectionStart = editor.getSelectionModel().getSelectionStart();
  int oldSelectionEnd = editor.getSelectionModel().getSelectionEnd();
  if(!editor.getSelectionModel().hasSelection()) {
    oldSelectionStart = editor.getCaretModel().getOffset();
    oldSelectionEnd = oldSelectionStart;
  }

  Document document = editor.getDocument();
  int startIndex = document.getLineNumber(oldSelectionStart);
  if(startIndex == -1) {
    startIndex = document.getLineCount() - 1;
  }
  int endIndex = document.getLineNumber(oldSelectionEnd);
  if(endIndex > 0 && document.getLineStartOffset(endIndex) == oldSelectionEnd && editor.getSelectionModel().hasSelection()) {
    endIndex --;
  }
  if(endIndex == -1) {
    endIndex = document.getLineCount() - 1;
  }

  PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
  int blockIndent = CodeStyleSettingsManager.getSettings(project).getIndentOptionsByFile(file).INDENT_SIZE;
  doIndent(endIndex, startIndex, document, project, editor, blockIndent);
}
 
Example 24
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(document, ranges);
}
 
Example 25
Source Project: consulo   Source File: CopyElementAction.java    License: Apache License 2.0 5 votes vote down vote up
private static PsiElement getTargetElement(final Editor editor, final Project project) {
  int offset = editor.getCaretModel().getOffset();
  PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  if (file == null) return null;
  PsiElement element = file.findElementAt(offset);
  if (element == null) element = file;
  return element;
}
 
Example 26
Source Project: BashSupport   Source File: BackquoteQuickfix.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
    Document document = PsiDocumentManager.getInstance(project).getDocument(file);
    if (document != null) {
        BashBackquote backquote = (BashBackquote) startElement;
        int endOffset = startElement.getTextRange().getEndOffset();
        String command = backquote.getCommandText();

        //fixme replace this with a PSI element created by the Bash psi factory
        document.replaceString(startElement.getTextOffset(), endOffset, "$(" + command + ")");

        PsiDocumentManager.getInstance(project).commitDocument(document);
    }
}
 
Example 27
Source Project: consulo   Source File: FileDocumentManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void saveAllDocumentsLater() {
  // later because some document might have been blocked by PSI right now
  TransactionGuard.getInstance().submitTransactionLater(ApplicationManager.getApplication(), () -> {
    final Document[] unsavedDocuments = getUnsavedDocuments();
    for (Document document : unsavedDocuments) {
      VirtualFile file = getFile(document);
      if (file == null) continue;
      Project project = ProjectUtil.guessProjectForFile(file);
      if (project == null) continue;
      if (PsiDocumentManager.getInstance(project).isDocumentBlockedByPsi(document)) continue;

      saveDocument(document);
    }
  });
}
 
Example 28
Source Project: consulo   Source File: SettingsImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private static Language getDocumentLanguage(@Nullable Project project, @Nonnull Document document) {
  if (project != null) {
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    PsiFile file = documentManager.getPsiFile(document);
    if (file != null) return file.getLanguage();
  }
  return null;
}
 
Example 29
@Override
public Document createDocument(
    final Project project,
    final String text,
    @Nullable XSourcePosition sourcePosition,
    final EvaluationMode mode) {
  final PsiElement context = OCDebuggerTypesHelper.getContextElement(sourcePosition, project);
  if (context != null && context.getLanguage() == OCLanguage.getInstance()) {
    return new WriteAction<Document>() {
      @Override
      protected void run(Result<Document> result) {
        PsiFile fragment =
            mode == EvaluationMode.EXPRESSION
                ? OCElementFactory.expressionCodeFragment(text, project, context, true, false)
                : OCElementFactory.expressionOrStatementsCodeFragment(
                    text, project, context, true, false);
        //noinspection ConstantConditions
        result.setResult(PsiDocumentManager.getInstance(project).getDocument(fragment));
      }
    }.execute().getResultObject();
  } else {
    final LightVirtualFile plainTextFile =
        new LightVirtualFile("oc-debug-editor-when-no-source-position-available.txt", text);
    //noinspection ConstantConditions
    return FileDocumentManager.getInstance().getDocument(plainTextFile);
  }
}
 
Example 30
Source Project: consulo   Source File: LightPlatformCodeInsightTestCase.java    License: Apache License 2.0 5 votes vote down vote up
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();
  }
}