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

The following examples show how to use com.intellij.openapi.editor.event.DocumentListener. 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: EditorBasedStatusBarPopup.java    License: 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 2
Source Project: consulo   Source File: StringTableCellEditor.java    License: 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 Project: consulo   Source File: CodeFragmentTableCellEditorBase.java    License: 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 4
Source Project: lsp4intellij   Source File: EditorEventManager.java    License: 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 Project: tmc-intellij   Source File: ActivateSnapshotsAction.java    License: 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 6
Source Project: consulo   Source File: SrcFileAnnotator.java    License: 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 7
Source Project: consulo   Source File: EncodingManagerImpl.java    License: 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 8
Source Project: consulo   Source File: EditorComponentImpl.java    License: 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 9
Source Project: consulo   Source File: OffsetTranslator.java    License: 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 10
Source Project: consulo   Source File: DocumentImpl.java    License: 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 11
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 12
Source Project: consulo   Source File: DocumentImpl.java    License: 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 13
Source Project: consulo   Source File: DocumentImpl.java    License: 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 14
Source Project: consulo   Source File: DocumentImpl.java    License: 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 15
Source Project: consulo   Source File: DocumentImpl.java    License: 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 16
/**
 * 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 17
Source Project: MavenHelper   Source File: GoalEditor.java    License: 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);
	}
 
Example 18
Source Project: consulo   Source File: MockDocument.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void addDocumentListener(@Nonnull DocumentListener listener) {
}
 
Example 19
Source Project: consulo   Source File: MockDocument.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void addDocumentListener(@Nonnull DocumentListener listener, @Nonnull Disposable parentDisposable) {
}
 
Example 20
Source Project: consulo   Source File: MockDocument.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void removeDocumentListener(@Nonnull DocumentListener listener) {
}
 
Example 21
Source Project: consulo   Source File: Document.java    License: Apache License 2.0 4 votes vote down vote up
default void addDocumentListener(@Nonnull DocumentListener listener, @Nonnull Disposable parentDisposable) {
}
 
Example 22
Source Project: consulo   Source File: TextComponentDocument.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void addDocumentListener(@Nonnull final DocumentListener listener) {
  throw new UnsupportedOperationException("Not implemented");
}
 
Example 23
Source Project: consulo   Source File: TextComponentDocument.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void addDocumentListener(@Nonnull final DocumentListener listener, @Nonnull final Disposable parentDisposable) {
  throw new UnsupportedOperationException("Not implemented");
}
 
Example 24
Source Project: consulo   Source File: TextComponentDocument.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void removeDocumentListener(@Nonnull final DocumentListener listener) {
  throw new UnsupportedOperationException("Not implemented");
}
 
Example 25
Source Project: consulo   Source File: EditorComponentImpl.java    License: Apache License 2.0 4 votes vote down vote up
/** Redispatch an IDE {@link DocumentEvent} to a Swing {@link javax.swing.event.DocumentListener} */
private void fireJTextComponentDocumentChange(final DocumentEvent event) {
  //noinspection deprecation
  List<javax.swing.event.DocumentListener> listeners = ((EditorAccessibilityDocument)getDocument()).getListeners();
  if (listeners == null) {
    return;
  }

  javax.swing.event.DocumentEvent swingEvent = new javax.swing.event.DocumentEvent() {
    @Override
    public int getOffset() {
      return event.getOffset();
    }

    @Override
    public int getLength() {
      return event.getNewLength();
    }

    @Override
    public javax.swing.text.Document getDocument() {
      //noinspection deprecation
      return EditorComponentImpl.this.getDocument();
    }

    @Override
    public EventType getType() {
      return event.getOldLength() == 0 ? EventType.INSERT : event.getNewLength() == 0 ? EventType.REMOVE : EventType.CHANGE;
    }

    @Nullable
    @Override
    public ElementChange getChange(Element element) {
      return null;
    }
  };
  for (javax.swing.event.DocumentListener listener : listeners) {
    javax.swing.event.DocumentEvent.EventType type = swingEvent.getType();
    if (type == javax.swing.event.DocumentEvent.EventType.INSERT) {
      listener.insertUpdate(swingEvent);
    } else if (type == javax.swing.event.DocumentEvent.EventType.REMOVE) {
      listener.removeUpdate(swingEvent);
    } else if (type == javax.swing.event.DocumentEvent.EventType.CHANGE) {
      listener.changedUpdate(swingEvent);
    }
  }
}
 
Example 26
Source Project: consulo   Source File: EditorComponentImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Nullable
public List<javax.swing.event.DocumentListener> getListeners() {
  return myListeners;
}
 
Example 27
Source Project: consulo   Source File: EditorComponentImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void removeDocumentListener(javax.swing.event.DocumentListener documentListener) {
  if (myListeners != null) {
    myListeners.remove(documentListener);
  }
}
 
Example 28
Source Project: consulo   Source File: EditorTextField.java    License: Apache License 2.0 4 votes vote down vote up
public void addDocumentListener(DocumentListener listener) {
  myDocumentListeners.add(listener);
  installDocumentListener();
}
 
Example 29
Source Project: consulo   Source File: EditorTextField.java    License: Apache License 2.0 4 votes vote down vote up
public void removeDocumentListener(DocumentListener listener) {
  myDocumentListeners.remove(listener);
  uninstallDocumentListener(false);
}
 
Example 30
Source Project: consulo   Source File: EditorTextField.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void beforeDocumentChange(DocumentEvent event) {
  for (DocumentListener documentListener : myDocumentListeners) {
    documentListener.beforeDocumentChange(event);
  }
}