monaco-react icon indicating copy to clipboard operation
monaco-react copied to clipboard

How do I insert text at the cursor position of the mouse?

Open santiviquez opened this issue 4 years ago • 2 comments

Or how do I get the cursor position inside monaco editor?

santiviquez avatar Jul 09 '21 04:07 santiviquez

Do you mean the actual mouse position or the caret? (The caret is the blinky thingy where text goes when you type)

LoganDark avatar Jul 30 '21 23:07 LoganDark

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

Xoffio avatar Aug 04 '21 23:08 Xoffio

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 :)

barak-illumex avatar Sep 18 '22 08:09 barak-illumex