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!