(eww-submit): Rewrite to use the new-style form methods.
[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-form-submit
47   '((((type x w32 ns) (class color))    ; Like default mode line
48      :box (:line-width 2 :style released-button)
49      :background "#808080" :foreground "black"))
50   "Face for eww buffer buttons."
51   :version "24.4"
52   :group 'eww)
53
54 (defface eww-form-checkbox
55   '((((type x w32 ns) (class color))    ; Like default mode line
56      :box (:line-width 2 :style released-button)
57      :background "lightgrey" :foreground "black"))
58   "Face for eww buffer buttons."
59   :version "24.4"
60   :group 'eww)
61
62 (defface eww-form-select
63   '((((type x w32 ns) (class color))    ; Like default mode line
64      :box (:line-width 2 :style released-button)
65      :background "lightgrey" :foreground "black"))
66   "Face for eww buffer buttons."
67   :version "24.4"
68   :group 'eww)
69
70 (defface eww-form-text
71   '((t (:background "#505050"
72                     :foreground "white"
73                     :box (:line-width 1))))
74   "Face for eww text inputs."
75   :version "24.4"
76   :group 'eww)
77
78 (defvar eww-current-url nil)
79 (defvar eww-current-title ""
80   "Title of current page.")
81 (defvar eww-history nil)
82
83 (defvar eww-next-url nil)
84 (defvar eww-previous-url nil)
85 (defvar eww-up-url nil)
86 (defvar eww-top-url nil)
87
88 ;;;###autoload
89 (defun eww (url)
90   "Fetch URL and render the page."
91   (interactive "sUrl: ")
92   (unless (string-match-p "\\`[a-zA-Z][-a-zA-Z0-9+.]*://" url)
93     (setq url (concat "http://" url)))
94   (url-retrieve url 'eww-render (list url)))
95
96 ;;;###autoload
97 (defun eww-open-file (file)
98   "Render a file using EWW."
99   (interactive "fFile: ")
100   (eww (concat "file://" (expand-file-name file))))
101
102 (defun eww-render (status url &optional point)
103   (let ((redirect (plist-get status :redirect)))
104     (when redirect
105       (setq url redirect)))
106   (set (make-local-variable 'eww-next-url) nil)
107   (set (make-local-variable 'eww-previous-url) nil)
108   (set (make-local-variable 'eww-up-url) nil)
109   (set (make-local-variable 'eww-top-url) nil)
110   (let* ((headers (eww-parse-headers))
111          (shr-target-id
112           (and (string-match "#\\(.*\\)" url)
113                (match-string 1 url)))
114          (content-type
115           (mail-header-parse-content-type
116            (or (cdr (assoc "content-type" headers))
117                "text/plain")))
118          (charset (intern
119                    (downcase
120                     (or (cdr (assq 'charset (cdr content-type)))
121                         (eww-detect-charset (equal (car content-type)
122                                                    "text/html"))
123                         "utf8"))))
124          (data-buffer (current-buffer)))
125     (unwind-protect
126         (progn
127           (cond
128            ((equal (car content-type) "text/html")
129             (eww-display-html charset url))
130            ((string-match "^image/" (car content-type))
131             (eww-display-image))
132            (t
133             (eww-display-raw charset)))
134           (cond
135            (point
136             (goto-char point))
137            (shr-target-id
138             (let ((point (next-single-property-change
139                           (point-min) 'shr-target-id)))
140               (when point
141                 (goto-char (1+ point)))))))
142       (kill-buffer data-buffer))))
143
144 (defun eww-parse-headers ()
145   (let ((headers nil))
146     (goto-char (point-min))
147     (while (and (not (eobp))
148                 (not (eolp)))
149       (when (looking-at "\\([^:]+\\): *\\(.*\\)")
150         (push (cons (downcase (match-string 1))
151                     (match-string 2))
152               headers))
153       (forward-line 1))
154     (unless (eobp)
155       (forward-line 1))
156     headers))
157
158 (defun eww-detect-charset (html-p)
159   (let ((case-fold-search t)
160         (pt (point)))
161     (or (and html-p
162              (re-search-forward
163               "<meta[\t\n\r ]+[^>]*charset=\"?\\([^\t\n\r \"/>]+\\)" nil t)
164              (goto-char pt)
165              (match-string 1))
166         (and (looking-at
167               "[\t\n\r ]*<\\?xml[\t\n\r ]+[^>]*encoding=\"\\([^\"]+\\)")
168              (match-string 1)))))
169
170 (defun eww-display-html (charset url)
171   (unless (eq charset 'utf8)
172     (decode-coding-region (point) (point-max) charset))
173   (let ((document
174          (list
175           'base (list (cons 'href url))
176           (libxml-parse-html-region (point) (point-max)))))
177     (eww-setup-buffer)
178     (setq eww-current-url url)
179     (eww-update-header-line-format)
180     (let ((inhibit-read-only t)
181           (after-change-functions nil)
182           (shr-width nil)
183           (shr-external-rendering-functions
184            '((title . eww-tag-title)
185              (form . eww-tag-form)
186              (input . eww-tag-input)
187              (textarea . eww-tag-textarea)
188              (body . eww-tag-body)
189              (select . eww-tag-select)
190              (link . eww-tag-link)
191              (a . eww-tag-a))))
192       (shr-insert-document document))
193     (goto-char (point-min))))
194
195 (defun eww-handle-link (cont)
196   (let* ((rel (assq :rel cont))
197         (href (assq :href cont))
198         (where (assoc (cdr rel)
199                       '(("next" . eww-next-url)
200                         ("previous" . eww-previous-url)
201                         ("start" . eww-top-url)
202                         ("up" . eww-up-url)))))
203     (and href
204          where
205          (set (cdr where) (cdr href)))))
206
207 (defun eww-tag-link (cont)
208   (eww-handle-link cont)
209   (shr-generic cont))
210
211 (defun eww-tag-a (cont)
212   (eww-handle-link cont)
213   (shr-tag-a cont))
214
215 (defun eww-update-header-line-format ()
216   (if eww-header-line-format
217       (setq header-line-format (format-spec eww-header-line-format
218                                             `((?u . ,eww-current-url)
219                                               (?t . ,eww-current-title))))
220     (setq header-line-format nil)))
221
222 (defun eww-tag-title (cont)
223   (setq eww-current-title "")
224   (dolist (sub cont)
225     (when (eq (car sub) 'text)
226       (setq eww-current-title (concat eww-current-title (cdr sub)))))
227   (eww-update-header-line-format))
228
229 (defun eww-tag-body (cont)
230   (let* ((start (point))
231          (fgcolor (cdr (or (assq :fgcolor cont)
232                            (assq :text cont))))
233          (bgcolor (cdr (assq :bgcolor cont)))
234          (shr-stylesheet (list (cons 'color fgcolor)
235                                (cons 'background-color bgcolor))))
236     (shr-generic cont)
237     (eww-colorize-region start (point) fgcolor bgcolor)))
238
239 (defun eww-colorize-region (start end fg &optional bg)
240   (when (or fg bg)
241     (let ((new-colors (shr-color-check fg bg)))
242       (when new-colors
243         (when fg
244           (add-face-text-property start end
245                                   (list :foreground (cadr new-colors))
246                                   t))
247         (when bg
248           (add-face-text-property start end
249                                   (list :background (car new-colors))
250                                   t))))))
251
252 (defun eww-display-raw (charset)
253   (let ((data (buffer-substring (point) (point-max))))
254     (eww-setup-buffer)
255     (let ((inhibit-read-only t))
256       (insert data))
257     (goto-char (point-min))))
258
259 (defun eww-display-image ()
260   (let ((data (buffer-substring (point) (point-max))))
261     (eww-setup-buffer)
262     (let ((inhibit-read-only t))
263       (shr-put-image data nil))
264     (goto-char (point-min))))
265
266 (defun eww-setup-buffer ()
267   (pop-to-buffer (get-buffer-create "*eww*"))
268   (remove-overlays)
269   (let ((inhibit-read-only t))
270     (erase-buffer))
271   (eww-mode))
272
273 (defvar eww-mode-map
274   (let ((map (make-sparse-keymap)))
275     (suppress-keymap map)
276     (define-key map "q" 'eww-quit)
277     (define-key map "g" 'eww-reload)
278     (define-key map [tab] 'shr-next-link)
279     (define-key map [backtab] 'shr-previous-link)
280     (define-key map [delete] 'scroll-down-command)
281     (define-key map "\177" 'scroll-down-command)
282     (define-key map " " 'scroll-up-command)
283     (define-key map "l" 'eww-back-url)
284     (define-key map "n" 'eww-next-url)
285     (define-key map "p" 'eww-previous-url)
286     (define-key map "u" 'eww-up-url)
287     (define-key map "t" 'eww-top-url)
288     map))
289
290 (define-derived-mode eww-mode nil "eww"
291   "Mode for browsing the web.
292
293 \\{eww-mode-map}"
294   (set (make-local-variable 'eww-current-url) 'author)
295   (set (make-local-variable 'browse-url-browser-function) 'eww-browse-url)
296   (set (make-local-variable 'after-change-functions) 'eww-process-text-input)
297   ;;(setq buffer-read-only t)
298   )
299
300 (defun eww-browse-url (url &optional new-window)
301   (when (and (equal major-mode 'eww-mode)
302              eww-current-url)
303     (push (list eww-current-url (point))
304           eww-history))
305   (eww url))
306
307 (defun eww-quit ()
308   "Exit the Emacs Web Wowser."
309   (interactive)
310   (setq eww-history nil)
311   (kill-buffer (current-buffer)))
312
313 (defun eww-back-url ()
314   "Go to the previously displayed page."
315   (interactive)
316   (when (zerop (length eww-history))
317     (error "No previous page"))
318   (let ((prev (pop eww-history)))
319     (url-retrieve (car prev) 'eww-render (list (car prev) (cadr prev)))))
320
321 (defun eww-next-url ()
322   "Go to the page marked `next'.
323 A page is marked `next' if rel=\"next\" appears in a <link>
324 or <a> tag."
325   (interactive)
326   (if eww-next-url
327       (eww-browse-url (shr-expand-url eww-next-url eww-current-url))
328     (error "No `next' on this page")))
329
330 (defun eww-previous-url ()
331   "Go to the page marked `previous'.
332 A page is marked `previous' if rel=\"previous\" appears in a <link>
333 or <a> tag."
334   (interactive)
335   (if eww-previous-url
336       (eww-browse-url (shr-expand-url eww-previous-url eww-current-url))
337     (error "No `previous' on this page")))
338
339 (defun eww-up-url ()
340   "Go to the page marked `up'.
341 A page is marked `up' if rel=\"up\" appears in a <link>
342 or <a> tag."
343   (interactive)
344   (if eww-up-url
345       (eww-browse-url (shr-expand-url eww-up-url eww-current-url))
346     (error "No `up' on this page")))
347
348 (defun eww-top-url ()
349   "Go to the page marked `top'.
350 A page is marked `top' if rel=\"start\" appears in a <link>
351 or <a> tag."
352   (interactive)
353   (if eww-top-url
354       (eww-browse-url (shr-expand-url eww-top-url eww-current-url))
355     (error "No `top' on this page")))
356
357 (defun eww-reload ()
358   "Reload the current page."
359   (interactive)
360   (url-retrieve eww-current-url 'eww-render
361                 (list eww-current-url (point))))
362
363 ;; Form support.
364
365 (defvar eww-form nil)
366
367 (defvar eww-submit-map
368   (let ((map (make-sparse-keymap)))
369     (define-key map "\r" 'eww-submit)
370     map))
371
372 (defvar eww-checkbox-map
373   (let ((map (make-sparse-keymap)))
374     (define-key map [space] 'eww-toggle-checkbox)
375     (define-key map "\r" 'eww-toggle-checkbox)
376     map))
377
378 (defvar eww-text-map
379   (let ((map (make-keymap)))
380     (set-keymap-parent map text-mode-map)
381     (define-key map "\r" 'eww-submit)
382     (define-key map [(control a)] 'eww-beginning-of-text)
383     (define-key map [(control e)] 'eww-end-of-text)
384     (define-key map [tab] 'shr-next-link)
385     (define-key map [backtab] 'shr-previous-link)
386     map))
387
388 (defun eww-beginning-of-text ()
389   "Move to the start of the input field."
390   (interactive)
391   (goto-char (eww-beginning-of-field)))
392
393 (defun eww-end-of-text ()
394   "Move to the end of the text in the input field."
395   (interactive)
396   (goto-char (eww-end-of-field))
397   (let ((start (eww-beginning-of-field)))
398     (while (and (equal (following-char) ? )
399                 (> (point) start))
400       (forward-char -1))
401     (when (> (point) start)
402       (forward-char 1))))
403
404 (defun eww-beginning-of-field ()
405   (previous-single-property-change
406    (point) 'eww-form nil (point-min)))
407
408 (defun eww-end-of-field ()
409   (1- (next-single-property-change
410        (point) 'eww-form nil (point-max))))
411
412 (defvar eww-textarea-map
413   (let ((map (make-sparse-keymap)))
414     (set-keymap-parent map text-mode-map)
415     map))
416
417 (defvar eww-select-map
418   (let ((map (make-sparse-keymap)))
419     (define-key map "\r" 'eww-change-select)
420     map))
421
422 (defun eww-tag-form (cont)
423   (let ((eww-form
424          (list (assq :method cont)
425                (assq :action cont)))
426         (start (point)))
427     (shr-ensure-paragraph)
428     (shr-generic cont)
429     (unless (bolp)
430       (insert "\n"))
431     (insert "\n")
432     (when (> (point) start)
433       (put-text-property start (1+ start)
434                          'eww-form eww-form))))
435
436 (defun eww-form-submit (cont)
437   (let ((start (point))
438         (value (cdr (assq :value cont))))
439     (setq value
440           (if (zerop (length value))
441               "Submit"
442             value))
443     (insert value)
444     (add-face-text-property start (point) 'eww-form-submit)
445     (put-text-property start (point) 'eww-form
446                        (list :eww-form eww-form
447                              :value value
448                              :name (cdr (assq :name cont))))
449     (put-text-property start (point) 'keymap eww-submit-map)
450     (insert " ")))
451
452 (defun eww-form-checkbox (cont)
453   (let ((start (point)))
454     (if (cdr (assq :checked cont))
455         (insert "[X]")
456       (insert "[ ]"))
457     (add-face-text-property start (point) 'eww-form-checkbox)
458     (put-text-property start (point) 'eww-form
459                        (list :eww-form eww-form
460                              :value (cdr (assq :value cont))
461                              :type (downcase (cdr (assq :type cont)))
462                              :name (cdr (assq :name cont))))
463     (put-text-property start (point) 'keymap eww-checkbox-map)
464     (insert " ")))
465
466 (defun eww-form-text (cont)
467   (let ((start (point))
468         (type (downcase (or (cdr (assq :type cont))
469                             "text")))
470         (value (or (cdr (assq :value cont)) ""))
471         (width (string-to-number
472                 (or (cdr (assq :size cont))
473                     "40"))))
474     (insert value)
475     (when (< (length value) width)
476       (insert (make-string (- width (length value)) ? )))
477     (put-text-property start (point) 'face 'eww-form-text)
478     (put-text-property start (point) 'local-map eww-text-map)
479     (put-text-property start (point) 'inhibit-read-only t)
480     (put-text-property start (point) 'eww-form
481                        (list :eww-form eww-form
482                              :value value
483                              :type type
484                              :name (cdr (assq :name cont))))))
485
486 (defun eww-process-text-input (beg end length)
487   (let ((form (get-text-property end 'eww-form))
488         (properties (text-properties-at end)))
489     (when form
490       (cond
491        ((zerop length)
492         ;; Delete some text
493         (save-excursion
494           (goto-char (eww-end-of-field))
495           (let ((new (- end beg)))
496             (while (and (> new 0)
497                         (eql (following-char) ? ))
498               (delete-region (point) (1+ (point)))
499               (setq new (1- new))))
500           (set-text-properties beg end properties)))
501        ((> length 0)
502         ;; Add padding.
503         (save-excursion
504           (goto-char (1+ (eww-end-of-field)))
505           (let ((start (point)))
506             (insert (make-string length ? ))
507             (set-text-properties start (point) properties)))))
508       (plist-put form :value (buffer-substring-no-properties
509                               (eww-beginning-of-field)
510                               (eww-end-of-field))))))
511
512 (defun eww-form-textarea (cont)
513   (let ((start (point))
514         (value (or (cdr (assq :value cont)) ""))
515         (lines (string-to-number
516                 (or (cdr (assq :rows cont))
517                     "10")))
518         (width (string-to-number
519                 (or (cdr (assq :cols cont))
520                     "10")))
521         end)
522     (shr-ensure-newline)
523     (insert value)
524     (shr-ensure-newline)
525     (when (< (count-lines start (point)) lines)
526       (dotimes (i (- lines (count-lines start (point))))
527         (insert "\n")))
528     (setq end (point))
529     (goto-char start)
530     (while (< (point) end)
531       (end-of-line)
532       (let ((pad (- width (- (point) (line-beginning-position)))))
533         (when (> pad 0)
534           (insert (make-string pad ? ))))
535       (add-face-text-property (line-beginning-position)
536                               (point) 'eww-form-text)
537       (put-text-property (line-beginning-position) (point)
538                          'keymap eww-text-map)))
539   (put-text-property start (point) 'eww-form
540                      (list :eww-form eww-form
541                            :value value
542                            :type (downcase (cdr (assq :type cont)))
543                            :name (cdr (assq :name cont)))))
544
545 (defun eww-tag-input (cont)
546   (let ((type (downcase (or (cdr (assq :type cont))
547                              "text"))))
548     (cond
549      ((or (equal type "checkbox")
550           (equal type "radio"))
551       (eww-form-checkbox cont))
552      ((equal type "submit")
553       (eww-form-submit cont))
554      ((equal type "hidden")
555       (let ((form eww-form)
556             (name (cdr (assq :name cont))))
557         ;; Don't add <input type=hidden> elements repeatedly.
558         (while (and form
559                     (or (not (consp (car form)))
560                         (not (eq (caar form) 'hidden))
561                         (not (equal (plist-get (cdr (car form)) :name)
562                                     name))))
563           (setq form (cdr form)))
564         (unless form
565           (nconc eww-form (list
566                            (list 'hidden
567                                  :name name
568                                  :value (cdr (assq :value cont))))))))
569      (t
570       (eww-form-text cont)))))
571
572 (defun eww-tag-textarea (cont)
573   (eww-form-textarea cont))
574
575 (defun eww-tag-select (cont)
576   (shr-ensure-paragraph)
577   (let ((menu (list :name (cdr (assq :name cont))
578                     :eww-form eww-form))
579         (options nil)
580         (start (point))
581         (max 0))
582     (dolist (elem cont)
583       (when (eq (car elem) 'option)
584         (when (cdr (assq :selected (cdr elem)))
585           (nconc menu (list :value
586                             (cdr (assq :value (cdr elem))))))
587         (let ((display (or (cdr (assq 'text (cdr elem))) "")))
588           (setq max (max max (length display))))
589         (push (list 'item
590                     :value (cdr (assq :value (cdr elem)))
591                     :display display)
592               options)))
593     (when options
594       ;; If we have no selected values, default to the first value.
595       (unless (plist-get menu :value)
596         (nconc menu (list :value (nth 2 (car options)))))
597       (nconc menu options)
598       (let ((selected (eww-element-value menu)))
599         (insert selected
600                 (make-string (- max (length selected)) ? )))
601       (put-text-property start (point) 'eww-form menu)
602       (add-face-text-property start (point) 'eww-form-select)
603       (put-text-property start (point) 'keymap eww-select-map)
604       (shr-ensure-paragraph))))
605
606 (defun eww-click-radio (widget &rest ignore)
607   (let ((form (plist-get (cdr widget) :eww-form))
608         (name (plist-get (cdr widget) :name)))
609     (when (equal (plist-get (cdr widget) :type) "radio")
610       (if (widget-value widget)
611           ;; Switch all the other radio buttons off.
612           (dolist (overlay (overlays-in (point-min) (point-max)))
613             (let ((field (plist-get (overlay-properties overlay) 'button)))
614               (when (and (eq (plist-get (cdr field) :eww-form) form)
615                          (equal name (plist-get (cdr field) :name)))
616                 (unless (eq field widget)
617                   (widget-value-set field nil)))))
618         (widget-value-set widget t)))
619     (eww-fix-widget-keymap)))
620
621 (defun eww-inputs (form)
622   (let ((start (point-min))
623         (inputs nil))
624     (while (and start
625                 (< start (point-max)))
626       (when (or (get-text-property start 'eww-form)
627                 (setq start (next-single-property-change start 'eww-form)))
628         (when (eq (plist-get (get-text-property start 'eww-form) :eww-form)
629                   form)
630           (push (cons start (get-text-property start 'eww-form))
631                 inputs))
632         (setq start (next-single-property-change start 'eww-form))))
633     (nreverse inputs)))
634
635 (defun eww-input-value (input)
636   (let ((type (plist-get input :type)))
637     (cond
638      ((equal type "select")
639       )
640      (t
641       (let ((value (plist-get input :value)))
642         (if (string-match " +" value)
643             (substring value 0 (match-beginning 0))
644           value))))))
645
646 (defun eww-submit ()
647   "Submit the current form."
648   (interactive)
649   (let* ((this-input (get-text-property (point) 'eww-form))
650          (form (plist-get this-input :eww-form))
651          values next-submit)
652     (dolist (elem (sort (eww-inputs form)
653                          (lambda (o1 o2)
654                            (< (car o1) (car o2)))))
655       (let* ((input (cdr elem))
656              (input-start (car elem))
657              (name (plist-get input :name)))
658         (when name
659           (cond
660            ((equal (plist-get input :type) "checkbox")
661             (when (plist-get input :checked)
662               (push (cons name (plist-get input :value))
663                     values)))
664            ((equal (plist-get input :type) "submit")
665             ;; We want the values from buttons if we hit a button if
666             ;; we hit enter on it, or if it's the first button after
667             ;; the field we did hit return on.
668             (when (or (eq input this-input)
669                       (and (not (eq input this-input))
670                            (null next-submit)
671                            (> input-start (point))))
672               (push (cons name (plist-get input :value))
673                     values)))
674            (t
675             (push (cons name (eww-input-value input))
676                   values))))))
677     (dolist (elem form)
678       (when (and (consp elem)
679                  (eq (car elem) 'hidden))
680         (push (cons (plist-get (cdr elem) :name)
681                     (plist-get (cdr elem) :value))
682               values)))
683     (if (and (stringp (cdr (assq :method form)))
684              (equal (downcase (cdr (assq :method form))) "post"))
685         (let ((url-request-method "POST")
686               (url-request-extra-headers
687                '(("Content-Type" . "application/x-www-form-urlencoded")))
688               (url-request-data (mm-url-encode-www-form-urlencoded values)))
689           (eww-browse-url (shr-expand-url (cdr (assq :action form))
690                                           eww-current-url)))
691       (eww-browse-url
692        (concat
693         (if (cdr (assq :action form))
694             (shr-expand-url (cdr (assq :action form))
695                             eww-current-url)
696           eww-current-url)
697         "?"
698         (mm-url-encode-www-form-urlencoded values))))))
699
700 (provide 'eww)
701
702 ;;; eww.el ends here