问题
I have a .py source with many class definitions, like so:
class C:
# code c
class A:
# code a
class B:
# code b
I want to turn it into:
class A:
# code a
class B:
# code b
class C:
# code c
Is there a tool for this? What about doing it with emacs?
回答1:
I coded it for you, but only because I was interested in seeing how sort-subr
works. I do not condone the intent of the original question. :)
Also, if you upvote this answer, plase also upvote @db48x's didactic answer.
Use python-sort-defs the same way you would use 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)))
回答2:
I agree with bobince that alphabetical order isn't a useful way to sort functions or other bits of code, but you might give sort-paragraphs
a go. It might even work.
If it doesn't, then I can see by looking at the implementation of sort-paragraphs
that it does this:
(sort-subr reverse
(function
(lambda ()
(while (and (not (eobp)) (looking-at paragraph-separate))
(forward-line 1))))
'forward-paragraph))))
I bet you could come up with some functions to plug in there that would make it work. The first one moves point to the start of the next record and the second one moves the point to the end of the current record. There are some optional arguments for functions that tell it where the sort key is within the record which might also come in handy.
These functions are in sort.el; you can use C-h f sort-paragraphs
and C-h f sort-subr
to pull up the documentation for them; this will include a link to the source.
Have fun :)
来源:https://stackoverflow.com/questions/7616911/whats-the-best-way-to-sort-class-definitions-in-a-python-source-file