Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 850
Lorem Ipsum Avatar asked Sep 21 '26 02:09

Lorem Ipsum


1 Answers

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.

like image 137
Ealhad Avatar answered Sep 23 '26 16:09

Ealhad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!