emacs: sorting and aligning

Sort and align are useful when do format.

Sorting

Sorting in Emacs works a lot like the command line utility sort. All commands sort lines, except the lone paragraph command.

Command Description
M-x sort-lines Sorts alphabetically
M-x sort-fields Sorts field(s) Lexicographically
M-x sort-numeric-fields Sorts field(s) numerically
M-x sort-columns Sorts column(s) alphabetically
M-x sort-paragraphs Sorts paragraphs alphabetically
M-x sort-regexp-fields Sorts by regexp-defined fields lexicographically

M-x sort-lines sorts in ascending order, but if you call it with a universal argument it will reverse the sort order.

Aligning

Text alignment in Emacs encompasses both justification and columnated text. In fact, the alignment engine in Emacs is so sophisticated that it is able to automatically align and justify code based on regexp patterns.

Command Description
M-x align Aligns region based on align rules
M-x align-current Aligns section based on align rules
M-x align-regexp Aligns region based on regexp

Emacs’s align commands are powerful and useful if you often deal with unformatted text or code. The only downside is that you have to wade through the complex mode to repeat the alignment process more than once on a single line.

Sorting and aligning are alway use regex to match, then use rules to do some modify, it is also the main idea of formatting code.