I'm trying to create a function that places/aligns/indents curly brackets according to Allman-style formatting (for coding in C).
Generally speaking, I am fan of Smartparens' interface available to users for customizing functionality. I've written a bunch of other functions using the Smartparens interface so would have a strong preference not to switch packages at this point. That said, I'm open to package-agnostic implementations (e.g., could defadvice
be relevant here?).
On to the problem at hand. What's the end goal? Let's suppose we're coding and we reach the state represented below. The pipe symbol represents the cursor; I've typed the function header and the opening brace {
, and Smartparens has automatically added the closing brace }
. At this point, I'd like it so that pressing RET
...
int main {|}
...leads to the following:
int main
{
|
}
I've been able to write the function that results in this behavior but it only works for the first level of indentation (e.g., for our main function in the example above). I can't get it to work for subsequent levels of indentation (see gif):
The relevant code is below. The function isn't pretty but I think it should work... The very last line is the interface to Smartparens.
Any suggestions?
(defun my-create-newline-and-enter-sexp (&rest _ignored)
"Open a new brace or bracket expression, with relevant newlines and indent. "
(interactive)
(progn
(backward-char 2) (newline) (forward-char) (newline)
(indent-according-to-mode)
(previous-line 2) (indent-according-to-mode)
(next-line) (next-line) (indent-according-to-mode)))
(sp-local-pair 'c-mode "{" nil :post-handlers '((my-create-newline-and-enter-sexp "RET")))