Sorting lines in Emacs is fairly straightforward with sort-lines.

However, how do I sort within a line? For example: John Ringo Paul George -> George John Paul Ringo

  • Why the downvotes?
    – Fergie
    Commented Aug 23, 2023 at 10:38

2 Answers 2


Evaluate the following form (or put it into your .emacs):

(defun your/sort-line ()
  "Sort the current line as you wish."
  (interactive "*")  ; Complain if buffer is read-only.
  (insert (mapconcat #'identity
                     (sort (split-string (prog1 (buffer-substring-no-properties (line-beginning-position) (line-end-position))

Type M-x your/sort-line when the cursor is at the line you want to sort.

  • 1
    Why redefine sort-line for this, instead of defining a new command, my-sort-line?
    – Drew
    Commented Aug 23, 2023 at 14:41
  • @Drew: "Why redefine sort-line for this" -- My Emacs doesn't have a function named sort-line.
    – shynur
    Commented Aug 23, 2023 at 14:52
  • 1
    @Drew: OK, anyway, adding a prefix is a good idea. I will do that.
    – shynur
    Commented Aug 23, 2023 at 14:54

There are several sorting commands, and some let you specify how you want "fields" to be defined, and they sort fields. See, for example, sort(-regexp)-fields and sort-numeric-fields, and maybe even sort-columns, depending on what you need.

See the Elisp manual, node Sorting.

  • I like the idea of using an existing built-in command, but it’s not clear to be from the linked documentation how to sort all tokens on a single line 🤔
    – Fergie
    Commented Aug 24, 2023 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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