If statement emacs lisp:如果找不到字符串,请插入字符串
我正在尝试编写一个函数,该函数将(1)在给定文件中搜索给定字符串,(2)如果文件不包含该字符串,则将该字符串添加到文件中。到目前为止,我有:If statement emacs lisp:如果找不到字符串,请插入字符串,if-statement,elisp,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-
(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告诉我搜索失败:“\\nosite{test input}”
“
这很好,但是当搜索失败时,它没有做我希望它做的任何事情。我不知道我的陈述有什么问题
理想情况下,该函数将在后台将字符串附加到文件并保存,而无需手动保存和终止缓冲区,但我还没有解决这一部分。计划是将其绑定到击键,这样我就可以在不中断工作流的情况下输入BibTex键。您的代码中有两个问题需要解决 首先,看一下
向前搜索的文档,它告诉您使用第3个参数来确保没有抛出错误
第二,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)))))
这看起来像是elisp的一个片段,它将对我完全无关的项目有所帮助。向上投票!