2009-01-17 61 views
4

我幾個月來一直在使用Emacs,並且我想開始使用elisp編程。具體來說,我想寫我自己的interactive函數。但是,我有點失落。 (interactive ...)有很多選項,我不確定我想要哪一個。然後,我真的不知道我需要的功能的名稱。如果有人能夠幫助我將我的僞代碼變成真正的代碼,我會非常感激! (和往常一樣,以翔實的地方的任何鏈接將是一件好事現在我剛讀了this.。)用交互式Emacs Lisp函數替換文本幫助

這裏是僞代碼是我想要做的:

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

回答

5

首先,從你可能會在當前緩衝區中執行你的函數的外觀,所以不,你不需要有'緩衝區'參數。如果這是一個糟糕的假設,我可以更改代碼。接下來,在'let'中,如果您正在分配變量,則需要在每對var/value周圍添加另一組parens。最後,當循環訪問列表時,我更喜歡使用函數式編程函數(mapcar,mapc等)。我將在這裏內嵌了一些意見:

(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 

至於讀什麼書,我建議自帶的Emacs的elisp的手冊。

+0

非常感謝,這幫助我瞭解發生了什麼並走上正軌。我只需要使用`re-search-forward`而不是非regexp版本,並且不會將`t`傳遞給`replace-match`,以便引用匹配的組。再次感謝! – 2009-01-18 03:48:56