I’m trying to define a command to customize my C/C++ function definitions in emacs.
What I’d like to obtain is to automatically reformat the code to look like this:
type func(type arg1,
type arg2,
...
type argN) {
starting from a generic declaration such as:
type func(type arg1, type arg2, ..., type argN) {
My idea was to search for the specific pattern of a function definition, and replace it with itself with a new line after each comma, and then adjust the indentation.
I messed around for a while with regexp and so on, but I couldn’t come up with anything.
I can’t figure out how to properly perform replacement within the string obtained using my regex.
What follows is everything I got so far, which basically is almost nothing.
(defun fix-arg-definition ()
(interactive)
(goto-char (point-min))
(replace-regexp "([^,()]+\\([,][^,()]+\\)+)[ ]*{" "WHAT TO PUT HERE?")
)
I’m completely new to the world of customizing coding style in emacs, and this has proven more difficult than I thought. Any help is appreciated.
UPDATE
I’ve managed to get something that seems to work, although I’ve still got to try test it thoroughly.
(defun fix-args ()
(interactive)
(goto-char 1)
(while (search-forward-regexp "\\(([^,()]+\\([,][^,()]+\\)+)[ ]*{\\)" nil t)
(replace-match (replace-commas) t nil)))
(defun replace-commas ()
(let (matchedText newText)
(setq matchedText
(buffer-substring-no-properties
(match-beginning 1) (match-end 1)))
(setq newText
(replace-regexp-in-string "," ",\n" matchedText) )
newText))
I can live with this, and then adjust the indentation manually with another command, at least for now.
You can do this easily by recording a keyboard macro:
Here is one I prepared earlier shown through
edit-named-kbd-macro.Having a better understanding of structural navigation commands like
beginning-of-defunandforward-listwill also help you.For more in depth discussions of keyboard macros see the manual and my previous answers.