A common practice of software developers is to sort lists of things alphabetically. A predictable order makes navigating lists easier and adding new entries faster. When another order isn’t obvious, use alphabetic ordering.
For text editing use cases outside of software, such as data editing and note taking, alphabetical sorting can be even more valuable.
The sort-motion plugin can make doing this easy, where it is otherwise tedious and involved. From the README:
sort-motion
has four different sorting modes:
Linewise: sort a sequence of lines (require statements, gem lists, etc)
Character: sort a comma separated list (argument lists, attribute lists, etc)
Visual (linewise or normal): provided for continuity, similar to linewise
Block Visual: By default behaves the same as the other visual modes. Optionally, you can provide a specific sort command which you might use to sort by a column (example:
Vissort
)
The mode I use the most is visual: Select a block of text and use gs
to sort the selection linewise. And if you need to reselect the same visual selection again, there’s a trick for that!
In the screencast below I demonstrate two examples of how to use sort-motion:
gsa)
with my cursor on the open paren to sort the items to the close parenThen I move down 2 lines with
2j
gsi{
with my cursor on the open curly bracket to sort the close curly bracket
For minimum keystrokes and maximum sort options, use the sort-motion plugin. But if you’re set on avoiding plugins, Vim has some built in options for you:
:sort
to sort all the lines in the file, alphabetically:sort!
to sort all the lines but in reverse:sort u
removes duplicate lines while sorting:sort i
ignores the case when sorting:sort n
sorts numerically to prevent 100 from coming before 20
All of these also work with visual selections of lines as well. Of course, there are ways to sort elements of a single line in vanilla Vim as well, as detailed in this StackExchange response, but they will involve some regex. The basic line sorting is easy to remember, but for power sorts, use sort-motion.
Was this useful? Help us improve!
With your feedback, we can improve VimTricks. Click a link to vote:
And :sort i ingnores case!