如何让 Emacs 按长度对行进行排序?

How to get Emacs to sort lines by length?

我希望能够在 Emacs 中突出显示一个区域,然后按行长度对该区域进行排序。

我找到的最接近的是下面的代码,我认为它会按长度排序:

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

但我不知道如何将它变成一个交互功能,让我通过突出显示一个区域来使用它。有人可以帮忙吗?

您可以将 sort-lines 命令定义与您的代码段结合起来形成一个新命令:

(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)))))))))