com.intellij.openapi.editor.Document Java Examples
The following examples show how to use
com.intellij.openapi.editor.Document.
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: PsiDocumentManagerBase.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull public DocumentEx getLastCommittedDocument(@Nonnull Document document) { if (document instanceof FrozenDocument) return (DocumentEx)document; if (document instanceof DocumentWindow) { DocumentWindow window = (DocumentWindow)document; Document delegate = window.getDelegate(); if (delegate instanceof FrozenDocument) return (DocumentEx)window; if (!window.isValid()) { throw new AssertionError("host committed: " + isCommitted(delegate) + ", window=" + window); } UncommittedInfo info = myUncommittedInfos.get(delegate); DocumentWindow answer = info == null ? null : info.myFrozenWindows.get(document); if (answer == null) answer = freezeWindow(window); if (info != null) answer = ConcurrencyUtil.cacheOrGet(info.myFrozenWindows, window, answer); return (DocumentEx)answer; } assert document instanceof DocumentImpl; UncommittedInfo info = myUncommittedInfos.get(document); return info != null ? info.myFrozen : ((DocumentImpl)document).freeze(); }
Example #2
Source File: InsertToClipboardHandler.java From markdown-image-kit with MIT License | 6 votes |
@Override public boolean execute(EventData data) { ProgressIndicator indicator = data.getIndicator(); int size = data.getSize(); int totalProcessed = 0; StringBuilder marks = new StringBuilder(); for (Map.Entry<Document, List<MarkdownImage>> imageEntry : data.getWaitingProcessMap().entrySet()) { int totalCount = imageEntry.getValue().size(); for (MarkdownImage markdownImage : imageEntry.getValue()) { String imageName = markdownImage.getImageName(); indicator.setText2("Processing " + imageName); marks.append(markdownImage.getFinalMark()).append(ImageContents.LINE_BREAK); indicator.setFraction(((++totalProcessed * 1.0) + data.getIndex() * size) / totalCount * size); } } ImageUtils.setStringToClipboard(marks.toString()); return true; }
Example #3
Source File: UnifiedEditorRangeHighlighter.java From consulo with Apache License 2.0 | 6 votes |
public void apply(@javax.annotation.Nullable Project project, @Nonnull Document document) { MarkupModel model = DocumentMarkupModel.forDocument(document, project, true); for (Element piece : myPieces) { RangeHighlighterEx delegate = piece.getDelegate(); if (!delegate.isValid()) continue; RangeHighlighter highlighter = model .addRangeHighlighter(piece.getStart(), piece.getEnd(), delegate.getLayer(), delegate.getTextAttributes(), delegate.getTargetArea()); highlighter.setEditorFilter(delegate.getEditorFilter()); highlighter.setCustomRenderer(delegate.getCustomRenderer()); highlighter.setErrorStripeMarkColor(delegate.getErrorStripeMarkColor()); highlighter.setErrorStripeTooltip(delegate.getErrorStripeTooltip()); highlighter.setGutterIconRenderer(delegate.getGutterIconRenderer()); highlighter.setLineMarkerRenderer(delegate.getLineMarkerRenderer()); highlighter.setLineSeparatorColor(delegate.getLineSeparatorColor()); highlighter.setThinErrorStripeMark(delegate.isThinErrorStripeMark()); highlighter.setLineSeparatorPlacement(delegate.getLineSeparatorPlacement()); highlighter.setLineSeparatorRenderer(delegate.getLineSeparatorRenderer()); } }
Example #4
Source File: GaugeConsoleProperties.java From Intellij-Plugin with Apache License 2.0 | 6 votes |
@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 #5
Source File: TemplateManagerImpl.java From consulo with Apache License 2.0 | 6 votes |
@Nullable public Runnable startNonCustomTemplates(final Map<TemplateImpl, String> template2argument, final Editor editor, @Nullable final PairProcessor<String, String> processor) { final int caretOffset = editor.getCaretModel().getOffset(); final Document document = editor.getDocument(); final CharSequence text = document.getCharsSequence(); if (template2argument == null || template2argument.isEmpty()) { return null; } return () -> { if (template2argument.size() == 1) { TemplateImpl template = template2argument.keySet().iterator().next(); String argument = template2argument.get(template); int templateStart = getTemplateStart(template, argument, caretOffset, text); startTemplateWithPrefix(editor, template, templateStart, processor, argument); } else { ListTemplatesHandler.showTemplatesLookup(myProject, editor, template2argument); } }; }
Example #6
Source File: UsageInfo2UsageAdapter.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull private TextChunk[] initChunks() { PsiFile psiFile = getPsiFile(); Document document = psiFile == null ? null : PsiDocumentManager.getInstance(getProject()).getDocument(psiFile); TextChunk[] chunks; if (document == null) { // element over light virtual file PsiElement element = getElement(); if (element == null) { chunks = new TextChunk[]{new TextChunk(SimpleTextAttributes.ERROR_ATTRIBUTES.toTextAttributes(), UsageViewBundle.message("node.invalid"))}; } else { chunks = new TextChunk[]{new TextChunk(new TextAttributes(), element.getText())}; } } else { chunks = ChunkExtractor.extractChunks(psiFile, this); } myTextChunks = new SoftReference<>(chunks); return chunks; }
Example #7
Source File: FormatterTestCase.java From consulo with Apache License 2.0 | 6 votes |
@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 #8
Source File: AbstractUploadCloudActionTest.java From markdown-image-kit with MIT License | 6 votes |
/** * 获取 VirtualFile 的几种方式 * * @param e the e */ private void getVirtualFile(AnActionEvent e) { // 获取 VirtualFile 方式一: VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE); // 获取多个 VirtualFile VirtualFile[] virtualFiles = e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY); // 方式二: 从本地文件系统路径获取 VirtualFile virtualFileFromLocalFileSystem = LocalFileSystem.getInstance().findFileByIoFile(new File("path")); // 方式三: 从 PSI 文件 (如果 PSI 文件仅存在内存中, 则可能返回 null) PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE); if (psiFile != null) { psiFile.getVirtualFile(); } // 方式四: 从 document 中 Document document = Objects.requireNonNull(e.getData(PlatformDataKeys.EDITOR)).getDocument(); VirtualFile virtualFileFromDocument = FileDocumentManager.getInstance().getFile(document); // 获取 document getDocument(e); }
Example #9
Source File: FactoryImpl.java From floobits-intellij with Apache License 2.0 | 6 votes |
@Override public IDoc getDocument(IFile virtualFile) { if (virtualFile == null) { return null; } Document document; try { document = FileDocumentManager.getInstance().getDocument(((FileImpl) virtualFile).virtualFile); } catch (RuntimeException e) { // We've seen an java.io.EOFException here before. Flog.error(e); return null; } if (document == null) { return null; } return new DocImpl(context, document); }
Example #10
Source File: PsiDocumentManagerBase.java From consulo with Apache License 2.0 | 6 votes |
@Override @Nullable public PsiFile getPsiFile(@Nonnull Document document) { if (document instanceof DocumentWindow && !((DocumentWindow)document).isValid()) { return null; } PsiFile psiFile = getCachedPsiFile(document); if (psiFile != null) { return ensureValidFile(psiFile, "Cached PSI"); } final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); if (virtualFile == null || !virtualFile.isValid()) return null; psiFile = getPsiFile(virtualFile); if (psiFile == null) return null; fireFileCreated(document, psiFile); return psiFile; }
Example #11
Source File: WrapWithCustomTemplateAction.java From consulo with Apache License 2.0 | 6 votes |
@Override public void actionPerformed(AnActionEvent e) { final Document document = myEditor.getDocument(); final VirtualFile file = FileDocumentManager.getInstance().getFile(document); if (file != null) { ReadonlyStatusHandler.getInstance(myFile.getProject()).ensureFilesWritable(file); } String selection = myEditor.getSelectionModel().getSelectedText(true); if (selection != null) { selection = selection.trim(); PsiDocumentManager.getInstance(myFile.getProject()).commitAllDocuments(); myTemplate.wrap(selection, new CustomTemplateCallback(myEditor, myFile)); } }
Example #12
Source File: ExternalFormatterCodeStyleManager.java From intellij with Apache License 2.0 | 6 votes |
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 #13
Source File: PsiFileImpl.java From consulo with Apache License 2.0 | 6 votes |
final void rebuildStub() { ApplicationManager.getApplication().invokeLater(() -> { if (!myManager.isDisposed()) { myManager.dropPsiCaches(); } final VirtualFile vFile = getVirtualFile(); if (vFile != null && vFile.isValid()) { final Document doc = FileDocumentManager.getInstance().getCachedDocument(vFile); if (doc != null) { FileDocumentManager.getInstance().saveDocument(doc); } FileContentUtilCore.reparseFiles(vFile); StubTreeLoader.getInstance().rebuildStubTree(vFile); } }, ModalityState.NON_MODAL); }
Example #14
Source File: ChangeFileEncodingAction.java From consulo with Apache License 2.0 | 6 votes |
@Nullable public ListPopup createPopup(@Nonnull DataContext dataContext) { final VirtualFile virtualFile = dataContext.getData(CommonDataKeys.VIRTUAL_FILE); if (virtualFile == null) return null; boolean enabled = checkEnabled(virtualFile); if (!enabled) return null; Editor editor = dataContext.getData(CommonDataKeys.EDITOR); FileDocumentManager documentManager = FileDocumentManager.getInstance(); final Document document = documentManager.getDocument(virtualFile); if (!allowDirectories && virtualFile.isDirectory() || document == null && !virtualFile.isDirectory()) return null; final byte[] bytes; try { bytes = virtualFile.isDirectory() ? null : VfsUtilCore.loadBytes(virtualFile); } catch (IOException e) { return null; } DefaultActionGroup group = createActionGroup(virtualFile, editor, document, bytes, null); return JBPopupFactory.getInstance().createActionGroupPopup(getTemplatePresentation().getText(), group, dataContext, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false); }
Example #15
Source File: LineStatusTracker.java From consulo with Apache License 2.0 | 5 votes |
private LineStatusTracker(@Nonnull final Project project, @Nonnull final Document document, @Nonnull final VirtualFile virtualFile, @Nonnull final Mode mode) { super(project, document); myVirtualFile = virtualFile; myMode = mode; myFileEditorManager = FileEditorManager.getInstance(project); myVcsDirtyScopeManager = VcsDirtyScopeManager.getInstance(project); }
Example #16
Source File: LocalFilePath.java From consulo with Apache License 2.0 | 5 votes |
@Override @javax.annotation.Nullable public Document getDocument() { VirtualFile file = getVirtualFile(); if (file == null || file.getFileType().isBinary()) { return null; } return FileDocumentManager.getInstance().getDocument(file); }
Example #17
Source File: RemoveUnusedParameterFix.java From bamboo-soy with Apache License 2.0 | 5 votes |
@Override void runFix(SoyAtParamSingle element) { final Document document = getContainingDocument(element); if (document == null) { return; } SoyParamDefinitionIdentifier paramDefinitionIdentifier = element.getParamDefinitionIdentifier(); if (paramDefinitionIdentifier == null) { return; } deleteParamSpecifications(paramDefinitionIdentifier); deleteElement(element, document); }
Example #18
Source File: CompletionInitializationUtil.java From consulo with Apache License 2.0 | 5 votes |
private static void syncAcceptSlashR(Document originalDocument, Document documentCopy) { if (!(originalDocument instanceof DocumentImpl) || !(documentCopy instanceof DocumentImpl)) { return; } ((DocumentImpl)documentCopy).setAcceptSlashR(((DocumentImpl)originalDocument).acceptsSlashR()); }
Example #19
Source File: PsiDocumentManagerBase.java From consulo with Apache License 2.0 | 5 votes |
private boolean commitToExistingPsi(@Nonnull Document document, @Nonnull List<? extends BooleanRunnable> finishProcessors, @Nonnull List<? extends BooleanRunnable> reparseInjectedProcessors, boolean synchronously, @Nullable VirtualFile virtualFile) { for (BooleanRunnable finishRunnable : finishProcessors) { boolean success = finishRunnable.run(); if (synchronously) { assert success : finishRunnable + " in " + finishProcessors; } if (!success) { return false; } } clearUncommittedInfo(document); if (virtualFile != null) { getSmartPointerManager().updatePointerTargetsAfterReparse(virtualFile); } FileViewProvider viewProvider = getCachedViewProvider(document); if (viewProvider != null) { viewProvider.contentsSynchronized(); } for (BooleanRunnable runnable : reparseInjectedProcessors) { if (!runnable.run()) return false; } return true; }
Example #20
Source File: LineOrientedDocumentChangeAdapter.java From consulo with Apache License 2.0 | 5 votes |
private static int normalize(Document document, int offset) { if (offset < 0) { return 0; } if (offset >= document.getTextLength()) { return Math.max(document.getTextLength() - 1, 0); } return offset; }
Example #21
Source File: HaxeRearrangerModel.java From intellij-haxe with Apache License 2.0 | 5 votes |
@NotNull @Override public List parse(@NotNull PsiElement element, @Nullable Document document, @NotNull Collection collection, @Nullable ArrangementSettings settings) { return null; }
Example #22
Source File: PsiFileService.java From intellij-swagger with MIT License | 5 votes |
public Optional<PsiFile> fromDocument(final Document document) { final Project[] openProjects = projectManager.getOpenProjects(); if (openProjects.length > 0) { final Project openProject = openProjects[0]; return Optional.ofNullable(psiDocumentManager.getPsiFile(openProject, document)); } return Optional.empty(); }
Example #23
Source File: SpecFormatter.java From Intellij-Plugin with Apache License 2.0 | 5 votes |
@Override public void actionPerformed(AnActionEvent anActionEvent) { final Project project = anActionEvent.getData(LangDataKeys.PROJECT); if (project == null) { return; } String projectDir = project.getBasePath(); if (projectDir == null) { return; } FileEditorManager fileEditorManager = FileEditorManager.getInstance(project); VirtualFile selectedFile = fileEditorManager.getSelectedFiles()[0]; String fileName = selectedFile.getCanonicalPath(); Document doc = FileDocumentManager.getInstance().getDocument(selectedFile); if (doc != null) { FileDocumentManager.getInstance().saveDocument(doc); } try { GaugeSettingsModel settings = getGaugeSettings(); ProcessBuilder processBuilder = new ProcessBuilder(settings.getGaugePath(), Constants.FORMAT, fileName); GaugeUtil.setGaugeEnvironmentsTo(processBuilder, settings); processBuilder.directory(new File(projectDir)); Process process = processBuilder.start(); int exitCode = process.waitFor(); if (exitCode != 0) { String output = String.format("<pre>%s</pre>", GaugeUtil.getOutput(process.getInputStream(), "\n").replace("<", "<").replace(">", ">")); Notifications.Bus.notify(new Notification("Spec Formatting", "Error: Spec Formatting", output, NotificationType.ERROR)); return; } VirtualFileManager.getInstance().syncRefresh(); selectedFile.refresh(false, false); } catch (Exception e) { e.printStackTrace(); LOG.debug(e); Messages.showErrorDialog("Error on formatting spec", "Format Error"); } }
Example #24
Source File: CSharpStatementMover.java From consulo-csharp with Apache License 2.0 | 5 votes |
@RequiredReadAction 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); }
Example #25
Source File: EmbeditorUtil.java From neovim-intellij-complete with MIT License | 5 votes |
public static int getOffsetFromLineStart(@NotNull CompletionParameters completionParameters, @NotNull Document document) { TextRange range = completionParameters.getPosition().getTextRange(); if (range != null) { int offset = range.getStartOffset(); int lineNumber = document.getLineNumber(offset); return offset - document.getLineStartOffset(lineNumber); } return 0; }
Example #26
Source File: LSPIJUtils.java From intellij-quarkus with Eclipse Public License 2.0 | 5 votes |
public static Editor[] editorsForFile(VirtualFile file) { Editor[] editors = new Editor[0]; Document document = FileDocumentManager.getInstance().getDocument(file); if (document != null) { editors = editorsForFile(file, document); } return editors; }
Example #27
Source File: PsiDocumentManagerBase.java From consulo with Apache License 2.0 | 5 votes |
boolean finishCommit(@Nonnull final Document document, @Nonnull List<? extends BooleanRunnable> finishProcessors, @Nonnull List<? extends BooleanRunnable> reparseInjectedProcessors, final boolean synchronously, @Nonnull final Object reason) { assert !myProject.isDisposed() : "Already disposed"; ApplicationManager.getApplication().assertIsDispatchThread(); final boolean[] ok = {true}; Runnable runnable = new DocumentRunnable(document, myProject) { @Override public void run() { ok[0] = finishCommitInWriteAction(document, finishProcessors, reparseInjectedProcessors, synchronously, false); } }; if (synchronously) { runnable.run(); } else { ApplicationManager.getApplication().runWriteAction(runnable); } if (ok[0]) { // run after commit actions outside write action runAfterCommitActions(document); if (DebugUtil.DO_EXPENSIVE_CHECKS && !ApplicationInfoImpl.isInPerformanceTest()) { checkAllElementsValid(document, reason); } } return ok[0]; }
Example #28
Source File: TextMergeViewer.java From consulo with Apache License 2.0 | 5 votes |
private void setInitialOutputContent() { final Document baseDocument = ThreeSide.BASE.select(myMergeRequest.getContents()).getDocument(); final Document outputDocument = myMergeRequest.getOutputContent().getDocument(); DiffUtil.executeWriteCommand(outputDocument, getProject(), "Init merge content", () -> { outputDocument.setText(baseDocument.getCharsSequence()); DiffUtil.putNonundoableOperation(getProject(), outputDocument); }); }
Example #29
Source File: EditorPool.java From saros with GNU General Public License v2.0 | 5 votes |
/** * Returns the <code>IFile</code> for the given document. * * @param doc the <code>Document</code> to get the file for * @return the <code>IFile</code> for the given document or <code>null</code> if no matching file * could be found in the editor pool */ @Nullable IFile getFile(@Nullable Document doc) { for (Map.Entry<IFile, Editor> entry : editors.entrySet()) { if (entry.getValue().getDocument().equals(doc)) { return entry.getKey(); } } return null; }
Example #30
Source File: IdeaGateway.java From consulo with Apache License 2.0 | 5 votes |
@Nullable private Entry doCreateEntry(@Nonnull VirtualFile file, boolean forDeletion) { if (!file.isDirectory()) { if (!isVersioned(file)) return null; Pair<StoredContent, Long> contentAndStamps; if (forDeletion) { FileDocumentManager m = FileDocumentManager.getInstance(); Document d = m.isFileModified(file) ? m.getCachedDocument(file) : null; // should not try to load document contentAndStamps = acquireAndClearCurrentContent(file, d); } else { contentAndStamps = getActualContentNoAcquire(file); } return doCreateFileEntry(file, contentAndStamps); } DirectoryEntry newDir = null; if (file instanceof VirtualFileSystemEntry) { int nameId = ((VirtualFileSystemEntry)file).getNameId(); if (nameId > 0) { newDir = new DirectoryEntry(nameId); } } if (newDir == null) { newDir = new DirectoryEntry(file.getName()); } doCreateChildren(newDir, iterateDBChildren(file), forDeletion); if (!isVersioned(file) && newDir.getChildren().isEmpty()) return null; return newDir; }