Keeping lists alphabetized is important for organized, maintainable code. Fortunately, Vim has a number of ways to sort lines.
First and foremost, Vim has a built-in sort function. In this example, some sloppy, inattentive chap has left the Gemfile in utter shambles. We can clean it up easily.
With our cursor on the first gem line,
V will put us in
visual select mode and
G will highlight to the end of the file. Then
will use Vim’s built-in sort capability and we’ll end up with a vastly more
If we wanted to sort in reverse, then
:sort! will do the trick. But don’t get
that confused with
! command on a block of text executes the
proceeding command in the shell, passing the highlighted text to stdin and
returning the output into Vim. That means
:!sort, assuming a Unix-like
operating system, will do the same as Vim’s built-in
:sort: alphabetize the
highlighted text from A-Z.
There are lots of variations we can do on sorts either with the Unix sort utility or Vim’s:
Sort and remove duplicate lines, the Vim way and the Unix way:
Sort and respect month order by month name:
For more options and ideas, check out the docs for Vim’s sort with
or man sort for the Unix utility.