2012-08-08 89 views
1

我想寫一個函數,它將(1)爲給定的字符串搜索給定的文件,(2)如果文件不包含字符串,添加字符串到文件。到目前爲止,我有這樣的:emacs lisp:如果找不到字符串,插入字符串

(setq nocite-file "~/Dropbox/docs/school/thesis/_nocites.tex") 

(defun add-nocite-prompt (key) 
    "Prompts for a BibTex key. If that key does not already exist in the file 
nocite-file, add-nocite-prompt appends a \nocite{} instruction to that file." 
    (interactive "sBibTex Key: ") 
;; check for definition of nocite-file, else prompt 
    (unless (boundp 'nocite-file) 
    (setq nocite-file (read-from-minibuffer "Define nocite-file: "))) 
    (setq nocite-string (concat "\\nocite{" key "}\n")) 
    (with-current-buffer (find-file-noselect nocite-file) 
    (goto-char (point-min)) 
    (unless (search-forward nocite-string) 
     (lambda() 
    (goto-char (point-max)) 
    (insert nocite-string))))) 

當我運行它,但是,emacs的告訴我Search failed: "\\nocite{test-input} "這很好,但它不會做任何我希望它在搜索失敗做的事情。我不能說出我的除非聲明有什麼問題。

理想情況下,該函數會將字符串追加到後臺的文件中,並保存而不必手動保存並終止緩衝區,但我尚未解決該問題。計劃是將它綁定到按鍵,以便我可以在不中斷工作流的情況下輸入BibTex密鑰。

回答

3

在代碼中有兩件事需要解決。

首先,看看search-forward的文檔,它告訴你使用第三個參數來確保不會引發錯誤。

二,lambda不會做你想做的。 Lambda定義了一個新函數,但您要做的是評估一個函數,該函數可以在一行中執行兩個函數。你應該使用progn

這裏是修改後的代碼,增加了自動保存文件的功能。

(defun add-nocite-prompt (key) 
    "Prompts for a BibTex key. If that key does not already exist in the file 
nocite-file, add-nocite-prompt appends a \nocite{} instruction to that file." 
    (interactive "sBibTex Key: ") 
;; check for definition of nocite-file, else prompt 
    (unless (boundp 'nocite-file) 
    (setq nocite-file (read-from-minibuffer "Define nocite-file: "))) 
    (setq nocite-string (concat "\\nocite{" key "}\n")) 
    (with-current-buffer (find-file-noselect nocite-file) 
    (goto-char (point-min)) 
    (unless (search-forward nocite-string nil t) 
     (progn 
    (goto-char (point-max)) 
    (insert nocite-string) 
    (save-buffer))))) 
+0

謝謝!那很完美! – Wolf 2012-08-08 20:58:58

+0

我剛剛編輯添加'save-buffer'部分。 – 2012-08-08 20:59:33

+0

這看起來像elisp的片段,這對我完全無關的項目會有所幫助。 Upvoted! – 2012-08-08 21:28:50