Lorem Ipsum
Lorem Ipsum

Reputation: 4534

Define variable local to function

I am working (joyfully) through the Introduction to Emacs Lisp Programming and have solved the first 8.7 Searching Exercise. It states,

Write an interactive function that searches for a string. If the search finds the string, leave point after it and display a message that says “Found!”.

My solution is

(defun test-search (string)
  "Searches for STRING in document.
Displays message 'Found!' or 'Not found...'"
  (interactive "sEnter search word: ")
  (save-excursion
    (beginning-of-buffer)
    (setq found (search-forward string nil t nil))) 
  (if found
      (progn
        (goto-char found)
        (message "Found!"))
    (message "Not found...")))

How do I make found be local to the function? I know that a let statement defines a local variable. However, I only want to move point if the string is found. It's not clear to me how to define found locally, yet not have the point be set to the beginning-of-buffer if the string isn't found. Is let the proper command for this situation?

Upvotes: 3

Views: 1136

Answers (1)

Ealhad
Ealhad

Reputation: 2240

As stated in some comments, let is what you want to use here, although it will not define a variable local to the function, but a scope of its own.

Your code becomes:

(defun test-search (string)
   "Searches for STRING in document.
Displays message 'Found!' or 'Not found...'"
   (interactive "sEnter search word: ")
   (let ((found (save-excursion
                  (goto-char (point-min))
                  (search-forward string nil t nil))))
     (if found
       (progn
         (goto-char found)
         (message "Found!"))
       (message "Not found..."))))

Edit: code modified thanks to phils'comment.

Upvotes: 2

Related Questions