user2941893
user2941893

Reputation: 43

Emacs lisp escaping regexp

As a first experience in defining a function for emacs, I would like to make write a function that take all occurences of argv[some number] and renumber them in order.

This is done inside emacs with replace-regexp, entering as search/replace strings

argv\[\([0-9]+\)\]
argv[\,(+ 1 \#)]

Now, I want to write this in my .emacs so I understand I need to escape also for Lisp special characters. So in my opinion it should write

(defun argv-order () 
  (interactive)
  (goto-char 1)
  (replace-regexp "argv\\[[0-9]+\\]" "argv[\\,\(+ 1 \\#\)]")
)

The search string works fine but the replacement string gives me the error "invalid use of \ in replacement text. I've been trying around adding or removing some \ but with no success.

Any idea ?

Upvotes: 4

Views: 1243

Answers (1)

juanleon
juanleon

Reputation: 9380

Quoting the help from replace-regexp (the bold is mine):

In interactive calls, the replacement text may contain `\,'

You are not using it interactively in your defun, hence the error message. Another quote from the same help that helps solving your problem:

This function is usually the wrong thing to use in a Lisp program.
What you probably want is a loop like this:
  (while (re-search-forward REGEXP nil t)
    (replace-match TO-STRING nil nil))
which will run faster and will not set the mark or print anything.

And a solution based on that:

(defun argv-order ()
  (interactive)
  (let ((count 0))
    (while (re-search-forward "argv\\[[0-9]+\\]" nil t)
      (replace-match (format "argv[%d]" count) nil nil)
      (setq count (1+ count)))))

Upvotes: 6

Related Questions