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

[Feature Request] Triggering Snippets with Keybindings

Open ShafSpecs opened this issue 3 years ago • 2 comments

Context

  • [X] This issue is not a bug report. (please use a different template for reporting a bug)
  • [X] This issue is not a duplicate of an existing issue. (please use the search to find existing issues)

Description

Hello, I was wondering if it's possible to trigger suggestion snippets with registerCompletionItemProvider using keybindings, like how addAction does it.

editor.addAction({
	// An unique identifier of the contributed action.
	id: 'my-unique-id',

	// A label of the action that will be presented to the user.
	label: 'My Label!!!',

	// An optional array of keybindings for the action.
	keybindings: [
		monaco.KeyMod.CtrlCmd | monaco.KeyCode.F10,
		// chord
		monaco.KeyMod.chord(
			monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyK,
			monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyM
		)
	],

	// A precondition for this action.
	precondition: null,

	// A rule to evaluate on top of the precondition in order to dispatch the keybindings.
	keybindingContext: null,

	contextMenuGroupId: 'navigation',

	contextMenuOrder: 1.5,

	// Method that will be executed when the action is triggered.
	// @param editor The editor instance is passed in as a convenience
	run: function (ed) {
		alert("i'm running => " + ed.getPosition());
	}
});

Something like this that enables us to embed with just pre-defined shortcuts

ShafSpecs avatar Jan 29 '22 02:01 ShafSpecs

The editor.action.insertSnippet action does not appear to exist in Monaco (even though it exists in Visual Studio Code). Not sure why... 🤔

rcjsuen avatar Feb 02 '22 12:02 rcjsuen

In case anyone is still trying to figure this out in TS, this is how I got it to work:

// Get the contribution registered.
import 'monaco-editor/esm/vs/editor/contrib/snippet/browser/snippetController2.js';

// ...

const snippetController = editor.getContribution('snippetController2') as
  | { insert: (template: string) => void }
  | null
  | undefined;
if (snippetController) {
  snippetController.insert(snippet);
  return;
}
// ...place fallback here in case the controller fails...

The main issue is that ../snippetController2.d.ts is an empty export.

I use it from a React useCallback() to paste snippets via buttons. It works like a charm.

srfrog avatar Sep 27 '25 03:09 srfrog