Access current editor from a sidebar plugin

I’m building a simple sidebar plugin to show synonyms for the word at the current cursor position in the active editor.

Despite hours of experimenting and searching the API docs I cannot find how to access the cursor position in the active editor when the sidebar is active.

Could anyone point me in the right direction?

What do you mean by “when the sidebar is active”?

As far as I understand, when the focus goes to the sidebar (the user clicks on the sidebar or open it) the main editor file is no longer active.

If you want to get the cursor or the selection of the main editor (the page in the middle of obsidian app) you can use these functions:

this.app.workspace.activeEditor?.editor?.getCursor() // Get cursor position
this.app.workspace.activeEditor?.editor?.getSelection() // Get selection

Not sure if it will solve your problem.

Thanks for taking the time to reply. As you say, when the user clicks on or activates the sidebar it get the focus and becomes the active view. So the activeEditor object is null and is not avaiable.

However with a bit more reading I discovered the getMostRecentLeaf() function which provides exactly what I needed: access the previously active editor view. For example:

  const view = this.app.workspace.getMostRecentLeaf().view;
  if (view) {
    const editor = view.editor;
    ...

This allows me to capture the word at the cursor and return a list of synonyms, and even do a one-click replacement.

Hope this helps any other budding plugin authors who are trying to solve the same problem. :wink:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.