1

How can I perform the equivalent of M-x sort-columns with a stable sort?

For example, let's say my text is:

a 99
b 98
b 97
a 96
a 95
b 94
a 93
b 92
c 91
...

And I want to perform a stable sort against the first column.

With sort-columns I would put mark at the beginning of the buffer, put point in the last line just after the first column, and M-x sort-columns RET.

My problem is that this sort is not stable. The output is:

a 93
a 95
a 96
a 99
b 92
b 94
b 97
b 98
c 91

Whereas I need to keep the line order for each first column:

a 99
a 96
a 95
a 93
b 98
b 97
b 94
b 92
c 91

How could I do that? Is there a hidden option in sort-columns? Or is some Elisp necessary? I know sort --stable could do the trick but I want a solution that works on Windows where the sort command-line tool is absent.

0

I think that sort-fields does what you want. At least it does so with the example text you show.

See also the Elisp manual, node Sorting.

  • "sort-fields" doesn't seem documented as being a stable sort, though in practice it looks like it is. So it might stop being stable in the next Emacs releases? – user1735594 May 6 at 12:58
  • Yes, presumably so. But it's been the way it is for many decades. Please consider sending an enhancement request to document that it is a stable sort (and thus have Emacs commit to that), using M-x report-emacs-bug. – Drew May 6 at 13:37

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.