2

Many of my python files have an import section that looks like this:

from   datetime import datetime, timedelta
from   typing import Callable
import numpy as np
import pandas as pd

I'd like to sort those lines by the library names. I'd like to run sort-lines but somehow tell it to overlook the first seven characters when assigning the order to a line, but to of course include those seven characters when it actually moves the line. That is, I'd like to end up with this:

from   datetime import datetime, timedelta
import numpy as np
import pandas as pd
from   typing import Callable
1
  • 1
    I don't think you can do it with sort-lines but you should be able to go one level below it and use sort-subr.
    – NickD
    Feb 9 at 20:46
3

C-h f sort-columns:

sort-columns is an interactive autoloaded compiled Lisp function in sort.el.

It is bound to menu-bar edit sort sort-columns.

(sort-columns REVERSE &optional BEG END)

Sort lines in region alphabetically by a certain range of columns.

For the purpose of this command, the region BEG...END includes the entire line that point is in and the entire line the mark is in. The column positions of point and mark bound the range of columns to sort on. A prefix argument means sort into REVERSE order. The variable sort-fold-case determines whether alphabetic case affects the sort order.

Note that sort-columns rejects text that contains tabs, because tabs could be split across the specified columns and it doesn't know how to handle that. Also, when possible, it uses the sort utility program, which doesn't understand tabs. Use M-x untabify to convert tabs to spaces before sorting.

See also the Elisp manual, node Sorting:

Command: sort-columns reverse &optional beg end

This command sorts the lines in the region between beg and end, comparing them alphabetically by a certain range of columns. The column positions of beg and end bound the range of columns to sort on.

If reverse is non-nil, the sort is in reverse order.

One unusual thing about this command is that the entire line containing position beg, and the entire line containing position end, are included in the region sorted.

Note that sort-columns rejects text that contains tabs, because tabs could be split across the specified columns. Use M-x untabify to convert tabs to spaces before sorting.

When possible, this command actually works by calling the sort utility program.

1

If you are working on linux or Unix, you should have a sort command at the command line. Emacs has shell-command-on-region (on my machine, bound to M-|). Mark the region to sort, press M-|, and type sort -k 2. The sorted results appear in a buffer named *Shell Command Output*.

The -k option to sort tells what key (or field) to sort by.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.