Java Code Examples for com.intellij.openapi.fileEditor.FileDocumentManager

The following examples show how to use com.intellij.openapi.fileEditor.FileDocumentManager. 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: consulo   Source File: UndoChangeRevertingVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@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 2
Source Project: lsp4intellij   Source File: LSPQuickDocAction.java    License: Apache License 2.0 6 votes vote down vote up
@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 3
Source Project: consulo   Source File: WrapWithCustomTemplateAction.java    License: Apache License 2.0 6 votes vote down vote up
@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 4
Source Project: consulo   Source File: CopyReferenceAction.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
Source Project: consulo   Source File: ToggleReadOnlyAttributeAction.java    License: Apache License 2.0 6 votes vote down vote up
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 6
Source Project: consulo   Source File: XValueHint.java    License: Apache License 2.0 6 votes vote down vote up
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 7
Source Project: reasonml-idea-plugin   Source File: ORFileEditorListener.java    License: MIT License 6 votes vote down vote up
@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 8
Source Project: JHelper   Source File: FileUtils.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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 9
Source Project: consulo-unity3d   Source File: Unity3dTestDebuggerRunner.java    License: Apache License 2.0 6 votes vote down vote up
@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 10
Source Project: consulo   Source File: MemoryDiskConflictResolver.java    License: Apache License 2.0 6 votes vote down vote up
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 11
Source Project: consulo   Source File: DiffRequestFactoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 12
Source Project: netbeans-mmd-plugin   Source File: SelectInTargetImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 13
@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 14
Source Project: consulo   Source File: CreateFileFix.java    License: Apache License 2.0 6 votes vote down vote up
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 15
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 16
Source Project: consulo   Source File: EncodingManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @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 17
Source Project: consulo   Source File: PsiFileImplUtil.java    License: Apache License 2.0 6 votes vote down vote up
@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 18
Source Project: consulo   Source File: PsiFileImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 19
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 20
Source Project: consulo   Source File: RangeMarkerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public final DocumentEx getDocument() {
  Object file = myDocumentOrFile;
  DocumentEx document = file instanceof VirtualFile ? (DocumentEx)FileDocumentManager.getInstance().getDocument((VirtualFile)file) : (DocumentEx)file;
  if (document == null) {
    LOG.error("document is null; isValid=" + isValid() + "; file=" + file);
  }
  return document;
}
 
Example 21
Source Project: buck   Source File: BuckEventsConsumerTest.java    License: Apache License 2.0 5 votes vote down vote up
public BuckEventsConsumer initialiseEventsConsumer(MockProject project) {
  MockDisposable mockDisposable = new MockDisposable();

  MockApplication application = new MyMockApplication(mockDisposable);
  ApplicationManager.setApplication(application, mockDisposable);
  application.registerService(
      FileDocumentManager.class, new MockFileDocumentManagerImpl(null, null));
  application.registerService(
      VirtualFileManager.class,
      (VirtualFileManager) EasyMock.createMock(VirtualFileManager.class));
  project.registerService(BuckUIManager.class, new MockBuckUIManager(project));
  project.registerService(ToolWindowManager.class, new Mock.MyToolWindowManager());
  return new BuckEventsConsumer(project);
}
 
Example 22
Source Project: consulo   Source File: SurroundWithHandler.java    License: Apache License 2.0 5 votes vote down vote up
static void doSurround(final Project project, final Editor editor, final Surrounder surrounder, final PsiElement[] elements) {
  if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
    return;
  }

  try {
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    int col = editor.getCaretModel().getLogicalPosition().column;
    int line = editor.getCaretModel().getLogicalPosition().line;
    if (!editor.getCaretModel().supportsMultipleCarets()) {
      LogicalPosition pos = new LogicalPosition(0, 0);
      editor.getCaretModel().moveToLogicalPosition(pos);
    }
    TextRange range = surrounder.surroundElements(project, editor, elements);
    if (range != CARET_IS_OK) {
      if (TemplateManager.getInstance(project).getActiveTemplate(editor) == null &&
          InplaceRefactoring.getActiveInplaceRenamer(editor) == null) {
        LogicalPosition pos1 = new LogicalPosition(line, col);
        editor.getCaretModel().moveToLogicalPosition(pos1);
      }
      if (range != null) {
        int offset = range.getStartOffset();
        editor.getCaretModel().removeSecondaryCarets();
        editor.getCaretModel().moveToOffset(offset);
        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
        editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
      }
    }
  }
  catch (IncorrectOperationException e) {
    LOG.error(e);
  }
}
 
Example 23
Source Project: consulo   Source File: IdeaGateway.java    License: 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 24
Source Project: consulo   Source File: FileStatusManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Inject
public FileStatusManagerImpl(Project project, StartupManager startupManager, @SuppressWarnings("UnusedParameters") DirectoryIndex makeSureIndexIsInitializedFirst) {
  myProject = project;

  project.getMessageBus().connect().subscribe(EditorColorsManager.TOPIC, new EditorColorsListener() {
    @Override
    public void globalSchemeChange(EditorColorsScheme scheme) {
      fileStatusesChanged();
    }
  });

  if (project.isDefault()) return;

  startupManager.registerPreStartupActivity(() -> {
    DocumentAdapter documentListener = new DocumentAdapter() {
      @Override
      public void documentChanged(DocumentEvent event) {
        if (event.getOldLength() == 0 && event.getNewLength() == 0) return;
        VirtualFile file = FileDocumentManager.getInstance().getFile(event.getDocument());
        if (file != null) {
          refreshFileStatusFromDocument(file, event.getDocument());
        }
      }
    };

    final EditorFactory factory = EditorFactory.getInstance();
    if (factory != null) {
      factory.getEventMulticaster().addDocumentListener(documentListener, myProject);
    }
  });
  startupManager.registerPostStartupActivity(new DumbAwareRunnable() {
    @Override
    public void run() {
      fileStatusesChanged();
    }
  });
}
 
Example 25
Source Project: innerbuilder   Source File: InnerBuilderHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
    final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    final Document currentDocument = psiDocumentManager.getDocument(file);
    if (currentDocument == null) {
        return;
    }

    psiDocumentManager.commitDocument(currentDocument);

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

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

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

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

        InnerBuilderGenerator.generate(project, editor, file, selectedFields);
    }
}
 
Example 26
Source Project: consulo   Source File: DocumentImpl.java    License: 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 27
Source Project: consulo   Source File: AbstractFileViewProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Document getDocument() {
  Document document = com.intellij.reference.SoftReference.dereference(myDocument);
  if (document == null) {
    document = FileDocumentManager.getInstance().getDocument(getVirtualFile());
    myDocument = document == null ? null : new SoftReference<>(document);
  }
  return document;
}
 
Example 28
Source Project: consulo   Source File: PsiDocumentManagerBase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Document getDocument(@Nonnull PsiFile file) {
  Document document = getCachedDocument(file);
  if (document != null) {
    if (!file.getViewProvider().isPhysical()) {
      PsiUtilCore.ensureValid(file);
      associatePsi(document, file);
    }
    return document;
  }

  FileViewProvider viewProvider = file.getViewProvider();
  if (!viewProvider.isEventSystemEnabled()) return null;

  document = FileDocumentManager.getInstance().getDocument(viewProvider.getVirtualFile());
  if (document != null) {
    if (document.getTextLength() != file.getTextLength()) {
      String message = "Document/PSI mismatch: " + file + " (" + file.getClass() + "); physical=" + viewProvider.isPhysical();
      if (document.getTextLength() + file.getTextLength() < 8096) {
        message += "\n=== document ===\n" + document.getText() + "\n=== PSI ===\n" + file.getText();
      }
      throw new AssertionError(message);
    }

    if (!viewProvider.isPhysical()) {
      PsiUtilCore.ensureValid(file);
      associatePsi(document, file);
      file.putUserData(HARD_REF_TO_DOCUMENT, document);
    }
  }

  return document;
}
 
Example 29
Source Project: azure-devops-intellij   Source File: TfIgnoreUtil.java    License: MIT License 5 votes vote down vote up
private static void addLineToFile(VirtualFile file, String line) {
    FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
    Document document = ObjectUtils.assertNotNull(fileDocumentManager.getDocument(file));
    CharSequence contents = document.getCharsSequence();
    if (!StringUtil.isEmpty(contents) && !StringUtil.endsWith(contents, "\n")) {
        document.insertString(contents.length(), "\n");
    }
    document.insertString(document.getTextLength(), line);
    fileDocumentManager.saveDocument(document);
}
 
Example 30
Source Project: consulo   Source File: RangeMarkerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean canHaveDocument(@Nonnull VirtualFile file) {
  Document document = FileDocumentManager.getInstance().getCachedDocument(file);
  if (document != null) return true;
  if (!file.isValid() || file.isDirectory() || isBinaryWithoutDecompiler(file)) return false;

  return !file.getFileType().isBinary() || !FileUtilRt.isTooLarge(file.getLength());
}