How can I make a VS Code keybinding only apply when a specific View is visible/focused?

54 Views Asked by At

I'm coming from other IDEs in which when you globally search for some content across your project (in Visual studio code it's done by pressing CMD+SHIT+F) and then want to move between the founded items, you just press down/up and start moving between them.

I was looking to get this kind of behavior in Visual Studio Code, I found out there's a command for that that is describerd here: In vscode, how do I jump to the results of "find in files" without using the mouse

But when I was doing the following inkeybinds.json:

[
  {
    "key": "down",
    "command": "runCommands",
    "args": { 
        "commands": [
            "search.action.focusSearchList",
            "list.focusDown",
            "workbench.action.focusActiveEditorGroup"
        ]
    }
  },
  {
      "key": "up",
      "command": "runCommands",
      "args": { 
          "commands": [
              "search.action.focusSearchList",
              "list.focusUp",
              "workbench.action.focusActiveEditorGroup"
          ]
      }
  }
]

It just messed up, so when I'm coding and want to move line down by pressing the down key, it applies the sequence commands in the keybinds.json

Is there a way to achieve my goal? So for instance only to apply the above commands when I'm focused on the search pane?

1

There are 1 best solutions below

0
On

See https://code.visualstudio.com/api/references/when-clause-contexts#visible-view-container-when-clause-context. You can check which viewlet is visible with the activeViewlet context key, and check if the sidebar is focused with the sideBarFocus context key.

You want to add a when clause like "sideBarFocus && activeViewlet == 'workbench.view.search'". If you also want to cover cases where the Search View is moved into the Panel area or the Secondary/Auxiliary sidebar, then do "sideBarFocus && (activeViewlet == 'workbench.view.search' || activePanel == 'workbench.view.search' || activeAuxiliary == 'workbench.view.search')".

For visiblility, see also the list of Global UI context keys

Or, for the focused view, see https://code.visualstudio.com/api/references/when-clause-contexts#visiblefocused-view-when-clause-context. Use the view.${viewId}.visible context key. Not all views seem to be supported here though.