1

我正在尝试编写一个函数,该函数将(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 键而不会中断工作流程。

4

1 回答 1

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)))))
于 2012-08-08T20:56:27.827 回答