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:

				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 =;
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 :(
        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'.
            // If we get here, then we did not recognise 'view_mode'.

(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: