Vim: How would I recursively run ": sort" on everything between curly braces?

I am a web developer and I often have to write CSS:

I always sort the style alphabetically like so:

.sorted_product_mens_color_list li, .sorted_product_womens_color_list li {
    margin: 0 5px 0 5px;
    padding: 5px;
    border: 2px solid black;
}

      

turns into:

.sorted_product_mens_color_list li, .sorted_product_womens_color_list li {
    border: 2px solid black;
    margin: 0 5px 0 5px;
    padding: 5px;
}

      

However, this is getting repetitive and I want to just automate it by writing a script that does it in VIM.

How could I: 1) run :sort

in a loop within the file in all curly braces or 2) Run this on all css files in the directory? (one)

+3


source to share


2 answers


For a single file you could do:

:g/{/normal! f{viB:sort^M

      

What does it do:

  • :g/{/

    : for every line containing a {

  • normal!

    : enter normal mode ( !

    just skips mappings in the command)
  • f{

    : find (first, but that shouldn't be a problem in css (?)) {

  • viB

    : enter visual mode between curly braces
  • :sort

    : well ... collect visual selection
  • ^M

    : press enter (this is one character, use <C-v><CR>

    to enter it)



For multiple files you could do:

# From you shell
# In zsh you would use 'vim **/*.css' to open all the css files in nested directories
# Not sure about your shell
$> vim *.css     # open css files in the current directory

      

" In vim
:argdo g/{/normal! f{viB:sort^M:update^M

      

:update

is the same as :write

, except that it will not cause a write if the buffer has not been modified.

+8


source


As requested by @Edmund , I'll add an answer to explain :g/{/+,/}/-sort

further. Command syntax:g

:{range}g/pattern/{ex command(s)}

      

The initial search range is empty; by default, the entire file is searched. A pattern {

that looks for an open parenthesis.



:g/{/{ex command(s)}

      

The team is the remainder. In this case, this command is ex +,/}/-sort

. This is interrupted as an extra range (" +,/}/-

") followed by a command ( sort

) to execute in that range. This range starts at the current line (found by the " :g

" command ) and goes forward one ( +

which will be a synonym +1

since it defaults to 1) line. Then " ,

" separates the start of the range from the end of the range. To find the second line of the range, we search forward for the next parenthesis (" /}/

") and then back down to one line (" -

", again equivalent to " -1

"). Now that we have defined the range as "from the line following the opening parenthesis that we found, along the line before the closing parenthesis",we execute sort

ex command in this range.

+9


source







All Articles