Make links not shadow local commands
[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   (when (and (equal major-mode 'eww-mode)
274              eww-current-url)
275     (push (list eww-current-url (point))
276           eww-history))
277   (eww url))
278
279 (defun eww-quit ()
280   "Exit the Emacs Web Wowser."
281   (interactive)
282   (setq eww-history nil)
283   (kill-buffer (current-buffer)))
284
285 (defun eww-back-url ()
286   "Go to the previously displayed page."
287   (interactive)
288   (when (zerop (length eww-history))
289     (error "No previous page"))
290   (let ((prev (pop eww-history)))
291     (url-retrieve (car prev) 'eww-render (list (car prev) (cadr prev)))))
292
293 (defun eww-next-url ()
294   "Go to the page marked `next'.
295 A page is marked `next' if rel=\"next\" appears in a <link>
296 or <a> tag."
297   (interactive)
298   (if eww-next-url
299       (eww-browse-url (shr-expand-url eww-next-url eww-current-url))
300     (error "No `next' on this page")))
301
302 (defun eww-previous-url ()
303   "Go to the page marked `previous'.
304 A page is marked `previous' if rel=\"previous\" appears in a <link>
305 or <a> tag."
306   (interactive)
307   (if eww-previous-url
308       (eww-browse-url (shr-expand-url eww-previous-url eww-current-url))
309     (error "No `previous' on this page")))
310
311 (defun eww-up-url ()
312   "Go to the page marked `up'.
313 A page is marked `up' if rel=\"up\" appears in a <link>
314 or <a> tag."
315   (interactive)
316   (if eww-up-url
317       (eww-browse-url (shr-expand-url eww-up-url eww-current-url))
318     (error "No `up' on this page")))
319
320 (defun eww-top-url ()
321   "Go to the page marked `top'.
322 A page is marked `top' if rel=\"start\" appears in a <link>
323 or <a> tag."
324   (interactive)
325   (if eww-top-url
326       (eww-browse-url (shr-expand-url eww-top-url eww-current-url))
327     (error "No `top' on this page")))
328
329 (defun eww-reload ()
330   "Reload the current page."
331   (interactive)
332   (url-retrieve eww-current-url 'eww-render
333                 (list eww-current-url (point))))
334
335 ;; Form support.
336
337 (defvar eww-form nil)
338
339 (defun eww-tag-form (cont)
340   (let ((eww-form
341          (list (assq :method cont)
342                (assq :action cont)))
343         (start (point)))
344     (shr-ensure-paragraph)
345     (shr-generic cont)
346     (unless (bolp)
347       (insert "\n"))
348     (insert "\n")
349     (when (> (point) start)
350       (put-text-property start (1+ start)
351                          'eww-form eww-form))))
352
353 (defun eww-tag-input (cont)
354   (let* ((start (point))
355          (type (downcase (or (cdr (assq :type cont))
356                              "text")))
357          (value (cdr (assq :value cont)))
358          (widget
359           (cond
360            ((or (equal type "submit")
361                 (equal type "image"))
362             (list 'push-button
363                   :notify 'eww-submit
364                   :name (cdr (assq :name cont))
365                   :value (if (zerop (length value))
366                              "Submit"
367                            value)
368                   :eww-form eww-form
369                   (or (if (zerop (length value))
370                           "Submit"
371                         value))))
372            ((or (equal type "radio")
373                 (equal type "checkbox"))
374             (list 'checkbox
375                   :notify 'eww-click-radio
376                   :name (cdr (assq :name cont))
377                   :checkbox-value value
378                   :checkbox-type type
379                   :eww-form eww-form
380                   (cdr (assq :checked cont))))
381            ((equal type "hidden")
382             (list 'hidden
383                   :name (cdr (assq :name cont))
384                   :value value))
385            (t
386             (list 'editable-field
387                   :size (string-to-number
388                          (or (cdr (assq :size cont))
389                              "40"))
390                   :value (or value "")
391                   :secret (and (equal type "password") ?*)
392                   :action 'eww-submit
393                   :name (cdr (assq :name cont))
394                   :eww-form eww-form)))))
395     (nconc eww-form (list widget))
396     (unless (eq (car widget) 'hidden)
397       (apply 'widget-create widget)
398       (put-text-property start (point) 'eww-widget widget)
399       (insert " "))))
400
401 (defun eww-tag-textarea (cont)
402   (let* ((start (point))
403          (widget
404           (list 'text
405                 :size (string-to-number
406                        (or (cdr (assq :cols cont))
407                            "40"))
408                 :value (or (cdr (assq 'text cont)) "")
409                 :action 'eww-submit
410                 :name (cdr (assq :name cont))
411                 :eww-form eww-form)))
412     (nconc eww-form (list widget))
413     (apply 'widget-create widget)
414     (put-text-property start (point) 'eww-widget widget)))
415
416 (defun eww-tag-select (cont)
417   (shr-ensure-paragraph)
418   (let ((menu (list 'menu-choice
419                     :name (cdr (assq :name cont))
420                     :eww-form eww-form))
421         (options nil)
422         (start (point)))
423     (dolist (elem cont)
424       (when (eq (car elem) 'option)
425         (when (cdr (assq :selected (cdr elem)))
426           (nconc menu (list :value
427                             (cdr (assq :value (cdr elem))))))
428         (push (list 'item
429                     :value (cdr (assq :value (cdr elem)))
430                     :tag (cdr (assq 'text (cdr elem))))
431               options)))
432     (when options
433       ;; If we have no selected values, default to the first value.
434       (unless (plist-get (cdr menu) :value)
435         (nconc menu (list :value (nth 2 (car options)))))
436       (nconc menu options)
437       (apply 'widget-create menu)
438       (put-text-property start (point) 'eww-widget menu)
439       (shr-ensure-paragraph))))
440
441 (defun eww-click-radio (widget &rest ignore)
442   (let ((form (plist-get (cdr widget) :eww-form))
443         (name (plist-get (cdr widget) :name)))
444     (when (equal (plist-get (cdr widget) :type) "radio")
445       (if (widget-value widget)
446           ;; Switch all the other radio buttons off.
447           (dolist (overlay (overlays-in (point-min) (point-max)))
448             (let ((field (plist-get (overlay-properties overlay) 'button)))
449               (when (and (eq (plist-get (cdr field) :eww-form) form)
450                          (equal name (plist-get (cdr field) :name)))
451                 (unless (eq field widget)
452                   (widget-value-set field nil)))))
453         (widget-value-set widget t)))
454     (eww-fix-widget-keymap)))
455
456 (defun eww-submit (widget &rest ignore)
457   (let ((form (plist-get (cdr widget) :eww-form))
458         values)
459     (dolist (overlay (sort (overlays-in (point-min) (point-max))
460                            (lambda (o1 o2)
461                              (< (overlay-start o1) (overlay-start o2)))))
462       (let ((field (or (plist-get (overlay-properties overlay) 'field)
463                        (plist-get (overlay-properties overlay) 'button))))
464         (when (eq (plist-get (cdr field) :eww-form) form)
465           (let ((name (plist-get (cdr field) :name)))
466             (when name
467               (cond
468                ((eq (car field) 'checkbox)
469                 (when (widget-value field)
470                   (push (cons name (plist-get (cdr field) :checkbox-value))
471                         values)))
472                ((eq (car field) 'push-button)
473                 ;; We want the values from buttons if we hit a button,
474                 ;; if it's the first button in the DOM after the field
475                 ;; hit ENTER on.
476                 (when (and (eq (car widget) 'push-button)
477                            (eq widget field))
478                   (push (cons name (widget-value field))
479                         values)))
480                (t
481                 (push (cons name (widget-value field))
482                       values))))))))
483     (dolist (elem form)
484       (when (and (consp elem)
485                  (eq (car elem) 'hidden))
486         (push (cons (plist-get (cdr elem) :name)
487                     (plist-get (cdr elem) :value))
488               values)))
489     ;; If we hit ENTER in a non-button field, include the value of the
490     ;; first submit button after it.
491     (unless (eq (car widget) 'push-button)
492       (let ((rest form)
493             (name (plist-get (cdr widget) :name)))
494         (when rest
495           (while (and rest
496                       (or (not (consp (car rest)))
497                           (not (equal name (plist-get (cdar rest) :name)))))
498             (pop rest)))
499         (while rest
500           (let ((elem (pop rest)))
501             (when (and (consp (car rest))
502                        (eq (car elem) 'push-button))
503               (push (cons (plist-get (cdr elem) :name)
504                           (plist-get (cdr elem) :value))
505                     values)
506               (setq rest nil))))))
507     (if (and (stringp (cdr (assq :method form)))
508              (equal (downcase (cdr (assq :method form))) "post"))
509         (let ((url-request-method "POST")
510               (url-request-extra-headers
511                '(("Content-Type" . "application/x-www-form-urlencoded")))
512               (url-request-data (mm-url-encode-www-form-urlencoded values)))
513           (eww-browse-url (shr-expand-url (cdr (assq :action form))
514                                           eww-current-url)))
515       (eww-browse-url
516        (concat
517         (if (cdr (assq :action form))
518             (shr-expand-url (cdr (assq :action form))
519                             eww-current-url)
520           eww-current-url)
521         "?"
522         (mm-url-encode-www-form-urlencoded values))))))
523
524 (defun eww-convert-widgets ()
525   (let ((start (point-min))
526         widget)
527     ;; Some widgets come from different buffers (rendered for tables),
528     ;; so we need to nix out the list of widgets and recreate them.
529     (setq widget-field-list nil
530           widget-field-new nil)
531     (while (setq start (if (get-text-property start 'eww-widget)
532                            start
533                          (next-single-property-change start 'eww-widget)))
534       (setq widget (get-text-property start 'eww-widget))
535       (goto-char start)
536       (let ((end (next-single-property-change start 'eww-widget)))
537         (dolist (overlay (overlays-in start end))
538           (when (or (plist-get (overlay-properties overlay) 'button)
539                     (plist-get (overlay-properties overlay) 'field))
540             (delete-overlay overlay)))
541         (delete-region start end))
542       (when (and widget
543                  (not (eq (car widget) 'hidden)))
544         (apply 'widget-create widget)
545         (put-text-property start (point) 'help-echo
546                            (if (memq (car widget) '(text editable-field))
547                                "Input field"
548                              "Button"))
549         (when (eq (car widget) 'push-button)
550           (add-face-text-property start (point) 'eww-button t))))
551     (widget-setup)
552     (eww-fix-widget-keymap)))
553
554 (defun eww-fix-widget-keymap ()
555   (dolist (overlay (overlays-in (point-min) (point-max)))
556     (when (plist-get (overlay-properties overlay) 'button)
557       (overlay-put overlay 'local-map widget-keymap))))
558
559 (provide 'eww)
560
561 ;;; eww.el ends here