See the various sort commands, such as sort-pages
, sort-paragraphs
, and sort-regexp-fields
.
The first two require the things you want to sort to be what Emacs recognizes as pages and paragraphs, respectively. E.g., pages are separated by C-l
characters.
The third one lets you define the things to sort by the text that matches a regexp you supply. It sounds like that one will work for your use case, which seems to be sorting lists (matching corresponding (
and )
chars).
See the Elisp manual, node Sorting.
C-h f
sort-regexp-fields`:
sort-regexp-fields
is an interactive autoloaded Lisp function in
sort.el
.
It is bound to menu-bar edit sort sort-regexp-fields
.
(sort-regexp-fields REVERSE RECORD-REGEXP KEY-REGEXP BEG END)
Sort the text in the region lexicographically.
If called interactively, prompt for two regular expressions,
RECORD-REGEXP
and KEY-REGEXP
.
RECORD-REGEXP
specifies the textual units to be sorted.
For example, to sort lines, RECORD-REGEXP
would be "^.*$"
.
KEY-REGEXP
specifies the part of each record (i.e. each match for
RECORD-REGEXP
to be used for sorting.
If it is "\\digit"
, use the digit'th "\\(...\\)"
match field specified by RECORD-REGEXP
.
If it is "\\&"
, use the whole record.
Otherwise, KEY-REGEXP
should be a regular expression with which
to search within the record. If a match for KEY-REGEXP
is not
found within a record, that record is ignored.
With a negative prefix arg, sort in reverse order.
The variable sort-fold-case
determines whether alphabetic case affects
the sort order.
For example: to sort lines in the region by the first word on each line starting with the letter "f",
RECORD-REGEXP
would be "^.*$"
and KEY
would be "\\<f\\w*\\>"
'(("x" "b" ...) ("a" "y" ...))
?