My boss is a bit of a neat freak. He wants the functions in my functions.sh be ordered alphabetically.

foo() {
  echo foo

baa() {
  echo baa

So baa should appear first in the file.

Can emacs help me do this? I have tons of methods in this file.

2 Answers 2


If you only have things like you show, and no blank lines, then sort-paragraphs will do what you want. Go to the start of the file, and invoke it.

Assuming that your real life example is harder than this, I think you will need to write a little bit of lisp to provide some functions to use with sort-subr.


Similar to @icarus' answer, you could potentially use sort-pages with a custom page-delimiter.

If it's true that a line starting with } is always the end of a function, then:

  • M-: (setq-local page-delimiter "^}") RET
  • Mark the region
  • M-x sort-pages RET

A classic hack is to substitute some non-conflicting token for newlines such that every record becomes a single line, then sort the lines, and finally turn the tokens back into newlines.

You could also use common shell commands for this approach. Your delimiter might be multiple characters, but the NUL character is a good delimiter, if your tools support using it. The following won't be portable across all systems, but may work for you.

C-uM-| sed -z -e 's/\n}\n\n*/&\x0/g' | sort -z | tr -d '\000' RET

As before, this assumes that records end with } on a line by itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.