eww.el 44.3 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

34 35 36
(defgroup eww nil
  "Emacs Web Wowser"
  :version "24.4"
37
  :link '(custom-manual "(eww) Top")
38 39 40 41 42 43 44
  :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."
45 46 47 48 49 50 51
  :version "24.4"
  :group 'eww
  :type 'string)

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

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

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

67 68 69 70 71 72 73 74
(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))

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
(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))

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
(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)

(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
111 112 113 114 115 116 117
  '((((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)

118 119 120 121 122 123 124 125
(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
126 127 128 129 130 131 132 133
(defface eww-form-textarea
  '((t (:background "#C0C0C0"
		    :foreground "black"
		    :box (:line-width 1))))
  "Face for eww textarea inputs."
  :version "24.4"
  :group 'eww)

134
(defvar eww-current-url nil)
135
(defvar eww-current-dom nil)
136
(defvar eww-current-source nil)
137 138
(defvar eww-current-title ""
  "Title of current page.")
139
(defvar eww-history nil)
140
(defvar eww-history-position 0)
141

142 143 144
(defvar eww-next-url nil)
(defvar eww-previous-url nil)
(defvar eww-up-url nil)
145 146 147
(defvar eww-home-url nil)
(defvar eww-start-url nil)
(defvar eww-contents-url nil)
148

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

152 153 154 155 156
(defvar eww-link-keymap
  (let ((map (copy-keymap shr-map)))
    (define-key map "\r" 'eww-follow-link)
    map))

157
;;;###autoload
158
(defun eww (url)
159 160 161 162
  "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: ")
163
  (cond ((string-match-p "\\`file:/" url))
164 165 166 167
        ((string-match-p "\\`ftp://" url)
         (user-error "FTP is not supported."))
        (t
         (if (and (= (length (split-string url)) 1)
168
                 (or (and (not (string-match-p "\\`[\"\'].*[\"\']\\'" url))
169
                          (> (length (split-string url "[.:]")) 1))
170
                     (string-match eww-local-regex url)))
171 172 173 174 175 176 177 178
             (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))))))
179 180
  (url-retrieve url 'eww-render (list url)))

181 182
;;;###autoload (defalias 'browse-web 'eww)

183 184 185 186
;;;###autoload
(defun eww-open-file (file)
  "Render a file using EWW."
  (interactive "fFile: ")
187 188 189 190
  (eww (concat "file://"
	       (and (memq system-type '(windows-nt ms-dos))
		    "/")
	       (expand-file-name file))))
191

192
(defun eww-render (status url &optional point)
193 194 195
  (let ((redirect (plist-get status :redirect)))
    (when redirect
      (setq url redirect)))
196 197 198 199 200 201 202 203
  (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)))
204 205
			(eww-detect-charset (equal (car content-type)
						   "text/html"))
206 207 208 209
			"utf8"))))
	 (data-buffer (current-buffer)))
    (unwind-protect
	(progn
210
          (setq eww-current-title "")
211
	  (cond
212 213 214 215
           ((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))
216
	   ((equal (car content-type) "text/html")
217
	    (eww-display-html charset url nil point))
218 219
	   ((equal (car content-type) "application/pdf")
	    (eww-display-pdf))
220
	   ((string-match-p "\\`image/" (car content-type))
221
	    (eww-display-image)
222
	    (eww-update-header-line-format))
223
	   (t
224 225
	    (eww-display-raw)
	    (eww-update-header-line-format)))
226
	  (setq eww-current-url url
227
		eww-history-position 0))
228 229 230 231
      (kill-buffer data-buffer))))

(defun eww-parse-headers ()
  (let ((headers nil))
232
    (goto-char (point-min))
233 234 235 236 237 238 239 240 241 242 243
    (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))

244 245 246 247 248
(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
249
	      "<meta[\t\n\r ]+[^>]*charset=\"?\\([^\t\n\r \"/>]+\\)[\\\"'.*]" nil t)
250 251 252 253 254 255
	     (goto-char pt)
	     (match-string 1))
	(and (looking-at
	      "[\t\n\r ]*<\\?xml[\t\n\r ]+[^>]*encoding=\"\\([^\"]+\\)")
	     (match-string 1)))))

256 257 258
(declare-function libxml-parse-html-region "xml.c"
		  (start end &optional base-url))

259
(defun eww-display-html (charset url &optional document point)
260 261
  (or (fboundp 'libxml-parse-html-region)
      (error "This function requires Emacs to be compiled with libxml2"))
262 263 264
  ;; There should be a better way to abort loading images
  ;; asynchronously.
  (setq url-queue nil)
265
  (let ((document
266 267 268
	 (or document
	     (list
	      'base (list (cons 'href url))
269 270 271 272 273 274 275 276
	      (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)))))
277
    (eww-setup-buffer)
278 279
    (setq eww-current-source source
	  eww-current-dom document)
280
    (let ((inhibit-read-only t)
281
	  (after-change-functions nil)
282
	  (shr-target-id (url-target (url-generic-parse-url url)))
283
	  (shr-external-rendering-functions
284 285
	   '((title . eww-tag-title)
	     (form . eww-tag-form)
286
	     (input . eww-tag-input)
287 288
	     (textarea . eww-tag-textarea)
	     (body . eww-tag-body)
289 290 291
	     (select . eww-tag-select)
	     (link . eww-tag-link)
	     (a . eww-tag-a))))
292 293 294 295 296
      (shr-insert-document document)
      (cond
       (point
	(goto-char point))
       (shr-target-id
297
	(goto-char (point-min))
298 299
	(let ((point (next-single-property-change
		      (point-min) 'shr-target-id)))
300 301
	  (when point
	    (goto-char point))))
302 303 304 305 306
       (t
	(goto-char (point-min)))))
    (setq eww-current-url url
	  eww-history-position 0)
    (eww-update-header-line-format)))
307

308 309 310
(defun eww-handle-link (cont)
  (let* ((rel (assq :rel cont))
  	(href (assq :href cont))
311 312 313
	(where (assoc
		;; The text associated with :rel is case-insensitive.
		(if rel (downcase (cdr rel)))
314
		      '(("next" . eww-next-url)
315 316
			;; Texinfo uses "previous", but HTML specifies
			;; "prev", so recognize both.
317
			("previous" . eww-previous-url)
318 319 320 321 322 323 324 325 326
			("prev" . eww-previous-url)
			;; 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.
			("start" . eww-start-url)
			("home" . eww-home-url)
			("contents" . eww-contents-url)
327 328 329 330 331 332 333 334 335 336 337
			("up" . eww-up-url)))))
    (and href
	 where
	 (set (cdr where) (cdr href)))))

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

(defun eww-tag-a (cont)
  (eww-handle-link cont)
338 339 340
  (let ((start (point)))
    (shr-tag-a cont)
    (put-text-property start (point) 'keymap eww-link-keymap)))
341

342 343
(defun eww-update-header-line-format ()
  (if eww-header-line-format
344 345 346
      (setq header-line-format
	    (replace-regexp-in-string
	     "%" "%%"
347 348
	     ;; FIXME?  Title can be blank.  Default to, eg, last component
	     ;; of url?
349 350 351
	     (format-spec eww-header-line-format
			  `((?u . ,eww-current-url)
			    (?t . ,eww-current-title)))))
352 353 354 355 356 357 358
    (setq header-line-format nil)))

(defun eww-tag-title (cont)
  (setq eww-current-title "")
  (dolist (sub cont)
    (when (eq (car sub) 'text)
      (setq eww-current-title (concat eww-current-title (cdr sub)))))
359 360 361 362
  (setq eww-current-title
	(replace-regexp-in-string
	 "^ \\| $" ""
	 (replace-regexp-in-string "[ \t\r\n]+" " " eww-current-title)))
363 364 365 366 367 368 369 370 371 372
  (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)
373
    (shr-colorize-region start (point) fgcolor bgcolor)))
374

375
(defun eww-display-raw ()
376 377 378 379 380 381 382
  (let ((data (buffer-substring (point) (point-max))))
    (eww-setup-buffer)
    (let ((inhibit-read-only t))
      (insert data))
    (goto-char (point-min))))

(defun eww-display-image ()
383
  (let ((data (shr-parse-image-data)))
384 385 386 387 388
    (eww-setup-buffer)
    (let ((inhibit-read-only t))
      (shr-put-image data nil))
    (goto-char (point-min))))

389 390 391 392 393 394 395 396 397 398
(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)))

399
(defun eww-setup-buffer ()
400
  (switch-to-buffer (get-buffer-create "*eww*"))
401
  (let ((inhibit-read-only t))
402
    (remove-overlays)
403
    (erase-buffer))
404
  (unless (eq major-mode 'eww-mode)
405 406 407 408 409 410 411
    (eww-mode))
  (setq-local eww-next-url nil)
  (setq-local eww-previous-url nil)
  (setq-local eww-up-url nil)
  (setq-local eww-home-url nil)
  (setq-local eww-start-url nil)
  (setq-local eww-contents-url nil))
412

413
(defun eww-view-source ()
414
  "View the HTML source code of the current page."
415 416 417 418 419
  (interactive)
  (let ((buf (get-buffer-create "*eww-source*"))
        (source eww-current-source))
    (with-current-buffer buf
      (delete-region (point-min) (point-max))
420
      (insert (or source "no source"))
421
      (goto-char (point-min))
422
      (when (fboundp 'html-mode)
423 424 425
        (html-mode)))
    (view-buffer buf)))

426 427 428 429 430 431 432 433 434 435
(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)
  (let* ((source eww-current-source)
	 (dom (shr-transform-dom
	       (with-temp-buffer
		 (insert source)
436 437 438
		 (condition-case nil
		     (decode-coding-region (point-min) (point-max) 'utf-8)
		   (coding-system-error nil))
439 440
		 (libxml-parse-html-region (point-min) (point-max))))))
    (eww-score-readability dom)
441
    (eww-save-history)
442 443 444
    (eww-display-html nil nil
		      (shr-retransform-dom
		       (eww-highest-readability dom)))
445 446 447 448 449 450 451 452 453
    (setq eww-current-source source)))

(defun eww-score-readability (node)
  (let ((score -1))
    (cond
     ((memq (car node) '(script head))
      (setq score -2))
     ((eq (car node) 'meta)
      (setq score -1))
454 455
     ((eq (car node) 'img)
      (setq score 2))
456 457 458 459 460 461
     ((eq (car node) 'a)
      (setq score (- (length (split-string
			      (or (cdr (assoc 'text (cdr node))) ""))))))
     (t
      (dolist (elem (cdr node))
	(cond
462 463
	 ((and (stringp (cdr elem))
	       (eq (car elem) 'text))
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
	  (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))

488 489 490
(defvar eww-mode-map
  (let ((map (make-sparse-keymap)))
    (suppress-keymap map)
491
    (define-key map "q" 'quit-window)
492
    (define-key map "g" 'eww-reload)
493 494
    (define-key map [?\t] 'shr-next-link)
    (define-key map [?\M-\t] 'shr-previous-link)
495
    (define-key map [delete] 'scroll-down-command)
496
    (define-key map [?\S-\ ] 'scroll-down-command)
497 498
    (define-key map "\177" 'scroll-down-command)
    (define-key map " " 'scroll-up-command)
499
    (define-key map "l" 'eww-back-url)
500
    (define-key map "r" 'eww-forward-url)
501
    (define-key map "n" 'eww-next-url)
502
    (define-key map "p" 'eww-previous-url)
503 504
    (define-key map "u" 'eww-up-url)
    (define-key map "t" 'eww-top-url)
505
    (define-key map "&" 'eww-browse-with-external-browser)
506
    (define-key map "d" 'eww-download)
507
    (define-key map "w" 'eww-copy-page-url)
508
    (define-key map "C" 'url-cookie-list)
509
    (define-key map "v" 'eww-view-source)
510
    (define-key map "R" 'eww-readable)
511
    (define-key map "H" 'eww-list-histories)
512

513 514 515 516 517
    (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)

518
    (easy-menu-define nil map ""
519
      '("Eww"
520
	["Exit" quit-window t]
521
	["Close browser" quit-window t]
522 523 524 525 526 527 528
	["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]
529
	["View page source" eww-view-source]
530
	["Copy page URL" eww-copy-page-url t]
531
	["List histories" eww-list-histories t]
532
	["Add bookmark" eww-add-bookmark t]
Kenjiro NAKAYAMA's avatar
Kenjiro NAKAYAMA committed
533
	["List bookmarks" eww-list-bookmarks t]
534
	["List cookies" url-cookie-list t]))
535 536
    map))

537 538 539
(defvar eww-tool-bar-map
  (let ((map (make-sparse-keymap)))
    (dolist (tool-bar-item
540
             '((quit-window . "close")
541 542 543 544 545 546 547 548 549 550 551
               (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'.")

552
(define-derived-mode eww-mode nil "eww"
553 554 555
  "Mode for browsing the web.

\\{eww-mode-map}"
556
  ;; FIXME?  This seems a strange default.
557 558 559
  (setq-local eww-current-url 'author)
  (setq-local eww-current-dom nil)
  (setq-local eww-current-source nil)
560
  (setq-local eww-current-title "")
561 562 563 564 565 566
  (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))
567
  (buffer-disable-undo)
568 569
  ;;(setq buffer-read-only t)
  )
570

571
;;;###autoload
Daniel Hackney's avatar
Daniel Hackney committed
572
(defun eww-browse-url (url &optional _new-window)
573 574
  (when (and (equal major-mode 'eww-mode)
	     eww-current-url)
575
    (eww-save-history))
576
  (eww url))
577

578
(defun eww-back-url ()
579 580
  "Go to the previously displayed page."
  (interactive)
581
  (when (>= eww-history-position (length eww-history))
582
    (user-error "No previous page"))
583 584 585
  (eww-save-history)
  (setq eww-history-position (+ eww-history-position 2))
  (eww-restore-history (elt eww-history (1- eww-history-position))))
586 587 588 589 590

(defun eww-forward-url ()
  "Go to the next displayed page."
  (interactive)
  (when (zerop eww-history-position)
591
    (user-error "No next page"))
592 593
  (eww-save-history)
  (eww-restore-history (elt eww-history (1- eww-history-position))))
594 595 596

(defun eww-restore-history (elem)
  (let ((inhibit-read-only t))
597
    (erase-buffer)
598
    (insert (plist-get elem :text))
599 600
    (setq eww-current-source (plist-get elem :source)
	  eww-current-dom (plist-get elem :dom))
601
    (goto-char (plist-get elem :point))
602
    (setq eww-current-url (plist-get elem :url)
603 604
	  eww-current-title (plist-get elem :title))
    (eww-update-header-line-format)))
605

606 607 608 609 610 611 612
(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)
  (if eww-next-url
      (eww-browse-url (shr-expand-url eww-next-url eww-current-url))
613
    (user-error "No `next' on this page")))
614 615 616 617 618 619 620 621

(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)
  (if eww-previous-url
      (eww-browse-url (shr-expand-url eww-previous-url eww-current-url))
622
    (user-error "No `previous' on this page")))
623 624 625 626 627 628 629 630

(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)
  (if eww-up-url
      (eww-browse-url (shr-expand-url eww-up-url eww-current-url))
631
    (user-error "No `up' on this page")))
632 633 634

(defun eww-top-url ()
  "Go to the page marked `top'.
635 636
A page is marked `top' if rel=\"start\", rel=\"home\", or rel=\"contents\"
appears in a <link> or <a> tag."
637
  (interactive)
638 639 640 641 642
  (let ((best-url (or eww-start-url
		      eww-contents-url
		      eww-home-url)))
    (if best-url
	(eww-browse-url (shr-expand-url best-url eww-current-url))
643
      (user-error "No `top' for this page"))))
644

645 646 647 648 649 650
(defun eww-reload ()
  "Reload the current page."
  (interactive)
  (url-retrieve eww-current-url 'eww-render
		(list eww-current-url (point))))

651 652 653 654
;; Form support.

(defvar eww-form nil)

655 656 657
(defvar eww-submit-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\r" 'eww-submit)
658
    (define-key map [(control c) (control c)] 'eww-submit)
659 660 661 662
    map))

(defvar eww-checkbox-map
  (let ((map (make-sparse-keymap)))
Kenjiro NAKAYAMA's avatar
Kenjiro NAKAYAMA committed
663
    (define-key map " " 'eww-toggle-checkbox)
664
    (define-key map "\r" 'eww-toggle-checkbox)
665
    (define-key map [(control c) (control c)] 'eww-submit)
666 667 668 669 670 671 672
    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)
673
    (define-key map [(control c) (control c)] 'eww-submit)
674
    (define-key map [(control e)] 'eww-end-of-text)
675 676
    (define-key map [?\t] 'shr-next-link)
    (define-key map [?\M-\t] 'shr-previous-link)
677 678 679 680 681 682
    map))

(defvar eww-textarea-map
  (let ((map (make-keymap)))
    (set-keymap-parent map text-mode-map)
    (define-key map "\r" 'forward-line)
683
    (define-key map [(control c) (control c)] 'eww-submit)
684 685
    (define-key map [?\t] 'shr-next-link)
    (define-key map [?\M-\t] 'shr-previous-link)
686 687 688 689 690
    map))

(defvar eww-select-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\r" 'eww-change-select)
691
    (define-key map [(control c) (control c)] 'eww-submit)
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
    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))))

725 726 727 728 729 730 731
(defun eww-tag-form (cont)
  (let ((eww-form
	 (list (assq :method cont)
	       (assq :action cont)))
	(start (point)))
    (shr-ensure-paragraph)
    (shr-generic cont)
732 733 734
    (unless (bolp)
      (insert "\n"))
    (insert "\n")
735 736 737
    (when (> (point) start)
      (put-text-property start (1+ start)
			 'eww-form eww-form))))
738

739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
(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))
759 760
	(insert eww-form-checkbox-selected-symbol)
      (insert eww-form-checkbox-symbol))
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
    (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 " ")))

(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))
778 779 780 781 782
		    "40")))
        (readonly-property (if (or (cdr (assq :disabled cont))
                                   (cdr (assq :readonly cont)))
                               'read-only
                             'inhibit-read-only)))
783 784 785 786 787
    (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)
788
    (put-text-property start (point) readonly-property t)
789
    (put-text-property start (point) 'eww-form
790 791 792 793
                       (list :eww-form eww-form
                             :value value
                             :type type
                             :name (cdr (assq :name cont))))
794 795
    (insert " ")))

796 797 798 799 800 801 802
(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'.")

803
(defun eww-process-text-input (beg end length)
804
  (let* ((form (get-text-property (min (1+ end) (point-max)) 'eww-form))
805 806 807
	 (properties (text-properties-at end))
	 (type (plist-get form :type)))
    (when (and form
808
	       (member type eww-text-input-types))
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
      (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) ?*))))))))
844

845
(defun eww-tag-textarea (cont)
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
  (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
869
			      (point) 'eww-form-textarea)
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 896 897 898 899 900 901 902 903 904 905 906 907
      (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))
     ((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"))))
908

909 910
(defun eww-tag-select (cont)
  (shr-ensure-paragraph)
911
  (let ((menu (list :name (cdr (assq :name cont))
912 913
		    :eww-form eww-form))
	(options nil)
914
	(start (point))
915 916 917 918 919 920 921 922
	(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)
923 924 925 926
      (when (eq (car elem) 'option)
	(when (cdr (assq :selected (cdr elem)))
	  (nconc menu (list :value
			    (cdr (assq :value (cdr elem))))))
927 928 929 930 931 932
	(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))))
933
    (when options
934
      (setq options (nreverse options))
935
      ;; If we have no selected values, default to the first value.
936
      (unless (plist-get menu :value)
937 938
	(nconc menu (list :value (nth 2 (car options)))))
      (nconc menu options)
939 940 941 942 943 944
      (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)
945 946
      (unless (= start (point))
       (put-text-property start (1+ start) 'help-echo "select field"))
947
      (shr-ensure-paragraph))))
948

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
(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))))

(defun eww-update-field (string)
  (let ((properties (text-properties-at (point)))
	(start (eww-beginning-of-field))
	(end (1+ (eww-end-of-field))))
    (delete-region start end)
    (insert string
	    (make-string (- (- end start) (length string)) ? ))
    (set-text-properties start end properties)
    start))

(defun eww-toggle-checkbox ()
  "Toggle the value of the checkbox under point."
  (interactive)
  (let* ((input (get-text-property (point) 'eww-form))
	 (type (plist-get input :type)))
    (if (equal type "checkbox")
	(goto-char
	 (1+
	  (if (plist-get input :checked)
	      (progn
		(plist-put input :checked nil)
1000
		(eww-update-field eww-form-checkbox-symbol))
1001
	    (plist-put input :checked t)
1002
	    (eww-update-field eww-form-checkbox-selected-symbol))))
1003 1004 1005 1006 1007 1008 1009 1010 1011
      ;; Radio button.  Switch all other buttons off.
      (let ((name (plist-get input :name)))
	(save-excursion
	  (dolist (elem (eww-inputs (plist-get input :eww-form)))
	    (when (equal (plist-get (cdr elem) :name) name)
	      (goto-char (car elem))
	      (if (not (eq (cdr elem) input))
		  (progn
		    (plist-put input :checked nil)
1012
		    (eww-update-field eww-form-checkbox-symbol))
1013
		(plist-put input :checked t)
1014
		(eww-update-field eww-form-checkbox-selected-symbol)))))
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
	(forward-char 1)))))

(defun eww-inputs (form)
  (let ((start (point-min))
	(inputs nil))
    (while (and start
		(< start (point-max)))
      (when (or (get-text-property start 'eww-form)
		(setq start (next-single-property-change start 'eww-form)))
	(when (eq (plist-get (get-text-property start 'eww-form) :eww-form)
		  form)
	  (push (cons start (get-text-property start 'eww-form))
		inputs))
	(setq start (next-single-property-change start 'eww-form))))
    (nreverse inputs)))

(defun eww-input-value (input)
  (let ((type (plist-get input :type))
	(value (plist-get input :value)))
    (cond
     ((equal type "textarea")
      (with-temp-buffer
	(insert value)
	(goto-char (point-min))
	(while (re-search-forward "^ +\n\\| +$" nil t)
	  (replace-match "" t t))
	(buffer-string)))
     (t
      (if (string-match " +\\'" value)
	  (substring value 0 (match-beginning 0))
	value)))))

(defun eww-submit ()
  "Submit the current form."
  (interactive)
  (let* ((this-input (get-text-property (point) 'eww-form))
	 (form (plist-get this-input :eww-form))
	 values next-submit)
    (dolist (elem (sort (eww-inputs form)
			 (lambda (o1 o2)
			   (< (car o1) (car o2)))))
      (let* ((input (cdr elem))
	     (input-start (car elem))
	     (name (plist-get input :name)))
	(when name
	  (cond
	   ((member (plist-get input :type) '("checkbox" "radio"))
	    (when (plist-get input :checked)
	      (push (cons name (plist-get input :value))
		    values)))
	   ((equal (plist-get input :type) "submit")
	    ;; We want the values from buttons if we hit a button if
	    ;; we hit enter on it, or if it's the first button after
	    ;; the field we did hit return on.
	    (when (or (eq input this-input)
		      (and (not (eq input this-input))
			   (null next-submit)
			   (> input-start (point))))
	      (setq next-submit t)
	      (push (cons name (plist-get input :value))
		    values)))
	   (t
	    (push (cons name (eww-input-value input))
		  values))))))
1079 1080 1081 1082
    (dolist (elem form)
      (when (and (consp elem)
		 (eq (car elem) 'hidden))
	(push (cons (plist-get (cdr elem) :name)
1083
		    (or (plist-get (cdr elem) :value) ""))
1084
	      values)))
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
    (if (and (stringp (cdr (assq :method form)))
	     (equal (downcase (cdr (assq :method form))) "post"))
	(let ((url-request-method "POST")
	      (url-request-extra-headers
	       '(("Content-Type" . "application/x-www-form-urlencoded")))
	      (url-request-data (mm-url-encode-www-form-urlencoded values)))
	  (eww-browse-url (shr-expand-url (cdr (assq :action form))
					  eww-current-url)))
      (eww-browse-url
       (concat
	(if (cdr (assq :action form))
	    (shr-expand-url (cdr (assq :action form))
			    eww-current-url)
	  eww-current-url)
	"?"
	(mm-url-encode-www-form-urlencoded values))))))
1101

1102
(defun eww-browse-with-external-browser (&optional url)
1103