Say I have a simple block of code:

if(a===b){
  console.log('yay');
}

Is there a way in VSCode to have an automatic comment added to the closing bracket like so:

if(a===b){
  console.log('yay');
} // close-if-block

I have seen this behavior in Dart plugin in IntelliJ Android Studio and was wondering if something similar is available in VSCode

1

There are 1 best solutions below

1
On BEST ANSWER

Yes, but not really in a user-friendly way.

You can remap your } key to append text with it by adding an argument to your keybinds.json:

{
    "key": "shift+]",
    "command": "type",
    "args": {
        "text": "} // end of region"
    },
    "when": "editorTextFocus"
}

Where this gets tricky, is....well, everywhere.

Consider you don't want this for every possible language, obviously plaintext files, you would have to add some logic to your when expression for the languages you do want it to populate, which is no problem, doable:

{
    "key": "shift+]",
    "command": "type",
    "args": {
        "text": "} // end of region"
    },
    "when": "editorTextFocus && resourceExtname =~ /^\\.(?:js|ts)$/"
}

Now, consider you are inside of a comment:

// this is a js comment, } //end of block

You can not mitigate this scenario, I don't think.

Another caveat is that most people employ autoclosing brackets, meaning, you only type the opening symbol, and the closing symbol is populated for you, which in this case would not apply.

Another caveat, is that it just is not scope-aware, meaning, it would be static text (not like a snippet) so there's no insight on if it is a close-if-block or a close-switch-statement, for example.

In short, there would be some maintenance with this method, however, this is a native solution for those that don't mind it.