66180d90fc02c11c7cbd54c0fcb507b63fdba85f
[gnus] / lisp / eww.el
1 ;;; eww.el --- Emacs Web Wowser
2
3 ;; Copyright (C) 2013 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: html
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (eval-when-compile (require 'cl))
28 (require 'format-spec)
29 (require 'shr)
30 (require 'url)
31 (require 'mm-url)
32
33 (defgroup eww nil
34   "Emacs Web Wowser"
35   :version "24.4"
36   :group 'hypermedia
37   :prefix "eww-")
38
39 (defcustom eww-header-line-format "%t: %u"
40   "Header line format.
41 - %t is replaced by the title.
42 - %u is replaced by the URL."
43   :group 'eww
44   :type 'string)
45
46 (defface eww-button
47   '((((type x w32 ns) (class color))    ; Like default mode line
48      :box (:line-width 2 :style released-button)
49      :background "lightgrey" :foreground "black"))
50   "Face for eww buffer buttons."
51   :version "24.4"
52   :group 'eww)
53
54 (defvar eww-current-url nil)
55 (defvar eww-current-title ""
56   "Title of current page.")
57 (defvar eww-history nil)
58
59 (defvar eww-next-url nil)
60 (defvar eww-previous-url nil)
61 (defvar eww-up-url nil)
62 (defvar eww-top-url nil)
63
64 ;;;###autoload
65 (defun eww (url)
66   "Fetch URL and render the page."
67   (interactive "sUrl: ")
68   (unless (string-match-p "\\`[a-zA-Z][-a-zA-Z0-9+.]*://" url)
69     (setq url (concat "http://" url)))
70   (url-retrieve url 'eww-render (list url)))
71
72 ;;;###autoload
73 (defun eww-open-file (file)
74   "Render a file using EWW."
75   (interactive "fFile: ")
76   (eww (concat "file://" (expand-file-name file))))
77
78 (defun eww-render (status url &optional point)
79   (let ((redirect (plist-get status :redirect)))
80     (when redirect
81       (setq url redirect)))
82   (set (make-local-variable 'eww-next-url) nil)
83   (set (make-local-variable 'eww-previous-url) nil)
84   (set (make-local-variable 'eww-up-url) nil)
85   (set (make-local-variable 'eww-top-url) nil)
86   (let* ((headers (eww-parse-headers))
87          (shr-target-id
88           (and (string-match "#\\(.*\\)" url)
89                (match-string 1 url)))
90          (content-type
91           (mail-header-parse-content-type
92            (or (cdr (assoc "content-type" headers))
93                "text/plain")))
94          (charset (intern
95                    (downcase
96                     (or (cdr (assq 'charset (cdr content-type)))
97                         (eww-detect-charset (equal (car content-type)
98                                                    "text/html"))
99                         "utf8"))))
100          (data-buffer (current-buffer)))
101     (unwind-protect
102         (progn
103           (cond
104            ((equal (car content-type) "text/html")
105             (eww-display-html charset url))
106            ((string-match "^image/" (car content-type))
107             (eww-display-image))
108            (t
109             (eww-display-raw charset)))
110           (cond
111            (point
112             (goto-char point))
113            (shr-target-id
114             (let ((point (next-single-property-change
115                           (point-min) 'shr-target-id)))
116               (when point
117                 (goto-char (1+ point)))))))
118       (kill-buffer data-buffer))))
119
120 (defun eww-parse-headers ()
121   (let ((headers nil))
122     (goto-char (point-min))
123     (while (and (not (eobp))
124                 (not (eolp)))
125       (when (looking-at "\\([^:]+\\): *\\(.*\\)")
126         (push (cons (downcase (match-string 1))
127                     (match-string 2))
128               headers))
129       (forward-line 1))
130     (unless (eobp)
131       (forward-line 1))
132     headers))
133
134 (defun eww-detect-charset (html-p)
135   (let ((case-fold-search t)
136         (pt (point)))
137     (or (and html-p
138              (re-search-forward
139               "<meta[\t\n\r ]+[^>]*charset=\"?\\([^\t\n\r \"/>]+\\)" nil t)
140              (goto-char pt)
141              (match-string 1))
142         (and (looking-at
143               "[\t\n\r ]*<\\?xml[\t\n\r ]+[^>]*encoding=\"\\([^\"]+\\)")
144              (match-string 1)))))
145
146 (defun eww-display-html (charset url)
147   (unless (eq charset 'utf8)
148     (decode-coding-region (point) (point-max) charset))
149   (let ((document
150          (list
151           'base (list (cons 'href url))
152           (libxml-parse-html-region (point) (point-max)))))
153     (eww-setup-buffer)
154     (setq eww-current-url url)
155     (eww-update-header-line-format)
156     (let ((inhibit-read-only t)
157           (shr-width nil)
158           (shr-external-rendering-functions
159            '((title . eww-tag-title)
160              (form . eww-tag-form)
161              (input . eww-tag-input)
162              (textarea . eww-tag-textarea)
163              (body . eww-tag-body)
164              (select . eww-tag-select)
165              (link . eww-tag-link)
166              (a . eww-tag-a))))
167       (shr-insert-document document)
168       (eww-convert-widgets))
169     (goto-char (point-min))))
170
171 (defun eww-handle-link (cont)
172   (let* ((rel (assq :rel cont))
173         (href (assq :href cont))
174         (where (assoc (cdr rel)
175                       '(("next" . eww-next-url)
176                         ("previous" . eww-previous-url)
177                         ("start" . eww-top-url)
178                         ("up" . eww-up-url)))))
179     (and href
180          where
181          (set (cdr where) (cdr href)))))
182
183 (defun eww-tag-link (cont)
184   (eww-handle-link cont)
185   (shr-generic cont))
186
187 (defun eww-tag-a (cont)
188   (eww-handle-link cont)
189   (shr-tag-a cont))
190
191 (defun eww-update-header-line-format ()
192   (if eww-header-line-format
193       (setq header-line-format (format-spec eww-header-line-format
194                                             `((?u . ,eww-current-url)
195                                               (?t . ,eww-current-title))))
196     (setq header-line-format nil)))
197
198 (defun eww-tag-title (cont)
199   (setq eww-current-title "")
200   (dolist (sub cont)
201     (when (eq (car sub) 'text)
202       (setq eww-current-title (concat eww-current-title (cdr sub)))))
203   (eww-update-header-line-format))
204
205 (defun eww-tag-body (cont)
206   (let* ((start (point))
207          (fgcolor (cdr (or (assq :fgcolor cont)
208                            (assq :text cont))))
209          (bgcolor (cdr (assq :bgcolor cont)))
210          (shr-stylesheet (list (cons 'color fgcolor)
211                                (cons 'background-color bgcolor))))
212     (shr-generic cont)
213     (eww-colorize-region start (point) fgcolor bgcolor)))
214
215 (defun eww-colorize-region (start end fg &optional bg)
216   (when (or fg bg)
217     (let ((new-colors (shr-color-check fg bg)))
218       (when new-colors
219         (when fg
220           (add-face-text-property start end
221                                   (list :foreground (cadr new-colors))))
222         (when bg
223           (add-face-text-property start end
224                                   (list :background (car new-colors))))))))
225
226 (defun eww-display-raw (charset)
227   (let ((data (buffer-substring (point) (point-max))))
228     (eww-setup-buffer)
229     (let ((inhibit-read-only t))
230       (insert data))
231     (goto-char (point-min))))
232
233 (defun eww-display-image ()
234   (let ((data (buffer-substring (point) (point-max))))
235     (eww-setup-buffer)
236     (let ((inhibit-read-only t))
237       (shr-put-image data nil))
238     (goto-char (point-min))))
239
240 (defun eww-setup-buffer ()
241   (pop-to-buffer (get-buffer-create "*eww*"))
242   (remove-overlays)
243   (setq widget-field-list nil)
244   (let ((inhibit-read-only t))
245     (erase-buffer))
246   (eww-mode))
247
248 (defvar eww-mode-map
249   (let ((map (make-sparse-keymap)))
250     (suppress-keymap map)
251     (define-key map "q" 'eww-quit)
252     (define-key map "g" 'eww-reload)
253     (define-key map [tab] 'shr-next-link)
254     (define-key map [backtab] 'shr-previous-link)
255     (define-key map [delete] 'scroll-down-command)
256     (define-key map "\177" 'scroll-down-command)
257     (define-key map " " 'scroll-up-command)
258     (define-key map "l" 'eww-back-url)
259     (define-key map "n" 'eww-next-url)
260     (define-key map "p" 'eww-previous-url)
261     (define-key map "u" 'eww-up-url)
262     (define-key map "t" 'eww-top-url)
263     map))
264
265 (define-derived-mode eww-mode nil "eww"
266   "Mode for browsing the web.
267
268 \\{eww-mode-map}"
269   (set (make-local-variable 'eww-current-url) 'author)
270   (set (make-local-variable 'browse-url-browser-function) 'eww-browse-url))
271
272 (defun eww-browse-url (url &optional new-window)
273   (push (list eww-current-url (point))
274         eww-history)
275   (eww url))
276
277 (defun eww-quit ()
278   "Exit the Emacs Web Wowser."
279   (interactive)
280   (setq eww-history nil)
281   (kill-buffer (current-buffer)))
282
283 (defun eww-back-url ()
284   "Go to the previously displayed page."
285   (interactive)
286   (when (zerop (length eww-history))
287     (error "No previous page"))
288   (let ((prev (pop eww-history)))
289     (url-retrieve (car prev) 'eww-render (list (car prev) (cadr prev)))))
290
291 (defun eww-next-url ()
292   "Go to the page marked `next'.
293 A page is marked `next' if rel=\"next\" appears in a <link>
294 or <a> tag."
295   (interactive)
296   (if eww-next-url
297       (eww-browse-url (shr-expand-url eww-next-url eww-current-url))
298     (error "No `next' on this page")))
299
300 (defun eww-previous-url ()
301   "Go to the page marked `previous'.
302 A page is marked `previous' if rel=\"previous\" appears in a <link>
303 or <a> tag."
304   (interactive)
305   (if eww-previous-url
306       (eww-browse-url (shr-expand-url eww-previous-url eww-current-url))
307     (error "No `previous' on this page")))
308
309 (defun eww-up-url ()
310   "Go to the page marked `up'.
311 A page is marked `up' if rel=\"up\" appears in a <link>
312 or <a> tag."
313   (interactive)
314   (if eww-up-url
315       (eww-browse-url (shr-expand-url eww-up-url eww-current-url))
316     (error "No `up' on this page")))
317
318 (defun eww-top-url ()
319   "Go to the page marked `top'.
320 A page is marked `top' if rel=\"start\" appears in a <link>
321 or <a> tag."
322   (interactive)
323   (if eww-top-url
324       (eww-browse-url (shr-expand-url eww-top-url eww-current-url))
325     (error "No `top' on this page")))
326
327 (defun eww-reload ()
328   "Reload the current page."
329   (interactive)
330   (url-retrieve eww-current-url 'eww-render
331                 (list eww-current-url (point))))
332
333 ;; Form support.
334
335 (defvar eww-form nil)
336
337 (defun eww-tag-form (cont)
338   (let ((eww-form
339          (list (assq :method cont)
340                (assq :action cont)))
341         (start (point)))
342     (shr-ensure-paragraph)
343     (shr-generic cont)
344     (unless (bolp)
345       (insert "\n"))
346     (insert "\n")
347     (when (> (point) start)
348       (put-text-property start (1+ start)
349                          'eww-form eww-form))))
350
351 (defun eww-tag-input (cont)
352   (let* ((start (point))
353          (type (downcase (or (cdr (assq :type cont))
354                              "text")))
355          (value (cdr (assq :value cont)))
356          (widget
357           (cond
358            ((or (equal type "submit")
359                 (equal type "image"))
360             (list 'push-button
361                   :notify 'eww-submit
362                   :name (cdr (assq :name cont))
363                   :value (if (zerop (length value))
364                              "Submit"
365                            value)
366                   :eww-form eww-form
367                   (or (if (zerop (length value))
368                           "Submit"
369                         value))))
370            ((or (equal type "radio")
371                 (equal type "checkbox"))
372             (list 'checkbox
373                   :notify 'eww-click-radio
374                   :name (cdr (assq :name cont))
375                   :checkbox-value value
376                   :checkbox-type type
377                   :eww-form eww-form
378                   (cdr (assq :checked cont))))
379            ((equal type "hidden")
380             (list 'hidden
381                   :name (cdr (assq :name cont))
382                   :value value))
383            (t
384             (list 'editable-field
385                   :size (string-to-number
386                          (or (cdr (assq :size cont))
387                              "40"))
388                   :value (or value "")
389                   :secret (and (equal type "password") ?*)
390                   :action 'eww-submit
391                   :name (cdr (assq :name cont))
392                   :eww-form eww-form)))))
393     (nconc eww-form (list widget))
394     (unless (eq (car widget) 'hidden)
395       (apply 'widget-create widget)
396       (put-text-property start (point) 'eww-widget widget)
397       (insert " "))))
398
399 (defun eww-tag-textarea (cont)
400   (let* ((start (point))
401          (widget
402           (list 'text
403                 :size (string-to-number
404                        (or (cdr (assq :cols cont))
405                            "40"))
406                 :value (or (cdr (assq 'text cont)) "")
407                 :action 'eww-submit
408                 :name (cdr (assq :name cont))
409                 :eww-form eww-form)))
410     (nconc eww-form (list widget))
411     (apply 'widget-create widget)
412     (put-text-property start (point) 'eww-widget widget)))
413
414 (defun eww-tag-select (cont)
415   (shr-ensure-paragraph)
416   (let ((menu (list 'menu-choice
417                     :name (cdr (assq :name cont))
418                     :eww-form eww-form))
419         (options nil)
420         (start (point)))
421     (dolist (elem cont)
422       (when (eq (car elem) 'option)
423         (when (cdr (assq :selected (cdr elem)))
424           (nconc menu (list :value
425                             (cdr (assq :value (cdr elem))))))
426         (push (list 'item
427                     :value (cdr (assq :value (cdr elem)))
428                     :tag (cdr (assq 'text (cdr elem))))
429               options)))
430     (when options
431       ;; If we have no selected values, default to the first value.
432       (unless (plist-get (cdr menu) :value)
433         (nconc menu (list :value (nth 2 (car options)))))
434       (nconc menu options)
435       (apply 'widget-create menu)
436       (put-text-property start (point) 'eww-widget menu)
437       (shr-ensure-paragraph))))
438
439 (defun eww-click-radio (widget &rest ignore)
440   (let ((form (plist-get (cdr widget) :eww-form))
441         (name (plist-get (cdr widget) :name)))
442     (when (equal (plist-get (cdr widget) :type) "radio")
443       (if (widget-value widget)
444           ;; Switch all the other radio buttons off.
445           (dolist (overlay (overlays-in (point-min) (point-max)))
446             (let ((field (plist-get (overlay-properties overlay) 'button)))
447               (when (and (eq (plist-get (cdr field) :eww-form) form)
448                          (equal name (plist-get (cdr field) :name)))
449                 (unless (eq field widget)
450                   (widget-value-set field nil)))))
451         (widget-value-set widget t)))
452     (eww-fix-widget-keymap)))
453
454 (defun eww-submit (widget &rest ignore)
455   (let ((form (plist-get (cdr widget) :eww-form))
456         values)
457     (dolist (overlay (sort (overlays-in (point-min) (point-max))
458                            (lambda (o1 o2)
459                              (< (overlay-start o1) (overlay-start o2)))))
460       (let ((field (or (plist-get (overlay-properties overlay) 'field)
461                        (plist-get (overlay-properties overlay) 'button))))
462         (when (eq (plist-get (cdr field) :eww-form) form)
463           (let ((name (plist-get (cdr field) :name)))
464             (when name
465               (cond
466                ((eq (car field) 'checkbox)
467                 (when (widget-value field)
468                   (push (cons name (plist-get (cdr field) :checkbox-value))
469                         values)))
470                ((eq (car field) 'push-button)
471                 ;; We want the values from buttons if we hit a button,
472                 ;; if it's the first button in the DOM after the field
473                 ;; hit ENTER on.
474                 (when (and (eq (car widget) 'push-button)
475                            (eq widget field))
476                   (push (cons name (widget-value field))
477                         values)))
478                (t
479                 (push (cons name (widget-value field))
480                       values))))))))
481     (dolist (elem form)
482       (when (and (consp elem)
483                  (eq (car elem) 'hidden))
484         (push (cons (plist-get (cdr elem) :name)
485                     (plist-get (cdr elem) :value))
486               values)))
487     ;; If we hit ENTER in a non-button field, include the value of the
488     ;; first submit button after it.
489     (unless (eq (car widget) 'push-button)
490       (let ((rest form)
491             (name (plist-get (cdr widget) :name)))
492         (when rest
493           (while (and rest
494                       (or (not (consp (car rest)))
495                           (not (equal name (plist-get (cdar rest) :name)))))
496             (pop rest)))
497         (while rest
498           (let ((elem (pop rest)))
499             (when (and (consp (car rest))
500                        (eq (car elem) 'push-button))
501               (push (cons (plist-get (cdr elem) :name)
502                           (plist-get (cdr elem) :value))
503                     values)
504               (setq rest nil))))))
505     (if (and (stringp (cdr (assq :method form)))
506              (equal (downcase (cdr (assq :method form))) "post"))
507         (let ((url-request-method "POST")
508               (url-request-extra-headers
509                '(("Content-Type" . "application/x-www-form-urlencoded")))
510               (url-request-data (mm-url-encode-www-form-urlencoded values)))
511           (eww-browse-url (shr-expand-url (cdr (assq :action form))
512                                           eww-current-url)))
513       (eww-browse-url
514        (concat
515         (if (cdr (assq :action form))
516             (shr-expand-url (cdr (assq :action form))
517                             eww-current-url)
518           eww-current-url)
519         "?"
520         (mm-url-encode-www-form-urlencoded values))))))
521
522 (defun eww-convert-widgets ()
523   (let ((start (point-min))
524         widget)
525     ;; Some widgets come from different buffers (rendered for tables),
526     ;; so we need to nix out the list of widgets and recreate them.
527     (setq widget-field-list nil
528           widget-field-new nil)
529     (while (setq start (if (get-text-property start 'eww-widget)
530                            start
531                          (next-single-property-change start 'eww-widget)))
532       (setq widget (get-text-property start 'eww-widget))
533       (goto-char start)
534       (let ((end (next-single-property-change start 'eww-widget)))
535         (dolist (overlay (overlays-in start end))
536           (when (or (plist-get (overlay-properties overlay) 'button)
537                     (plist-get (overlay-properties overlay) 'field))
538             (delete-overlay overlay)))
539         (delete-region start end))
540       (when (and widget
541                  (not (eq (car widget) 'hidden)))
542         (apply 'widget-create widget)
543         (put-text-property start (point) 'help-echo
544                            (if (memq (car widget) '(text editable-field))
545                                "Input field"
546                              "Button"))
547         (when (eq (car widget) 'push-button)
548           (add-face-text-property start (point) 'eww-button t))))
549     (widget-setup)
550     (eww-fix-widget-keymap)))
551
552 (defun eww-fix-widget-keymap ()
553   (dolist (overlay (overlays-in (point-min) (point-max)))
554     (when (plist-get (overlay-properties overlay) 'button)
555       (overlay-put overlay 'local-map widget-keymap))))
556
557 (provide 'eww)
558
559 ;;; eww.el ends here