emacs lisp:如果找不到字符串,请插入字符串

时间:2012-08-08 18:23:17

标签: if-statement elisp

我试图编写一个函数,它将(1)搜索给定文件中的给定字符串,(2)如果文件不包含该字符串,则将该字符串添加到该文件中。到目前为止,我有这个:

(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键。

1 个答案:

答案 0 :(得分: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)))))