Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 444
Ana Avatar asked Jun 07 '15 19:06

Ana


1 Answers

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)))))))))
like image 189
event_jr Avatar answered Oct 20 '22 23:10

event_jr