开发者

Fixing Sass / SCSS bracket indentation

开发者 https://www.devze.com 2023-03-26 00:09 出处:网络
I have a regex puzzle for you all! A week or so ago, I decided to change the formatting of my Sass file from this:

I have a regex puzzle for you all!

A week or so ago, I decided to change the formatting of my Sass file from this:

a {
  color: red;
  text-decoration: none;

  &:hover: {
    color: blue;
    text-decoration: underline;
  }
}

div { ... }

To this:

a {
  color: red;
  text-decoration: none;

  &:hover: {
    color: blue;
    text-decoration: underline; } }

div { ... }

The second syntax seems nice -- it saves you lines and improves readability -- but it is actually a disaster for writing code. Imagine if I wanted to add another line after a:hover's text-decoration: I'd have to bring those two parentheses with me.

Anyway, I've been trying to find the perfect regex to change the formatting back but to no avail.

My thinking:

  1. Match and capture 2 spaces since all closing brackets are indented at least one level: (\s{2})
  2. Match and capture all additional spaces: (\s*)
  3. Match and captu开发者_如何转开发re all other characters (my CSS code): (.*)
  4. Match space + closing bracket: }

Replace that with two lines: \1\2\3\n\2}

Doesn't exactly work quite yet. Appreciate any ideas.


Regex won't really work, as you've discovered, because the meaning/desired position depends on the parsing of the Document that has come before.

You need a parser or a filter for this job.

Fortunately, a standard JS beautifier, or a CSS indenter should whip that file right back into shape.


PS: Also consider more frequent backups and version control. (^_^)


Another easy way to do it is to do a quick replace on your editor, no regex, just make it match the spaces, replace with the new brackets/lines. Might not be as quick as using a css re-indenter though.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号