Search code examples
visual-studio-codeformatkey-bindings

Keyboard shortcut to enable/disable code formatting toggles (VSCode)


I often need to open and make small changes to projects which use different code formatting options than the ones I use. In order not to reformat the whole file, I usually open the user settings, search for settings containing "format", and then disable the options Editor: Format On Paste, Editor: Format On Save, Editor: Format On Type. When I return to my projects, I re-enable those options.

I would like this to be simpler, such as, binding a keyboard shortcut to quickly toggle all three of those options. However, I could not find shortcut actions that could bind to those.

Does anyone know if what I'm trying to achieve is possible?


Solution

  • You can do this with an extension: Toggle, which allows you to toggle many settings at the same time.

    In your keybindings.json:

    {
      "key": "alt+capslock",       // whatever keybinding you wish
      "command": "toggle",
      "when": "editorTextFocus",
      "args": {
        "id": "toggleFormats",
        "value": [
          {
            "editor.formatOnType": true,
            "editor.formatOnPaste": true,
            "editor.formatOnSave": true,
            "window.enableMenuBarMnemonics": false
          },
          {
            "editor.formatOnType": false,
            "editor.formatOnPaste": false,
            "editor.formatOnSave": false,
            "window.enableMenuBarMnemonics": true
          }
        ]
      }
    },
    

    I haven't tested it but it should work.

    The only problem is there is no visual indicator which state you are in - perhaps you can find some other setting to toggle that would do so and be "innocuous." That is why I threw enableMenuBarMnemonics in there, on my keyboard the capslock key lights up when the formats are set to false and you can also check by doing alt+F to see if the main menu File option is opened. You may not need a visual reminder to indicate the state or come up with a better one.