VIM tip of the day

An operation I happen to do a lot:

Given a list of words spread on separate lines, sort the words.

One can try to do :sort or !sort on a range, but that will sort the lines, not the words inside the lines.

Easiest I found so far (but requires visual formatting which is only available in vim):

  • visual select of the lines you want to sort
  • !!fmt -1
  • visual select of the lines you want to sort
  • :sort
  • gw}

Clear as mud :-)

Explanation:

! will run the selection through an external program, in this case fmt (which is a Unix command to format a list of lines). -1 says to format with a text width of 1 character (which effectively breaks the words at the space)

:sort will sort the selected lines

gw} will format from where the cursor is to the end of the paragraph (re-joining the lines).

One thought on “VIM tip of the day

  1. Michael K Johnson

    or: !fmt -1 | sort | fmt

    Without visual mode, you can use marks: “m” sets a mark, the next character selects the register to store the mark in (“a” works fine if you aren’t already intentionally using it), go to the other end of the selection, then “!” (pipe) “‘” (reference mark) “a” (select register) “fmt -1 | sort | fmt”

    Where “gw}” re-wraps to the end of the paragraph, re-wrapping to a mark with “gw’a”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>