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