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