c3900
c3900

Reputation: 5

Emacs rule to format function declaration

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.

Upvotes: 0

Views: 196

Answers (1)

event_jr
event_jr

Reputation: 17707

You can do this easily by recording a keyboard macro:

Here is one I prepared earlier shown through edit-named-kbd-macro.

;; Keyboard Macro Editor.  Press C-c C-c to finish; press C-x k RET to cancel.
;; Original keys: M-C-a C-SPC M-C-n <<replace-regexp>> , RET , C-q LFD RET M-C-a C-SPC M-C-n TAB

Command: c-split-formal-params 
Key: none

Macro:

M-C-a           ;; c-beginning-of-defun
C-SPC           ;; set-mark-command
M-C-n           ;; forward-list
<<replace-regexp>>  ;; replace-regexp
,           ;; c-electric-semi&comma
RET         ;; newline
,           ;; c-electric-semi&comma
C-q         ;; quoted-insert
LFD         ;; newline-and-indent
RET         ;; newline
M-C-a           ;; c-beginning-of-defun
C-SPC           ;; set-mark-command
M-C-n           ;; forward-list
TAB         ;; c-indent-line-or-region

Having a better understanding of structural navigation commands like beginning-of-defun and forward-list will also help you.

For more in depth discussions of keyboard macros see the manual and my previous answers.

Upvotes: 1

Related Questions