cca59f9c226f5200a914fe4dc1ecbfca5eb233ea
[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 'shr)
29 (require 'url)
30 (require 'mm-url)
31
32 (defgroup eww nil
33   "Emacs Web Wowser"
34   :version "24.4"
35   :group 'hypermedia
36   :prefix "eww-")
37
38 (defcustom eww-header-line-format "%t: %u"
39   "Header line format.
40 - %t is replaced by the title.
41 - %u is replaced by the URL."
42   :group 'eww
43   :type 'string)
44
45 (defvar eww-current-url nil)
46 (defvar eww-current-title ""
47   "Title of current page.")
48 (defvar eww-history nil)
49
50 ;;;###autoload
51 (defun eww (url)
52   "Fetch URL and render the page."
53   (interactive "sUrl: ")
54   (unless (string-match-p "\\`[a-zA-Z][-a-zA-Z0-9+.]*://" url)
55     (setq url (concat "http://" url)))
56   (url-retrieve url 'eww-render (list url)))
57
58 (defun eww-detect-charset (html-p)
59   (let ((case-fold-search t)
60         (pt (point)))
61     (or (and html-p
62              (re-search-forward
63               "<meta[\t\n\r ]+[^>]*charset=\\([^\t\n\r \"/>]+\\)" nil t)
64              (goto-char pt)
65              (match-string 1))
66         (and (looking-at
67               "[\t\n\r ]*<\\?xml[\t\n\r ]+[^>]*encoding=\"\\([^\"]+\\)")
68              (match-string 1)))))
69
70 (defun eww-render (status url &optional point)
71   (let ((redirect (plist-get status :redirect)))
72     (when redirect
73       (setq url redirect)))
74   (let* ((headers (eww-parse-headers))
75          (content-type
76           (mail-header-parse-content-type
77            (or (cdr (assoc "content-type" headers))
78                "text/plain")))
79          (charset (intern
80                    (downcase
81                     (or (cdr (assq 'charset (cdr content-type)))
82                         (eww-detect-charset (equal (car content-type)
83                                                    "text/html"))
84                         "utf8"))))
85          (data-buffer (current-buffer)))
86     (unwind-protect
87         (progn
88           (cond
89            ((equal (car content-type) "text/html")
90             (eww-display-html charset url))
91            ((string-match "^image/" (car content-type))
92             (eww-display-image))
93            (t
94             (eww-display-raw charset)))
95           (when point
96             (goto-char point)))
97       (kill-buffer data-buffer))))
98
99 (defun eww-parse-headers ()
100   (let ((headers nil))
101     (goto-char (point-min))
102     (while (and (not (eobp))
103                 (not (eolp)))
104       (when (looking-at "\\([^:]+\\): *\\(.*\\)")
105         (push (cons (downcase (match-string 1))
106                     (match-string 2))
107               headers))
108       (forward-line 1))
109     (unless (eobp)
110       (forward-line 1))
111     headers))
112
113 (defun eww-display-html (charset url)
114   (unless (eq charset 'utf8)
115     (decode-coding-region (point) (point-max) charset))
116   (let ((document
117          (list
118           'base (list (cons 'href url))
119           (libxml-parse-html-region (point) (point-max)))))
120     (eww-setup-buffer)
121     (setq eww-current-url url)
122     (eww-update-header-line-format)
123     (let ((inhibit-read-only t)
124           (shr-external-rendering-functions
125            '((title . eww-tag-title)
126              (form . eww-tag-form)
127              (input . eww-tag-input)
128              (textarea . eww-tag-textarea)
129              (body . eww-tag-body)
130              (select . eww-tag-select))))
131       (shr-insert-document document)
132       (eww-convert-widgets))
133     (goto-char (point-min))))
134
135 (defun eww-update-header-line-format ()
136   (if eww-header-line-format
137       (setq header-line-format (format-spec eww-header-line-format
138                                             `((?u . ,eww-current-url)
139                                               (?t . ,eww-current-title))))
140     (setq header-line-format nil)))
141
142 (defun eww-tag-title (cont)
143   (setq eww-current-title "")
144   (dolist (sub cont)
145     (when (eq (car sub) 'text)
146       (setq eww-current-title (concat eww-current-title (cdr sub)))))
147   (eww-update-header-line-format))
148
149 (defun eww-tag-body (cont)
150   (let* ((start (point))
151          (fgcolor (cdr (or (assq :fgcolor cont)
152                            (assq :text cont))))
153          (bgcolor (cdr (assq :bgcolor cont)))
154          (shr-stylesheet (list (cons 'color fgcolor)
155                                (cons 'background-color bgcolor))))
156     (shr-generic cont)
157     (eww-colorize-region start (point) fgcolor bgcolor)))
158
159 (defun eww-colorize-region (start end fg &optional bg)
160   (when (or fg bg)
161     (let ((new-colors (shr-color-check fg bg)))
162       (when new-colors
163         (when fg
164           (eww-put-color start end :foreground (cadr new-colors)))
165         (when bg
166           (eww-put-color start end :background (car new-colors)))))))
167
168 (defun eww-put-color (start end type color)
169   (shr-put-color-1 start end type color))
170
171 (defun eww-display-raw (charset)
172   (let ((data (buffer-substring (point) (point-max))))
173     (eww-setup-buffer)
174     (let ((inhibit-read-only t))
175       (insert data))
176     (goto-char (point-min))))
177
178 (defun eww-display-image ()
179   (let ((data (buffer-substring (point) (point-max))))
180     (eww-setup-buffer)
181     (let ((inhibit-read-only t))
182       (shr-put-image data nil))
183     (goto-char (point-min))))
184
185 (defun eww-setup-buffer ()
186   (pop-to-buffer (get-buffer-create "*eww*"))
187   (remove-overlays)
188   (setq widget-field-list nil)
189   (let ((inhibit-read-only t))
190     (erase-buffer))
191   (eww-mode))
192
193 (defvar eww-mode-map
194   (let ((map (make-sparse-keymap)))
195     (suppress-keymap map)
196     (define-key map "q" 'eww-quit)
197     (define-key map "g" 'eww-reload)
198     (define-key map [tab] 'widget-forward)
199     (define-key map [backtab] 'widget-backward)
200     (define-key map [delete] 'scroll-down-command)
201     (define-key map "\177" 'scroll-down-command)
202     (define-key map " " 'scroll-up-command)
203     (define-key map "p" 'eww-previous-url)
204     ;;(define-key map "n" 'eww-next-url)
205     map))
206
207 (define-derived-mode eww-mode nil "eww"
208   "Mode for browsing the web.
209
210 \\{eww-mode-map}"
211   (set (make-local-variable 'eww-current-url) 'author)
212   (set (make-local-variable 'browse-url-browser-function) 'eww-browse-url))
213
214 (defun eww-browse-url (url &optional new-window)
215   (let ((url-request-extra-headers
216          (append '(("User-Agent" . "eww/1.0"))
217                  url-request-extra-headers)))
218     (push (list eww-current-url (point))
219           eww-history)
220     (eww url)))
221
222 (defun eww-quit ()
223   "Exit the Emacs Web Wowser."
224   (interactive)
225   (setq eww-history nil)
226   (kill-buffer (current-buffer)))
227
228 (defun eww-previous-url ()
229   "Go to the previously displayed page."
230   (interactive)
231   (when (zerop (length eww-history))
232     (error "No previous page"))
233   (let ((prev (pop eww-history)))
234     (url-retrieve (car prev) 'eww-render (list (car prev) (cadr prev)))))
235
236 (defun eww-reload ()
237   "Reload the current page."
238   (interactive)
239   (url-retrieve eww-current-url 'eww-render
240                 (list eww-current-url (point))))
241
242 ;; Form support.
243
244 (defvar eww-form nil)
245
246 (defun eww-tag-form (cont)
247   (let ((eww-form
248          (list (assq :method cont)
249                (assq :action cont)))
250         (start (point)))
251     (shr-ensure-paragraph)
252     (shr-generic cont)
253     (unless (bolp)
254       (insert "\n"))
255     (insert "\n")
256     (when (> (point) start)
257       (put-text-property start (1+ start)
258                          'eww-form eww-form))))
259
260 (defun eww-tag-input (cont)
261   (let* ((start (point))
262          (type (downcase (or (cdr (assq :type cont))
263                              "text")))
264          (widget
265           (cond
266            ((equal type "submit")
267             (list 'push-button
268                   :notify 'eww-submit
269                   :name (cdr (assq :name cont))
270                   :value (cdr (assq :value cont))
271                   :eww-form eww-form
272                   (or (cdr (assq :value cont)) "Submit")))
273            ((or (equal type "radio")
274                 (equal type "checkbox"))
275             (list 'checkbox
276                   :notify 'eww-click-radio
277                   :name (cdr (assq :name cont))
278                   :checkbox-value (cdr (assq :value cont))
279                   :checkbox-type type
280                   :eww-form eww-form
281                   (cdr (assq :checked cont))))
282            ((equal type "hidden")
283             (list 'hidden
284                   :name (cdr (assq :name cont))
285                   :value (cdr (assq :value cont))))
286            (t
287             (list 'editable-field
288                   :size (string-to-number
289                          (or (cdr (assq :size cont))
290                              "40"))
291                   :value (or (cdr (assq :value cont)) "")
292                   :secret (and (equal type "password") ?*)
293                   :action 'eww-submit
294                   :name (cdr (assq :name cont))
295                   :eww-form eww-form)))))
296     (nconc eww-form (list widget))
297     (unless (eq (car widget) 'hidden)
298       (apply 'widget-create widget)
299       (put-text-property start (point) 'eww-widget widget))))
300
301 (defun eww-tag-textarea (cont)
302   (let* ((start (point))
303          (widget
304           (list 'text
305                 :size (string-to-number
306                        (or (cdr (assq :cols cont))
307                            "40"))
308                 :value (or (cdr (assq 'text cont)) "")
309                 :action 'eww-submit
310                 :name (cdr (assq :name cont))
311                 :eww-form eww-form)))
312     (nconc eww-form (list widget))
313     (apply 'widget-create widget)
314     (put-text-property start (point) 'eww-widget widget)))
315
316 (defun eww-tag-select (cont)
317   (shr-ensure-paragraph)
318   (let ((menu (list 'menu-choice
319                     :name (cdr (assq :name cont))
320                     :eww-form eww-form))
321         (options nil)
322         (start (point)))
323     (dolist (elem cont)
324       (when (eq (car elem) 'option)
325         (when (cdr (assq :selected (cdr elem)))
326           (nconc menu (list :value
327                             (cdr (assq :value (cdr elem))))))
328         (push (list 'item
329                     :value (cdr (assq :value (cdr elem)))
330                     :tag (cdr (assq 'text (cdr elem))))
331               options)))
332     ;; If we have no selected values, default to the first value.
333     (unless (plist-get (cdr menu) :value)
334       (nconc menu (list :value (nth 2 (car options)))))
335     (nconc menu options)
336     (apply 'widget-create menu)
337     (put-text-property start (point) 'eww-widget menu)
338     (shr-ensure-paragraph)))
339
340 (defun eww-click-radio (widget &rest ignore)
341   (let ((form (plist-get (cdr widget) :eww-form))
342         (name (plist-get (cdr widget) :name)))
343     (when (equal (plist-get (cdr widget) :type) "radio")
344       (if (widget-value widget)
345           ;; Switch all the other radio buttons off.
346           (dolist (overlay (overlays-in (point-min) (point-max)))
347             (let ((field (plist-get (overlay-properties overlay) 'button)))
348               (when (and (eq (plist-get (cdr field) :eww-form) form)
349                          (equal name (plist-get (cdr field) :name)))
350                 (unless (eq field widget)
351                   (widget-value-set field nil)))))
352         (widget-value-set widget t)))
353     (eww-fix-widget-keymap)))
354
355 (defun eww-submit (widget &rest ignore)
356   (let ((form (plist-get (cdr widget) :eww-form))
357         values)
358     (dolist (overlay (sort (overlays-in (point-min) (point-max))
359                            (lambda (o1 o2)
360                              (< (overlay-start o1) (overlay-start o2)))))
361       (let ((field (or (plist-get (overlay-properties overlay) 'field)
362                        (plist-get (overlay-properties overlay) 'button))))
363         (when (eq (plist-get (cdr field) :eww-form) form)
364           (let ((name (plist-get (cdr field) :name)))
365             (when name
366               (cond
367                ((eq (car field) 'checkbox)
368                 (when (widget-value field)
369                   (push (cons name (plist-get (cdr field) :checkbox-value))
370                         values)))
371                ((eq (car field) 'push-button)
372                 ;; We want the values from buttons if we hit a button,
373                 ;; if it's the first button in the DOM after the field
374                 ;; hit ENTER on.
375                 (when (and (eq (car widget) 'push-button)
376                            (eq widget field))
377                   (push (cons name (widget-value field))
378                         values)))
379                (t
380                 (push (cons name (widget-value field))
381                       values))))))))
382     (dolist (elem form)
383       (when (and (consp elem)
384                  (eq (car elem) 'hidden))
385         (push (cons (plist-get (cdr elem) :name)
386                     (plist-get (cdr elem) :value))
387               values)))
388     ;; If we hit ENTER in a non-button field, include the value of the
389     ;; first submit button after it.
390     (unless (eq (car widget) 'push-button)
391       (let ((rest form)
392             (name (plist-get (cdr widget) :name)))
393         (when rest
394           (while (and rest
395                       (or (not (consp (car rest)))
396                           (not (equal name (plist-get (cdar rest) :name)))))
397             (pop rest)))
398         (while rest
399           (let ((elem (pop rest)))
400             (when (and (consp (car rest))
401                        (eq (car elem) 'push-button))
402               (push (cons (plist-get (cdr elem) :name)
403                           (plist-get (cdr elem) :value))
404                     values)
405               (setq rest nil))))))
406     (if (and (stringp (cdr (assq :method form)))
407              (equal (downcase (cdr (assq :method form))) "post"))
408         (let ((url-request-method "POST")
409               (url-request-extra-headers
410                '(("Content-Type" . "application/x-www-form-urlencoded")))
411               (url-request-data (mm-url-encode-www-form-urlencoded values)))
412           (eww-browse-url (shr-expand-url (cdr (assq :action form))
413                                           eww-current-url)))
414       (eww-browse-url
415        (concat
416         (if (cdr (assq :action form))
417             (shr-expand-url (cdr (assq :action form))
418                             eww-current-url)
419           eww-current-url)
420         "?"
421         (mm-url-encode-www-form-urlencoded values))))))
422
423 (defun eww-convert-widgets ()
424   (let ((start (point-min))
425         widget)
426     ;; Some widgets come from different buffers (rendered for tables),
427     ;; so we need to nix out the list of widgets and recreate them.
428     (setq widget-field-list nil
429           widget-field-new nil)
430     (while (setq start (next-single-property-change start 'eww-widget))
431       (setq widget (get-text-property start 'eww-widget))
432       (goto-char start)
433       (let ((end (next-single-property-change start 'eww-widget)))
434         (dolist (overlay (overlays-in start end))
435           (when (or (plist-get (overlay-properties overlay) 'button)
436                     (plist-get (overlay-properties overlay) 'field))
437             (delete-overlay overlay)))
438         (delete-region start end))
439       (when (and widget
440                  (not (eq (car widget) 'hidden)))
441         (apply 'widget-create widget)))
442     (widget-setup)
443     (eww-fix-widget-keymap)))
444
445 (defun eww-fix-widget-keymap ()
446   (dolist (overlay (overlays-in (point-min) (point-max)))
447     (when (plist-get (overlay-properties overlay) 'button)
448       (overlay-put overlay 'local-map widget-keymap))))
449
450 (provide 'eww)
451
452 ;;; eww.el ends here