The thoughts of G. Allen Morris III

The VIM global command

July 22nd 2018

The vim global command is helpful in many ways this little trick with the global command uses it to do work (here sort) on a block of text.

Let us say we want to sort all of the hashes we have in a file

x = {
   'a' => 'x',
   'd' => 'x',
   'c' => 'x',
   'b' => 'x',
}

y = {
   'b' => 'x',
   'a' => 'x',
   'c' => 'x',
   'd' => 'x',
}

if we run the ex command :g/{/.+1,/}/-1 sort we will end up with:

x = {
   'a' => 'x',
   'b' => 'x',
   'c' => 'x',
   'd' => 'x',
}

y = {
   'a' => 'x',
   'b' => 'x',
   'c' => 'x',
   'd' => 'x',
}

What this command does is search for all lines that match '/{/' in the file. Then on each of those lines it runs the ex commenad: :.+1,/}/-1 sort. which sorts from the current line +1 to the line before the next closing brace.