PageRenderTime 4ms CodeModel.GetById 52ms app.highlight 15ms RepoModel.GetById 1ms app.codeStats 0ms

/emacs.d/elpa/helm-20150628.2150/helm-net.el

https://gitlab.com/glor/.dots
Lisp | 563 lines | 440 code | 69 blank | 54 comment | 23 complexity | 2be21d0f89ae7f4ddfa8931a15fd6474 MD5 | raw file
  1;;; helm-net.el --- helm browse url and search web. -*- lexical-binding: t -*-
  2
  3;; Copyright (C) 2012 ~ 2015 Thierry Volpiatto <thierry.volpiatto@gmail.com>
  4
  5;; This program is free software; you can redistribute it and/or modify
  6;; it under the terms of the GNU General Public License as published by
  7;; the Free Software Foundation, either version 3 of the License, or
  8;; (at your option) any later version.
  9
 10;; This program is distributed in the hope that it will be useful,
 11;; but WITHOUT ANY WARRANTY; without even the implied warranty of
 12;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 13;; GNU General Public License for more details.
 14
 15;; You should have received a copy of the GNU General Public License
 16;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
 17
 18;;; Code:
 19
 20(require 'cl-lib)
 21(require 'helm)
 22(require 'url)
 23(require 'xml)
 24(require 'browse-url)
 25
 26
 27(defgroup helm-net nil
 28  "Net related applications and libraries for Helm."
 29  :group 'helm)
 30
 31(defcustom helm-google-suggest-default-browser-function nil
 32  "The browse url function you prefer to use with google suggest.
 33When nil, use the first browser function available
 34See `helm-browse-url-default-browser-alist'."
 35  :group 'helm-net
 36  :type 'symbol)
 37
 38(defcustom helm-home-url "http://www.google.fr"
 39  "Default url to use as home url."
 40  :group 'helm-net
 41  :type 'string)
 42
 43(defcustom helm-surfraw-default-browser-function nil
 44  "The browse url function you prefer to use with surfraw.
 45When nil, fallback to `browse-url-browser-function'."
 46  :group 'helm-net
 47  :type 'symbol)
 48
 49(defcustom helm-google-suggest-url
 50  "http://google.com/complete/search?output=toolbar&q="
 51  "URL used for looking up Google suggestions."
 52  :type 'string
 53  :group 'helm-net)
 54
 55(defcustom helm-google-suggest-search-url
 56  "http://www.google.com/search?ie=utf-8&oe=utf-8&q=%s"
 57  "URL used for Google searching."
 58  :type 'string
 59  :group 'helm-net)
 60
 61(defcustom helm-google-suggest-use-curl-p nil
 62  "When non--nil use CURL to get info from `helm-google-suggest-url'.
 63Otherwise `url-retrieve-synchronously' is used."
 64  :type 'boolean
 65  :group 'helm-net)
 66
 67(defcustom helm-yahoo-suggest-url
 68  "http://search.yahooapis.com/WebSearchService/V1/relatedSuggestion?appid=Generic&query="
 69  "Url used for looking up Yahoo suggestions."
 70  :type 'string
 71  :group 'helm-net)
 72
 73(defcustom helm-yahoo-suggest-search-url
 74  "http://search.yahoo.com/search?&ei=UTF-8&fr&h=c&p=%s"
 75  "Url used for Yahoo searching."
 76  :type 'string
 77  :group 'helm-net)
 78
 79(defcustom helm-surfraw-duckduckgo-url
 80  "https://duckduckgo.com/lite/?q=%s&kp=1"
 81  "The duckduckgo url.
 82This is a format string, don't forget the `%s'.
 83If you have personal settings saved on duckduckgo you should have
 84a personal url, see your settings on duckduckgo."
 85  :type 'string
 86  :group 'helm-net)
 87
 88(defcustom helm-wikipedia-suggest-url
 89  "http://en.wikipedia.org/w/api.php?action=opensearch&search="
 90  "Url used for looking up Wikipedia suggestions."
 91  :type 'string
 92  :group 'helm-net)
 93
 94(defcustom helm-search-suggest-action-wikipedia-url
 95  "https://en.wikipedia.org/wiki/Special:Search?search=%s"
 96  "The Wikipedia search url.
 97This is a format string, don't forget the `%s'."
 98  :type 'string
 99  :group 'helm-net)
100
101(defcustom helm-wikipedia-summary-url
102  "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=0&page="
103  "URL for getting the summary of a Wikipedia topic."
104  :type 'string
105  :group 'helm-net)
106
107(defcustom helm-wikipedia-follow-delay 2
108  "Delay before wikipedia summary popup."
109  :type 'number
110  :group 'helm-net)
111
112(defcustom helm-search-suggest-action-youtube-url
113  "http://www.youtube.com/results?aq=f&search_query=%s"
114  "The Youtube search url.
115This is a format string, don't forget the `%s'."
116  :type 'string
117  :group 'helm-net)
118
119(defcustom helm-search-suggest-action-imdb-url
120  "http://www.imdb.com/find?s=all&q=%s"
121  "The IMDb search url.
122This is a format string, don't forget the `%s'."
123  :type 'string
124  :group 'helm-net)
125
126(defcustom helm-search-suggest-action-google-maps-url
127  "http://maps.google.com/maps?f=q&source=s_q&q=%s"
128  "The Google Maps search url.
129This is a format string, don't forget the `%s'."
130  :type 'string
131  :group 'helm-net)
132
133(defcustom helm-search-suggest-action-google-news-url
134  "http://www.google.com/search?safe=off&prmd=nvlifd&source=lnms&tbs=nws:1&q=%s"
135  "The Google News search url.
136This is a format string, don't forget the `%s'."
137  :type 'string
138  :group 'helm-net)
139
140
141;;; Additional actions for search suggestions
142;;
143;;
144;; Internal
145
146(defun helm-search-suggest-perform-additional-action (url query)
147  "Perform the search via URL using QUERY as input."
148  (browse-url (format url (url-hexify-string query))))
149
150(defvar helm-search-suggest-additional-actions
151  '(("Wikipedia" . (lambda (candidate)
152                     (helm-search-suggest-perform-additional-action
153                      helm-search-suggest-action-wikipedia-url
154                      candidate)))
155    ("Youtube" . (lambda (candidate)
156                   (helm-search-suggest-perform-additional-action
157                    helm-search-suggest-action-youtube-url
158                    candidate)))
159    ("IMDb" . (lambda (candidate)
160                (helm-search-suggest-perform-additional-action
161                 helm-search-suggest-action-imdb-url
162                 candidate)))
163    ("Google Maps" . (lambda (candidate)
164                       (helm-search-suggest-perform-additional-action
165                        helm-search-suggest-action-google-maps-url
166                        candidate)))
167    ("Google News" . (lambda (candidate)
168                       (helm-search-suggest-perform-additional-action
169                        helm-search-suggest-action-google-news-url
170                        candidate))))
171  "List of additional actions for suggest sources.")
172
173
174;;; Google Suggestions
175;;
176;;
177(defun helm-google-suggest-fetch (input)
178  "Fetch suggestions for INPUT from XML buffer."
179  (let ((request (concat helm-google-suggest-url
180                         (url-hexify-string input)))
181        (fetch #'(lambda ()
182                   (cl-loop
183                    with result-alist = (xml-get-children
184                                         (car (xml-parse-region
185                                               (point-min) (point-max)))
186                                         'CompleteSuggestion)
187                    for i in result-alist collect
188                    (cdr (cl-caadr (assoc 'suggestion i)))))))
189    (if helm-google-suggest-use-curl-p
190        (with-temp-buffer
191          (call-process "curl" nil t nil request)
192          (funcall fetch))
193        (with-current-buffer
194            (url-retrieve-synchronously request)
195          (funcall fetch)))))
196
197(defun helm-google-suggest-set-candidates (&optional request-prefix)
198  "Set candidates with result and number of google results found."
199  (let ((suggestions (helm-google-suggest-fetch
200                      (or (and request-prefix
201                               (concat request-prefix
202                                       " " helm-pattern))
203                          helm-pattern))))
204    (if (member helm-pattern suggestions)
205        suggestions
206        ;; if there is no suggestion exactly matching the input then
207        ;; prepend a Search on Google item to the list
208        (append
209         suggestions
210         (list (cons (format "Search for '%s' on Google" helm-input)
211                     helm-input))))))
212
213(defun helm-ggs-set-number-result (num)
214  (if num
215      (progn
216        (and (numberp num) (setq num (number-to-string num)))
217        (cl-loop for i in (reverse (split-string num "" t))
218              for count from 1
219              append (list i) into C
220              when (= count 3)
221              append (list ",") into C
222              and do (setq count 0)
223              finally return
224              (replace-regexp-in-string
225               "^," "" (mapconcat 'identity (reverse C) ""))))
226    "?"))
227
228(defun helm-google-suggest-action (candidate)
229  "Default action to jump to a google suggested candidate."
230  (let ((arg (format helm-google-suggest-search-url
231                     (url-hexify-string candidate))))
232    (helm-aif helm-google-suggest-default-browser-function
233        (funcall it arg)
234      (helm-browse-url arg))))
235
236(defvar helm-google-suggest-default-function
237  'helm-google-suggest-set-candidates
238  "Default function to use in helm google suggest.")
239
240(defvar helm-source-google-suggest
241  `((name . "Google Suggest")
242    (candidates . (lambda ()
243                    (funcall helm-google-suggest-default-function)))
244    (action . ,(cons '("Google Search" . helm-google-suggest-action)
245                     helm-search-suggest-additional-actions))
246    (volatile)
247    (keymap . ,helm-map)
248    (requires-pattern . 3)))
249
250(defun helm-google-suggest-emacs-lisp ()
251  "Try to emacs lisp complete with google suggestions."
252  (helm-google-suggest-set-candidates "emacs lisp"))
253
254
255;;; Yahoo suggestions
256;;
257;;
258(defun helm-yahoo-suggest-fetch (input)
259  "Fetch Yahoo suggestions for INPUT from XML buffer.
260Return an alist with elements like (data . number_results)."
261  (let ((request (concat helm-yahoo-suggest-url
262                         (url-hexify-string input))))
263    (with-current-buffer
264        (url-retrieve-synchronously request)
265      (cl-loop with result-alist =
266            (xml-get-children
267             (car (xml-parse-region
268                   (point-min) (point-max)))
269             'Result)
270            for i in result-alist
271            collect (cl-caddr i)))))
272
273(defun helm-yahoo-suggest-set-candidates ()
274  "Set candidates with Yahoo results found."
275  (let ((suggestions (helm-yahoo-suggest-fetch helm-input)))
276    (or suggestions
277        (append
278         suggestions
279         (list (cons (concat "Search for " "'" helm-input "'" " on Yahoo")
280                     helm-input))))))
281
282(defun helm-yahoo-suggest-action (candidate)
283  "Default action to jump to a Yahoo suggested candidate."
284  (helm-browse-url (format helm-yahoo-suggest-search-url
285                           (url-hexify-string candidate))))
286
287(defvar helm-source-yahoo-suggest
288  `((name . "Yahoo Suggest")
289    (candidates . helm-yahoo-suggest-set-candidates)
290    (action . (("Yahoo Search" . helm-yahoo-suggest-action)))
291    (volatile)
292    (keymap . ,helm-map)
293    (requires-pattern . 3)))
294
295;;; Wikipedia suggestions
296;;
297;;
298(declare-function json-read-from-string "json" (string))
299(defun helm-wikipedia-suggest-fetch ()
300  "Fetch Wikipedia suggestions and return them as a list."
301  (require 'json)
302  (let ((request (concat helm-wikipedia-suggest-url
303                         (url-hexify-string helm-pattern))))
304    (if helm-google-suggest-use-curl-p
305        (with-temp-buffer
306          (call-process "curl" nil t nil request)
307          (helm-wikipedia--parse-buffer))
308      (with-current-buffer
309          (url-retrieve-synchronously request)
310        (helm-wikipedia--parse-buffer)))))
311
312(defun helm-wikipedia--parse-buffer ()
313  (goto-char (point-min))
314  (when (re-search-forward "^\\[.+\\[\\(.*\\)\\]\\]" nil t)
315    (cl-loop for i across (aref (json-read-from-string (match-string 0)) 1)
316          collect i into result
317          finally return (or result
318                             (append
319                              result
320                              (list (cons (format "Search for '%s' on wikipedia"
321                                                  helm-pattern)
322                                          helm-pattern)))))))
323
324(defvar helm-wikipedia--summary-cache (make-hash-table :test 'equal))
325(defun helm-wikipedia-persistent-action (candidate)
326  (unless (string= (format "Search for '%s' on wikipedia"
327                           helm-pattern)
328                   (helm-get-selection nil t))
329    (message "Fetching summary from Wikipedia...")
330    (let ((buf (get-buffer-create "*helm wikipedia summary*"))
331          result mess)
332      (while (progn
333               (setq result (or (gethash candidate helm-wikipedia--summary-cache)
334                                (puthash candidate
335                                         (prog1
336                                             (helm-wikipedia-fetch-summary candidate)
337                                           (setq mess "Done"))
338                                         helm-wikipedia--summary-cache)))
339               (when (and result
340                          (listp result))
341                 (setq candidate (cdr result))
342                 (message "Redirected to %s" candidate)
343                 t)))
344      (if (not result)
345          (message "Error when getting summary.")
346        (with-current-buffer buf
347          (erase-buffer)
348          (setq cursor-type nil)
349          (insert result)
350          (fill-region (point-min) (point-max))
351          (goto-char (point-min)))
352        (display-buffer buf)
353        (message mess)))))
354
355
356(defun helm-wikipedia-fetch-summary (input)
357  (let* ((request (concat helm-wikipedia-summary-url (url-hexify-string input))))
358    (if helm-google-suggest-use-curl-p
359        (with-temp-buffer
360          (call-process "curl" nil t nil request)
361          (helm-wikipedia--parse-summary))
362      (with-current-buffer
363          (url-retrieve-synchronously request)
364        (helm-wikipedia--parse-summary)))))
365
366
367(defun helm-wikipedia--parse-summary ()
368  (goto-char (point-min))
369  (when (search-forward "{" nil t)
370    (let ((result (cdr (assoc '*
371                              (assoc 'text
372                                     (assoc 'parse
373                                            (json-read-from-string
374                                             (buffer-substring-no-properties
375                                              (1- (point)) (point-max)))))))))
376      (when result
377        (if (string-match "<span class=\"redirectText\"><a href=[^>]+>\\([^<]+\\)" result)
378            (cons 'redirect (match-string 1 result))
379
380          ;; find the beginning of the summary text in the result
381
382          ;; check if there is a table before the summary and skip that
383          (when (or (string-match "</table>\\(\n<div.*?</div>\\)?\n<p>" result)
384                    ;; otherwise just find the first paragraph
385                    (string-match "<p>" result))
386            ;; remove cruft and do a simple formatting 
387            (replace-regexp-in-string
388             "Cite error: .*" ""
389             (replace-regexp-in-string
390              "&#160;" ""
391              (replace-regexp-in-string
392               "\\[[^\]]+\\]" ""
393               (replace-regexp-in-string
394                "<[^>]*>" ""
395                (replace-regexp-in-string
396                 "</p>\n<p>" "\n\n"
397                 (substring result (match-end 0)))))))))))))
398
399
400(defvar helm-source-wikipedia-suggest
401  `((name . "Wikipedia Suggest")
402    (candidates . helm-wikipedia-suggest-fetch)
403    (action . (("Wikipedia" . (lambda (candidate)
404                                (helm-search-suggest-perform-additional-action
405                                 helm-search-suggest-action-wikipedia-url
406                                 candidate)))))
407    (persistent-action . helm-wikipedia-persistent-action)
408    (volatile)
409    (keymap . ,helm-map)
410    (follow . 1)
411    (follow-delay . ,helm-wikipedia-follow-delay)
412    (requires-pattern . 3)))
413
414
415;;; Web browser functions.
416;;
417;;
418;; If default setting of `w3m-command' is not
419;; what you want and you modify it, you will have to reeval
420;; also `helm-browse-url-default-browser-alist'.
421
422(defvar helm-browse-url-chromium-program "chromium-browser")
423(defvar helm-browse-url-uzbl-program "uzbl-browser")
424(defvar helm-browse-url-conkeror-program "conkeror")
425(defvar helm-browse-url-default-browser-alist
426  `((,(or (and (boundp 'w3m-command) w3m-command)
427          "/usr/bin/w3m") . w3m-browse-url)
428    (,browse-url-firefox-program . browse-url-firefox)
429    (,helm-browse-url-chromium-program . helm-browse-url-chromium)
430    (,helm-browse-url-conkeror-program . helm-browse-url-conkeror)
431    (,helm-browse-url-uzbl-program . helm-browse-url-uzbl)
432    (,browse-url-kde-program . browse-url-kde)
433    (,browse-url-gnome-moz-program . browse-url-gnome-moz)
434    (,browse-url-mozilla-program . browse-url-mozilla)
435    (,browse-url-galeon-program . browse-url-galeon)
436    (,browse-url-netscape-program . browse-url-netscape)
437    (,browse-url-mosaic-program . browse-url-mosaic)
438    (,browse-url-xterm-program . browse-url-text-xterm)
439    ("emacs" . eww-browse-url))
440  "*Alist of \(executable . function\) to try to find a suitable url browser.")
441
442(cl-defun helm-generic-browser (url cmd-name &rest args)
443  "Browse URL with NAME browser."
444  (let ((proc (concat cmd-name " " url)))
445    (message "Starting %s..." cmd-name)
446    (apply 'start-process proc nil cmd-name
447           (append args (list url)))
448    (set-process-sentinel
449     (get-process proc)
450     #'(lambda (process event)
451         (when (string= event "finished\n")
452           (message "%s process %s" process event))))))
453
454(defun helm-browse-url-chromium (url &optional _ignore)
455  "Browse URL with google chrome browser."
456  (interactive "sURL: ")
457  (helm-generic-browser
458   url helm-browse-url-chromium-program))
459
460(defun helm-browse-url-uzbl (url &optional _ignore)
461  "Browse URL with uzbl browser."
462  (interactive "sURL: ")
463  (helm-generic-browser url helm-browse-url-uzbl-program "-u"))
464
465(defun helm-browse-url-conkeror (url &optional _ignore)
466  "Browse URL with conkeror browser."
467  (interactive "sURL: ")
468  (helm-generic-browser url helm-browse-url-conkeror-program))
469
470(defun helm-browse-url-default-browser (url &rest args)
471  "Find the first available browser and ask it to load URL."
472  (let ((default-browser-fn
473         (cl-loop for (exe . fn) in helm-browse-url-default-browser-alist
474               thereis (and exe (executable-find exe) (fboundp fn) fn))))
475    (if default-browser-fn
476        (apply default-browser-fn url args)
477      (error "No usable browser found"))))
478
479(defun helm-browse-url (url &rest args)
480  "Default command to browse URL."
481  (if browse-url-browser-function
482      (browse-url url args)
483    (helm-browse-url-default-browser url args)))
484
485
486;;; Surfraw
487;;
488;; Need external program surfraw.
489;; <http://surfraw.alioth.debian.org/>
490
491;; Internal
492(defvar helm-surfraw-engines-history nil)
493(defvar helm-surfraw-input-history nil)
494(defvar helm-surfraw--elvi-cache nil)
495
496(defun helm-build-elvi-list ()
497  "Return list of all engines and descriptions handled by surfraw."
498  (or helm-surfraw--elvi-cache
499      (setq helm-surfraw--elvi-cache
500            (cdr (with-temp-buffer
501                   (call-process "surfraw" nil t nil "-elvi")
502                   (split-string (buffer-string) "\n"))))))
503
504;;;###autoload
505(defun helm-surfraw (pattern engine)
506  "Preconfigured `helm' to search PATTERN with search ENGINE."
507  (interactive (list (read-string "SearchFor: "
508                                  nil 'helm-surfraw-input-history
509                                  (thing-at-point 'symbol))
510                     (helm-comp-read
511                      "Engine: "
512                      (helm-build-elvi-list)
513                      :must-match t
514                      :name "Surfraw Search Engines"
515                      :del-input nil
516                      :history helm-surfraw-engines-history)))
517  (let* ((engine-nodesc (car (split-string engine)))
518         (url (if (string= engine-nodesc "duckduckgo")
519                  ;; "sr duckduckgo -p foo" is broken, workaround.
520                  (format helm-surfraw-duckduckgo-url
521                          (url-hexify-string pattern))
522                (with-temp-buffer
523                  (apply 'call-process "surfraw" nil t nil
524                         (append  (list engine-nodesc "-p") (split-string pattern)))
525                  (replace-regexp-in-string
526                   "\n" "" (buffer-string)))))
527         (browse-url-browser-function (or helm-surfraw-default-browser-function
528                                          browse-url-browser-function)))
529    (if (string= engine-nodesc "W")
530        (helm-browse-url helm-home-url)
531      (helm-browse-url url)
532      (setq helm-surfraw-engines-history
533            (cons engine (delete engine helm-surfraw-engines-history))))))
534
535;;;###autoload
536(defun helm-google-suggest ()
537  "Preconfigured `helm' for google search with google suggest."
538  (interactive)
539  (helm-other-buffer 'helm-source-google-suggest "*helm google*"))
540
541;;;###autoload
542(defun helm-yahoo-suggest ()
543  "Preconfigured `helm' for Yahoo searching with Yahoo suggest."
544  (interactive)
545  (helm-other-buffer 'helm-source-yahoo-suggest "*helm yahoo*"))
546
547;;;###autoload
548(defun helm-wikipedia-suggest ()
549  "Preconfigured `helm' for Wikipedia lookup with Wikipedia suggest."
550  (interactive)
551  (helm :sources 'helm-source-wikipedia-suggest
552        :buffer "*helm wikipedia*"))
553
554
555(provide 'helm-net)
556
557;; Local Variables:
558;; byte-compile-warnings: (not cl-functions obsolete)
559;; coding: utf-8
560;; indent-tabs-mode: nil
561;; End:
562
563;;; helm-net.el ends here