4

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 ?

3
  • The amount of backslashes in string should be double of that for interactive use. That's it. Commented Oct 31, 2013 at 14:59
  • This is not enough because you have to escape the parentheses that are a special character in List but not in regexp. Commented Oct 31, 2013 at 21:12
  • It's enough. Interactively, you put \(\) if you want to capture. In elisp you put \\(\\) in the same place. If you want plain parens, you don't have to escape them in both cases. Commented Oct 31, 2013 at 21:17

1 Answer 1

6

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)))))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, this work perfectly! I thought putting (interactive) would have been enough for my solution, but I missed that help page ...

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.