Search code examples
sortingemacselisp

How to get Emacs to sort lines by length?


I'd like to be able to highlight a region in Emacs and then sort the region by line length.

The closest I've found is the following code which I think will sort by length:

 (sort-subr t #'forward-line #'end-of-line nil nil 
             (lambda (l1 l2) 
               (apply #'< (mapcar (lambda (range) (- (cdr range) (car range))) 
                                  (list l1 l2))))) 

But I don't know how to turn this into an interactive function that lets me use it by highlighting a region. Can someone help?


Solution

  • You can combine the sort-lines command definition with your snippet to form a new command:

    (defun sort-lines-by-length (reverse beg end)
      "Sort lines by length."
      (interactive "P\nr")
      (save-excursion
        (save-restriction
          (narrow-to-region beg end)
          (goto-char (point-min))
          (let ;; To make `end-of-line' and etc. to ignore fields.
              ((inhibit-field-text-motion t))
            (sort-subr reverse 'forward-line 'end-of-line nil nil
                       (lambda (l1 l2)
                         (apply #'< (mapcar (lambda (range) (- (cdr range) (car range)))
                                            (list l1 l2)))))))))