Dec 13, 2004 17:25
Lets assume you just work in a console or in a some other X11 application. You just select something with a mouse and now you wish to search this in emacs. Of course it is very easy - Control/S, Enter, Paste, Enter. But is it nice and convenient? I don't think so.
If you insert the following code fragment in your .emacs file, you can select something in any application (aka X11 selection) or in emacs buffer itself. Then you can press F2 (when you are in emacs window, of course), and the search is executed. The subsequent F2 will repeat the search.
(defvar xsel-search-overlay nil)
(defvar xsel-prev-search nil)
(defvar mysearch-overlay nil)
(global-set-key [f2] '(lambda() ; F2
(interactive nil)
(xsel-search)))
(defun mysearch-dehighlight ()
(remove-hook 'mouse-leave-buffer-hook 'mysearch-dehighlight)
(if mysearch-overlay
(delete-overlay mysearch-overlay)))
(defun mysearch-highlight (beg end)
(if (or (null search-highlight) (null window-system))
nil
(add-hook 'mouse-leave-buffer-hook 'mysearch-dehighlight)
(or mysearch-overlay (setq mysearch-overlay (make-overlay beg end)))
(move-overlay mysearch-overlay beg end (current-buffer))
(overlay-put mysearch-overlay 'face
(if (internal-find-face 'isearch nil)
'isearch 'region))))
(defun xsel-search ()
"Search of X11 selection"
(let ((new-seacrh "")
(found nil)
)
(cond
((x-selection-exists-p)
(setq new-seacrh (x-get-selection))
)
(mark-active
(setq new-seacrh (buffer-substring (point) (mark)))
(deactivate-mark)
)
(t
(setq new-seacrh xsel-prev-search)
)
)
(if new-seacrh
(progn
(save-excursion
(goto-char (1+ (point)))
(setq found (search-forward new-seacrh (point-max) t 1))
)
(if found
(progn
(goto-char (match-beginning 0))
(message "<%s> found: Line = %d; Column = %d"
new-seacrh
(if (bolp)
(1+ (count-lines 1 (point)))
(count-lines 1 (point))
)
(1+ (current-column))
)
(mysearch-highlight (match-beginning 0) (match-end 0))
t
)
(message "<%s> not found." new-seacrh)
)
(setq xsel-prev-search new-seacrh)
t
)
)
)
)