Search code examples
regexvisual-studio-codesassvscode-snippets

Add a comment on closing SASS/CSS brackets automatically in VScode


I would like to add a comment on closing brackets, so when the code gets too nested the I can tell where each bracket belongs, something like this:


.parent{
    position: relative;
    height: 100px;
    width: 100px;

   .child{
       position: absolute;
       height: 50px;
       left: 25px;
       width: 50px;

       &:before{
           content: '';
           background: red;
           position: absolute;
           height: 50px;
           top: 25px;
           width: 50px;
       } // before
   } // .child
} // .parent

It would be awesome if this could be implemented as I type or on autosave.


Solution

  • You can do this with a snippet if you don't find an extension that will do it. Put this in one of your snippets files:

    "css: add comment": {
      "prefix": "|c",
      "body": [
        "${TM_CURRENT_LINE/(\\s*)&*:*(.*)?\\s*\\|c/{\n$1${1:-\t}\n$1} \\/* $2 *\\//}",
      ],
      "description": "add comment after closing bracket"
    },
    

    I am using |c as the prefix because it is the same as the emmet html comment filter. I am not aware if you can get emmet to use a css comment filter. But you can use whatever prefix you wish to trigger the snippet. Here is a demo:

    demo of adding indented css elements with comments


    Here is a breakdown of the snippet body transform.

    ${TM_CURRENT_LINE/(\\s*)&*:*(.*)?\\s*\\|c/ get the current line, capture group one will have the amount of indentation you need for the next indented child element. Capture group 2 will have that current element's name - but any preceding &: will not be included in the name capture group.

    /{\n$1${1:-\t}\n$1} \\/* $2 *\\// is the transformed text.

    Add a newline, then add the proper amount of indentation (whitespace). If there was no previous indentation - like the first .parent entry - capture group 1 will be empty but we still need to add one tab in the middle of the next child element anyhow.

    ${1:-\t} is an else conditional that will add a tab when capture group 1 is empty as it will be when a parent element is started flush left.

    Lastly, add the closing bracket and the name of the current element (capture group 2) surrounded by css comment indicators.


    If you have an element that you don't want commented, just don't add the snippet prefix.