uiwjs / react-markdown-editor

A markdown editor with preview, implemented with React.js and TypeScript.
https://uiwjs.github.io/react-markdown-editor
MIT License
337 stars 34 forks source link

How to Insert text to current cursor position using custom toolbar #209

Open simian114 opened 1 year ago

simian114 commented 1 year ago

How can i insert a specific string at the current cursor position using the custom toolbar feature?

Is theme a method to get current cursor position and insert text? thank you!

this is my code, and it doesn't work properly.

please give me some advice, Thank you!

    execute: (mirror: ReactCodeMirrorRef) => {
      const { view, state, editor } = mirror
      if (!view || !state || !editor) {
        return
      }
      // NOTE: how to get current position of cursor?
      const lineInfo = view.state.doc.lineAt(view.state.selection.main.from)
      console.log(lineInfo)
      const insert = `![image title](image url)`
      view.dispatch({
        changes: {
          from: lineInfo.from,
          to: lineInfo.from + insert.length,
          insert,
        },
        selection: { anchor: lineInfo.from },
      })
    },
jaywcjlove commented 1 year ago

@simian114 Here are some examples you can refer to

https://github.com/uiwjs/react-markdown-editor/blob/56b09debd3bebbe2e30f20b635cf874f0d55815a/core/src/commands/bold.tsx#L1-L28

simian114 commented 1 year ago

@jaywcjlove thank you! it works perfectly!