2012-08-08 85 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