Wolf
Wolf

Reputation: 183

emacs lisp: if string not found, insert string

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.

Upvotes: 1

Views: 303

Answers (1)

Nicolas Dudebout
Nicolas Dudebout

Reputation: 9262

There are two things to fix in your code.

First, take a look at the documentation for search-forward it tells you to use the 3rd argument to make sure an error is not thrown.

Second, lambda does not do what you want. Lambda defines a new function, but what you are trying to do is to evaluate a function that executes two functions in a row. You whould be using progn for that.

Here is the modified code with the added functionality of saving automatically the file.

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

Upvotes: 3

Related Questions