How to listen to file open event?

I am trying to listen to file open event, i.e, a callback when a file is opened in the editor. 

I am using this now:

project.messageBus.connect(project).subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener {
override fun fileOpened(source: FileEditorManager, file: VirtualFile) {
super.fileOpened(source, file)
println("File Opened: ${file.name}")
}
})

This works fine for all files that I open.

1. But what about the files that are already opened, when I open the project? How do I listen to those as well?

2. Is this the right API to use to listen to file open event?

 

3 comments

You can use:

Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();

to get the currently open editor,

Editor[] editors = EditorFactory.getInstance().getAllEditors();

to get all open Editors, and

FileEditor[] editors = FileEditorManager.getInstance(project).getAllEditors()

to get all open FileEditors in your project.

1

Events for files reopened at project opening are generated as well. You listener might not have received it because it was registered after those files were already opened. I've checked that registering a listener at some project component's instantiation time will ensure that those events will be catched.

 

0

I am trying to access the Psi, so I really have to wait for the Indexing to complete. So I want this to work only after the project is fully initialized.

So I ended up using

FileEditor[] editors = FileEditorManager.getInstance(project).getAllEditors()

I knew about this, but was totally consumed with `messageBus`, I forgot this.

Thank you for your help.

0

Please sign in to leave a comment.