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.
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):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:
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.