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

114 Views Asked by At

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.

3

There are 3 best solutions below

8
Mark On BEST ANSWER

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.

0
starball On

VS Code's default JavaScript and TypeScript formatter come from TypeScript. The closest thing to what you want that I'm aware of that providing is javascript.format.insertSpaceBeforeAndAfterBinaryOperators and typescript.format.insertSpaceBeforeAndAfterBinaryOperators. But I'm pretty sure that only makes one space and not two.

If you want something relatively vanilla, you could use search and replace as a workaround. Use the search view's replace feature, turn on regex mode, put \s*(&&|\|\|)\s* in the search field, and put $1 in the replace field, and click the triple dots to open up the extra menu and put *.ts,*.js in the "files to include" field.

2
Tiran Harsha On

So use the Prittier extension. It will be easy for you. And also you can configure it from the VS Code setting.json according to the languages.