eww.el 47.6 KB
Newer Older
1 2
;;; eww.el --- Emacs Web Wowser

3
;; Copyright (C) 2013-2014 Free Software Foundation, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
;; Keywords: html

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;;; Code:

(eval-when-compile (require 'cl))
28
(require 'format-spec)
29 30
(require 'shr)
(require 'url)
31
(require 'url-queue)
32
(require 'mm-url)
33
(eval-when-compile (require 'subr-x)) ;; for string-trim
34

35 36 37
(defgroup eww nil
  "Emacs Web Wowser"
  :version "24.4"
38
  :link '(custom-manual "(eww) Top")
39 40 41 42 43 44 45
  :group 'hypermedia
  :prefix "eww-")

(defcustom eww-header-line-format "%t: %u"
  "Header line format.
- %t is replaced by the title.
- %u is replaced by the URL."
46 47 48 49 50 51 52
  :version "24.4"
  :group 'eww
  :type 'string)

(defcustom eww-search-prefix "https://duckduckgo.com/html/?q="
  "Prefix URL to search engine"
  :version "24.4"
53 54 55
  :group 'eww
  :type 'string)

56 57
(defcustom eww-download-directory "~/Downloads/"
  "Directory where files will downloaded."
58 59 60 61
  :version "24.4"
  :group 'eww
  :type 'string)

62 63
(defcustom eww-bookmarks-directory user-emacs-directory
  "Directory where bookmark files will be stored."
Stefan Monnier's avatar
Stefan Monnier committed
64
  :version "25.1"
65 66 67
  :group 'eww
  :type 'string)

68 69 70 71 72 73 74 75
(defcustom eww-use-external-browser-for-content-type
  "\\`\\(video/\\|audio/\\|application/ogg\\)"
  "Always use external browser for specified content-type."
  :version "24.4"
  :group 'eww
  :type '(choice (const :tag "Never" nil)
                 regexp))

76 77 78 79 80 81
(defcustom eww-after-render-hook nil
  "A hook called after eww has finished rendering the buffer."
  :version "25.1"
  :group 'eww
  :type 'hook)

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
(defcustom eww-form-checkbox-selected-symbol "[X]"
  "Symbol used to represent a selected checkbox.
See also `eww-form-checkbox-symbol'."
  :version "24.4"
  :group 'eww
  :type '(choice (const "[X]")
                 (const "☒")            ; Unicode BALLOT BOX WITH X
                 (const "☑")            ; Unicode BALLOT BOX WITH CHECK
                 string))

(defcustom eww-form-checkbox-symbol "[ ]"
  "Symbol used to represent a checkbox.
See also `eww-form-checkbox-selected-symbol'."
  :version "24.4"
  :group 'eww
  :type '(choice (const "[ ]")
                 (const "☐")            ; Unicode BALLOT BOX
                 string))

101 102 103 104 105 106 107 108
(defface eww-form-submit
  '((((type x w32 ns) (class color))	; Like default mode line
     :box (:line-width 2 :style released-button)
     :background "#808080" :foreground "black"))
  "Face for eww buffer buttons."
  :version "24.4"
  :group 'eww)

109 110 111 112 113
(defface eww-form-file
  '((((type x w32 ns) (class color))	; Like default mode line
     :box (:line-width 2 :style released-button)
     :background "#808080" :foreground "black"))
  "Face for eww buffer buttons."
114
  :version "25.1"
115
  :group 'eww)
116

117 118 119 120 121 122 123 124 125
(defface eww-form-checkbox
  '((((type x w32 ns) (class color))	; Like default mode line
     :box (:line-width 2 :style released-button)
     :background "lightgrey" :foreground "black"))
  "Face for eww buffer buttons."
  :version "24.4"
  :group 'eww)

(defface eww-form-select
126 127 128 129 130 131 132
  '((((type x w32 ns) (class color))	; Like default mode line
     :box (:line-width 2 :style released-button)
     :background "lightgrey" :foreground "black"))
  "Face for eww buffer buttons."
  :version "24.4"
  :group 'eww)

133 134 135 136 137 138 139 140
(defface eww-form-text
  '((t (:background "#505050"
		    :foreground "white"
		    :box (:line-width 1))))
  "Face for eww text inputs."
  :version "24.4"
  :group 'eww)

Kenjiro NAKAYAMA's avatar
Kenjiro NAKAYAMA committed
141 142 143 144 145 146 147 148
(defface eww-form-textarea
  '((t (:background "#C0C0C0"
		    :foreground "black"
		    :box (:line-width 1))))
  "Face for eww textarea inputs."
  :version "24.4"
  :group 'eww)

149
(defvar eww-data nil)
150
(defvar eww-history nil)
151
(defvar eww-history-position 0)
152

153 154 155
(defvar eww-local-regex "localhost"
  "When this regex is found in the URL, it's not a keyword but an address.")

156 157 158 159 160
(defvar eww-link-keymap
  (let ((map (copy-keymap shr-map)))
    (define-key map "\r" 'eww-follow-link)
    map))

161
;;;###autoload
162
(defun eww (url)
163 164 165 166
  "Fetch URL and render the page.
If the input doesn't look like an URL or a domain name, the
word(s) will be searched for via `eww-search-prefix'."
  (interactive "sEnter URL or keywords: ")
167
  (setq url (string-trim url))
168
  (cond ((string-match-p "\\`file:/" url))
169
	;; Don't mangle file: URLs at all.
170 171 172 173
        ((string-match-p "\\`ftp://" url)
         (user-error "FTP is not supported."))
        (t
         (if (and (= (length (split-string url)) 1)
174 175 176
		  (or (and (not (string-match-p "\\`[\"\'].*[\"\']\\'" url))
			   (> (length (split-string url "[.:]")) 1))
		      (string-match eww-local-regex url)))
177 178 179 180 181 182 183 184
             (progn
               (unless (string-match-p "\\`[a-zA-Z][-a-zA-Z0-9+.]*://" url)
                 (setq url (concat "http://" url)))
               ;; some site don't redirect final /
               (when (string= (url-filename (url-generic-parse-url url)) "")
                 (setq url (concat url "/"))))
           (setq url (concat eww-search-prefix
                             (replace-regexp-in-string " " "+" url))))))
185 186 187 188
  (url-retrieve url 'eww-render
		(list url nil
		      (and (eq major-mode 'eww-mode)
			   (current-buffer)))))
189

190 191
;;;###autoload (defalias 'browse-web 'eww)

192 193 194 195
;;;###autoload
(defun eww-open-file (file)
  "Render a file using EWW."
  (interactive "fFile: ")
196 197 198 199
  (eww (concat "file://"
	       (and (memq system-type '(windows-nt ms-dos))
		    "/")
	       (expand-file-name file))))
200

201 202 203 204 205 206
;;;###autoload
(defun eww-search-words (&optional beg end)
  "Search the web for the text between the point and marker."
  (interactive "r")
  (eww (buffer-substring beg end)))

207
(defun eww-render (status url &optional point buffer)
208 209 210
  (let ((redirect (plist-get status :redirect)))
    (when redirect
      (setq url redirect)))
211 212 213 214 215 216 217 218
  (let* ((headers (eww-parse-headers))
	 (content-type
	  (mail-header-parse-content-type
	   (or (cdr (assoc "content-type" headers))
	       "text/plain")))
	 (charset (intern
		   (downcase
		    (or (cdr (assq 'charset (cdr content-type)))
219 220
			(eww-detect-charset (equal (car content-type)
						   "text/html"))
221 222 223 224
			"utf8"))))
	 (data-buffer (current-buffer)))
    (unwind-protect
	(progn
225
          (plist-put eww-data :title "")
226
	  (cond
227 228 229 230
           ((and eww-use-external-browser-for-content-type
                 (string-match-p eww-use-external-browser-for-content-type
                                 (car content-type)))
            (eww-browse-with-external-browser url))
231
	   ((equal (car content-type) "text/html")
232
	    (eww-display-html charset url nil point buffer))
233 234
	   ((equal (car content-type) "application/pdf")
	    (eww-display-pdf))
235
	   ((string-match-p "\\`image/" (car content-type))
236
	    (eww-display-image buffer)
237
	    (eww-update-header-line-format))
238
	   (t
239
	    (eww-display-raw buffer)
240
	    (eww-update-header-line-format)))
241
	  (plist-put eww-data :url url)
242 243
	  (setq eww-history-position 0)
	  (run-hooks 'eww-after-render-hook))
244 245 246 247
      (kill-buffer data-buffer))))

(defun eww-parse-headers ()
  (let ((headers nil))
248
    (goto-char (point-min))
249 250 251 252 253 254 255 256 257 258 259
    (while (and (not (eobp))
		(not (eolp)))
      (when (looking-at "\\([^:]+\\): *\\(.*\\)")
	(push (cons (downcase (match-string 1))
		    (match-string 2))
	      headers))
      (forward-line 1))
    (unless (eobp)
      (forward-line 1))
    headers))

260 261 262 263 264
(defun eww-detect-charset (html-p)
  (let ((case-fold-search t)
	(pt (point)))
    (or (and html-p
	     (re-search-forward
Ivan Kanis's avatar
Ivan Kanis committed
265
	      "<meta[\t\n\r ]+[^>]*charset=\"?\\([^\t\n\r \"/>]+\\)[\\\"'.*]" nil t)
266 267 268 269 270 271
	     (goto-char pt)
	     (match-string 1))
	(and (looking-at
	      "[\t\n\r ]*<\\?xml[\t\n\r ]+[^>]*encoding=\"\\([^\"]+\\)")
	     (match-string 1)))))

272 273 274
(declare-function libxml-parse-html-region "xml.c"
		  (start end &optional base-url))

275
(defun eww-display-html (charset url &optional document point buffer)
276 277
  (or (fboundp 'libxml-parse-html-region)
      (error "This function requires Emacs to be compiled with libxml2"))
278 279 280
  ;; There should be a better way to abort loading images
  ;; asynchronously.
  (setq url-queue nil)
281
  (let ((document
282 283 284
	 (or document
	     (list
	      'base (list (cons 'href url))
285 286 287 288 289 290 291 292
	      (progn
		(unless (eq charset 'utf-8)
		  (condition-case nil
		      (decode-coding-region (point) (point-max) charset)
		    (coding-system-error nil)))
		(libxml-parse-html-region (point) (point-max))))))
	(source (and (null document)
		     (buffer-substring (point) (point-max)))))
293
    (eww-setup-buffer buffer)
294 295
    (plist-put eww-data :source source)
    (plist-put eww-data :dom document)
296
    (let ((inhibit-read-only t)
297
	  (after-change-functions nil)
298
	  (shr-target-id (url-target (url-generic-parse-url url)))
299
	  (shr-external-rendering-functions
300 301
	   '((title . eww-tag-title)
	     (form . eww-tag-form)
302
	     (input . eww-tag-input)
303 304
	     (textarea . eww-tag-textarea)
	     (body . eww-tag-body)
305 306 307
	     (select . eww-tag-select)
	     (link . eww-tag-link)
	     (a . eww-tag-a))))
308 309 310 311 312
      (shr-insert-document document)
      (cond
       (point
	(goto-char point))
       (shr-target-id
313
	(goto-char (point-min))
314 315
	(let ((point (next-single-property-change
		      (point-min) 'shr-target-id)))
316 317
	  (when point
	    (goto-char point))))
318
       (t
319 320 321 322 323 324
	(goto-char (point-min))
	;; Don't leave point inside forms, because the normal eww
	;; commands aren't available there.
	(while (and (not (eobp))
		    (get-text-property (point) 'eww-form))
	  (forward-line 1)))))
325 326
    (plist-put eww-data :url url)
    (setq eww-history-position 0)
327
    (eww-update-header-line-format)))
328

329 330 331
(defun eww-handle-link (cont)
  (let* ((rel (assq :rel cont))
  	(href (assq :href cont))
332 333 334
	(where (assoc
		;; The text associated with :rel is case-insensitive.
		(if rel (downcase (cdr rel)))
335
		      '(("next" . :next)
336 337
			;; Texinfo uses "previous", but HTML specifies
			;; "prev", so recognize both.
338 339
			("previous" . :previous)
			("prev" . :previous)
340 341 342 343 344
			;; HTML specifies "start" but also "contents",
			;; and Gtk seems to use "home".  Recognize
			;; them all; but store them in different
			;; variables so that we can readily choose the
			;; "best" one.
345 346 347 348
			("start" . :start)
			("home" . :home)
			("contents" . :contents)
			("up" . up)))))
349 350
    (and href
	 where
351
	 (plist-put eww-data (cdr where) (cdr href)))))
352 353 354 355 356 357 358

(defun eww-tag-link (cont)
  (eww-handle-link cont)
  (shr-generic cont))

(defun eww-tag-a (cont)
  (eww-handle-link cont)
359 360 361
  (let ((start (point)))
    (shr-tag-a cont)
    (put-text-property start (point) 'keymap eww-link-keymap)))
362

363 364
(defun eww-update-header-line-format ()
  (if eww-header-line-format
365 366 367
      (setq header-line-format
	    (replace-regexp-in-string
	     "%" "%%"
368 369
	     ;; FIXME?  Title can be blank.  Default to, eg, last component
	     ;; of url?
370
	     (format-spec eww-header-line-format
371 372
			  `((?u . ,(plist-get eww-data :url))
			    (?t . ,(or (plist-get eww-data :title) ""))))))
373 374 375
    (setq header-line-format nil)))

(defun eww-tag-title (cont)
376 377 378 379 380 381 382 383
  (let ((title ""))
    (dolist (sub cont)
      (when (eq (car sub) 'text)
	(setq title (concat title (cdr sub)))))
    (plist-put eww-data :title
	       (replace-regexp-in-string
		"^ \\| $" ""
		(replace-regexp-in-string "[ \t\r\n]+" " " title))))
384 385 386 387 388 389 390 391 392 393
  (eww-update-header-line-format))

(defun eww-tag-body (cont)
  (let* ((start (point))
	 (fgcolor (cdr (or (assq :fgcolor cont)
                           (assq :text cont))))
	 (bgcolor (cdr (assq :bgcolor cont)))
	 (shr-stylesheet (list (cons 'color fgcolor)
			       (cons 'background-color bgcolor))))
    (shr-generic cont)
394
    (shr-colorize-region start (point) fgcolor bgcolor)))
395

396
(defun eww-display-raw (&optional buffer)
397
  (let ((data (buffer-substring (point) (point-max))))
398
    (eww-setup-buffer buffer)
399 400 401 402
    (let ((inhibit-read-only t))
      (insert data))
    (goto-char (point-min))))

403
(defun eww-display-image (&optional buffer)
404
  (let ((data (shr-parse-image-data)))
405
    (eww-setup-buffer buffer)
406 407 408 409
    (let ((inhibit-read-only t))
      (shr-put-image data nil))
    (goto-char (point-min))))

410 411 412 413 414 415 416 417 418 419
(defun eww-display-pdf ()
  (let ((data (buffer-substring (point) (point-max))))
    (switch-to-buffer (get-buffer-create "*eww pdf*"))
    (let ((coding-system-for-write 'raw-text)
	  (inhibit-read-only t))
      (erase-buffer)
      (insert data)
      (doc-view-mode)))
  (goto-char (point-min)))

420 421 422 423 424
(defun eww-setup-buffer (&optional buffer)
  (switch-to-buffer
   (if (buffer-live-p buffer)
       buffer
     (get-buffer-create "*eww*")))
425
  (let ((inhibit-read-only t))
426
    (remove-overlays)
427
    (erase-buffer))
428
  (unless (eq major-mode 'eww-mode)
429
    (eww-mode)))
430

431
(defun eww-view-source ()
432
  "View the HTML source code of the current page."
433 434
  (interactive)
  (let ((buf (get-buffer-create "*eww-source*"))
435
        (source (plist-get eww-data :source)))
436
    (with-current-buffer buf
437 438 439 440 441 442
      (let ((inhibit-read-only t))
	(delete-region (point-min) (point-max))
	(insert (or source "no source"))
	(goto-char (point-min))
	(when (fboundp 'html-mode)
	  (html-mode))))
443 444
    (view-buffer buf)))

445 446 447 448 449 450
(defun eww-readable ()
  "View the main \"readable\" parts of the current web page.
This command uses heuristics to find the parts of the web page that
contains the main textual portion, leaving out navigation menus and
the like."
  (interactive)
451
  (let* ((old-data eww-data)
452 453
	 (dom (shr-transform-dom
	       (with-temp-buffer
454
		 (insert (plist-get old-data :source))
455 456 457
		 (condition-case nil
		     (decode-coding-region (point-min) (point-max) 'utf-8)
		   (coding-system-error nil))
458 459
		 (libxml-parse-html-region (point-min) (point-max))))))
    (eww-score-readability dom)
460
    (eww-save-history)
461 462
    (eww-display-html nil nil
		      (shr-retransform-dom
463 464
		       (eww-highest-readability dom))
		      nil (current-buffer))
465 466 467
    (dolist (elem '(:source :url :title :next :previous :up))
      (plist-put eww-data elem (plist-get old-data elem)))
    (eww-update-header-line-format)))
468 469 470 471

(defun eww-score-readability (node)
  (let ((score -1))
    (cond
472
     ((memq (car node) '(script head comment))
473 474 475
      (setq score -2))
     ((eq (car node) 'meta)
      (setq score -1))
476 477
     ((eq (car node) 'img)
      (setq score 2))
478 479 480 481 482 483
     ((eq (car node) 'a)
      (setq score (- (length (split-string
			      (or (cdr (assoc 'text (cdr node))) ""))))))
     (t
      (dolist (elem (cdr node))
	(cond
484 485
	 ((and (stringp (cdr elem))
	       (eq (car elem) 'text))
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
	  (setq score (+ score (length (split-string (cdr elem))))))
	 ((consp (cdr elem))
	  (setq score (+ score
			 (or (cdr (assoc :eww-readability-score (cdr elem)))
			     (eww-score-readability elem)))))))))
    ;; Cache the score of the node to avoid recomputing all the time.
    (setcdr node (cons (cons :eww-readability-score score) (cdr node)))
    score))

(defun eww-highest-readability (node)
  (let ((result node)
	highest)
    (dolist (elem (cdr node))
      (when (and (consp (cdr elem))
		 (> (or (cdr (assoc
			      :eww-readability-score
			      (setq highest
				    (eww-highest-readability elem))))
			most-negative-fixnum)
		    (or (cdr (assoc :eww-readability-score (cdr result)))
			most-negative-fixnum)))
	(setq result highest)))
    result))

510 511 512
(defvar eww-mode-map
  (let ((map (make-sparse-keymap)))
    (suppress-keymap map)
513
    (define-key map "q" 'quit-window)
514
    (define-key map "g" 'eww-reload)
515 516
    (define-key map [?\t] 'shr-next-link)
    (define-key map [?\M-\t] 'shr-previous-link)
517
    (define-key map [delete] 'scroll-down-command)
518
    (define-key map [?\S-\ ] 'scroll-down-command)
519 520
    (define-key map "\177" 'scroll-down-command)
    (define-key map " " 'scroll-up-command)
521
    (define-key map "l" 'eww-back-url)
522
    (define-key map "r" 'eww-forward-url)
523
    (define-key map "n" 'eww-next-url)
524
    (define-key map "p" 'eww-previous-url)
525 526
    (define-key map "u" 'eww-up-url)
    (define-key map "t" 'eww-top-url)
527
    (define-key map "&" 'eww-browse-with-external-browser)
528
    (define-key map "d" 'eww-download)
529
    (define-key map "w" 'eww-copy-page-url)
530
    (define-key map "C" 'url-cookie-list)
531
    (define-key map "v" 'eww-view-source)
532
    (define-key map "R" 'eww-readable)
533
    (define-key map "H" 'eww-list-histories)
534

535 536 537 538 539
    (define-key map "b" 'eww-add-bookmark)
    (define-key map "B" 'eww-list-bookmarks)
    (define-key map [(meta n)] 'eww-next-bookmark)
    (define-key map [(meta p)] 'eww-previous-bookmark)

540
    (easy-menu-define nil map ""
541
      '("Eww"
542
	["Exit" quit-window t]
543
	["Close browser" quit-window t]
544 545 546 547 548 549 550
	["Reload" eww-reload t]
	["Back to previous page" eww-back-url
	 :active (not (zerop (length eww-history)))]
	["Forward to next page" eww-forward-url
	 :active (not (zerop eww-history-position))]
	["Browse with external browser" eww-browse-with-external-browser t]
	["Download" eww-download t]
551
	["View page source" eww-view-source]
552
	["Copy page URL" eww-copy-page-url t]
553
	["List histories" eww-list-histories t]
554
	["Add bookmark" eww-add-bookmark t]
Kenjiro NAKAYAMA's avatar
Kenjiro NAKAYAMA committed
555
	["List bookmarks" eww-list-bookmarks t]
556
	["List cookies" url-cookie-list t]))
557 558
    map))

559 560 561
(defvar eww-tool-bar-map
  (let ((map (make-sparse-keymap)))
    (dolist (tool-bar-item
562
             '((quit-window . "close")
563 564 565 566 567 568 569 570 571 572 573
               (eww-reload . "refresh")
               (eww-back-url . "left-arrow")
               (eww-forward-url . "right-arrow")
               (eww-view-source . "show")
               (eww-copy-page-url . "copy")
               (eww-add-bookmark . "bookmark_add"))) ;; ...
      (tool-bar-local-item-from-menu
       (car tool-bar-item) (cdr tool-bar-item) map eww-mode-map))
    map)
  "Tool bar for `eww-mode'.")

574
(define-derived-mode eww-mode nil "eww"
575 576 577
  "Mode for browsing the web.

\\{eww-mode-map}"
578
  (setq-local eww-data (list :title ""))
579 580 581 582 583 584
  (setq-local browse-url-browser-function 'eww-browse-url)
  (setq-local after-change-functions 'eww-process-text-input)
  (setq-local eww-history nil)
  (setq-local eww-history-position 0)
  (when (boundp 'tool-bar-map)
   (setq-local tool-bar-map eww-tool-bar-map))
585
  (buffer-disable-undo)
586 587
  ;;(setq buffer-read-only t)
  )
588

589
;;;###autoload
Daniel Hackney's avatar
Daniel Hackney committed
590
(defun eww-browse-url (url &optional _new-window)
591
  (when (and (equal major-mode 'eww-mode)
592
	     (plist-get eww-data :url))
593
    (eww-save-history))
594
  (eww url))
595

596
(defun eww-back-url ()
597 598
  "Go to the previously displayed page."
  (interactive)
599
  (when (>= eww-history-position (length eww-history))
600
    (user-error "No previous page"))
601 602 603
  (eww-save-history)
  (setq eww-history-position (+ eww-history-position 2))
  (eww-restore-history (elt eww-history (1- eww-history-position))))
604 605 606 607 608

(defun eww-forward-url ()
  "Go to the next displayed page."
  (interactive)
  (when (zerop eww-history-position)
609
    (user-error "No next page"))
610 611
  (eww-save-history)
  (eww-restore-history (elt eww-history (1- eww-history-position))))
612 613 614

(defun eww-restore-history (elem)
  (let ((inhibit-read-only t))
615
    (erase-buffer)
616 617
    (insert (plist-get elem :text))
    (goto-char (plist-get elem :point))
618
    (setq eww-data elem)
619
    (eww-update-header-line-format)))
620

621 622 623 624 625
(defun eww-next-url ()
  "Go to the page marked `next'.
A page is marked `next' if rel=\"next\" appears in a <link>
or <a> tag."
  (interactive)
626 627 628
  (if (plist-get eww-data :next)
      (eww-browse-url (shr-expand-url (plist-get eww-data :next)
				      (plist-get eww-data :url)))
629
    (user-error "No `next' on this page")))
630 631 632 633 634 635

(defun eww-previous-url ()
  "Go to the page marked `previous'.
A page is marked `previous' if rel=\"previous\" appears in a <link>
or <a> tag."
  (interactive)
636 637
  (if (plist-get eww-data :previous)
      (eww-browse-url (shr-expand-url (plist-get eww-data :previous)
638
				      (plist-get eww-data :url)))
639
    (user-error "No `previous' on this page")))
640 641 642 643 644 645

(defun eww-up-url ()
  "Go to the page marked `up'.
A page is marked `up' if rel=\"up\" appears in a <link>
or <a> tag."
  (interactive)
646 647 648
  (if (plist-get eww-data :up)
      (eww-browse-url (shr-expand-url (plist-get eww-data :up)
				      (plist-get eww-data :url)))
649
    (user-error "No `up' on this page")))
650 651 652

(defun eww-top-url ()
  "Go to the page marked `top'.
653 654
A page is marked `top' if rel=\"start\", rel=\"home\", or rel=\"contents\"
appears in a <link> or <a> tag."
655
  (interactive)
656 657 658
  (let ((best-url (or (plist-get eww-data :start)
		      (plist-get eww-data :contents)
		      (plist-get eww-data :home))))
659
    (if best-url
660
	(eww-browse-url (shr-expand-url best-url (plist-get eww-data :url)))
661
      (user-error "No `top' for this page"))))
662

663 664 665
(defun eww-reload ()
  "Reload the current page."
  (interactive)
666 667
  (let ((url (plist-get eww-data :url)))
    (url-retrieve url 'eww-render (list url (point)))))
668

669 670 671 672
;; Form support.

(defvar eww-form nil)

673 674 675
(defvar eww-submit-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\r" 'eww-submit)
676
    (define-key map [(control c) (control c)] 'eww-submit)
677 678
    map))

679 680 681 682 683 684
(defvar eww-submit-file
  (let ((map (make-sparse-keymap)))
    (define-key map "\r" 'eww-select-file)
    (define-key map [(control c) (control c)] 'eww-submit)
    map))

685 686
(defvar eww-checkbox-map
  (let ((map (make-sparse-keymap)))
Kenjiro NAKAYAMA's avatar
Kenjiro NAKAYAMA committed
687
    (define-key map " " 'eww-toggle-checkbox)
688
    (define-key map "\r" 'eww-toggle-checkbox)
689
    (define-key map [(control c) (control c)] 'eww-submit)
690 691 692 693 694 695 696
    map))

(defvar eww-text-map
  (let ((map (make-keymap)))
    (set-keymap-parent map text-mode-map)
    (define-key map "\r" 'eww-submit)
    (define-key map [(control a)] 'eww-beginning-of-text)
697
    (define-key map [(control c) (control c)] 'eww-submit)
698
    (define-key map [(control e)] 'eww-end-of-text)
699 700
    (define-key map [?\t] 'shr-next-link)
    (define-key map [?\M-\t] 'shr-previous-link)
701 702 703 704 705 706
    map))

(defvar eww-textarea-map
  (let ((map (make-keymap)))
    (set-keymap-parent map text-mode-map)
    (define-key map "\r" 'forward-line)
707
    (define-key map [(control c) (control c)] 'eww-submit)
708 709
    (define-key map [?\t] 'shr-next-link)
    (define-key map [?\M-\t] 'shr-previous-link)
710 711 712 713 714
    map))

(defvar eww-select-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\r" 'eww-change-select)
715
    (define-key map [(control c) (control c)] 'eww-submit)
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
    map))

(defun eww-beginning-of-text ()
  "Move to the start of the input field."
  (interactive)
  (goto-char (eww-beginning-of-field)))

(defun eww-end-of-text ()
  "Move to the end of the text in the input field."
  (interactive)
  (goto-char (eww-end-of-field))
  (let ((start (eww-beginning-of-field)))
    (while (and (equal (following-char) ? )
		(> (point) start))
      (forward-char -1))
    (when (> (point) start)
      (forward-char 1))))

(defun eww-beginning-of-field ()
  (cond
   ((bobp)
    (point))
   ((not (eq (get-text-property (point) 'eww-form)
	     (get-text-property (1- (point)) 'eww-form)))
    (point))
   (t
    (previous-single-property-change
     (point) 'eww-form nil (point-min)))))

(defun eww-end-of-field ()
  (1- (next-single-property-change
       (point) 'eww-form nil (point-max))))

749 750 751 752 753 754 755
(defun eww-tag-form (cont)
  (let ((eww-form
	 (list (assq :method cont)
	       (assq :action cont)))
	(start (point)))
    (shr-ensure-paragraph)
    (shr-generic cont)
756 757 758
    (unless (bolp)
      (insert "\n"))
    (insert "\n")
759 760 761
    (when (> (point) start)
      (put-text-property start (1+ start)
			 'eww-form eww-form))))
762

763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
(defun eww-form-submit (cont)
  (let ((start (point))
	(value (cdr (assq :value cont))))
    (setq value
	  (if (zerop (length value))
	      "Submit"
	    value))
    (insert value)
    (add-face-text-property start (point) 'eww-form-submit)
    (put-text-property start (point) 'eww-form
		       (list :eww-form eww-form
			     :value value
			     :type "submit"
			     :name (cdr (assq :name cont))))
    (put-text-property start (point) 'keymap eww-submit-map)
    (insert " ")))

(defun eww-form-checkbox (cont)
  (let ((start (point)))
    (if (cdr (assq :checked cont))
783 784
	(insert eww-form-checkbox-selected-symbol)
      (insert eww-form-checkbox-symbol))
785 786 787 788 789 790 791 792 793 794
    (add-face-text-property start (point) 'eww-form-checkbox)
    (put-text-property start (point) 'eww-form
		       (list :eww-form eww-form
			     :value (cdr (assq :value cont))
			     :type (downcase (cdr (assq :type cont)))
			     :checked (cdr (assq :checked cont))
			     :name (cdr (assq :name cont))))
    (put-text-property start (point) 'keymap eww-checkbox-map)
    (insert " ")))

795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
(defun eww-form-file (cont)
  (let ((start (point))
	(value (cdr (assq :value cont))))
    (setq value
	  (if (zerop (length value))
	      " No file selected"
	    value))
    (insert "Browse")
    (add-face-text-property start (point) 'eww-form-file)
    (insert value)
    (put-text-property start (point) 'eww-form
		       (list :eww-form eww-form
			     :value (cdr (assq :value cont))
			     :type (downcase (cdr (assq :type cont)))
			     :name (cdr (assq :name cont))))
    (put-text-property start (point) 'keymap eww-submit-file)
    (insert " ")))

(defun eww-select-file ()
  "Change the value of the upload file menu under point."
  (interactive)
  (let*  ((input (get-text-property (point) 'eww-form)))
    (let ((filename
	   (let ((insert-default-directory t))
	     (read-file-name "filename:  "))))
      (eww-update-field filename (length "Browse"))
              (plist-put input :filename filename))))

823 824 825 826 827 828 829
(defun eww-form-text (cont)
  (let ((start (point))
	(type (downcase (or (cdr (assq :type cont))
			    "text")))
	(value (or (cdr (assq :value cont)) ""))
	(width (string-to-number
		(or (cdr (assq :size cont))
830 831 832 833 834
		    "40")))
        (readonly-property (if (or (cdr (assq :disabled cont))
                                   (cdr (assq :readonly cont)))
                               'read-only
                             'inhibit-read-only)))
835 836 837 838 839
    (insert value)
    (when (< (length value) width)
      (insert (make-string (- width (length value)) ? )))
    (put-text-property start (point) 'face 'eww-form-text)
    (put-text-property start (point) 'local-map eww-text-map)
840
    (put-text-property start (point) readonly-property t)
841
    (put-text-property start (point) 'eww-form
842 843 844 845
                       (list :eww-form eww-form
                             :value value
                             :type type
                             :name (cdr (assq :name cont))))
846 847
    (insert " ")))

848 849 850 851 852 853 854
(defconst eww-text-input-types '("text" "password" "textarea"
                                 "color" "date" "datetime" "datetime-local"
                                 "email" "month" "number" "search" "tel"
                                 "time" "url" "week")
  "List of input types which represent a text input.
See URL `https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input'.")

855
(defun eww-process-text-input (beg end length)
856
  (let* ((form (get-text-property (min (1+ end) (point-max)) 'eww-form))
857 858 859
	 (properties (text-properties-at end))
	 (type (plist-get form :type)))
    (when (and form
860
	       (member type eww-text-input-types))
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
      (cond
       ((zerop length)
	;; Delete some space at the end.
	(save-excursion
	  (goto-char
	   (if (equal type "textarea")
	       (1- (line-end-position))
	     (eww-end-of-field)))
	  (let ((new (- end beg)))
	    (while (and (> new 0)
			(eql (following-char) ? ))
	      (delete-region (point) (1+ (point)))
	      (setq new (1- new))))
	  (set-text-properties beg end properties)))
       ((> length 0)
	;; Add padding.
	(save-excursion
	  (goto-char
	   (if (equal type "textarea")
	       (1- (line-end-position))
	     (eww-end-of-field)))
	  (let ((start (point)))
	    (insert (make-string length ? ))
	    (set-text-properties start (point) properties)))))
      (let ((value (buffer-substring-no-properties
		    (eww-beginning-of-field)
		    (eww-end-of-field))))
	(when (string-match " +\\'" value)
	  (setq value (substring value 0 (match-beginning 0))))
	(plist-put form :value value)
	(when (equal type "password")
	  ;; Display passwords as asterisks.
	  (let ((start (eww-beginning-of-field)))
	    (put-text-property start (+ start (length value))
			       'display (make-string (length value) ?*))))))))
896

897
(defun eww-tag-textarea (cont)
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
  (let ((start (point))
	(value (or (cdr (assq :value cont)) ""))
	(lines (string-to-number
		(or (cdr (assq :rows cont))
		    "10")))
	(width (string-to-number
		(or (cdr (assq :cols cont))
		    "10")))
	end)
    (shr-ensure-newline)
    (insert value)
    (shr-ensure-newline)
    (when (< (count-lines start (point)) lines)
      (dotimes (i (- lines (count-lines start (point))))
	(insert "\n")))
    (setq end (point-marker))
    (goto-char start)
    (while (< (point) end)
      (end-of-line)
      (let ((pad (- width (- (point) (line-beginning-position)))))
	(when (> pad 0)
	  (insert (make-string pad ? ))))
      (add-face-text-property (line-beginning-position)
Kenjiro NAKAYAMA's avatar
Kenjiro NAKAYAMA committed
921
			      (point) 'eww-form-textarea)
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
      (put-text-property (line-beginning-position) (point)
			 'local-map eww-textarea-map)
      (forward-line 1))
    (put-text-property start (point) 'eww-form
		       (list :eww-form eww-form
			     :value value
			     :type "textarea"
			     :name (cdr (assq :name cont))))))

(defun eww-tag-input (cont)
  (let ((type (downcase (or (cdr (assq :type cont))
			     "text")))
	(start (point)))
    (cond
     ((or (equal type "checkbox")
	  (equal type "radio"))
      (eww-form-checkbox cont))
939 940
     ((equal type "file")
      (eww-form-file cont))
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
     ((equal type "submit")
      (eww-form-submit cont))
     ((equal type "hidden")
      (let ((form eww-form)
	    (name (cdr (assq :name cont))))
	;; Don't add <input type=hidden> elements repeatedly.
	(while (and form
		    (or (not (consp (car form)))
			(not (eq (caar form) 'hidden))
			(not (equal (plist-get (cdr (car form)) :name)
				    name))))
	  (setq form (cdr form)))
	(unless form
	  (nconc eww-form (list
			   (list 'hidden
				 :name name
				 :value (cdr (assq :value cont))))))))
     (t
      (eww-form-text cont)))
    (unless (= start (point))
      (put-text-property start (1+ start) 'help-echo "Input field"))))
962

963 964
(defun eww-tag-select (cont)
  (shr-ensure-paragraph)
965
  (let ((menu (list :name (cdr (assq :name cont))
966 967
		    :eww-form eww-form))
	(options nil)
968
	(start (point))
969 970 971 972 973 974 975 976
	(max 0)
	opelem)
    (if (eq (car (car cont)) 'optgroup)
	(dolist (groupelem cont)
	  (unless (cdr (assq :disabled (cdr groupelem)))
	    (setq opelem (append opelem (cdr (cdr groupelem))))))
      (setq opelem cont))
    (dolist (elem opelem)
977 978 979 980
      (when (eq (car elem) 'option)
	(when (cdr (assq :selected (cdr elem)))
	  (nconc menu (list :value
			    (cdr (assq :value (cdr elem))))))
981 982 983 984 985 986
	(let ((display (or (cdr (assq 'text (cdr elem))) "")))
	  (setq max (max max (length display)))
	  (push (list 'item
		      :value (cdr (assq :value (cdr elem)))
		      :display display)
		options))))
987
    (when options
988
      (setq options (nreverse options))
989
      ;; If we have no selected values, default to the first value.
990
      (unless (plist-get menu :value)
991 992
	(nconc menu (list :value (nth 2 (car options)))))
      (nconc menu options)
993 994 995 996 997 998
      (let ((selected (eww-select-display menu)))
	(insert selected
		(make-string (- max (length selected)) ? )))
      (put-text-property start (point) 'eww-form menu)
      (add-face-text-property start (point) 'eww-form-select)
      (put-text-property start (point) 'keymap eww-select-map)
999 1000
      (unless (= start (point))
       (put-text-property start (1+ start) 'help-echo "select field"))
1001
      (shr-ensure-paragraph))))
1002

1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
(defun eww-select-display (select)
  (let ((value (plist-get select :value))
	display)
    (dolist (elem select)
      (when (and (consp elem)
		 (eq (car elem) 'item)
		 (equal value (plist-get (cdr elem) :value)))
	(setq display (plist-get (cdr elem) :display))))
    display))

(defun eww-change-select ()
  "Change the value of the select drop-down menu under point."
  (interactive)
  (let* ((input (get-text-property (point) 'eww-form))
	 (completion-ignore-case t)
	 (options
	  (delq nil
		(mapcar (lambda (elem)
			  (and (consp elem)
			       (eq (car elem) 'item)
			       (cons (plist-get (cdr elem) :display)
				     (plist-get (cdr elem) :value))))
			input)))
	 (display
	  (completing-read "Change value: " options nil 'require-match))
	 (inhibit-read-only t))
    (plist-put input :value (cdr (assoc-string display options t)))
    (goto-char
     (eww-update-field display))))

1033 1034
(defun eww-update-field (string &optional offset)
  (if (not offset) (setq offset 0))
1035
  (let ((properties (text-properties-at (point)))
1036 1037 1038 1039 1040
	(start (+ (eww-beginning-of-field) offset))
	(current-end (1+ (eww-end-of-field)))
	(new-end (1+ (+ (eww-beginning-of-field) (length string)))))
    (delete-region <