Search code examples
monaco-editor

Enable keyboard shortcut for escaping Monaco suggestions widget only when it is visible


I've added a shortcut to escape the Monaco suggestions widget with the space bar, which caused the space bar not to work anymore as a space bar. I'm thinking that ideally, I would just have to add a conditional that would enable the shortcut only when the Monaco suggestions widget is visible, is it something that is feasible?

Here is my code, so far:

const hideSuggestions = editor.createContextKey('hideSuggestions', true)

editor.addCommand(
  monaco.KeyCode.Space, function () {editor.trigger('', 'hideSuggestWidget', null) }, 'hideSuggestions' )

I'm only missing some way of changing hideSuggestions from true to false whether the Monaco suggestions widget is triggered or not.


Solution

  • Instead of addCommand use the more advanced addAction method, which allows to specify preconditions:

            const blockContext = "editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode " +
                "&& !quickFixWidgetVisible";
    
                editor.addAction({
                    id: "executeCurrent",
                    label: "Execute Block",
                    keybindings: [KeyMod.Shift | KeyCode.Enter],
                    contextMenuGroupId: "2_execution",
                    precondition: blockContext,
                    run: () => { return this.executeCurrentContext(false, false); },
                });
    

    I use this for running an action when the user presses shift+enter.