Emacs lisp shielding regexp

As the first experience in defining a function for emacs, I would like to write a function that takes all occurrences of argv [some number] and numbers them in order.

This is done inside emacs with replacement-regexp by entering a search / replace string

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

Now I want to write this in my .emacs, so I understand that I need to also avoid special Lisp characters. Therefore, in my opinion, he 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 \ in the replacement text. I am trying to add or remove some of them, but without success.

Any idea?

+4
source share
1 answer

replace-regexp ( - ):

`\, '

defun, . , :

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.

, :

(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)))))
+6

All Articles