Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
simian114 opened this issue Oct 23, 2023 · 2 comments
Open

Comments

@simian114
Copy link

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
Copy link
Member

@simian114 Here are some examples you can refer to

import { EditorSelection } from '@codemirror/state';
import { ICommand } from '.';
export const bold: ICommand = {
name: 'bold',
keyCommand: 'bold',
button: { 'aria-label': 'Add bold text' },
icon: (
<svg width="13" height="13" viewBox="0 0 384 512">
<path
fill="currentColor"
d="M304.793 243.891c33.639-18.537 53.657-54.16 53.657-95.693 0-48.236-26.25-87.626-68.626-104.179C265.138 34.01 240.849 32 209.661 32H24c-8.837 0-16 7.163-16 16v33.049c0 8.837 7.163 16 16 16h33.113v318.53H24c-8.837 0-16 7.163-16 16V464c0 8.837 7.163 16 16 16h195.69c24.203 0 44.834-1.289 66.866-7.584C337.52 457.193 376 410.647 376 350.014c0-52.168-26.573-91.684-71.207-106.123zM142.217 100.809h67.444c16.294 0 27.536 2.019 37.525 6.717 15.828 8.479 24.906 26.502 24.906 49.446 0 35.029-20.32 56.79-53.029 56.79h-76.846V100.809zm112.642 305.475c-10.14 4.056-22.677 4.907-31.409 4.907h-81.233V281.943h84.367c39.645 0 63.057 25.38 63.057 63.057.001 28.425-13.66 52.483-34.782 61.284z"
/>
</svg>
),
execute: ({ state, view }) => {
if (!state || !view) return;
view.dispatch(
view.state.changeByRange((range) => ({
changes: [
{ from: range.from, insert: '**' },
{ from: range.to, insert: '**' },
],
range: EditorSelection.range(range.from + 2, range.to + 2),
})),
);
},
};

@simian114
Copy link
Author

@jaywcjlove thank you! it works perfectly!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants