12

I have a bunch of C macros in files, stuff like NEXT( pL ) which is expanded to ( ( pL ) -> next )

I want to remove most of them because they're unnecessary.

What I would like to do, is get the text inside the parentheses in the macro, pL. I want the replacing regexp to use that text for the rewriting. For example, in Perl I could do something like /NEXT\(\s*(.+)\s*) (may be a little incorrect) and then output something like $1->next, which should turn a line

if ( NEXT( pL ) != NULL ) { 

into

if ( pL->next != NULL ) {

In Emacs, I would like to use match groups in an emacs replace-regexp on a file by file basis. I'm not entirely sure how to do this in Emacs.

2
  • M-x c-macro-expansion or M-x c-macro-expand could be used. But what you ask for looks like it will need a new function around the M-x c-macro-expansion to work on a whole file or buffer. Commented Dec 1, 2010 at 21:32
  • c-macro-expand doesn't know the macros though? They are located in a separate file/buffer. Commented Dec 1, 2010 at 21:37

1 Answer 1

23
M-x query-replace-regexp NEXT(\([^)]+\)) RET \1->next RET

Which can be done inside a function like so (to apply to an entire buffer)

(defun expand-next ()
  "interactive"
  (goto-char (point-min))
  (while (re-search-forward "\\<NEXT(\\([^\)]+\\))" nil t)
    (replace-match "\\1->next")))

And, to apply this to multiple files, you can mark the files in Dired and type Q to do a query-replace-regexp on all the marked files (use the regexp/replacement in the first line of this answer).

Sign up to request clarification or add additional context in comments.

1 Comment

I'm dredging up some old muck here rather than submit a new question since this is the correct topic ... I'm using Emacs 23.1. When I use \1 as the replacement, I get "No matches found." I use the same regexp built from regexp-builder which matches the found text correctly. Any Ideas??

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.