eww.el 55.7 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 'url-util)			; for url-get-url-at-point
33
(require 'mm-url)
34
(eval-when-compile (require 'subr-x)) ;; for string-trim
35

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

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

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

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

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
(defcustom eww-suggest-uris
  '(eww-links-at-point
    url-get-url-at-point
    eww-current-url)
  "List of functions called to form the list of default URIs for `eww'.
Each of the elements is a function returning either a string or a list
of strings.  The results will be joined into a single list with
duplicate entries (if any) removed."
  :version "25.1"
  :group 'eww
  :type 'hook
  :options '(eww-links-at-point
	     url-get-url-at-point
	     eww-current-url))

78 79
(defcustom eww-bookmarks-directory user-emacs-directory
  "Directory where bookmark files will be stored."
Stefan Monnier's avatar
Stefan Monnier committed
80
  :version "25.1"
81 82 83
  :group 'eww
  :type 'string)

Ivan Shmakov's avatar
Ivan Shmakov committed
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
(defcustom eww-desktop-remove-duplicates t
  "Whether to remove duplicates from the history when saving desktop data.
If non-nil, repetitive EWW history entries (comprising of the URI, the
title, and the point position) will not be saved as part of the Emacs
desktop.  Otherwise, such entries will be retained."
  :version "25.1"
  :group 'eww
  :type 'boolean)

(defcustom eww-restore-desktop nil
  "How to restore EWW buffers on `desktop-restore'.
If t or 'auto, the buffers will be reloaded automatically.
If nil, buffers will require manual reload, and will contain the text
specified in `eww-restore-reload-prompt' instead of the actual Web
page contents."
  :version "25.1"
  :group 'eww
  :type '(choice (const :tag "Restore all automatically" t)
                 (const :tag "Require manual reload" nil)))

(defcustom eww-restore-reload-prompt
  "\n\n *** Use \\[eww-reload] to reload this buffer. ***\n"
  "The string to put in the buffers not reloaded on `desktop-restore'.
This prompt will be used if `eww-restore-desktop' is nil.

The string will be passed through `substitute-command-keys'."
  :version "25.1"
  :group 'eww
  :type 'string)

114 115 116 117 118 119
(defcustom eww-history-limit 50
  "Maximum number of entries to retain in the history."
  :version "25.1"
  :group 'eww
  :type '(choice (const :tag "Unlimited" nil)
                 integer))
120

121 122 123 124 125 126 127 128
(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))

129 130 131 132 133 134
(defcustom eww-after-render-hook nil
  "A hook called after eww has finished rendering the buffer."
  :version "25.1"
  :group 'eww
  :type 'hook)

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
(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))

154 155 156 157 158 159 160 161
(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)

162 163 164 165 166
(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."
167
  :version "25.1"
168
  :group 'eww)
169

170 171 172 173 174 175 176 177 178
(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
179 180 181 182 183 184 185
  '((((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)

186 187 188 189 190 191 192 193
(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
194 195 196 197 198 199 200 201
(defface eww-form-textarea
  '((t (:background "#C0C0C0"
		    :foreground "black"
		    :box (:line-width 1))))
  "Face for eww textarea inputs."
  :version "24.4"
  :group 'eww)

202
(defvar eww-data nil)
203
(defvar eww-history nil)
204
(defvar eww-history-position 0)
205

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

209 210 211 212 213
(defvar eww-link-keymap
  (let ((map (copy-keymap shr-map)))
    (define-key map "\r" 'eww-follow-link)
    map))

214 215 216 217 218 219 220 221 222 223 224 225 226
(defun eww-suggested-uris nil
  "Return the list of URIs to suggest at the `eww' prompt.
This list can be customized via `eww-suggest-uris'."
  (let ((obseen (make-vector 42 0))
	(uris nil))
    (dolist (fun eww-suggest-uris)
      (let ((ret (funcall fun)))
	(dolist (uri (if (stringp ret) (list ret) ret))
	  (when (and uri (not (intern-soft uri obseen)))
	    (intern uri obseen)
	    (push   uri uris)))))
    (nreverse uris)))

227
;;;###autoload
228
(defun eww (url)
229 230 231
  "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'."
232 233 234 235 236 237
  (interactive
   (let* ((uris (eww-suggested-uris))
	  (prompt (concat "Enter URL or keywords"
			  (if uris (format " (default %s)" (car uris)) "")
			  ": ")))
     (list (read-string prompt nil nil uris))))
238
  (setq url (string-trim url))
239
  (cond ((string-match-p "\\`file:/" url))
240
	;; Don't mangle file: URLs at all.
241 242 243 244
        ((string-match-p "\\`ftp://" url)
         (user-error "FTP is not supported."))
        (t
         (if (and (= (length (split-string url)) 1)
245 246 247
		  (or (and (not (string-match-p "\\`[\"\'].*[\"\']\\'" url))
			   (> (length (split-string url "[.:]")) 1))
		      (string-match eww-local-regex url)))
248 249 250 251 252 253 254 255
             (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))))))
256 257
  (unless (eq major-mode 'eww-mode)
    (eww-setup-buffer)
258
    (plist-put eww-data :url url)
259 260
    (eww-update-header-line-format)
    (let ((inhibit-read-only t))
261 262
      (insert (format "Loading %s..." url))
      (goto-char (point-min))))
263
  (url-retrieve url 'eww-render
264
		(list url nil (current-buffer))))
265

266 267
;;;###autoload (defalias 'browse-web 'eww)

268 269 270 271
;;;###autoload
(defun eww-open-file (file)
  "Render a file using EWW."
  (interactive "fFile: ")
272 273 274 275
  (eww (concat "file://"
	       (and (memq system-type '(windows-nt ms-dos))
		    "/")
	       (expand-file-name file))))
276

277 278
;;;###autoload
(defun eww-search-words (&optional beg end)
279 280
  "Search the web for the text between the point and marker.
See the `eww-search-prefix' variable for the search engine used."
281 282 283
  (interactive "r")
  (eww (buffer-substring beg end)))

284
(defun eww-render (status url &optional point buffer encode)
285 286 287
  (let ((redirect (plist-get status :redirect)))
    (when redirect
      (setq url redirect)))
288 289 290 291 292 293 294 295
  (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)))
296 297
			(eww-detect-charset (equal (car content-type)
						   "text/html"))
298
			"utf-8"))))
299 300 301 302
	 (data-buffer (current-buffer)))
    (unwind-protect
	(progn
	  (cond
303 304 305 306
           ((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))
307
	   ((equal (car content-type) "text/html")
308
	    (eww-display-html charset url nil point buffer encode))
309 310
	   ((equal (car content-type) "application/pdf")
	    (eww-display-pdf))
311
	   ((string-match-p "\\`image/" (car content-type))
312
	    (eww-display-image buffer))
313
	   (t
314 315 316 317 318 319
	    (eww-display-raw buffer encode)))
	  (with-current-buffer buffer
	    (plist-put eww-data :url url)
	    (eww-update-header-line-format)
	    (setq eww-history-position 0)
	    (run-hooks 'eww-after-render-hook)))
320 321 322 323
      (kill-buffer data-buffer))))

(defun eww-parse-headers ()
  (let ((headers nil))
324
    (goto-char (point-min))
325 326 327 328 329 330 331 332 333 334 335
    (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))

336 337 338 339 340
(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
341
	      "<meta[\t\n\r ]+[^>]*charset=\"?\\([^\t\n\r \"/>]+\\)[\\\"'.*]" nil t)
342 343 344 345 346 347
	     (goto-char pt)
	     (match-string 1))
	(and (looking-at
	      "[\t\n\r ]*<\\?xml[\t\n\r ]+[^>]*encoding=\"\\([^\"]+\\)")
	     (match-string 1)))))

348 349 350
(declare-function libxml-parse-html-region "xml.c"
		  (start end &optional base-url))

351
(defun eww-display-html (charset url &optional document point buffer encode)
352 353 354 355
  (unless (fboundp 'libxml-parse-html-region)
    (error "This function requires Emacs to be compiled with libxml2"))
  (unless (buffer-live-p buffer)
    (error "Buffer %s doesn't exist" buffer))
356 357 358
  ;; There should be a better way to abort loading images
  ;; asynchronously.
  (setq url-queue nil)
359
  (let ((document
360 361 362
	 (or document
	     (list
	      'base (list (cons 'href url))
363
	      (progn
364 365 366
		(when (or (and encode
			       (not (eq charset encode)))
			  (not (eq charset 'utf-8)))
367
		  (condition-case nil
368 369
		      (decode-coding-region (point) (point-max)
					    (or encode charset))
370 371 372 373
		    (coding-system-error nil)))
		(libxml-parse-html-region (point) (point-max))))))
	(source (and (null document)
		     (buffer-substring (point) (point-max)))))
374 375 376 377
    (with-current-buffer buffer
      (plist-put eww-data :source source)
      (plist-put eww-data :dom document)
      (let ((inhibit-read-only t)
378
	    (inhibit-modification-hooks t)
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
	    (shr-target-id (url-target (url-generic-parse-url url)))
	    (shr-external-rendering-functions
	     '((title . eww-tag-title)
	       (form . eww-tag-form)
	       (input . eww-tag-input)
	       (textarea . eww-tag-textarea)
	       (body . eww-tag-body)
	       (select . eww-tag-select)
	       (link . eww-tag-link)
	       (a . eww-tag-a))))
	(erase-buffer)
	(shr-insert-document document)
	(cond
	 (point
	  (goto-char point))
	 (shr-target-id
	  (goto-char (point-min))
	  (let ((point (next-single-property-change
			(point-min) 'shr-target-id)))
	    (when point
	      (goto-char point))))
	 (t
	  (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)))))
407
      (eww-size-text-inputs))))
408

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
(defun eww-handle-link (dom)
  (let* ((rel (dom-attr dom 'rel))
	 (href (dom-attr dom 'href))
	 (where (assoc
		 ;; The text associated with :rel is case-insensitive.
		 (if rel (downcase rel))
		 '(("next" . :next)
		   ;; Texinfo uses "previous", but HTML specifies
		   ;; "prev", so recognize both.
		   ("previous" . :previous)
		   ("prev" . :previous)
		   ;; 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" . :start)
		   ("home" . :home)
		   ("contents" . :contents)
		   ("up" . up)))))
429 430
    (and href
	 where
431
	 (plist-put eww-data (cdr where) href))))
432

433 434 435
(defun eww-tag-link (dom)
  (eww-handle-link dom)
  (shr-generic dom))
436

437 438
(defun eww-tag-a (dom)
  (eww-handle-link dom)
439
  (let ((start (point)))
440
    (shr-tag-a dom)
441
    (put-text-property start (point) 'keymap eww-link-keymap)))
442

443 444
(defun eww-update-header-line-format ()
  (if eww-header-line-format
445 446 447
      (setq header-line-format
	    (replace-regexp-in-string
	     "%" "%%"
448 449
	     ;; FIXME?  Title can be blank.  Default to, eg, last component
	     ;; of url?
450
	     (format-spec eww-header-line-format
451
			  `((?u . ,(or (plist-get eww-data :url) ""))
452
			    (?t . ,(or (plist-get eww-data :title) ""))))))
453 454
    (setq header-line-format nil)))

455
(defun eww-tag-title (dom)
456 457 458 459
  (plist-put eww-data :title
	     (replace-regexp-in-string
	      "^ \\| $" ""
	      (replace-regexp-in-string "[ \t\r\n]+" " " (dom-text dom))))
460 461
  (eww-update-header-line-format))

462
(defun eww-tag-body (dom)
463
  (let* ((start (point))
464 465
	 (fgcolor (or (dom-attr dom 'fgcolor) (dom-attr dom 'text)))
	 (bgcolor (dom-attr dom 'bgcolor))
466 467
	 (shr-stylesheet (list (cons 'color fgcolor)
			       (cons 'background-color bgcolor))))
468
    (shr-generic dom)
469
    (shr-colorize-region start (point) fgcolor bgcolor)))
470

471
(defun eww-display-raw (buffer &optional encode)
472
  (let ((data (buffer-substring (point) (point-max))))
473 474 475 476 477 478 479 480 481 482 483 484 485 486
    (unless (buffer-live-p buffer)
      (error "Buffer %s doesn't exist" buffer))
    (with-current-buffer buffer
      (let ((inhibit-read-only t))
	(erase-buffer)
	(insert data)
	(unless (eq encode 'utf-8)
	  (encode-coding-region (point-min) (1+ (length data)) 'utf-8)
	  (condition-case nil
	      (decode-coding-region (point-min) (1+ (length data)) encode)
	    (coding-system-error nil))))
      (goto-char (point-min)))))

(defun eww-display-image (buffer)
487
  (let ((data (shr-parse-image-data)))
488 489 490 491 492 493 494
    (unless (buffer-live-p buffer)
      (error "Buffer %s doesn't exist" buffer))
    (with-current-buffer buffer
      (let ((inhibit-read-only t))
	(erase-buffer)
	(shr-put-image data nil))
      (goto-char (point-min)))))
495

496
(declare-function mailcap-view-mime "mailcap" (type))
497 498 499 500 501 502 503
(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)
504
      (mailcap-view-mime "application/pdf")))
505 506
  (goto-char (point-min)))

507 508
(defun eww-setup-buffer ()
  (switch-to-buffer (get-buffer-create "*eww*"))
509
  (let ((inhibit-read-only t))
510
    (remove-overlays)
511
    (erase-buffer))
512
  (unless (eq major-mode 'eww-mode)
513
    (eww-mode)))
514

515 516 517 518 519 520 521 522 523 524
(defun eww-current-url nil
  "Return URI of the Web page the current EWW buffer is visiting."
  (plist-get eww-data :url))

(defun eww-links-at-point (&optional pt)
  "Return list of URIs, if any, linked at point."
  (remq nil
	(list (get-text-property (point) 'shr-url)
	      (get-text-property (point) 'image-url))))

525
(defun eww-view-source ()
526
  "View the HTML source code of the current page."
527 528
  (interactive)
  (let ((buf (get-buffer-create "*eww-source*"))
529
        (source (plist-get eww-data :source)))
530
    (with-current-buffer buf
531 532 533 534 535 536
      (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))))
537 538
    (view-buffer buf)))

539 540 541 542 543 544
(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)
545
  (let* ((old-data eww-data)
546 547 548 549 550 551
	 (dom (with-temp-buffer
		(insert (plist-get old-data :source))
		(condition-case nil
		    (decode-coding-region (point-min) (point-max) 'utf-8)
		  (coding-system-error nil))
		(libxml-parse-html-region (point-min) (point-max)))))
552
    (eww-score-readability dom)
553
    (eww-save-history)
554
    (eww-display-html nil nil
555
		      (eww-highest-readability dom)
556
		      nil (current-buffer))
557 558 559
    (dolist (elem '(:source :url :title :next :previous :up))
      (plist-put eww-data elem (plist-get old-data elem)))
    (eww-update-header-line-format)))
560 561 562 563

(defun eww-score-readability (node)
  (let ((score -1))
    (cond
564
     ((memq (dom-tag node) '(script head comment))
565
      (setq score -2))
566
     ((eq (dom-tag node) 'meta)
567
      (setq score -1))
568
     ((eq (dom-tag node) 'img)
569
      (setq score 2))
570 571
     ((eq (dom-tag node) 'a)
      (setq score (- (length (split-string (dom-text node))))))
572
     (t
573 574 575
      (dolist (elem (dom-children node))
	(if (stringp elem)
	    (setq score (+ score (length (split-string elem))))
576 577
	  (setq score (+ score
			 (or (cdr (assoc :eww-readability-score (cdr elem)))
578
			     (eww-score-readability elem))))))))
579
    ;; Cache the score of the node to avoid recomputing all the time.
580
    (dom-set-attribute node :eww-readability-score score)
581 582 583 584 585
    score))

(defun eww-highest-readability (node)
  (let ((result node)
	highest)
586 587 588 589 590 591 592
    (dolist (elem (dom-non-text-children node))
      (when (> (or (dom-attr
		    (setq highest (eww-highest-readability elem))
		    :eww-readability-score)
		   most-negative-fixnum)
	       (or (dom-attr result :eww-readability-score)
		   most-negative-fixnum))
593 594 595
	(setq result highest)))
    result))

596 597 598
(defvar eww-mode-map
  (let ((map (make-sparse-keymap)))
    (suppress-keymap map)
599
    (define-key map "q" 'quit-window)
600
    (define-key map "g" 'eww-reload)
601
    (define-key map "G" 'eww)
602 603
    (define-key map [?\t] 'shr-next-link)
    (define-key map [?\M-\t] 'shr-previous-link)
604
    (define-key map [backtab] 'shr-previous-link)
605
    (define-key map [delete] 'scroll-down-command)
606
    (define-key map [?\S-\ ] 'scroll-down-command)
607 608
    (define-key map "\177" 'scroll-down-command)
    (define-key map " " 'scroll-up-command)
609
    (define-key map "l" 'eww-back-url)
610
    (define-key map "r" 'eww-forward-url)
611
    (define-key map "n" 'eww-next-url)
612
    (define-key map "p" 'eww-previous-url)
613 614
    (define-key map "u" 'eww-up-url)
    (define-key map "t" 'eww-top-url)
615
    (define-key map "&" 'eww-browse-with-external-browser)
616
    (define-key map "d" 'eww-download)
617
    (define-key map "w" 'eww-copy-page-url)
618
    (define-key map "C" 'url-cookie-list)
619
    (define-key map "v" 'eww-view-source)
620
    (define-key map "R" 'eww-readable)
621
    (define-key map "H" 'eww-list-histories)
622
    (define-key map "E" 'eww-set-character-encoding)
623

624 625 626 627 628
    (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)

629
    (easy-menu-define nil map ""
630
      '("Eww"
631
	["Exit" quit-window t]
632
	["Close browser" quit-window t]
633 634 635 636 637 638 639
	["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]
640
	["View page source" eww-view-source]
641
	["Copy page URL" eww-copy-page-url t]
642
	["List histories" eww-list-histories t]
643
	["Add bookmark" eww-add-bookmark t]
Kenjiro NAKAYAMA's avatar
Kenjiro NAKAYAMA committed
644
	["List bookmarks" eww-list-bookmarks t]
645 646
	["List cookies" url-cookie-list t]
       ["Character Encoding" eww-set-character-encoding]))
647 648
    map))

649 650 651
(defvar eww-tool-bar-map
  (let ((map (make-sparse-keymap)))
    (dolist (tool-bar-item
652
             '((quit-window . "close")
653 654 655 656 657 658 659 660 661 662 663
               (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'.")

664
(define-derived-mode eww-mode nil "eww"
665 666 667
  "Mode for browsing the web.

\\{eww-mode-map}"
668
  (setq-local eww-data (list :title ""))
669 670 671 672 673 674
  (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))
Ivan Shmakov's avatar
Ivan Shmakov committed
675 676
  ;; desktop support
  (setq-local desktop-save-buffer 'eww-desktop-misc-data)
677
  (buffer-disable-undo)
678
  (setq buffer-read-only t))
679

680
;;;###autoload
681 682 683 684 685 686 687 688 689 690 691 692
(defun eww-browse-url (url &optional new-window)
  (cond (new-window
         (let ((new-buffer "*eww*")
               (num 0))
           (while (get-buffer new-buffer)
             (setq num (1+ num)
                   new-buffer (format "*eww*<%d>" num)))
           (switch-to-buffer new-buffer))
         (eww-mode))
        ((and (equal major-mode 'eww-mode)
              (plist-get eww-data :url))
         (eww-save-history)))
693
  (eww url))
694

695
(defun eww-back-url ()
696 697
  "Go to the previously displayed page."
  (interactive)
698
  (when (>= eww-history-position (length eww-history))
699
    (user-error "No previous page"))
700 701 702
  (eww-save-history)
  (setq eww-history-position (+ eww-history-position 2))
  (eww-restore-history (elt eww-history (1- eww-history-position))))
703 704 705 706 707

(defun eww-forward-url ()
  "Go to the next displayed page."
  (interactive)
  (when (zerop eww-history-position)
708
    (user-error "No next page"))
709 710
  (eww-save-history)
  (eww-restore-history (elt eww-history (1- eww-history-position))))
711 712

(defun eww-restore-history (elem)
Ivan Shmakov's avatar
Ivan Shmakov committed
713
  (let ((inhibit-read-only t)
714
	(inhibit-modification-hooks t)
Ivan Shmakov's avatar
Ivan Shmakov committed
715
	(text (plist-get elem :text)))
716
    (setq eww-data elem)
Ivan Shmakov's avatar
Ivan Shmakov committed
717 718 719 720 721 722
    (if (null text)
	(eww-reload)			; FIXME: restore :point?
      (erase-buffer)
      (insert text)
      (goto-char (plist-get elem :point))
      (eww-update-header-line-format))))
723

724 725 726 727 728
(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)
729 730 731
  (if (plist-get eww-data :next)
      (eww-browse-url (shr-expand-url (plist-get eww-data :next)
				      (plist-get eww-data :url)))
732
    (user-error "No `next' on this page")))
733 734 735 736 737 738

(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)
739 740
  (if (plist-get eww-data :previous)
      (eww-browse-url (shr-expand-url (plist-get eww-data :previous)
741
				      (plist-get eww-data :url)))
742
    (user-error "No `previous' on this page")))
743 744 745 746 747 748

(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)
749 750 751
  (if (plist-get eww-data :up)
      (eww-browse-url (shr-expand-url (plist-get eww-data :up)
				      (plist-get eww-data :url)))
752
    (user-error "No `up' on this page")))
753 754 755

(defun eww-top-url ()
  "Go to the page marked `top'.
756 757
A page is marked `top' if rel=\"start\", rel=\"home\", or rel=\"contents\"
appears in a <link> or <a> tag."
758
  (interactive)
759 760 761
  (let ((best-url (or (plist-get eww-data :start)
		      (plist-get eww-data :contents)
		      (plist-get eww-data :home))))
762
    (if best-url
763
	(eww-browse-url (shr-expand-url best-url (plist-get eww-data :url)))
764
      (user-error "No `top' for this page"))))
765

766 767 768 769 770
(defun eww-reload (&optional local encode)
  "Reload the current page.
If LOCAL (the command prefix), don't reload the page from the
network, but just re-display the HTML already fetched."
  (interactive "P")
771
  (let ((url (plist-get eww-data :url)))
772 773 774 775 776 777 778
    (if local
	(if (null (plist-get eww-data :dom))
	    (error "No current HTML data")
	  (eww-display-html 'utf-8 url (plist-get eww-data :dom)
			    (point) (current-buffer)))
      (url-retrieve url 'eww-render
		    (list url (point) (current-buffer) encode)))))
779

780 781 782 783
;; Form support.

(defvar eww-form nil)

784 785 786
(defvar eww-submit-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\r" 'eww-submit)
787
    (define-key map [(control c) (control c)] 'eww-submit)
788 789
    map))

790 791 792 793 794 795
(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))

796 797
(defvar eww-checkbox-map
  (let ((map (make-sparse-keymap)))
Kenjiro NAKAYAMA's avatar
Kenjiro NAKAYAMA committed
798
    (define-key map " " 'eww-toggle-checkbox)
799
    (define-key map "\r" 'eww-toggle-checkbox)
800
    (define-key map [(control c) (control c)] 'eww-submit)
801 802 803 804 805 806 807
    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)
808
    (define-key map [(control c) (control c)] 'eww-submit)
809
    (define-key map [(control e)] 'eww-end-of-text)
810 811
    (define-key map [?\t] 'shr-next-link)
    (define-key map [?\M-\t] 'shr-previous-link)
812 813 814 815 816 817
    map))

(defvar eww-textarea-map
  (let ((map (make-keymap)))
    (set-keymap-parent map text-mode-map)
    (define-key map "\r" 'forward-line)
818
    (define-key map [(control c) (control c)] 'eww-submit)
819 820
    (define-key map [?\t] 'shr-next-link)
    (define-key map [?\M-\t] 'shr-previous-link)
821 822 823 824 825
    map))

(defvar eww-select-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\r" 'eww-change-select)
826
    (define-key map [(control c) (control c)] 'eww-submit)
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
    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))))

860 861 862
(defun eww-tag-form (dom)
  (let ((eww-form (list (cons :method (dom-attr dom 'method))
			(cons :action (dom-attr dom 'action))))
863 864
	(start (point)))
    (shr-ensure-paragraph)
865
    (shr-generic dom)
866 867 868
    (unless (bolp)
      (insert "\n"))
    (insert "\n")
869 870 871
    (when (> (point) start)
      (put-text-property start (1+ start)
			 'eww-form eww-form))))
872

873
(defun eww-form-submit (dom)
874
  (let ((start (point))
875
	(value (dom-attr dom 'value)))
876 877 878 879 880 881 882 883 884 885
    (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"
886
			     :name (dom-attr dom 'name)))
887 888 889
    (put-text-property start (point) 'keymap eww-submit-map)
    (insert " ")))

890
(defun eww-form-checkbox (dom)
891
  (let ((start (point)))
892
    (if (dom-attr dom 'checked)
893 894
	(insert eww-form-checkbox-selected-symbol)
      (insert eww-form-checkbox-symbol))
895 896 897
    (add-face-text-property start (point) 'eww-form-checkbox)
    (put-text-property start (point) 'eww-form
		       (list :eww-form eww-form
898 899 900 901
			     :value (dom-attr dom 'value)
			     :type (downcase (dom-attr dom 'type))
			     :checked (dom-attr dom 'checked)
			     :name (dom-attr dom 'name)))
902 903 904
    (put-text-property start (point) 'keymap eww-checkbox-map)
    (insert " ")))

905
(defun eww-form-file (dom)
906
  (let ((start (point))
907
	(value (dom-attr dom 'value)))
908 909 910 911 912 913 914 915 916
    (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
917 918 919
			     :value (dom-attr dom 'value)
			     :type (downcase (dom-attr dom 'type))
			     :name (dom-attr dom 'name)))
920 921 922 923 924 925 926 927 928 929 930 931 932
    (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))))

933
(defun eww-form-text (dom)
934
  (let ((start (point))
935 936 937 938 939
	(type (downcase (or (dom-attr dom 'type) "text")))
	(value (or (dom-attr dom 'value) ""))
	(width (string-to-number (or (dom-attr dom 'size) "40")))
        (readonly-property (if (or (dom-attr dom 'disabled)
				   (dom-attr dom 'readonly))
940 941
                               'read-only
                             'inhibit-read-only)))
942 943 944 945
    (insert value)
    (when (< (length value) width)
      (insert (make-string (- width (length value)) ? )))
    (put-text-property start (point) 'face 'eww-form-text)
946
    (put-text-property start (point) 'inhibit-read-only t)
947
    (put-text-property start (point) 'local-map eww-text-map)
948
    (put-text-property start (point) readonly-property t)
949
    (put-text-property start (point) 'eww-form
950 951 952
                       (list :eww-form eww-form
                             :value value
                             :type type
953
                             :name (dom-attr dom 'name)))
954 955
    (insert " ")))

956 957 958 959 960 961 962
(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'.")

963
(defun eww-process-text-input (beg end replace-length)
964 965 966 967
  (when-let (pos (and (< (1+ end) (point-max))
		      (> (1- end) (point-min))
		      (cond
		       ((get-text-property (1+ end) 'eww-form)
968 969 970
			(1+ end))
		       ((get-text-property (1- end) 'eww-form)
			(1- end)))))
971 972 973
    (let* ((form (get-text-property pos 'eww-form))
	   (properties (text-properties-at pos))
	   (inhibit-read-only t)
974
	   (length (- end beg replace-length))
975 976 977 978
	   (type (plist-get form :type)))
      (when (and form
		 (member type eww-text-input-types))
	(cond
979
	 ((> length 0)
980 981 982 983 984 985
	  ;; Delete some space at the end.
	  (save-excursion
	    (goto-char
	     (if (equal type "textarea")
		 (1- (line-end-position))
	       (eww-end-of-field)))
986 987 988 989 990
	    (while (and (> length 0)
			(eql (following-char) ? ))
	      (delete-region (1- (point)) (point))
	      (cl-decf length))))
	 ((< length 0)
991 992 993 994 995 996