com.intellij.openapi.editor.event.DocumentListener Java Examples

The following examples show how to use com.intellij.openapi.editor.event.DocumentListener. 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: CodeFragmentTableCellEditorBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
  myCodeFragment = (PsiCodeFragment)value;

  myDocument = PsiDocumentManager.getInstance(myProject).getDocument(myCodeFragment);
  myEditorTextField = createEditorField(myDocument);
  if (myEditorTextField != null) {
    for (DocumentListener listener : myListeners) {
      myEditorTextField.addDocumentListener(listener);
    }
    myEditorTextField.setDocument(myDocument);
    myEditorTextField.setBorder(new LineBorder(table.getSelectionBackground()));
  }

  return myEditorTextField;
}
 
Example #2
Source File: StringTableCellEditor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
  final EditorTextField editorTextField = new EditorTextField((String) value, myProject, InternalStdFileTypes.JAVA) {
          @Override
          protected boolean shouldHaveBorder() {
            return false;
          }
        };
  myDocument = editorTextField.getDocument();
  if (myDocument != null) {
    for (DocumentListener listener : myListeners) {
      editorTextField.addDocumentListener(listener);
    }
  }
  return editorTextField;
}
 
Example #3
Source File: EditorBasedStatusBarPopup.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void install(@Nonnull StatusBar statusBar) {
  super.install(statusBar);
  registerCustomListeners();
  EditorFactory.getInstance().getEventMulticaster().addDocumentListener(new DocumentListener() {
    @Override
    public void documentChanged(@Nonnull DocumentEvent e) {
      Document document = e.getDocument();
      updateForDocument(document);
    }
  }, this);
  if (myWriteableFileRequired) {
    ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(VirtualFileManager.VFS_CHANGES, new BulkVirtualFileListenerAdapter(new VirtualFileListener() {
      @Override
      public void propertyChanged(@Nonnull VirtualFilePropertyEvent event) {
        if (VirtualFile.PROP_WRITABLE.equals(event.getPropertyName())) {
          updateForFile(event.getFile());
        }
      }
    }));
  }
}
 
Example #4
Source File: EditorEventManager.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
public EditorEventManager(Editor editor, DocumentListener documentListener, EditorMouseListener mouseListener,
                          EditorMouseMotionListener mouseMotionListener, LSPCaretListenerImpl caretListener,
                          RequestManager requestManager, ServerOptions serverOptions, LanguageServerWrapper wrapper) {

    this.editor = editor;
    this.documentListener = documentListener;
    this.mouseListener = mouseListener;
    this.mouseMotionListener = mouseMotionListener;
    this.requestManager = requestManager;
    this.wrapper = wrapper;
    this.caretListener = caretListener;

    this.identifier = new TextDocumentIdentifier(FileUtils.editorToURIString(editor));
    this.changesParams = new DidChangeTextDocumentParams(new VersionedTextDocumentIdentifier(),
            Collections.singletonList(new TextDocumentContentChangeEvent()));
    this.syncKind = serverOptions.syncKind;

    this.completionTriggers = (serverOptions.completionOptions != null
            && serverOptions.completionOptions.getTriggerCharacters() != null) ?
            serverOptions.completionOptions.getTriggerCharacters() :
            new ArrayList<>();

    this.signatureTriggers = (serverOptions.signatureHelpOptions != null
            && serverOptions.signatureHelpOptions.getTriggerCharacters() != null) ?
            serverOptions.signatureHelpOptions.getTriggerCharacters() :
            new ArrayList<>();

    this.project = editor.getProject();

    EditorEventManagerBase.uriToManager.put(FileUtils.editorToURIString(editor), this);
    EditorEventManagerBase.editorToManager.put(editor, this);
    changesParams.getTextDocument().setUri(identifier.getUri());

    this.currentHint = null;
}
 
Example #5
Source File: OffsetTranslator.java    From consulo with Apache License 2.0 5 votes vote down vote up
public OffsetTranslator(Document originalDocument, PsiFile originalFile, Document copyDocument, int start, int end, String replacement) {
  myOriginalFile = originalFile;
  myCopyDocument = copyDocument;
  myCopyDocument.putUserData(RANGE_TRANSLATION, this);
  myTranslation.addFirst(new DocumentEventImpl(copyDocument, start, originalDocument.getImmutableCharSequence().subSequence(start, end), replacement, 0, false));
  Disposer.register(originalFile.getProject(), this);

  final LinkedList<DocumentEvent> sinceCommit = new LinkedList<>();
  originalDocument.addDocumentListener(new DocumentListener() {
    @Override
    public void documentChanged(@Nonnull DocumentEvent e) {
      if (isUpToDate()) {
        DocumentEventImpl inverse = new DocumentEventImpl(originalDocument, e.getOffset(), e.getNewFragment(), e.getOldFragment(), 0, false);
        sinceCommit.addLast(inverse);
      }
    }
  }, this);

  originalFile.getProject().getMessageBus().connect(this).subscribe(PsiModificationTracker.TOPIC, new PsiModificationTracker.Listener() {
    final long lastModCount = originalFile.getViewProvider().getModificationStamp();

    @Override
    public void modificationCountChanged() {
      if (isUpToDate() && lastModCount != originalFile.getViewProvider().getModificationStamp()) {
        myTranslation.addAll(sinceCommit);
        sinceCommit.clear();
      }
    }
  });

}
 
Example #6
Source File: DocumentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void fireMoveText(int start, int end, int newBase) {
  for (DocumentListener listener : getListeners()) {
    if (listener instanceof PrioritizedInternalDocumentListener) {
      ((PrioritizedInternalDocumentListener)listener).moveTextHappened(this, start, end, newBase);
    }
  }
}
 
Example #7
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 #8
Source File: DocumentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void addDocumentListener(@Nonnull DocumentListener listener) {
  if (ArrayUtil.contains(listener, getListeners())) {
    LOG.error("Already registered: " + listener);
  }
  myDocumentListeners.add(listener);
}
 
Example #9
Source File: EditorComponentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void addDocumentListener(javax.swing.event.DocumentListener documentListener) {
  if (myListeners == null) {
    myListeners = new ArrayList<>(2);
  }
  myListeners.add(documentListener);
}
 
Example #10
Source File: DocumentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void removeDocumentListener(@Nonnull DocumentListener listener) {
  boolean success = myDocumentListeners.remove(listener);
  if (!success) {
    LOG.error("Can't remove document listener (" + listener + "). Registered listeners: " + Arrays.toString(getListeners()));
  }
}
 
Example #11
Source File: DocumentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void notifyListenersOnBulkModeStarting() {
  DelayedExceptions exceptions = new DelayedExceptions();
  DocumentListener[] listeners = getListeners();
  for (int i = listeners.length - 1; i >= 0; i--) {
    try {
      listeners[i].bulkUpdateStarting(this);
    }
    catch (Throwable e) {
      exceptions.register(e);
    }
  }
  exceptions.rethrowPCE();
}
 
Example #12
Source File: EncodingManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public EncodingManagerImpl() {
  ApplicationManager.getApplication().getMessageBus().connect().subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener() {
    @Override
    public void appClosing() {
      // should call before dispose in write action
      // prevent any further re-detection and wait for the queue to clear
      myDisposed.set(true);
      clearDocumentQueue();
    }
  });

  EditorFactory editorFactory = EditorFactory.getInstance();
  editorFactory.getEventMulticaster().addDocumentListener(new DocumentListener() {
    @Override
    public void documentChanged(@Nonnull DocumentEvent e) {
      Document document = e.getDocument();
      if (isEditorOpenedFor(document)) {
        queueUpdateEncodingFromContent(document);
      }
    }
  }, this);
  editorFactory.addEditorFactoryListener(new EditorFactoryListener() {
    @Override
    public void editorCreated(@Nonnull EditorFactoryEvent event) {
      queueUpdateEncodingFromContent(event.getEditor().getDocument());
    }
  }, this);
}
 
Example #13
Source File: DocumentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void notifyListenersOnBulkModeFinished() {
  DelayedExceptions exceptions = new DelayedExceptions();
  DocumentListener[] listeners = getListeners();
  for (DocumentListener listener : listeners) {
    try {
      listener.bulkUpdateFinished(this);
    }
    catch (Throwable e) {
      exceptions.register(e);
    }
  }
  exceptions.rethrowPCE();
}
 
Example #14
Source File: SrcFileAnnotator.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void hideCoverageData() {
  if (myEditor == null) return;
  final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
  final List<RangeHighlighter> highlighters = myEditor.getUserData(COVERAGE_HIGHLIGHTERS);
  if (highlighters != null) {
    for (final RangeHighlighter highlighter : highlighters) {
      ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
          highlighter.dispose();
        }
      });
    }
    myEditor.putUserData(COVERAGE_HIGHLIGHTERS, null);
  }
  
  final Map<FileEditor, EditorNotificationPanel> map = myFile.getCopyableUserData(NOTIFICATION_PANELS);
  if (map != null) {
    final VirtualFile vFile = myFile.getVirtualFile();
    LOG.assertTrue(vFile != null);
    boolean freeAll = !fileEditorManager.isFileOpen(vFile);
    myFile.putCopyableUserData(NOTIFICATION_PANELS, null);
    for (FileEditor fileEditor : map.keySet()) {
      if (!freeAll && !isCurrentEditor(fileEditor)) {
        continue;
      }
      fileEditorManager.removeTopComponent(fileEditor, map.get(fileEditor));
    }
  }

  final DocumentListener documentListener = myEditor.getUserData(COVERAGE_DOCUMENT_LISTENER);
  if (documentListener != null) {
    myDocument.removeDocumentListener(documentListener);
    myEditor.putUserData(COVERAGE_DOCUMENT_LISTENER, null);
  }
}
 
Example #15
Source File: ActivateSnapshotsAction.java    From tmc-intellij with MIT License 5 votes vote down vote up
@Override
    public void execute(@NotNull final Editor editor, char cha, @NotNull DataContext dataContext) {
        if (!listenedDocuments.contains(editor.getDocument()) && isThisCorrectProject()) {
            DocumentListener docl = new TextInputListener();
            editor.getDocument().addDocumentListener(docl);
            listenedDocuments.add(editor.getDocument());
            logger.info("Added document listener to ", editor.getDocument().toString());
//            UsagesCollector.doPersistProjectUsages(new ObjectFinder().findCurrentProject());
            // the above line does not work with the new intellij (v2017.3). has it ever been necessary??
        }
        handler.execute(editor, cha, dataContext);
    }
 
Example #16
Source File: CopyrightManager.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Inject
public CopyrightManager(@Nonnull Project project,
                        @Nonnull final EditorFactory editorFactory,
                        @Nonnull final Application application,
                        @Nonnull final FileDocumentManager fileDocumentManager,
                        @Nonnull final ProjectRootManager projectRootManager,
                        @Nonnull final PsiManager psiManager,
                        @Nonnull StartupManager startupManager) {
  myProject = project;
  if (myProject.isDefault()) {
    return;
  }

  final NewFileTracker newFileTracker = NewFileTracker.getInstance();
  Disposer.register(myProject, newFileTracker::clear);
  startupManager.runWhenProjectIsInitialized(new Runnable() {
    @Override
    public void run() {
      DocumentListener listener = new DocumentAdapter() {
        @Override
        public void documentChanged(DocumentEvent e) {
          final Document document = e.getDocument();
          final VirtualFile virtualFile = fileDocumentManager.getFile(document);
          if (virtualFile == null) return;
          if (!newFileTracker.poll(virtualFile)) return;
          if (!CopyrightUpdaters.hasExtension(virtualFile)) return;
          final Module module = projectRootManager.getFileIndex().getModuleForFile(virtualFile);
          if (module == null) return;
          final PsiFile file = psiManager.findFile(virtualFile);
          if (file == null) return;
          application.invokeLater(new Runnable() {
            @Override
            public void run() {
              if (myProject.isDisposed()) return;
              if (file.isValid() && file.isWritable()) {
                final CopyrightProfile opts = getCopyrightOptions(file);
                if (opts != null) {
                  new UpdateCopyrightProcessor(myProject, module, file).run();
                }
              }
            }
          }, ModalityState.NON_MODAL, myProject.getDisposed());
        }
      };
      editorFactory.getEventMulticaster().addDocumentListener(listener, myProject);
    }
  });
}
 
Example #17
Source File: DocumentWindowImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void addDocumentListener(@Nonnull final DocumentListener listener) {
  myDelegate.addDocumentListener(listener);
}
 
Example #18
Source File: DocumentImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private DocumentListener[] getListeners() {
  return myDocumentListeners.getArray();
}
 
Example #19
Source File: DocumentWindowImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void addDocumentListener(@Nonnull DocumentListener listener, @Nonnull Disposable parentDisposable) {
  myDelegate.addDocumentListener(listener, parentDisposable);
}
 
Example #20
Source File: DocumentImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
DocumentListenerDisposable(@Nonnull LockFreeCOWSortedArray<? super DocumentListener> list, @Nonnull DocumentListener listener) {
  myList = list;
  myListener = listener;
}
 
Example #21
Source File: DocumentImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void addDocumentListener(@Nonnull final DocumentListener listener, @Nonnull Disposable parentDisposable) {
  addDocumentListener(listener);
  Disposer.register(parentDisposable, new DocumentListenerDisposable(myDocumentListeners, listener));
}
 
Example #22
Source File: DocumentWindowImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void removeDocumentListener(@Nonnull final DocumentListener listener) {
  myDelegate.removeDocumentListener(listener);
}
 
Example #23
Source File: StringTableCellEditor.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void addDocumentListener(DocumentListener listener) {
  myListeners.add(listener);
}
 
Example #24
Source File: CodeFragmentTableCellEditorBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void addDocumentListener(DocumentListener listener) {
  myListeners.add(listener);
}
 
Example #25
Source File: EditorComboBox.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void documentChanged(DocumentEvent event) {
  for (DocumentListener documentListener : myDocumentListeners) {
    documentListener.documentChanged(event);
  }
}
 
Example #26
Source File: EditorComboBox.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeDocumentChange(DocumentEvent event) {
  for (DocumentListener documentListener : myDocumentListeners) {
    documentListener.beforeDocumentChange(event);
  }
}
 
Example #27
Source File: EditorComboBox.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void removeDocumentListener(DocumentListener listener) {
  myDocumentListeners.remove(listener);
  uninstallDocumentListener(false);
}
 
Example #28
Source File: ReferenceEditorWithBrowseButton.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void removeDocumentListener(DocumentListener listener) {
  myDocumentListeners.remove(listener);
  getEditorTextField().getDocument().removeDocumentListener(listener);
}
 
Example #29
Source File: AbstractLocalDocumentModificationHandler.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Enables or disables the given DocumentListener by registering or unregistering it from the
 * local Intellij instance. Also updates the local <code>enabled</code> flag.
 *
 * @param enabled the new state of the listener
 * @param documentListener the listener whose state to change
 */
public void setEnabled(boolean enabled, @NotNull DocumentListener documentListener) {
  assert !disposed || !enabled : "disposed listeners must not be enabled";

  if (!this.enabled && enabled) {
    log.debug("Started listening for document events");

    EditorFactory.getInstance()
        .getEventMulticaster()
        .addDocumentListener(documentListener, project);

    this.enabled = true;

  } else if (this.enabled && !enabled) {

    log.debug("Stopped listening for document events");

    EditorFactory.getInstance().getEventMulticaster().removeDocumentListener(documentListener);

    this.enabled = false;
  }
}
 
Example #30
Source File: GoalEditor.java    From MavenHelper with Apache License 2.0 4 votes vote down vote up
public GoalEditor(String title, String initialValue, ApplicationSettings applicationSettings, boolean persist, Project project, DataContext dataContext) {
		super(true);
		setTitle(title);
		saveGoalCheckBox.setSelected(PropertiesComponent.getInstance().getBoolean(SAVE, true));
		saveGoalCheckBox.setVisible(persist);

		try {
//		optionsPanel.add(new JBLabel("Append:"));
//		optionsPanel.setLayout(new WrapLayout());
			optionsPanel.add(getLinkLabel("-DskipTests", null));
			optionsPanel.add(getLinkLabel(new ListItem("--update-snapshots", "Forces a check for updated releases and snapshots on remote repositories")));
			optionsPanel.add(getLinkLabel(new ListItem("--offline", "Work offline")));
			optionsPanel.add(getLinkLabel(new ListItem("--debug", "Produce execution debug output")));
			optionsPanel.add(getLinkLabel(new ListItem("--non-recursive", "Do not recurse into sub-projects")));

//		optionsPanel2.setLayout(new WrapLayout());
			optionsPanel2.add(listPopup("Option...", getOptions(false), false));
			optionsPanel2.add(listPopup("Short Option...", getOptions(true), true));

			optionsPanel2.add(listPopup("Alias...", toListItems(applicationSettings.getAliases().getAliases()), false));

//		goalsPanel.add(new JBLabel("Goals:"));
//		goalsPanel.setLayout(new WrapLayout());

			goalsPanel.add(listPopup("Lifecycle Goal...", getGoals(), false));
			goalsPanel.add(listPopup("Existing Goal...", getExistingGoals(applicationSettings), false));
			goalsPanel.add(listPopup("Util...", getHelpfulGoals(), false));


			if (dataContext != null) {
				MavenProject mavenProject = MavenActionUtil.getMavenProject(dataContext);
				if (mavenProject != null) {
					List<ListItem> listItems = new ArrayList<>();
					for (MavenPlugin mavenPlugin : mavenProject.getDeclaredPlugins()) {
						MavenPluginInfo pluginInfo = MavenArtifactUtil.readPluginInfo(
							MavenProjectsManager.getInstance(project).getLocalRepository(), mavenPlugin.getMavenId());
						if (pluginInfo != null) {
							boolean first = true;
							for (MavenPluginInfo.Mojo mojo : pluginInfo.getMojos()) {
								ListItem listItem = new ListItem(mojo.getDisplayName());
								if (first) {
									listItem.separatorAbove = new ListItem(mavenPlugin.getArtifactId());
								}
								listItems.add(listItem);
								first = false;
							}
						}
					}
					goalsPanel.add(listPopup("Plugin Goal...", listItems.toArray(new ListItem[0]), false));
				}


			}

		} catch (Throwable e) {
			LOG.error(Objects.toString(e), e);
		}

//		aliasesPanel.add(new JBLabel("Aliases:"));

		init();

		myEditor.getDocument().addDocumentListener(new DocumentListener() {
			@Override
			public void documentChanged(@NotNull DocumentEvent event) {
				updateControls();
			}
		});
		append(initialValue);

		updateControls();
//		IdeFocusManager.findInstanceByComponent(mainPanel).requestFocus(myEditor.getComponent(), true);
	}