1

I'm trying to write a function that will (1) search a given file for a given string, and (2) if the file does not contain the string, add the string to the file. So far I have this:

(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)))))

When I run it, however, emacs tells me Search failed: "\\nocite{test-input} " Which is fine, but it doesn't do any of the things I want it to do when the search fails. I can't tell what's wrong with my unless statement.

Ideally, the function would append the string to a file in the background and save without having to manually save and kill the buffer, but I haven't tackled that part of it yet. The plan is to bind this to a keystroke so I can enter the BibTex key without interrupting workflow.

4

1 に答える 1

3

コードで修正すべき点が 2 つあります。

search-forwardまず、エラーがスローされないようにするために 3 番目の引数を使用するように指示されているドキュメントを参照してください。

第二に、lambdaあなたが望むことをしません。Lambda は新しい関数を定義しますが、実行しようとしているのは、2 つの関数を連続して実行する関数を評価することです。あなたはそのために使っ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 に答える