Get current text selection

I’ve not managed to find a way to grab the current selected text in the editor in a plugin command - I’d like to be able to select a bit of text, and then run a command that takes that as input. Any suggestions?

So plugin Commands can be given an editorCallback that gets the current editor as an argument:

		{
				id:t.id,
				name: t.name,
				editorCallback: (editor, _ ) => {
					const { line } = editor.getCursor();
					const sel = editor.getSelection()
					console.log("From: ", editor.getCursor("from"))
					console.log("To: ", editor.getCursor("to"))
					console.log("Head: ", editor.getCursor("head"))
					console.log("Anchor: ", editor.getCursor("anchor"))
					console.log("Got selection: " + sel)
				}
			}

Hi, I’m replying in a hurry, so my post is not a completely finalised answer to your question.

You might use something like this:

let view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view) {
  // View can be null some times. Can't do anything in this case.
} else {
  let view_mode = view.getMode(); // "preview" or "source" (can also be "live" but I don't know when that happens)
  switch (view_mode) {
        case "preview":
            // The leaf is in preview mode, which makes things difficult.
            // I don't know how to get the selection when the editor is in preview mode :(
           break;
        case "source":
            // Ensure that view.editor exists!
            if ("editor" in view) {
                // Good, it exists.
                // @ts-ignore We already know that view.editor exists.
                let selection = view.editor.getSelection(); // THIS IS THE SELECTED TEXT, use it as you wish.
            }
            // If we get here, then 'view' does not have a property named 'editor'.
           break;
        default:
            // If we get here, then we did not recognise 'view_mode'.
            break;
    }
}

(I’ve copied and simplified this from my own plugin Shell commands. @Licat helped me with this a while ago, thanks to him!)

My question: How can we get the selection also when the current view is in preview mode? Thank you for support! :slight_smile:

In the editor.getCursor() method, there are 4 optional strings:

  • from
  • to
  • head
  • anchor

from and to are self-explanatory. But what exactly is represented by head and anchor?

head and anchor are just aliases for to and from where in a selection head is the head of the selection (where the cursor is) and anchor is the position where the selection is anchored to (where the selection began).

image

1 Like

Thanks I was experimenting with the code and was drawing the same conclusion- that they were the same thing but it’s good to get some confirmation!