How to wait for an event in Emacs Lisp function?
I'm trying to write the simplest function: send a query to w3m browser and then find a particular place on the webpage:
(defun w3m-define-word (word)
(interactive "sDefine: ")
(progn (w3m-search "Dictionary" word)
(set-window-start nil (search-forward "Search Results"))))
What is wrong here is that w3m-search
does not wait until page reloads and set-开发者_JAVA百科window-start
executes on the older page. Then the page reloads and places a cursor at the beginning of the buffer.
(sleep-for ..)
between w3m-search
and set-window-start
helps, but since loading time is arbitrary, it is not very convenient.
How can I rewrite this function, so it would wait until buffer reloads and only then do the rest?
The way to accomplish this in elisp is using hooks. So you'd need to see if w3m calls a hook when the page is loaded. If so then you can register a hook function for that hook that does what you want.
It looks like C-h v w3m-display-hook RET
is what you're looking for. Here's a good example to start from.
Just in case if anyone has same ideas, that's what I have ended up with thanks to Ross:
(defun w3m-goto-on-load (url)
"Go to a position after page has been loaded."
(cond
((string-match "domain" url)
(progn
(set-window-start nil (search-forward "Search" nil t) nil)))
(t nil)))
(add-hook 'w3m-display-hook 'w3m-goto-on-load)
where "domain"
is a keyword in URL to match and "Search"
is the unique string to jump to. Certainly, search-forward
can be replaced with re-search-forward
, if more flexible search is required.
精彩评论