How do I insert text at the cursor position of the mouse?
Or how do I get the cursor position inside monaco editor?
Do you mean the actual mouse position or the caret? (The caret is the blinky thingy where text goes when you type)
Hi @santiviquez,
I think that's more like a monaco-editor API question than a monaco-react question.
Anyway...
Here is someone that ask the same question.
Basically you have to make a ref of the editor so you can access it later, like this:
// Monaco instance reference
const monacoRef = useRef(null);
function handleEditorDidMount(editor, monaco) {
// here is another way to get monaco instance
// you can also store it in `useRef` for further usage
monacoRef.current = editor;
}
Then, as shown in the stack overflow answer
function handleEditorChange(value, event) {
var selection = monacoRef.current.getSelection();
var id = { major: 1, minor: 1 };
var text = "XXX";
var op = {identifier: id, range: selection, text: text, forceMoveMarkers: true};
monacoRef.current.executeEdits("my-source", [op]);
}
I hope this can help you
Hi @SpaceComet, Your answer helped me a lot so I thought I might add some react and typescript adaptations for the next one who tackles this issue.
import Editor, { Monaco, OnMount } from '@monaco-editor/react';
import { editor, languages } from 'monaco-editor';
...
const CustomEditor: React.FC = () => {
const [monacoInstance, setMonacoInstance] = React.useState<editor.IStandaloneCodeEditor | null>(null);
const insertText = (text: string) => {
if (monacoInstance) {
const selection = monacoInstance.getSelection();
const id = { major: 1, minor: 1 };
const op = {
identifier: id,
range: {
startLineNumber: selection?.selectionStartLineNumber || 1,
startColumn: selection?.selectionStartColumn || 1,
endLineNumber: selection?.endLineNumber || 1,
endColumn: selection?.endColumn || 1,
},
text,
forceMoveMarkers: true,
};
monacoInstance.executeEdits('my-source', [op]);
}
};
const editorMount: OnMount = (editorL: editor.IStandaloneCodeEditor) => {
setMonacoInstance(editorL);
};
...
<Editor
onMount={editorMount}
...
<StyledButton // styled comp
onClick={() => {insertText('inserted text');}}
>
Insert text
</StyledButton>
Hopefully this could help someone :)