tags:

views:

590

answers:

1

I've been using Emacs for a couple months now, and I want to get started in elisp programming. Specifically, I'd like to write my own interactive function. However, I'm more than a bit lost. (interactive ...) has tons of options and I'm not sure which one I want. Then, I don't really know the names of the functions I need. If someone could kindly help me turn my pseudocode into real code, I would be mighty appreciative! (And as always, any links to informative places would be good. Right now I've just been reading this.)

Here is pseudocode for what I'd like to do:

(defun my-func (buffer) ; I think I need the buffer as an arg?
  "does some replacements"
  (interactive ???) ; ?
  (let (replacements (list
   '("a-regexp-string" . "a-replacement-string-with-backreferences")
   ...)) ; more of the above
    (while replacements
      (let (current (car replacements)) ; get a regexp-replacement pair
        (some-regexp-replace-func buffer (car current) (cdr current)) ; do the replacement
        (setq replacements (cdr replacements))))))
+4  A: 

First, from the looks of your function you would probably be doing it in the current buffer, so no, you don't need to have a 'buffer' argument. If that's a bad assumption, I can change the code. Next, in a 'let' if you are assigning to variables you need another set of parens around each pair of var/value. Finally, when looping through a list I prefer to use functional-programming-like functions (mapcar, mapc, etc.). I'll try to inline some comments here:

(defun my-func ()
  "Do some replacements"
  (interactive)
  (let ((replacements (list '("foo" . "bar")
                            '("baz" . "quux"))))
    (save-excursion ; So point isn't moved after this function
      (mapc (lambda (x) ; Go through the list, with this 'inline' function
                        ; being called with each element as the variable 'x'
              (goto-char (point-min)) ; Start at the beginning of the buffer
              (while (re-search-forward (car x) nil t) ; Search for the car of the replacement
                (replace-match (cdr x)))) ; And replace it with the cdr
            replacements)))) ; The list we're mapc'ing through

As for what to read, I'd suggest the Elisp manual that comes with Emacs.

scottfrazer
Thank you very much, that helped me understand what was going on and get on the right track. I just had to use `re-search-forward` instead of the non-regexp version, and not pass `t` to `replace-match` so that referencing of matched groups works. Thanks again!
J Cooper
Yeah, I was just coming back to fix those :)
scottfrazer