Java Code Examples for com.intellij.openapi.editor.event.DocumentEvent#getDocument()

The following examples show how to use com.intellij.openapi.editor.event.DocumentEvent#getDocument() . 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: ORFileEditorListener.java    From reasonml-idea-plugin with 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 2
Source File: DocumentUndoProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeDocumentChange(@Nonnull DocumentEvent e) {
  Document document = e.getDocument();
  if (!shouldProcess(document)) {
    return;
  }

  handleBeforeDocumentChange(getUndoManager(null), document);

  ProjectManager projectManager = ProjectManager.getInstance();
  if (projectManager != null) {
    for (Project project : projectManager.getOpenProjects()) {
      handleBeforeDocumentChange(getUndoManager(project), document);
    }
  }
}
 
Example 3
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void documentChanged(@Nonnull DocumentEvent e) {
  final Document document = e.getDocument();
  if (!ApplicationManager.getApplication().hasWriteAction(ExternalChangeAction.ExternalDocumentChange.class)) {
    myUnsavedDocuments.add(document);
  }
  final Runnable currentCommand = CommandProcessor.getInstance().getCurrentCommand();
  Project project = currentCommand == null ? null : CommandProcessor.getInstance().getCurrentCommandProject();
  if (project == null) project = ProjectUtil.guessProjectForFile(getFile(document));
  String lineSeparator = CodeStyle.getProjectOrDefaultSettings(project).getLineSeparator();
  document.putUserData(LINE_SEPARATOR_KEY, lineSeparator);

  // avoid documents piling up during batch processing
  if (areTooManyDocumentsInTheQueue(myUnsavedDocuments)) {
    saveAllDocumentsLater();
  }
}
 
Example 4
Source File: DelayedDocumentWatcher.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void documentChanged(DocumentEvent event) {
  if (myDocumentSavingInProgress) {
    /* When {@link FileDocumentManager#saveAllDocuments} is called,
       {@link com.intellij.openapi.editor.impl.TrailingSpacesStripper} can change a document.
       These needless 'documentChanged' events should be filtered out.
     */
    return;
  }
  final Document document = event.getDocument();
  final VirtualFile file = FileDocumentManager.getInstance().getFile(document);
  if (file == null) {
    return;
  }
  if (!myChangedFiles.contains(file)) {
    if (ProjectCoreUtil.isProjectOrWorkspaceFile(file)) {
      return;
    }
    if (myChangedFileFilter != null && !myChangedFileFilter.value(file)) {
      return;
    }

    myChangedFiles.add(file);
  }

  myAlarm.cancelRequest(myAlarmRunnable);
  myAlarm.addRequest(myAlarmRunnable, myDelayMillis);
  myModificationStamp++;
}
 
Example 5
Source File: PsiDocumentManagerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeDocumentChange(@Nonnull DocumentEvent event) {
  if (myStopTrackingDocuments || myProject.isDisposed()) return;

  final Document document = event.getDocument();
  VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
  boolean isRelevant = virtualFile != null && isRelevant(virtualFile);

  if (document instanceof DocumentImpl && !myUncommittedInfos.containsKey(document)) {
    myUncommittedInfos.put(document, new UncommittedInfo((DocumentImpl)document));
  }

  final FileViewProvider viewProvider = getCachedViewProvider(document);
  boolean inMyProject = viewProvider != null && viewProvider.getManager() == myPsiManager;
  if (!isRelevant || !inMyProject) {
    return;
  }

  final List<PsiFile> files = viewProvider.getAllFiles();
  PsiFile psiCause = null;
  for (PsiFile file : files) {
    if (file == null) {
      throw new AssertionError("View provider " + viewProvider + " (" + viewProvider.getClass() + ") returned null in its files array: " + files + " for file " + viewProvider.getVirtualFile());
    }

    if (PsiToDocumentSynchronizer.isInsideAtomicChange(file)) {
      psiCause = file;
    }
  }

  if (psiCause == null) {
    beforeDocumentChangeOnUnlockedDocument(viewProvider);
  }
}
 
Example 6
Source File: LineOrientedDocumentChangeAdapter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void documentChanged(DocumentEvent event) {
  Document document = event.getDocument();
  int startLine = document.getLineNumber(normalize(event.getDocument(), event.getOffset()));
  int endLine = document.getLineNumber(normalize(event.getDocument(), event.getOffset() + event.getNewLength()));
  int symbolsDifference = event.getNewLength() - event.getOldLength();
  afterDocumentChange(startLine, endLine, symbolsDifference);
}
 
Example 7
Source File: LineOrientedDocumentChangeAdapter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeDocumentChange(DocumentEvent event) {
  Document document = event.getDocument();
  int startLine = document.getLineNumber(normalize(event.getDocument(), event.getOffset()));
  int endLine = document.getLineNumber(normalize(event.getDocument(), event.getOffset() + event.getOldLength()));
  int symbolsDifference = event.getNewLength() - event.getOldLength();
  beforeDocumentChange(startLine, endLine, symbolsDifference);
}
 
Example 8
Source File: DocumentUndoProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void documentChanged(@Nonnull DocumentEvent e) {
  Document document = e.getDocument();
  if (!shouldProcess(document)) {
    return;
  }

  handleDocumentChanged(getUndoManager(null), document, e);
  ProjectManager projectManager = ProjectManager.getInstance();
  if (projectManager != null) {
    for (Project project : projectManager.getOpenProjects()) {
      handleDocumentChanged(getUndoManager(project), document, e);
    }
  }
}
 
Example 9
Source File: QuickEditHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void documentChanged(DocumentEvent e) {
  UndoManager undoManager = UndoManager.getInstance(myProject);
  boolean undoOrRedo = undoManager.isUndoInProgress() || undoManager.isRedoInProgress();
  if (undoOrRedo) {
    // allow undo/redo up until 'creation stamp' back in time
    // and check it after action is completed
    if (e.getDocument() == myOrigDocument) {
      //noinspection SSBasedInspection
      SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
          if (myOrigCreationStamp > myOrigDocument.getModificationStamp()) {
            closeEditor();
          }
        }
      });
    }
  }
  else if (e.getDocument() == myNewDocument) {
    commitToOriginal(e);
    if (!isValid()) {
      ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
          closeEditor();
        }
      }, myProject.getDisposed());
    }
  }
  else if (e.getDocument() == myOrigDocument) {
    if (myCommittingToOriginal || myAltFullRange != null && myAltFullRange.isValid()) return;
    ApplicationManager.getApplication().invokeLater(new Runnable() {
      @Override
      public void run() {
        closeEditor();
      }
    }, myProject.getDisposed());
  }
}
 
Example 10
Source File: FoldingModelSupport.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void onDocumentChanged(@Nonnull DocumentEvent e) {
  if (StringUtil.indexOf(e.getOldFragment(), '\n') != -1 ||
      StringUtil.indexOf(e.getNewFragment(), '\n') != -1) {
    for (int i = 0; i < myCount; i++) {
      if (myEditors[i].getDocument() == e.getDocument()) {
        myShouldUpdateLineNumbers[i] = true;
      }
    }
  }
}
 
Example 11
Source File: LocalDocumentModificationHandler.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generates and dispatches a <code>TextEditActivity</code> for the given <code>DocumentEvent
 * </code>.
 *
 * @param event the event to react to
 * @see DocumentListener#beforeDocumentChange(DocumentEvent)
 */
private void generateTextEditActivity(@NotNull DocumentEvent event) {
  Document document = event.getDocument();

  IFile file = getFile(document);

  if (file == null) {
    return;
  }

  String newText = event.getNewFragment().toString();
  String replacedText = event.getOldFragment().toString();

  editorManager.generateTextEdit(event.getOffset(), newText, replacedText, file, document);
}
 
Example 12
Source File: LocalClosedEditorModificationHandler.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adjusts the annotations for the resource represented by the changed document if it is not
 * currently open in an editor. If it is currently open in an editor, this will be done
 * automatically by Intellij.
 *
 * @param event the event to react to
 * @see DocumentListener#beforeDocumentChange(DocumentEvent)
 */
private void cleanUpAnnotations(@NotNull DocumentEvent event) {
  Document document = event.getDocument();

  IFile file = getFile(document);

  if (file == null) {
    return;
  }

  int offset = event.getOffset();
  String newText = event.getNewFragment().toString();
  String replacedText = event.getOldFragment().toString();

  if (!ProjectAPI.isOpen(project, document)) {

    int replacedTextLength = replacedText.length();
    if (replacedTextLength > 0) {
      annotationManager.moveAnnotationsAfterDeletion(file, offset, offset + replacedTextLength);
    }

    int newTextLength = newText.length();
    if (newTextLength > 0) {
      annotationManager.moveAnnotationsAfterAddition(file, offset, offset + newTextLength);
    }
  }
}
 
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: PsiDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void documentChanged(@Nonnull DocumentEvent event) {
  super.documentChanged(event);
  // optimisation: avoid documents piling up during batch processing
  if (isUncommited(event.getDocument()) && FileDocumentManagerImpl.areTooManyDocumentsInTheQueue(myUncommittedDocuments)) {
    if (myUnitTestMode) {
      myStopTrackingDocuments = true;
      try {
        LOG.error("Too many uncommitted documents for " +
                  myProject +
                  "(" +
                  myUncommittedDocuments.size() +
                  ")" +
                  ":\n" +
                  StringUtil.join(myUncommittedDocuments, "\n") +
                  (myProject instanceof ProjectImpl ? "\n\n Project creation trace: " + ((ProjectImpl)myProject).getCreationTrace() : ""));
      }
      finally {
        //noinspection TestOnlyProblems
        clearUncommittedDocuments();
      }
    }
    // must not commit during document save
    if (PomModelImpl.isAllowPsiModification()
        // it can happen that document(forUseInNonAWTThread=true) outside write action caused this
        && ApplicationManager.getApplication().isWriteAccessAllowed()) {
      // commit one document to avoid OOME
      for (Document document : myUncommittedDocuments) {
        if (document != event.getDocument()) {
          doCommitWithoutReparse(document);
          break;
        }
      }
    }
  }
}
 
Example 15
Source File: DocumentContentSynchronizer.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Convert IntelliJ {@link DocumentEvent} to LS according {@link TextDocumentSyncKind}.
 *
 * @param event
 *            IntelliJ {@link DocumentEvent}
 * @return true if change event is ready to be sent
 */
private boolean createChangeEvent(DocumentEvent event) {
    changeParams = new DidChangeTextDocumentParams(new VersionedTextDocumentIdentifier(), Collections.singletonList(new TextDocumentContentChangeEvent()));
    changeParams.getTextDocument().setUri(fileUri.toString());

    Document document = event.getDocument();
    TextDocumentContentChangeEvent changeEvent = null;
    TextDocumentSyncKind syncKind = getTextDocumentSyncKind();
    switch (syncKind) {
        case None:
            return false;
        case Full:
            changeParams.getContentChanges().get(0).setText(event.getDocument().getText());
            break;
        case Incremental:
            changeEvent = changeParams.getContentChanges().get(0);
            CharSequence newText = event.getNewFragment();
            int offset = event.getOffset();
            int length = event.getOldLength();
            try {
                // try to convert the Eclipse start/end offset to LS range.
                Range range = new Range(LSPIJUtils.toPosition(offset, document),
                        LSPIJUtils.toPosition(offset + length, document));
                changeEvent.setRange(range);
                changeEvent.setText(newText.toString());
                changeEvent.setRangeLength(length);
            } finally {
            }
            break;
    }
    return true;
}
 
Example 16
Source File: EditorEventManager.java    From lsp4intellij with Apache License 2.0 4 votes vote down vote up
public void documentChanged(DocumentEvent event) {
    if (editor.isDisposed()) {
        return;
    }
    if (event.getDocument() == editor.getDocument()) {
        //Todo - restore when adding hover support
        // long predTime = System.nanoTime(); //So that there are no hover events while typing
        changesParams.getTextDocument().setVersion(version++);

        if (syncKind == TextDocumentSyncKind.Incremental) {
            TextDocumentContentChangeEvent changeEvent = changesParams.getContentChanges().get(0);
            CharSequence newText = event.getNewFragment();
            int offset = event.getOffset();
            int newTextLength = event.getNewLength();
            Position lspPosition = DocumentUtils.offsetToLSPPos(editor, offset);
            int startLine = lspPosition.getLine();
            int startColumn = lspPosition.getCharacter();
            CharSequence oldText = event.getOldFragment();

            //if text was deleted/replaced, calculate the end position of inserted/deleted text
            int endLine, endColumn;
            if (oldText.length() > 0) {
                endLine = startLine + StringUtil.countNewLines(oldText);
                String[] oldLines = oldText.toString().split("\n");
                int oldTextLength = oldLines.length == 0 ? 0 : oldLines[oldLines.length - 1].length();
                endColumn = oldLines.length == 1 ? startColumn + oldTextLength : oldTextLength;
            } else { //if insert or no text change, the end position is the same
                endLine = startLine;
                endColumn = startColumn;
            }
            Range range = new Range(new Position(startLine, startColumn), new Position(endLine, endColumn));
            changeEvent.setRange(range);
            changeEvent.setRangeLength(newTextLength);
            changeEvent.setText(newText.toString());
        } else if (syncKind == TextDocumentSyncKind.Full) {
            changesParams.getContentChanges().get(0).setText(editor.getDocument().getText());
        }
        requestManager.didChange(changesParams);
    } else {
        LOG.error("Wrong document for the EditorEventManager");
    }
}
 
Example 17
Source File: EditorChangeAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public EditorChangeAction(DocumentEvent e) {
  this((DocumentEx)e.getDocument(), e.getOffset(), e.getOldFragment(), e.getNewFragment(), e.getOldTimeStamp());
}
 
Example 18
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 19
Source File: ORFileEditorListener.java    From reasonml-idea-plugin with MIT License 4 votes vote down vote up
@Override
public void beforeDocumentChange(@NotNull DocumentEvent event) {
    Document document = event.getDocument();
    m_oldLinesCount = document.getLineCount();
}
 
Example 20
Source File: DocumentContentSynchronizer.java    From intellij-quarkus with Eclipse Public License 2.0 4 votes vote down vote up
private void checkEvent(DocumentEvent event) {
    if (this.document != event.getDocument()) {
        throw new IllegalStateException("Synchronizer should apply to only a single document, which is the one it was instantiated for"); //$NON-NLS-1$
    }
}