com.intellij.openapi.fileEditor.FileDocumentManager Java Examples
The following examples show how to use
com.intellij.openapi.fileEditor.FileDocumentManager.
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: 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 #2
Source File: PsiFileImplUtil.java From consulo with Apache License 2.0 | 6 votes |
@RequiredUIAccess public static PsiFile setName(final PsiFile file, String newName) throws IncorrectOperationException { VirtualFile vFile = file.getViewProvider().getVirtualFile(); PsiManagerImpl manager = (PsiManagerImpl)file.getManager(); try{ final FileType newFileType = FileTypeRegistry.getInstance().getFileTypeByFileName(newName); if (UnknownFileType.INSTANCE.equals(newFileType) || newFileType.isBinary()) { // before the file becomes unknown or a binary (thus, not openable in the editor), save it to prevent data loss final FileDocumentManager fdm = FileDocumentManager.getInstance(); final Document doc = fdm.getCachedDocument(vFile); if (doc != null) { fdm.saveDocumentAsIs(doc); } } vFile.rename(manager, newName); } catch(IOException e){ throw new IncorrectOperationException(e); } return file.getViewProvider().isPhysical() ? manager.findFile(vFile) : file; }
Example #3
Source File: MemoryDiskConflictResolver.java From consulo with Apache License 2.0 | 6 votes |
void beforeContentChange(@Nonnull VFileContentChangeEvent event) { if (event.isFromSave()) return; VirtualFile file = event.getFile(); if (!file.isValid() || hasConflict(file)) return; Document document = FileDocumentManager.getInstance().getCachedDocument(file); if (document == null || !FileDocumentManager.getInstance().isDocumentUnsaved(document)) return; long documentStamp = document.getModificationStamp(); long oldFileStamp = event.getOldModificationStamp(); if (documentStamp != oldFileStamp) { LOG.info("reload " + file.getName() + " from disk?"); LOG.info(" documentStamp:" + documentStamp); LOG.info(" oldFileStamp:" + oldFileStamp); if (myConflicts.isEmpty()) { if (ApplicationManager.getApplication().isUnitTestMode()) { myConflictAppeared = new Throwable(); } ApplicationManager.getApplication().invokeLater(this::processConflicts); } myConflicts.add(file); } }
Example #4
Source File: DiffRequestFactoryImpl.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull @Override public TextMergeRequest createTextMergeRequest(@Nullable Project project, @Nonnull VirtualFile output, @Nonnull List<byte[]> byteContents, @Nullable String title, @Nonnull List<String> contentTitles, @Nullable Consumer<MergeResult> applyCallback) throws InvalidDiffRequestException { if (byteContents.size() != 3) throw new IllegalArgumentException(); if (contentTitles.size() != 3) throw new IllegalArgumentException(); final Document outputDocument = FileDocumentManager.getInstance().getDocument(output); if (outputDocument == null) throw new InvalidDiffRequestException("Can't get output document: " + output.getPresentableUrl()); if (!DiffUtil.canMakeWritable(outputDocument)) throw new InvalidDiffRequestException("Output is read only: " + output.getPresentableUrl()); DocumentContent outputContent = myContentFactory.create(project, outputDocument); CharSequence originalContent = outputDocument.getImmutableCharSequence(); List<DocumentContent> contents = new ArrayList<>(3); for (byte[] bytes : byteContents) { contents.add(myContentFactory.createDocumentFromBytes(project, bytes, output)); } return new TextMergeRequestImpl(project, outputContent, originalContent, contents, title, contentTitles, applyCallback); }
Example #5
Source File: SelectInTargetImpl.java From netbeans-mmd-plugin with Apache License 2.0 | 6 votes |
@Override public boolean canSelect(@Nonnull final SelectInContext context) { if (this.myProject.isDisposed()) { return false; } else { VirtualFile virtualFile = context.getVirtualFile(); if (!virtualFile.isValid()) { return false; } else { final Document document = FileDocumentManager.getInstance().getDocument(virtualFile); Object psiFile; if (document != null) { psiFile = PsiDocumentManager.getInstance(this.myProject).getPsiFile(document); } else if (context.getSelectorInFile() instanceof PsiFile) { psiFile = context.getSelectorInFile(); } else if (virtualFile.isDirectory()) { psiFile = PsiManager.getInstance(this.myProject).findDirectory(virtualFile); } else { psiFile = PsiManager.getInstance(this.myProject).findFile(virtualFile); } return psiFile != null; } } }
Example #6
Source File: Unity3dTestDebuggerRunner.java From consulo-unity3d with Apache License 2.0 | 6 votes |
@Override @RequiredUIAccess protected RunContentDescriptor doExecute(@Nonnull RunProfileState state, @Nonnull ExecutionEnvironment env) throws ExecutionException { UnityProcess editorProcess = UnityEditorCommunication.findEditorProcess(); if(editorProcess == null) { throw new ExecutionException("Editor is not responding"); } FileDocumentManager.getInstance().saveAllDocuments(); ExecutionResult executionResult = state.execute(env.getExecutor(), this); if(executionResult == null) { return null; } return Unity3dAttachRunner.runContentDescriptor(executionResult, env, editorProcess, (ConsoleView) executionResult.getExecutionConsole(), true); }
Example #7
Source File: CopyReferenceAction.java From consulo with Apache License 2.0 | 6 votes |
@Override public void update(AnActionEvent e) { boolean plural = false; boolean enabled; DataContext dataContext = e.getDataContext(); Editor editor = dataContext.getData(CommonDataKeys.EDITOR); if (editor != null && FileDocumentManager.getInstance().getFile(editor.getDocument()) != null) { enabled = true; } else { List<PsiElement> elements = getElementsToCopy(editor, dataContext); enabled = !elements.isEmpty(); plural = elements.size() > 1; } e.getPresentation().setEnabled(enabled); if (ActionPlaces.isPopupPlace(e.getPlace())) { e.getPresentation().setVisible(enabled); } else { e.getPresentation().setVisible(true); } e.getPresentation().setText(plural ? "Cop&y References" : "Cop&y Reference"); }
Example #8
Source File: FlutterSdkAction.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public void actionPerformed(@NotNull AnActionEvent event) { final Project project = DumbAwareAction.getEventProject(event); if (enableActionInBazelContext()) { // See if the Bazel workspace exists for this project. final Workspace workspace = FlutterModuleUtils.getFlutterBazelWorkspace(project); if (workspace != null) { FlutterInitializer.sendAnalyticsAction(this); FileDocumentManager.getInstance().saveAllDocuments(); startCommandInBazelContext(project, workspace); return; } } final FlutterSdk sdk = project != null ? FlutterSdk.getFlutterSdk(project) : null; if (sdk == null) { showMissingSdkDialog(project); return; } FlutterInitializer.sendAnalyticsAction(this); FileDocumentManager.getInstance().saveAllDocuments(); startCommand(project, sdk, PubRoot.forEventWithRefresh(event), event.getDataContext()); }
Example #9
Source File: FileUtils.java From JHelper with GNU Lesser General Public License v3.0 | 6 votes |
public static void writeToFile(PsiFile outputFile, String... strings) { Project project = outputFile.getProject(); Document document = PsiDocumentManager.getInstance(project).getDocument(outputFile); if (document == null) { throw new NotificationException("Couldn't open output file as document"); } WriteCommandAction.writeCommandAction(project).run( () -> { document.deleteString(0, document.getTextLength()); for (String string : strings) { document.insertString(document.getTextLength(), string); } FileDocumentManager.getInstance().saveDocument(document); PsiDocumentManager.getInstance(project).commitDocument(document); } ); }
Example #10
Source File: CreateFileFix.java From consulo with Apache License 2.0 | 6 votes |
protected void openFile(@Nonnull Project project, PsiDirectory directory, PsiFile newFile, String text) { final FileEditorManager editorManager = FileEditorManager.getInstance(directory.getProject()); final FileEditor[] fileEditors = editorManager.openFile(newFile.getVirtualFile(), true); if (text != null) { for (FileEditor fileEditor : fileEditors) { if (fileEditor instanceof TextEditor) { // JSP is not safe to edit via Psi final Document document = ((TextEditor)fileEditor).getEditor().getDocument(); document.setText(text); if (ApplicationManager.getApplication().isUnitTestMode()) { FileDocumentManager.getInstance().saveDocument(document); } PsiDocumentManager.getInstance(project).commitDocument(document); break; } } } }
Example #11
Source File: TestLaunchState.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
static TestLaunchState create(@NotNull ExecutionEnvironment env, @NotNull TestConfig config) throws ExecutionException { final TestFields fields = config.getFields(); try { fields.checkRunnable(env.getProject()); } catch (RuntimeConfigurationError e) { throw new ExecutionException(e); } FileDocumentManager.getInstance().saveAllDocuments(); final VirtualFile fileOrDir = fields.getFileOrDir(); assert (fileOrDir != null); final PubRoot pubRoot = fields.getPubRoot(env.getProject()); assert (pubRoot != null); final FlutterSdk sdk = FlutterSdk.getFlutterSdk(env.getProject()); assert (sdk != null); final boolean testConsoleEnabled = sdk.getVersion().flutterTestSupportsMachineMode(); final TestLaunchState launcher = new TestLaunchState(env, config, fileOrDir, pubRoot, testConsoleEnabled); DaemonConsoleView.install(launcher, env, pubRoot.getRoot()); return launcher; }
Example #12
Source File: ToggleReadOnlyAttributeAction.java From consulo with Apache License 2.0 | 6 votes |
public void actionPerformed(final AnActionEvent e){ ApplicationManager.getApplication().runWriteAction( new Runnable(){ public void run(){ // Save all documents. We won't be able to save changes to the files that became read-only afterwards. FileDocumentManager.getInstance().saveAllDocuments(); try { VirtualFile[] files=getFiles(e.getDataContext()); for (VirtualFile file : files) { ReadOnlyAttributeUtil.setReadOnlyAttribute(file, file.isWritable()); } } catch(IOException exc){ Project project = e.getData(CommonDataKeys.PROJECT); Messages.showMessageDialog( project, exc.getMessage(), CommonBundle.getErrorTitle(),Messages.getErrorIcon() ); } } } ); }
Example #13
Source File: ORFileEditorListener.java From reasonml-idea-plugin with MIT License | 6 votes |
@Override public void documentChanged(@NotNull DocumentEvent event) { Document document = event.getDocument(); // When document lines count change, we move the type annotations int newLineCount = document.getLineCount(); if (newLineCount != m_oldLinesCount) { CodeLensView.CodeLensInfo userData = m_project.getUserData(CodeLensView.CODE_LENS); if (userData != null) { VirtualFile file = FileDocumentManager.getInstance().getFile(document); if (file != null) { FileEditor selectedEditor = FileEditorManager.getInstance(m_project).getSelectedEditor(file); if (selectedEditor instanceof TextEditor) { TextEditor editor = (TextEditor) selectedEditor; LogicalPosition cursorPosition = editor.getEditor().offsetToLogicalPosition(event.getOffset()); int direction = newLineCount - m_oldLinesCount; userData.move(file, cursorPosition, direction); } } } } m_queue.queue(m_project, document); }
Example #14
Source File: BazelTestLaunchState.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static BazelTestLaunchState create(@NotNull ExecutionEnvironment env, @NotNull BazelTestConfig config) throws ExecutionException { final BazelTestFields fields = config.getFields(); try { fields.checkRunnable(env.getProject()); } catch (RuntimeConfigurationError e) { throw new ExecutionException(e); } FileDocumentManager.getInstance().saveAllDocuments(); final VirtualFile virtualFile = fields.getFile(); final BazelTestLaunchState launcher = new BazelTestLaunchState(env, config, virtualFile); final Workspace workspace = FlutterModuleUtils.getFlutterBazelWorkspace(env.getProject()); if (workspace != null) { DaemonConsoleView.install(launcher, env, workspace.getRoot()); } return launcher; }
Example #15
Source File: XValueHint.java From consulo with Apache License 2.0 | 6 votes |
public XValueHint(@Nonnull Project project, @Nonnull Editor editor, @Nonnull Point point, @Nonnull ValueHintType type, @Nonnull ExpressionInfo expressionInfo, @Nonnull XDebuggerEvaluator evaluator, @Nonnull XDebugSession session) { super(project, editor, point, type, expressionInfo.getTextRange()); myEvaluator = evaluator; myDebugSession = session; myExpression = XDebuggerEvaluateActionHandler.getExpressionText(expressionInfo, editor.getDocument()); myValueName = XDebuggerEvaluateActionHandler.getDisplayText(expressionInfo, editor.getDocument()); myExpressionInfo = expressionInfo; VirtualFile file; ConsoleView consoleView = ConsoleViewImpl.CONSOLE_VIEW_IN_EDITOR_VIEW.get(editor); if (consoleView instanceof LanguageConsoleView) { LanguageConsoleView console = ((LanguageConsoleView)consoleView); file = console.getHistoryViewer() == editor ? console.getVirtualFile() : null; } else { file = FileDocumentManager.getInstance().getFile(editor.getDocument()); } myExpressionPosition = file != null ? XDebuggerUtil.getInstance().createPositionByOffset(file, expressionInfo.getTextRange().getStartOffset()) : null; }
Example #16
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 #17
Source File: LSPQuickDocAction.java From lsp4intellij with Apache License 2.0 | 6 votes |
@Override public void actionPerformed(AnActionEvent e) { Editor editor = e.getData(CommonDataKeys.EDITOR); VirtualFile file = FileDocumentManager.getInstance().getFile(editor.getDocument()); Language language = PsiManager.getInstance(editor.getProject()).findFile(file).getLanguage(); //Hack for IntelliJ 2018 TODO proper way if (LanguageDocumentation.INSTANCE.allForLanguage(language).isEmpty() || (Integer.parseInt(ApplicationInfo.getInstance().getMajorVersion()) > 2017) && language == PlainTextLanguage.INSTANCE) { EditorEventManager manager = EditorEventManagerBase.forEditor(editor); if (manager != null) { manager.quickDoc(editor); } else { super.actionPerformed(e); } } else super.actionPerformed(e); }
Example #18
Source File: EncodingManagerImpl.java From consulo with Apache License 2.0 | 6 votes |
/** * @param virtualFile * @return returns null if charset set cannot be determined from content */ @Nullable Charset computeCharsetFromContent(@Nonnull final VirtualFile virtualFile) { final Document document = FileDocumentManager.getInstance().getDocument(virtualFile); if (document == null) { return null; } Charset cached = EncodingManager.getInstance().getCachedCharsetFromContent(document); if (cached != null) { return cached; } final Project project = ProjectLocator.getInstance().guessProjectForFile(virtualFile); return ReadAction.compute(() -> { Charset charsetFromContent = LoadTextUtil.charsetFromContentOrNull(project, virtualFile, document.getImmutableCharSequence()); if (charsetFromContent != null) { setCachedCharsetFromContent(charsetFromContent, null, document); } return charsetFromContent; }); }
Example #19
Source File: UndoChangeRevertingVisitor.java From consulo with Apache License 2.0 | 6 votes |
@Override public void apply() throws IOException { if (!myContent.isAvailable()) return; boolean isReadOnly = !myFile.isWritable(); ReadOnlyAttributeUtil.setReadOnlyAttribute(myFile, false); Document doc = FileDocumentManager.getInstance().getCachedDocument(myFile); DocumentUndoProvider.startDocumentUndo(doc); try { myFile.setBinaryContent(myContent.getBytes(), -1, myTimestamp); } finally { DocumentUndoProvider.finishDocumentUndo(doc); } ReadOnlyAttributeUtil.setReadOnlyAttribute(myFile, isReadOnly); }
Example #20
Source File: EncodingUtil.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull static Magic8 isSafeToReloadIn(@Nonnull VirtualFile virtualFile, @Nonnull CharSequence text, @Nonnull byte[] bytes, @Nonnull Charset charset) { // file has BOM but the charset hasn't byte[] bom = virtualFile.getBOM(); if (bom != null && !CharsetToolkit.canHaveBom(charset, bom)) return Magic8.NO_WAY; // the charset has mandatory BOM (e.g. UTF-xx) but the file hasn't or has wrong byte[] mandatoryBom = CharsetToolkit.getMandatoryBom(charset); if (mandatoryBom != null && !ArrayUtil.startsWith(bytes, mandatoryBom)) return Magic8.NO_WAY; String loaded = LoadTextUtil.getTextByBinaryPresentation(bytes, charset).toString(); String separator = FileDocumentManager.getInstance().getLineSeparator(virtualFile, null); String toSave = StringUtil.convertLineSeparators(loaded, separator); LoadTextUtil.AutoDetectionReason failReason = LoadTextUtil.getCharsetAutoDetectionReason(virtualFile); if (failReason != null && StandardCharsets.UTF_8.equals(virtualFile.getCharset()) && !StandardCharsets.UTF_8.equals(charset)) { return Magic8.NO_WAY; // can't reload utf8-autodetected file in another charset } byte[] bytesToSave; try { bytesToSave = toSave.getBytes(charset); } // turned out some crazy charsets have incorrectly implemented .newEncoder() returning null catch (UnsupportedOperationException | NullPointerException e) { return Magic8.NO_WAY; } if (bom != null && !ArrayUtil.startsWith(bytesToSave, bom)) { bytesToSave = ArrayUtil.mergeArrays(bom, bytesToSave); // for 2-byte encodings String.getBytes(Charset) adds BOM automatically } return !Arrays.equals(bytesToSave, bytes) ? Magic8.NO_WAY : StringUtil.equals(loaded, text) ? Magic8.ABSOLUTELY : Magic8.WELL_IF_YOU_INSIST; }
Example #21
Source File: LayeredLexerEditorHighlighter.java From consulo with Apache License 2.0 | 5 votes |
private void checkNull(@Nonnull IElementType type, @Nullable MappedRange range) { if (range != null) { Document mainDocument = getDocument(); VirtualFile file = mainDocument == null ? null : FileDocumentManager.getInstance().getFile(mainDocument); LOG.error("Expected null range on " + type + ", found " + range + "; highlighter=" + getSyntaxHighlighter(), new Attachment(file != null ? file.getName() : "editorText.txt", myText.toString())); } }
Example #22
Source File: BaseRefactorHandler.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void run() { if (!EditorModificationUtil.checkModificationAllowed(editor)) { return; } if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) { return; } process(chooser.getSelectedElements()); }
Example #23
Source File: MemoryDiskConflictResolver.java From consulo with Apache License 2.0 | 5 votes |
private void processConflicts() { List<VirtualFile> conflicts = new ArrayList<>(myConflicts); myConflicts.clear(); for (VirtualFile file : conflicts) { Document document = FileDocumentManager.getInstance().getCachedDocument(file); if (document != null && file.getModificationStamp() != document.getModificationStamp() && askReloadFromDisk(file, document)) { FileDocumentManager.getInstance().reloadFromDisk(document); } } myConflictAppeared = null; }
Example #24
Source File: PsiVFSListener.java From consulo with Apache License 2.0 | 5 votes |
@Nullable private PsiFile createFileCopyWithNewName(VirtualFile vFile, String name) { // TODO[ik] remove this. Event handling and generation must be in view providers mechanism since we // need to track changes in _all_ psi views (e.g. namespace changes in XML) final FileTypeManager instance = FileTypeManager.getInstance(); if (instance.isFileIgnored(name)) return null; final FileType fileTypeByFileName = instance.getFileTypeByFileName(name); final Document document = FileDocumentManager.getInstance().getDocument(vFile); return PsiFileFactory.getInstance(myManager.getProject()) .createFileFromText(name, fileTypeByFileName, document != null ? document.getCharsSequence() : "", vFile.getModificationStamp(), true, false); }
Example #25
Source File: CodeInspectionAction.java From consulo with Apache License 2.0 | 5 votes |
protected void runInspections(Project project, AnalysisScope scope) { scope.setSearchInLibraries(false); FileDocumentManager.getInstance().saveAllDocuments(); final GlobalInspectionContextImpl inspectionContext = getGlobalInspectionContext(project); inspectionContext.setExternalProfile(myExternalProfile); inspectionContext.setCurrentScope(scope); inspectionContext.doInspections(scope); }
Example #26
Source File: EncodingProjectManagerImpl.java From consulo with Apache License 2.0 | 5 votes |
private static Processor<VirtualFile> createChangeCharsetProcessor() { return file -> { if (!(file instanceof VirtualFileSystemEntry)) return false; Document cachedDocument = FileDocumentManager.getInstance().getCachedDocument(file); if (cachedDocument == null) return true; ProgressManager.progress("Reloading files...", file.getPresentableUrl()); TransactionGuard.submitTransaction(ApplicationManager.getApplication(), () -> clearAndReload(file)); return true; }; }
Example #27
Source File: FileElementInfo.java From consulo with Apache License 2.0 | 5 votes |
@Nullable @Override Segment getPsiRange(@Nonnull SmartPointerManagerImpl manager) { Document currentDoc = FileDocumentManager.getInstance().getCachedDocument(myVirtualFile); Document committedDoc = currentDoc == null ? null : ((PsiDocumentManagerBase)PsiDocumentManager.getInstance(myProject)).getLastCommittedDocument(currentDoc); return committedDoc == null ? getRange(manager) : new TextRange(0, committedDoc.getTextLength()); }
Example #28
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 #29
Source File: HaxeDebuggerSupportUtils.java From intellij-haxe with Apache License 2.0 | 5 votes |
@Nullable public static PsiElement getContextElement(VirtualFile virtualFile, int offset, final @NotNull Project project) { Document document = FileDocumentManager.getInstance().getDocument(virtualFile); PsiFile file = PsiManager.getInstance(project).findFile(virtualFile); if (file == null || document == null) { return null; } if (offset < 0) offset = 0; if (offset > document.getTextLength()) offset = document.getTextLength(); int startOffset = offset; int lineEndOffset = document.getLineEndOffset(document.getLineNumber(offset)); PsiElement result = null; do { PsiElement element = file.findElementAt(offset); if (!(element instanceof PsiWhiteSpace) && !(element instanceof PsiComment)) { result = element; break; } offset = element.getTextRange().getEndOffset() + 1; } while (offset < lineEndOffset); if (result == null) { result = file.findElementAt(startOffset); } return result; }
Example #30
Source File: ApplyPatchAction.java From consulo with Apache License 2.0 | 5 votes |
public void actionPerformed(AnActionEvent e) { final Project project = e.getRequiredData(CommonDataKeys.PROJECT); if (ChangeListManager.getInstance(project).isFreezedWithNotification("Can not apply patch now")) return; FileDocumentManager.getInstance().saveAllDocuments(); VirtualFile vFile = null; final String place = e.getPlace(); if (isProjectOrScopeView(place) || ActionPlaces.MAIN_MENU.equals(place)) { vFile = e.getData(CommonDataKeys.VIRTUAL_FILE); } if (isPatchFile(vFile)) { showApplyPatch(project, vFile); } else { final FileChooserDescriptor descriptor = ApplyPatchDifferentiatedDialog.createSelectPatchDescriptor(); final VcsApplicationSettings settings = VcsApplicationSettings.getInstance(); final VirtualFile toSelect = settings.PATCH_STORAGE_LOCATION == null ? null : LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(settings.PATCH_STORAGE_LOCATION)); FileChooser.chooseFile(descriptor, project, toSelect).doWhenDone(file -> { final VirtualFile parent = file.getParent(); if (parent != null) { settings.PATCH_STORAGE_LOCATION = FileUtil.toSystemDependentName(parent.getPath()); } showApplyPatch(project, file); }); } }