在python源文件中对类定义进行排序的最佳方法是什么?

我有一个带有许多类定义的.py源代码,如下所示:

class C:
    # code c

class A:
    # code a

class B:
    # code b

我想把它变成:

class A:
    # code a

class B:
    # code b

class C:
    # code c

有这个工具吗?用emacs做什么呢?

最佳答案 我为你编写了代码,但仅仅因为我有兴趣了解sort-subr是如何工作的.我不宽恕原始问题的意图. 🙂

此外,如果你赞成这个答案,也可以提出@ db48x的教学答案.

使用python-sort-defs与使用sort-paragraph的方式相同.

(defun python-sort-defs (reverse beg end)
  (interactive "P\nr")
  (save-excursion
    (save-restriction
      (narrow-to-region beg end)
      (goto-char (point-min))
      (sort-subr reverse
                 (function
                  (lambda ()
                    (while (and (not (eobp)) (looking-at paragraph-separate))
                      (forward-line 1))))
                 'python-end-of-block-must-move))))

(defun python-end-of-block-must-move ()
  (when (eq (point) (progn
                      (python-end-of-block)
                      (point)))
    (forward-line 1)))
点赞