如何让Emacs按长度排序?

时间:2015-06-07 19:20:46

标签: sorting emacs elisp

我希望能够突出显示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))))) 

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

1 个答案:

答案 0 :(得分:8)

您可以将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)))))))))