2017-04-04 60 views
2

我工作(快乐)工作通过介绍Emacs Lisp编程并已解决了第一个8.7 Searching Exercise。它指出,定义变量本地功能

编写一个搜索字符串的交互功能。如果 搜索找到该字符串,则在该字符后面留下点,并显示一条消息 ,其中显示“找到!”。

我的解决办法是

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

我如何found是本地的功能?我知道let语句定义了一个局部变量。但是,如果找到string,我只想移动点。我不清楚如何在本地定义found,但如果未找到string,则没有将该点设置为beginning-of-bufferlet是否适合这种情况?

+1

对于临时范围变量(它是“let”形式的范围本地,而不是本地的*函数),你应该确实使用'let',除非正在使用词法绑定,变量是否则标记为动态)。 – phils

+1

例如:'(let((found(save-excursion(goto-char(point-min))(search-forward string nil t nil))))(if found ...))' – phils

+1

或者,您可以离开成功搜索后单独指向,但在失败后恢复原始位置。 – phils

回答

0

正如一些评论指出,let是你要在这里干什么用的,虽然会定义一个局部变量的功能,但它自己的范围。

您的代码就变成了:

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

编辑:代码修改感谢phils“评论。

+0

请注意,在编写elisp时,应该使用'(goto-char(point-min))'而不是'(缓冲区开始)'。 – phils

+0

谢谢@phils;) – Ealhad