The feature is more or less as the same as the navigation bar in most modern browsers: if it is a URL, load it; if not, use the default search engine to search the web for it. How can I achieve that in Emacs, such as modifying the default behavior of browse-url
?
-
Shift k is pretty cool. I don't know if it just works on doom emacs.– ArisMay 6 at 1:02
4 Answers
This mostly does what you want:
(defun my-search-or-browse ()
"If selected region, or thing at point, is a url, go there. Otherwise,
use region/thing as a keyword for a google search."
(interactive)
(let ((target
(if (use-region-p)
(buffer-substring (region-beginning) (region-end))
(thing-at-point 'symbol))))
(if (ffap-url-p target)
(browse-url target)
(browse-url (concat "http://www.google.com/search?q="
(url-hexify-string target))))))
This will only recognize actual URLs, with the http://
prefix. Plain addresses like www.example.com
will be treated like keywords. I haven't found any built-in functions that would distinguish between actual urls of the form google.com
and other strings with periods in them.
Some useful information are available at BrowseAproposURL to address this issue. One important package is keyword-search, which is available on MELPA. After installing the package, the command keyword-search
will be available, which will search a keyword or visit the URL depending on the text.
Another option which allows defining the search engine:
Here's my take on this :
(defun px-websearch (start end)
"Websearch selected string."
(interactive "r")
(let ((q (buffer-substring-no-properties start end)))
(browse-url (concat "https://qwant.com/?q="
(url-hexify-string q) "!g"))))