Java Code Examples for com.intellij.openapi.fileEditor.FileDocumentManager#getInstance()

The following examples show how to use com.intellij.openapi.fileEditor.FileDocumentManager#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: FileDocumentManagerImplTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();
  myReloadFromDisk = Boolean.TRUE;
  FileDocumentManagerImpl impl = (FileDocumentManagerImpl)FileDocumentManager.getInstance();
  impl.setAskReloadFromDisk(getTestRootDisposable(), new MemoryDiskConflictResolver() {
    @Override
    public boolean askReloadFromDisk(VirtualFile file, Document document) {
      if (myReloadFromDisk == null) {
        fail();
        return false;
      }
      return myReloadFromDisk.booleanValue();
    }
  });
  myDocumentManager = impl;
}
 
Example 2
Source File: LightPlatformCodeInsightTestCase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static Document setupFileEditorAndDocument(@Nonnull String fileName, @Nonnull String fileText) throws IOException {
  EncodingProjectManager.getInstance(getProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET);
  EncodingProjectManager.getInstance(ProjectManager.getInstance().getDefaultProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET);
  PostprocessReformattingAspect.getInstance(ourProject).doPostponedFormatting();
  deleteVFile();
  myVFile = getSourceRoot().createChildData(null, fileName);
  VfsUtil.saveText(myVFile, fileText);
  final FileDocumentManager manager = FileDocumentManager.getInstance();
  final Document document = manager.getDocument(myVFile);
  assertNotNull("Can't create document for '" + fileName + "'", document);
  manager.reloadFromDisk(document);
  document.insertString(0, " ");
  document.deleteString(0, 1);
  myFile = getPsiManager().findFile(myVFile);
  assertNotNull("Can't create PsiFile for '" + fileName + "'. Unknown file type most probably.", myFile);
  assertTrue(myFile.isPhysical());
  myEditor = createEditor(myVFile);
  myVFile.setCharset(CharsetToolkit.UTF8_CHARSET);

  PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
  return document;
}
 
Example 3
Source File: EncodingUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
static FailReason checkCanReload(@Nonnull VirtualFile virtualFile, @Nullable Ref<? super Charset> current) {
  if (virtualFile.isDirectory()) {
    return FailReason.IS_DIRECTORY;
  }
  FileDocumentManager documentManager = FileDocumentManager.getInstance();
  Document document = documentManager.getDocument(virtualFile);
  if (document == null) return FailReason.IS_BINARY;
  Charset charsetFromContent = ((EncodingManagerImpl)EncodingManager.getInstance()).computeCharsetFromContent(virtualFile);
  Charset existing = virtualFile.getCharset();
  LoadTextUtil.AutoDetectionReason autoDetectedFrom = LoadTextUtil.getCharsetAutoDetectionReason(virtualFile);
  FailReason result;
  if (autoDetectedFrom != null) {
    // no point changing encoding if it was auto-detected
    result = autoDetectedFrom == LoadTextUtil.AutoDetectionReason.FROM_BOM ? FailReason.BY_BOM : FailReason.BY_BYTES;
  }
  else if (charsetFromContent != null) {
    result = FailReason.BY_FILE;
    existing = charsetFromContent;
  }
  else {
    result = fileTypeDescriptionError(virtualFile);
  }
  if (current != null) current.set(existing);
  return result;
}
 
Example 4
Source File: ExternalSystemAutoImporter.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void documentChanged(DocumentEvent event) {
  Document document = event.getDocument();
  FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
  VirtualFile file = fileDocumentManager.getFile(document);
  if (file == null) {
    return;
  }

  String path = ExternalSystemApiUtil.getLocalFileSystemPath(file);
  for (MyEntry entry : myAutoImportAware) {
    if (entry.aware.getAffectedExternalProjectPath(path, myProject) != null) {
      // Document save triggers VFS event but FileDocumentManager might be registered after the current listener, that's why
      // call to 'saveDocument()' might not produce the desired effect. That's why we reschedule document save if necessary.
      scheduleDocumentSave(document);
      return;
    }
  } 
}
 
Example 5
Source File: ProjectFileIndexSampleAction.java    From intellij-sdk-docs with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
  Project project = event.getProject();
  final Editor editor = event.getData(CommonDataKeys.EDITOR);
  if (project == null || editor == null) return;
  Document document = editor.getDocument();
  FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
  VirtualFile virtualFile = fileDocumentManager.getFile(document);
  ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  if (virtualFile != null) {
    Module module = projectFileIndex.getModuleForFile(virtualFile);
    String moduleName;
    moduleName = module != null ? module.getName() : "No module defined for file";

    VirtualFile moduleContentRoot = projectFileIndex.getContentRootForFile(virtualFile);
    boolean isLibraryFile = projectFileIndex.isLibraryClassFile(virtualFile);
    boolean isInLibraryClasses = projectFileIndex.isInLibraryClasses(virtualFile);
    boolean isInLibrarySource = projectFileIndex.isInLibrarySource(virtualFile);
    Messages.showInfoMessage("Module: " + moduleName + "\n" +
                             "Module content root: " + moduleContentRoot + "\n" +
                             "Is library file: " + isLibraryFile + "\n" +
                             "Is in library classes: " + isInLibraryClasses +
                             ", Is in library source: " + isInLibrarySource,
                             "Main File Info for" + virtualFile.getName());
  }
}
 
Example 6
Source File: HaskellDocumentationProvider.java    From intellij-haskforce with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public String generateDoc(PsiElement element, @Nullable PsiElement originalElement) {
    int startOffset = element.getTextRange().getStartOffset();
    int endOffset = element.getTextRange().getEndOffset();
    Module module = ModuleUtilCore.findModuleForPsiElement(element);
    FileDocumentManager fileDocumentManager= FileDocumentManager.getInstance();
    VirtualFile projectFile = element.getContainingFile().getVirtualFile();
    Document cachedDocument = fileDocumentManager.getCachedDocument(projectFile);
    if (cachedDocument == null) {
        return null;
    }
    int startLineNumber = cachedDocument.getLineNumber(startOffset);
    int endLineNumber = cachedDocument.getLineNumber(endOffset);
    int startColumn = startOffset - cachedDocument.getLineStartOffset(startLineNumber);
    int endColumn = endOffset - cachedDocument.getLineStartOffset(endLineNumber);

    // and also correct them for (0,0) vs (1,1) leftmost coordinate (intellij -> ghc)
    VisualPosition startPosition = TypeInfoUtil.correctFor0BasedVS1Based(new VisualPosition(startLineNumber, startColumn));
    VisualPosition endPosition = TypeInfoUtil.correctFor0BasedVS1Based(new VisualPosition(endLineNumber, endColumn));
    return TypeInfoUtil.getTypeInfo(module,startPosition,endPosition, projectFile);
}
 
Example 7
Source File: DesktopEditorImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private boolean processKeyTyped(char c) {

    if (ProgressManager.getInstance().hasModalProgressIndicator()) {
      return false;
    }
    FileDocumentManager manager = FileDocumentManager.getInstance();
    final VirtualFile file = manager.getFile(myDocument);
    if (file != null && !file.isValid()) {
      return false;
    }

    DataContext context = getDataContext();

    Graphics graphics = GraphicsUtil.safelyGetGraphics(myEditorComponent);
    if (graphics != null) { // editor component is not showing
      PaintUtil.alignTxToInt((Graphics2D)graphics, PaintUtil.insets2offset(getInsets()), true, false, RoundingMode.CEIL);
      processKeyTypedImmediately(c, graphics, context);
      graphics.dispose();
    }

    ActionManagerEx.getInstanceEx().fireBeforeEditorTyping(c, context);
    EditorUIUtil.hideCursorInEditor(this);
    processKeyTypedNormally(c, context);

    return true;
  }
 
Example 8
Source File: CustomVisibleAreaListener.java    From jetbrains-wakatime with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void visibleAreaChanged(VisibleAreaEvent visibleAreaEvent) {
    FileDocumentManager instance = FileDocumentManager.getInstance();
    VirtualFile file = instance.getFile(visibleAreaEvent.getEditor().getDocument());
    Project project = visibleAreaEvent.getEditor().getProject();
    WakaTime.appendHeartbeat(file, project, false);
}
 
Example 9
Source File: FileDocumentManagerImplTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testFileTypeModificationDocumentPreservation() throws Exception {
  File ioFile = IoTestUtil.createTestFile("test.html", "<html>some text</html>");
  VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ioFile);
  assertNotNull(ioFile.getPath(), file);

  FileDocumentManager documentManager = FileDocumentManager.getInstance();
  Document original = documentManager.getDocument(file);
  assertNotNull(file.getPath(), original);

  renameFile(file, "test.wtf");
  Document afterRename = documentManager.getDocument(file);
  assertTrue(afterRename + " != " + original, afterRename == original);
}
 
Example 10
Source File: DocumentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void beforeChangedUpdate(DocumentEvent event, DelayedExceptions exceptions) {
  Application app = ApplicationManager.getApplication();
  if (app != null) {
    FileDocumentManager manager = FileDocumentManager.getInstance();
    VirtualFile file = manager.getFile(this);
    if (file != null && !file.isValid()) {
      LOG.error("File of this document has been deleted: " + file);
    }
  }
  assertInsideCommand();

  getLineSet(); // initialize line set to track changed lines

  if (!ShutDownTracker.isShutdownHookRunning()) {
    DocumentListener[] listeners = getListeners();
    for (int i = listeners.length - 1; i >= 0; i--) {
      try {
        listeners[i].beforeDocumentChange(event);
      }
      catch (Throwable e) {
        exceptions.register(e);
      }
    }
  }

  myEventsHandling = true;
}
 
Example 11
Source File: EclipseCodeFormatter.java    From EclipseCodeFormatter with Apache License 2.0 5 votes vote down vote up
private void formatWhenEditorIsClosed(Range range, PsiFile psiFile) throws FileDoesNotExistsException {
	LOG.debug("#formatWhenEditorIsClosed " + psiFile.getName());

	VirtualFile virtualFile = psiFile.getVirtualFile();
	FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
	Document document = fileDocumentManager.getDocument(virtualFile);
	fileDocumentManager.saveDocument(document); // when file is edited and editor is closed, it is needed to save
	// the text
	String text = document.getText();
	String reformat = reformat(range.getStartOffset(), range.getEndOffset(), text, psiFile);

	document.setText(reformat);
	postProcess(document, psiFile, range, fileDocumentManager);
}
 
Example 12
Source File: CustomEditorMouseListener.java    From jetbrains-wakatime with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void mousePressed(EditorMouseEvent editorMouseEvent) {
    FileDocumentManager instance = FileDocumentManager.getInstance();
    VirtualFile file = instance.getFile(editorMouseEvent.getEditor().getDocument());
    Project project = editorMouseEvent.getEditor().getProject();
    WakaTime.appendHeartbeat(file, project, false);
}
 
Example 13
Source File: CustomDocumentListener.java    From jetbrains-wakatime with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void documentChanged(DocumentEvent documentEvent) {
    Document document = documentEvent.getDocument();
    FileDocumentManager instance = FileDocumentManager.getInstance();
    VirtualFile file = instance.getFile(document);
    WakaTime.appendHeartbeat(file, WakaTime.getProject(document), false);
}
 
Example 14
Source File: IdeaGateway.java    From consulo with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 15
Source File: GTMVisibleAreaListener.java    From gtm-jetbrains-plugin with MIT License 5 votes vote down vote up
@Override
public void visibleAreaChanged(VisibleAreaEvent visibleAreaEvent) {
    final FileDocumentManager instance = FileDocumentManager.getInstance();
    final VirtualFile file = instance.getFile(visibleAreaEvent.getEditor().getDocument());
    if (file != null) {
        GTMRecord.record(file.getPath(), visibleAreaEvent.getEditor().getProject());
    }
}
 
Example 16
Source File: CustomSaveListener.java    From jetbrains-wakatime with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void beforeDocumentSaving(Document document) {
    FileDocumentManager instance = FileDocumentManager.getInstance();
    VirtualFile file = instance.getFile(document);
    WakaTime.appendHeartbeat(file, WakaTime.getProject(document), true);
}
 
Example 17
Source File: GenerateParserAction.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void actionPerformed(final AnActionEvent e) {
	Project project = e.getData(PlatformDataKeys.PROJECT);
	if ( project==null ) {
		LOG.error("actionPerformed no project for "+e);
		return; // whoa!
	}
	VirtualFile grammarFile = MyActionUtils.getGrammarFileFromEvent(e);
	LOG.info("actionPerformed "+(grammarFile==null ? "NONE" : grammarFile));
	if ( grammarFile==null ) return;
	String title = "ANTLR Code Generation";
	boolean canBeCancelled = true;

	// commit changes to PSI and file system
	PsiDocumentManager psiMgr = PsiDocumentManager.getInstance(project);
	FileDocumentManager docMgr = FileDocumentManager.getInstance();
	Document doc = docMgr.getDocument(grammarFile);
	if ( doc==null ) return;

	boolean unsaved = !psiMgr.isCommitted(doc) || docMgr.isDocumentUnsaved(doc);
	if ( unsaved ) {
		// save event triggers ANTLR run if autogen on
		psiMgr.commitDocument(doc);
		docMgr.saveDocument(doc);
	}

	boolean forceGeneration = true; // from action, they really mean it
	RunANTLROnGrammarFile gen =
		new RunANTLROnGrammarFile(grammarFile,
								  project,
								  title,
								  canBeCancelled,
								  forceGeneration);

	boolean autogen = ANTLRv4GrammarPropertiesStore.getGrammarProperties(project, grammarFile).shouldAutoGenerateParser();
	if ( !unsaved || !autogen ) {
		// if everything already saved (not stale) then run ANTLR
		// if had to be saved and autogen NOT on, then run ANTLR
		// Otherwise, the save file event will have or will run ANTLR.
		ProgressManager.getInstance().run(gen); //, "Generating", canBeCancelled, e.getData(PlatformDataKeys.PROJECT));

		// refresh from disk to see new files
		Set<File> generatedFiles = new HashSet<>();
		generatedFiles.add(new File(gen.getOutputDirName()));
		LocalFileSystem.getInstance().refreshIoFiles(generatedFiles, true, true, null);
		// pop up a notification
		Notification notification =
			new Notification(RunANTLROnGrammarFile.groupDisplayId,
							 "parser for " + grammarFile.getName() + " generated",
							 "to " + gen.getOutputDirName(),
							 NotificationType.INFORMATION);
		Notifications.Bus.notify(notification, project);
	}
}
 
Example 18
Source File: ActionsTest.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void saveDocument(VirtualFile f) {
  FileDocumentManager dm = FileDocumentManager.getInstance();
  dm.saveDocument(dm.getDocument(f));
}
 
Example 19
Source File: ChangelistConflictTracker.java    From consulo with Apache License 2.0 4 votes vote down vote up
public ChangelistConflictTracker(@Nonnull Project project,
                                 @Nonnull ChangeListManager changeListManager,
                                 @Nonnull FileStatusManager fileStatusManager,
                                 @Nonnull EditorNotifications editorNotifications) {
  myProject = project;

  myChangeListManager = changeListManager;
  myEditorNotifications = editorNotifications;
  myDocumentManager = FileDocumentManager.getInstance();
  myFileStatusManager = fileStatusManager;
  myCheckSetLock = new Object();
  myCheckSet = new HashSet<>();

  final Application application = ApplicationManager.getApplication();
  final ZipperUpdater zipperUpdater = new ZipperUpdater(300, Alarm.ThreadToUse.SWING_THREAD, project);
  final Runnable runnable = () -> {
    if (application.isDisposed() || myProject.isDisposed() || !myProject.isOpen()) {
      return;
    }
    final Set<VirtualFile> localSet;
    synchronized (myCheckSetLock) {
      localSet = new HashSet<>();
      localSet.addAll(myCheckSet);
      myCheckSet.clear();
    }
    checkFiles(localSet);
  };
  myDocumentListener = new DocumentAdapter() {
    @Override
    public void documentChanged(DocumentEvent e) {
      if (!myOptions.TRACKING_ENABLED) {
        return;
      }
      Document document = e.getDocument();
      VirtualFile file = myDocumentManager.getFile(document);
      if (ProjectUtil.guessProjectForFile(file) == myProject) {
        synchronized (myCheckSetLock) {
          myCheckSet.add(file);
        }
        zipperUpdater.queue(runnable);
      }
    }
  };

  myChangeListListener = new ChangeListAdapter() {
    @Override
    public void changeListChanged(ChangeList list) {
      if (myChangeListManager.isDefaultChangeList(list)) {
        clearChanges(list.getChanges());
      }
    }

    @Override
    public void changesMoved(Collection<Change> changes, ChangeList fromList, ChangeList toList) {
      if (myChangeListManager.isDefaultChangeList(toList)) {
        clearChanges(changes);
      }
    }

    @Override
    public void changesRemoved(Collection<Change> changes, ChangeList fromList) {
      clearChanges(changes);
    }

    @Override
    public void defaultListChanged(ChangeList oldDefaultList, ChangeList newDefaultList) {
      clearChanges(newDefaultList.getChanges());
    }
  };
}
 
Example 20
Source File: TrailingSpacesStripper.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void strip(@Nonnull final Document document) {
  if (!document.isWritable()) return;
  FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
  VirtualFile file = fileDocumentManager.getFile(document);
  if (file == null || !file.isValid() || Boolean.TRUE.equals(DISABLE_FOR_FILE_KEY.get(file))) return;

  final EditorSettingsExternalizable settings = EditorSettingsExternalizable.getInstance();
  if (settings == null) return;

  final String overrideStripTrailingSpacesData = file.getUserData(OVERRIDE_STRIP_TRAILING_SPACES_KEY);
  final Boolean overrideEnsureNewlineData = file.getUserData(OVERRIDE_ENSURE_NEWLINE_KEY);
  @EditorSettingsExternalizable.StripTrailingSpaces
  String stripTrailingSpaces = overrideStripTrailingSpacesData != null ? overrideStripTrailingSpacesData : settings.getStripTrailingSpaces();
  final boolean doStrip = !stripTrailingSpaces.equals(EditorSettingsExternalizable.STRIP_TRAILING_SPACES_NONE);
  final boolean ensureEOL = overrideEnsureNewlineData != null ? overrideEnsureNewlineData.booleanValue() : settings.isEnsureNewLineAtEOF();

  if (doStrip) {
    final boolean inChangedLinesOnly = !stripTrailingSpaces.equals(EditorSettingsExternalizable.STRIP_TRAILING_SPACES_WHOLE);
    boolean success = strip(document, inChangedLinesOnly, settings.isKeepTrailingSpacesOnCaretLine());
    if (!success) {
      myDocumentsToStripLater.add(document);
    }
  }

  final int lines = document.getLineCount();
  if (ensureEOL && lines > 0) {
    final int start = document.getLineStartOffset(lines - 1);
    final int end = document.getLineEndOffset(lines - 1);
    if (start != end) {
      final CharSequence content = document.getCharsSequence();
      ApplicationManager.getApplication().runWriteAction(new DocumentRunnable(document, null) {
        @Override
        public void run() {
          CommandProcessor.getInstance().runUndoTransparentAction(() -> {
            if (CharArrayUtil.containsOnlyWhiteSpaces(content.subSequence(start, end)) && doStrip) {
              document.deleteString(start, end);
            }
            else {
              document.insertString(end, "\n");
            }
          });
        }
      });
    }
  }
}