Search code examples
rustemacslanguage-server-protocol

How to get LSP like formatting in Emacs Elisp?


Here is a scenario I use constantly in Rust development:

  1. Rust LSP is always on.
  2. I call the LSP feature "format current buffer" (or whatever it's called).
  3. The LSP returns the buffer formatted (internally, the LSP uses rustfmt).

Since Emacs Elisp does not have an LSP implementation, how can I achieve something similar? E.g., I wanna press some button and have the code in the buffer be formatted (not just indented, formatted).

P.S. Emacs newbie here, transitioning from Neovim.


Solution

  • De facto, Elisp formatting rules are defined in users config files, .dir-locals.el per project, and often follow this style guide suggestions.

    Since Emacs 29, for which pretest is now available, new function pp-emacs-lisp-code can be used, which "applies formatting rules appropriate for Emacs Lisp code."

    The docstring of the function currently states:

    Insert SEXP into the current buffer, formatted as Emacs Lisp code. Use the pp-max-width variable to control the desired line length. Note that this could be slow for large SEXPs.

    A number of third-party packages for Elisp formatting are listed in Command that formats (prettifies) Elisp code thread.