javascripttypescriptif-statementvisual-studio-codeautoformatting

How to auto format one extra space around AND (&&) in VSCode?


Let's say there is an if statement like this:

if( a && b )
    c();

Is there a way to auto-format it to having extra spaces around AND (&&) / OR (||) operators using VSCode's default formatter (editor.formatOnSave)?

if( a  &&  b )
    c();

Most formatting settings I found, except for this one.


Solution

  • You can make your own "formatter on save" command. The following will run on save only.

    You will need an extension I wrote that enables you to specify a find and replace in a setting and then designate that to run on save. The extension is Find and Transform. After installing the extension, make these settings (in your settings.json):

     "findInCurrentFile": {
    
       "AddSpaceAround&&and||": {                   // whatever name you want
         "title": "add a space around && and ||",
         "find": "(?<=[^\\s]\\s)(&&|\\|\\|)(?=\\s[^\\s])",
         "replace": " $1 ",
         "isRegex": true
       }
     },
    
    
    "[javascript][typescript]": {         // will only run on these files
    
      "editor.codeActionsOnSave": [
        "source.AddSpaceAround&&and||"    // run this command (from above) on save
      ]
    }
    

    This find (?<=[^\\s]\\s)(&&|\\|\\|)(?=\\s[^\\s]) will get those && or || that are surrounded by one space only - so you don't have to worry about it continually adding a space around those operators when there are already two spaces there.

    Here is a demo:

    demo of wrapping operators with two spaces on save

    Note: this will not format as you type (there is probably no formatter that will make sure there are 2 spaces around an operator). But the above works on save which is pretty neat.

    Note: you can also run the command you created, here called AddSpaceAround&&and|| at any time from the Command Palette or a keybinding. Lots more info in the README's.