Dane O'Connor
Dane O'Connor

Reputation: 77298

How do I sort css selectors with vim?

I want to alphabetize css selectors (and properties) in my scss files. I'm sure vim can do this (even if I need to use some external tool). How would you sort the following?

h2 { 
  color:red;
  background-color:green;
}
h1 {
  font-size:12px;
}

To this:

h1 {
  font-size:12px;      
}
h2 {
  background-color:green;
  color:red;
}

Upvotes: 2

Views: 1344

Answers (2)

Vladimir Starkov
Vladimir Starkov

Reputation: 19803

Try CSScomb. This tool sorts your css in cusomizable way. You can try it online.

CSScomb has plugin for Vim.

From the CSScomb's site:

  • Sorting CSS properties (The order of properties in the help of professionals)
  • Setting the order of CSS properties (Use the order to which you are accustomed to)

Upvotes: 0

Randy Morris
Randy Morris

Reputation: 40927

For your simple example the following two snippets seem to work, however I fear they may fall down with larger, more complex css.


To order the properties I used a macro**:

:let @q = "/{^Mvi{:sort^M"|%norm! @q

** Note that the ^M's here are entered with Ctrl-vCtrl-m.

Explanation:

  1. Define a macro to:
    • Search for a "{"
    • Select text between "{" and "}"
    • Sort the selection by line
  2. Run the macro across all lines in the buffer.

To order the selectors I used substitute and sort:

:%s/\v([^}])\n/\1/g|%sort|%s/\v[;{]/&\r/g

Explanation:

  1. For every line that begins with something other than "}" remove the newline to collapse this block down to a single line.
  2. Sort the buffer linewise.
  3. After every ";" or "{" insert a newline.

Trailing whitespace throws this off a bit but you don't have any of that, right? :)

Upvotes: 5

Related Questions