easy-markdown-editor icon indicating copy to clipboard operation
easy-markdown-editor copied to clipboard

Is it possible to get the position of selected text?

Open khughitt opened this issue 1 year ago • 1 comments

Greetings!

Is there a way to determine the start + end position of selected text?

The goal is to add a custom keyboard short cut which triggers a function that modifies the selected text in a particular way (wraps it in some custom formatting).

The simplest approach seems like it would be to use mde.value() to retrieve the full text, replace the desired subsection, and then call mde.value(..) again to update the content, however, I couldn't figure out a straight-forward way to get the position of the selected region.

Any suggestions?

khughitt avatar Aug 10 '24 20:08 khughitt

I think you can get what you want from the codemirror instance

image

If you really want the char index, then maybe try the .getCursor() in any case, you really have to use the codemirror instance to get these kind of things, see their manual for all available methods

ghiscoding avatar Aug 26 '24 18:08 ghiscoding

I finally had the chance to follow up on this.. Your suggestion worked out perfectly - Thank you!

Here is an example of adding a keyboard shortcut using useHotkeys:

  useHotkeys('ctrl+1', () => {
    if (mde === undefined) return
    const selection = mde.codemirror.getSelection()
    mde.codemirror.replaceSelection(`[foo]${selection}[/foo]`)
  }, { preventDefault: true, enableOnFormTags: true, enableOnContentEditable: true });

And to insert a string at the current cursor position:

const cursor = mde.codemirror.getCursor()
mde.codemirror.replaceRange(`..string to insert..`, cursor)

khughitt avatar Apr 25 '25 01:04 khughitt