eww.el 70 KB
Newer Older
1
;;; eww.el --- Emacs Web Wowser  -*- lexical-binding:t -*-
2

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 2013-2019 Free Software Foundation, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

;; 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
21
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
22 23 24 25 26

;;; Commentary:

;;; Code:

27
(require 'cl-lib)
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
(require 'puny)
35
(eval-when-compile (require 'subr-x)) ;; for string-trim
36

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

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

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

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

64
;;;###autoload
65 66
(defcustom eww-suggest-uris
  '(eww-links-at-point
67 68
    url-get-url-at-point
    eww-current-url)
69 70 71 72
  "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."
73
  :version "25.1"
74 75 76
  :group 'eww
  :type 'hook
  :options '(eww-links-at-point
77 78
             url-get-url-at-point
             eww-current-url))
79

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

Ivan Shmakov's avatar
Ivan Shmakov committed
86 87 88 89 90 91 92 93 94 95 96
(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'.
97
If t or `auto', the buffers will be reloaded automatically.
Ivan Shmakov's avatar
Ivan Shmakov committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
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)

116 117 118 119 120 121
(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))
122

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

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

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

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

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

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

188
(defface eww-form-text
189 190 191
  '((t :background "#505050"
       :foreground "white"
       :box (:line-width 1)))
192 193 194 195
  "Face for eww text inputs."
  :version "24.4"
  :group 'eww)

Kenjiro NAKAYAMA's avatar
Kenjiro NAKAYAMA committed
196
(defface eww-form-textarea
197 198 199
  '((t :background "#C0C0C0"
       :foreground "black"
       :box (:line-width 1)))
Kenjiro NAKAYAMA's avatar
Kenjiro NAKAYAMA committed
200 201 202 203
  "Face for eww textarea inputs."
  :version "24.4"
  :group 'eww)

204 205 206 207 208 209 210 211 212 213 214 215 216 217
(defface eww-invalid-certificate
  '((default :weight bold)
    (((class color)) :foreground "red"))
  "Face for web pages with invalid certificates."
  :version "25.1"
  :group 'eww)

(defface eww-valid-certificate
  '((default :weight bold)
    (((class color)) :foreground "ForestGreen"))
  "Face for web pages with valid certificates."
  :version "25.1"
  :group 'eww)

218
(defvar eww-data nil)
219
(defvar eww-history nil)
220
(defvar eww-history-position 0)
221
(defvar eww-prompt-history nil)
222

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

226
(defvar eww-link-keymap
227 228 229 230 231
  (let ((map (copy-keymap shr-map)))
    (define-key map "\r" 'eww-follow-link)
    map))

(defvar eww-image-link-keymap
232
  (let ((map (copy-keymap shr-image-map)))
233 234 235
    (define-key map "\r" 'eww-follow-link)
    map))

236 237 238 239 240 241 242 243 244 245 246 247 248
(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)))

249
;;;###autoload
250
(defun eww (url &optional arg)
251 252
  "Fetch URL and render the page.
If the input doesn't look like an URL or a domain name, the
253 254 255 256
word(s) will be searched for via `eww-search-prefix'.

If called with a prefix ARG, use a new buffer instead of reusing
the default EWW buffer."
257
  (interactive
258
   (let* ((uris (eww-suggested-uris))
259 260 261
	  (prompt (concat "Enter URL or keywords"
			  (if uris (format " (default %s)" (car uris)) "")
			  ": ")))
262 263
     (list (read-string prompt nil 'eww-prompt-history uris)
           (prefix-numeric-value current-prefix-arg))))
264 265
  (setq url (eww--dwim-expand-url url))
  (pop-to-buffer-same-window
266 267 268 269 270 271 272
   (cond
    ((eq arg 4)
     (generate-new-buffer "*eww*"))
    ((eq major-mode 'eww-mode)
     (current-buffer))
    (t
     (get-buffer-create "*eww*"))))
273 274 275 276 277
  (eww-setup-buffer)
  ;; Check whether the domain only uses "Highly Restricted" Unicode
  ;; IDNA characters.  If not, transform to punycode to indicate that
  ;; there may be funny business going on.
  (let ((parsed (url-generic-parse-url url)))
278 279
    (when (url-host parsed)
      (unless (puny-highly-restrictive-domain-p (url-host parsed))
280 281 282 283 284 285 286
        (setf (url-host parsed) (puny-encode-domain (url-host parsed)))))
    ;; When the URL is on the form "http://a/../../../g", chop off all
    ;; the leading "/.."s.
    (when (url-filename parsed)
      (while (string-match "\\`/[.][.]/" (url-filename parsed))
        (setf (url-filename parsed) (substring (url-filename parsed) 3))))
    (setq url (url-recreate-url parsed)))
287 288 289 290 291 292 293
  (plist-put eww-data :url url)
  (plist-put eww-data :title "")
  (eww-update-header-line-format)
  (let ((inhibit-read-only t))
    (insert (format "Loading %s..." url))
    (goto-char (point-min)))
  (url-retrieve url 'eww-render
294
                (list url nil (current-buffer))))
295 296

(defun eww--dwim-expand-url (url)
297
  (setq url (string-trim url))
298
  (cond ((string-match-p "\\`file:/" url))
299
	;; Don't mangle file: URLs at all.
300
        ((string-match-p "\\`ftp://" url)
301
         (user-error "FTP is not supported"))
302
        (t
303 304 305
	 ;; Anything that starts with something that vaguely looks
	 ;; like a protocol designator is interpreted as a full URL.
         (if (or (string-match "\\`[A-Za-z]+:" url)
306 307
		 ;; Also try to match "naked" URLs like
		 ;; en.wikipedia.org/wiki/Free software
308
		 (string-match "\\`[A-Za-z_]+\\.[A-Za-z._]+/" url)
309
		 (and (= (length (split-string url)) 1)
310
		      (or (and (not (string-match-p "\\`[\"'].*[\"']\\'" url))
311 312
			       (> (length (split-string url "[.:]")) 1))
			  (string-match eww-local-regex url))))
313 314 315
             (progn
               (unless (string-match-p "\\`[a-zA-Z][-a-zA-Z0-9+.]*://" url)
                 (setq url (concat "http://" url)))
316
               ;; Some sites do not redirect final /
317 318 319
               (when (string= (url-filename (url-generic-parse-url url)) "")
                 (setq url (concat url "/"))))
           (setq url (concat eww-search-prefix
320 321
                             (mapconcat
                              #'url-hexify-string (split-string url) "+"))))))
322
  url)
323

324 325
;;;###autoload (defalias 'browse-web 'eww)

326 327
;;;###autoload
(defun eww-open-file (file)
328
  "Render FILE using EWW."
329
  (interactive "fFile: ")
330 331 332 333
  (eww (concat "file://"
	       (and (memq system-type '(windows-nt ms-dos))
		    "/")
	       (expand-file-name file))))
334

335
;;;###autoload
336
(defun eww-search-words ()
337
  "Search the web for the text between BEG and END.
338 339 340 341 342 343 344 345 346 347 348
If region is active (and not whitespace), search the web for
the text between BEG and END.  Else, prompt the user for a search
string.  See the `eww-search-prefix' variable for the search
engine used."
  (interactive)
  (if (use-region-p)
      (let ((region-string (buffer-substring (region-beginning) (region-end))))
        (if (not (string-match-p "\\`[ \n\t\r\v\f]*\\'" region-string))
            (eww region-string)
          (call-interactively 'eww)))
    (call-interactively 'eww)))
349

350 351 352 353 354 355 356 357 358 359
(defun eww-open-in-new-buffer ()
  "Fetch link at point in a new EWW buffer."
  (interactive)
  (let ((url (eww-suggested-uris)))
    (if (null url) (user-error "No link at point")
      ;; clone useful to keep history, but
      ;; should not clone from non-eww buffer
      (with-current-buffer
          (if (eq major-mode 'eww-mode) (clone-buffer)
            (generate-new-buffer "*eww*"))
360 361 362
        (unless (equal url (eww-current-url))
          (eww-mode)
          (eww (if (consp url) (car url) url)))))))
363

364 365 366 367 368 369
(defun eww-html-p (content-type)
  "Return non-nil if CONTENT-TYPE designates an HTML content type.
Currently this means either text/html or application/xhtml+xml."
  (member content-type '("text/html"
			 "application/xhtml+xml")))

370
(defun eww-render (status url &optional point buffer encode)
371 372 373
  (let* ((headers (eww-parse-headers))
	 (content-type
	  (mail-header-parse-content-type
374 375 376
           (if (zerop (length (cdr (assoc "content-type" headers))))
	       "text/plain"
             (cdr (assoc "content-type" headers)))))
377 378 379
	 (charset (intern
		   (downcase
		    (or (cdr (assq 'charset (cdr content-type)))
380
			(eww-detect-charset (eww-html-p (car content-type)))
381
			"utf-8"))))
382
	 (data-buffer (current-buffer))
383
	 (shr-target-id (url-target (url-generic-parse-url url)))
384
	 last-coding-system-used)
385 386 387
    (let ((redirect (plist-get status :redirect)))
      (when redirect
        (setq url redirect)))
388
    (with-current-buffer buffer
389 390 391
      ;; Save the https peer status.
      (plist-put eww-data :peer (plist-get status :peer))
      ;; Make buffer listings more informative.
392 393 394 395
      (setq list-buffers-directory url)
      ;; Let the URL library have a handle to the current URL for
      ;; referer purposes.
      (setq url-current-lastloc (url-generic-parse-url url)))
396 397 398
    (unwind-protect
	(progn
	  (cond
399 400 401
           ((and eww-use-external-browser-for-content-type
                 (string-match-p eww-use-external-browser-for-content-type
                                 (car content-type)))
402 403 404 405 406 407 408 409
            (erase-buffer)
            (insert "<title>Unsupported content type</title>")
            (insert (format "<h1>Content-type %s is unsupported</h1>"
                            (car content-type)))
            (insert (format "<a href=%S>Direct link to the document</a>"
                            url))
            (goto-char (point-min))
	    (eww-display-html charset url nil point buffer encode))
410
	   ((eww-html-p (car content-type))
411
	    (eww-display-html charset url nil point buffer encode))
412 413
	   ((equal (car content-type) "application/pdf")
	    (eww-display-pdf))
414
	   ((string-match-p "\\`image/" (car content-type))
415
	    (eww-display-image buffer))
416
	   (t
417
	    (eww-display-raw buffer (or encode charset 'utf-8))))
418 419 420 421
	  (with-current-buffer buffer
	    (plist-put eww-data :url url)
	    (eww-update-header-line-format)
	    (setq eww-history-position 0)
422 423
	    (and last-coding-system-used
		 (set-buffer-file-coding-system last-coding-system-used))
424
	    (run-hooks 'eww-after-render-hook)))
425 426 427 428
      (kill-buffer data-buffer))))

(defun eww-parse-headers ()
  (let ((headers nil))
429
    (goto-char (point-min))
430 431 432 433 434 435 436 437 438 439 440
    (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))

441 442 443 444 445
(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
446
	      "<meta[\t\n\r ]+[^>]*charset=\"?\\([^\t\n\r \"/>]+\\)[\\\"'.*]" nil t)
447 448 449 450 451 452
	     (goto-char pt)
	     (match-string 1))
	(and (looking-at
	      "[\t\n\r ]*<\\?xml[\t\n\r ]+[^>]*encoding=\"\\([^\"]+\\)")
	     (match-string 1)))))

453
(declare-function libxml-parse-html-region "xml.c"
454
		  (start end &optional base-url discard-comments))
455

456
(defun eww-display-html (charset url &optional document point buffer encode)
457 458 459 460
  (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))
461 462 463
  ;; There should be a better way to abort loading images
  ;; asynchronously.
  (setq url-queue nil)
464
  (let ((document
465 466 467
	 (or document
	     (list
	      'base (list (cons 'href url))
468
	      (progn
469 470 471 472
		(setq encode (or encode charset 'utf-8))
		(condition-case nil
		    (decode-coding-region (point) (point-max) encode)
		  (coding-system-error nil))
473 474 475 476 477 478
		(save-excursion
		  ;; Remove CRLF and NULL before parsing.
                  (while (re-search-forward "\\(\r$\\)\\|\\(\000\\)" nil t)
                    (replace-match (if (match-beginning 1)
                                       ""
                                     "\\0") t t)))
479 480 481
		(libxml-parse-html-region (point) (point-max))))))
	(source (and (null document)
		     (buffer-substring (point) (point-max)))))
482
    (with-current-buffer buffer
483
      (setq bidi-paragraph-direction nil)
484 485 486
      (plist-put eww-data :source source)
      (plist-put eww-data :dom document)
      (let ((inhibit-read-only t)
487
	    (inhibit-modification-hooks t)
488
	    (shr-external-rendering-functions
489 490 491 492 493
             (append
              shr-external-rendering-functions
              '((title . eww-tag-title)
                (form . eww-tag-form)
                (input . eww-tag-input)
494
                (button . eww-form-submit)
495 496 497
                (textarea . eww-tag-textarea)
                (select . eww-tag-select)
                (link . eww-tag-link)
498
                (meta . eww-tag-meta)
499
                (a . eww-tag-a)))))
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
	(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)))))
518
      (eww-size-text-inputs))))
519

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
(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)
Ivan Shmakov's avatar
Ivan Shmakov committed
539
		   ("up" . :up)))))
540 541
    (and href
	 where
542
	 (plist-put eww-data (cdr where) href))))
543

544 545 546 547 548
(defvar eww-redirect-level 1)

(defun eww-tag-meta (dom)
  (when (and (cl-equalp (dom-attr dom 'http-equiv) "refresh")
             (< eww-redirect-level 5))
549
    (when-let* ((refresh (dom-attr dom 'content)))
550
      (when (or (string-match "^\\([0-9]+\\) *;.*url=\"\\([^\"]+\\)\"" refresh)
551
                (string-match "^\\([0-9]+\\) *;.*url='\\([^']+\\)'" refresh)
552 553 554 555 556 557 558 559 560 561 562 563 564 565
                (string-match "^\\([0-9]+\\) *;.*url=\\([^ ]+\\)" refresh))
        (let ((timeout (match-string 1 refresh))
              (url (match-string 2 refresh))
              (eww-redirect-level (1+ eww-redirect-level)))
          (if (equal timeout "0")
              (eww (shr-expand-url url))
            (eww-tag-a
             (dom-node 'a `((href . ,(shr-expand-url url)))
                       (format "Auto refresh in %s second%s disabled"
                               timeout
                               (if (equal timeout "1")
                                   ""
                                 "s"))))))))))

566 567 568
(defun eww-tag-link (dom)
  (eww-handle-link dom)
  (shr-generic dom))
569

570 571
(defun eww-tag-a (dom)
  (eww-handle-link dom)
572
  (let ((start (point)))
573
    (shr-tag-a dom)
574 575 576 577 578
    (put-text-property start (point)
                       'keymap
                       (if (mm-images-in-region-p start (point))
                           eww-image-link-keymap
                         eww-link-keymap))))
579

580
(defun eww-update-header-line-format ()
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
  (setq header-line-format
	(and eww-header-line-format
	     (let ((title (plist-get eww-data :title))
		   (peer (plist-get eww-data :peer)))
	       (when (zerop (length title))
		 (setq title "[untitled]"))
	       ;; This connection has is https.
	       (when peer
		 (setq title
		       (propertize title 'face
				   (if (plist-get peer :warnings)
				       'eww-invalid-certificate
				     'eww-valid-certificate))))
	       (replace-regexp-in-string
		"%" "%%"
		(format-spec
		 eww-header-line-format
		 `((?u . ,(or (plist-get eww-data :url) ""))
		   (?t . ,title))))))))
600

601
(defun eww-tag-title (dom)
602 603 604 605
  (plist-put eww-data :title
	     (replace-regexp-in-string
	      "^ \\| $" ""
	      (replace-regexp-in-string "[ \t\r\n]+" " " (dom-text dom))))
606 607
  (eww-update-header-line-format))

608
(defun eww-display-raw (buffer &optional encode)
609
  (let ((data (buffer-substring (point) (point-max))))
610 611 612 613 614 615
    (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)
616 617 618
	(condition-case nil
	    (decode-coding-region (point-min) (1+ (length data)) encode)
	  (coding-system-error nil)))
619 620 621
      (goto-char (point-min)))))

(defun eww-display-image (buffer)
622
  (let ((data (shr-parse-image-data)))
623 624 625 626 627 628 629
    (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)))))
630

631
(declare-function mailcap-view-mime "mailcap" (type))
632 633
(defun eww-display-pdf ()
  (let ((data (buffer-substring (point) (point-max))))
634
    (pop-to-buffer-same-window (get-buffer-create "*eww pdf*"))
635 636 637 638
    (let ((coding-system-for-write 'raw-text)
	  (inhibit-read-only t))
      (erase-buffer)
      (insert data)
639
      (mailcap-view-mime "application/pdf")))
640 641
  (goto-char (point-min)))

642
(defun eww-setup-buffer ()
Lars Ingebrigtsen's avatar
Lars Ingebrigtsen committed
643 644 645
  (when (or (plist-get eww-data :url)
            (plist-get eww-data :dom))
    (eww-save-history))
646
  (let ((inhibit-read-only t))
647
    (remove-overlays)
648
    (erase-buffer))
649
  (setq bidi-paragraph-direction nil)
650
  (unless (eq major-mode 'eww-mode)
651
    (eww-mode)))
652

653 654 655 656
(defun eww-current-url nil
  "Return URI of the Web page the current EWW buffer is visiting."
  (plist-get eww-data :url))

657
(defun eww-links-at-point ()
658 659 660 661 662
  "Return list of URIs, if any, linked at point."
  (remq nil
	(list (get-text-property (point) 'shr-url)
	      (get-text-property (point) 'image-url))))

663
(defun eww-view-source ()
664
  "View the HTML source code of the current page."
665 666
  (interactive)
  (let ((buf (get-buffer-create "*eww-source*"))
667
        (source (plist-get eww-data :source)))
668
    (with-current-buffer buf
669 670 671 672
      (let ((inhibit-read-only t))
	(delete-region (point-min) (point-max))
	(insert (or source "no source"))
	(goto-char (point-min))
673 674 675 676 677 678 679 680 681
        ;; Decode the source and set the buffer's encoding according
        ;; to what the HTML source specifies in its 'charset' header,
        ;; if any.
        (let ((cs (find-auto-coding "" (point-max))))
          (when (consp cs)
            (setq cs (car cs))
            (when (coding-system-p cs)
              (decode-coding-region (point-min) (point-max) cs)
              (setq buffer-file-coding-system last-coding-system-used))))
Tom Tromey's avatar
Tom Tromey committed
682 683 684 685 686
        (cond
         ((fboundp 'mhtml-mode)
          (mhtml-mode))
         ((fboundp 'html-mode)
	  (html-mode)))))
687 688
    (view-buffer buf)))

689
(defun eww-toggle-paragraph-direction ()
690
  "Cycle the paragraph direction between left-to-right, right-to-left and auto."
691 692
  (interactive)
  (setq bidi-paragraph-direction
693 694 695 696 697 698 699 700 701 702
        (cond ((eq bidi-paragraph-direction 'left-to-right)
               nil)
              ((eq bidi-paragraph-direction 'right-to-left)
               'left-to-right)
              (t
               'right-to-left)))
  (message "The paragraph direction is now %s"
           (if (null bidi-paragraph-direction)
               "automatic"
             bidi-paragraph-direction)))
703

704 705 706 707 708 709
(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)
710
  (let* ((old-data eww-data)
711 712 713 714 715
	 (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))
716 717
		(libxml-parse-html-region (point-min) (point-max))))
         (base (plist-get eww-data :url)))
718
    (eww-score-readability dom)
719
    (eww-save-history)
720
    (eww-display-html nil nil
721 722
                      (list 'base (list (cons 'href base))
                            (eww-highest-readability dom))
723
		      nil (current-buffer))
724 725 726
    (dolist (elem '(:source :url :title :next :previous :up))
      (plist-put eww-data elem (plist-get old-data elem)))
    (eww-update-header-line-format)))
727 728 729 730

(defun eww-score-readability (node)
  (let ((score -1))
    (cond
731
     ((memq (dom-tag node) '(script head comment))
732
      (setq score -2))
733
     ((eq (dom-tag node) 'meta)
734
      (setq score -1))
735
     ((eq (dom-tag node) 'img)
736
      (setq score 2))
737 738
     ((eq (dom-tag node) 'a)
      (setq score (- (length (split-string (dom-text node))))))
739
     (t
740
      (dolist (elem (dom-children node))
741 742 743 744
	(cond
         ((stringp elem)
          (setq score (+ score (length (split-string elem)))))
         ((consp elem)
745 746
	  (setq score (+ score
			 (or (cdr (assoc :eww-readability-score (cdr elem)))
747
			     (eww-score-readability elem)))))))))
748
    ;; Cache the score of the node to avoid recomputing all the time.
749
    (dom-set-attribute node :eww-readability-score score)
750 751 752 753 754
    score))

(defun eww-highest-readability (node)
  (let ((result node)
	highest)
755 756 757 758 759 760 761
    (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))
762 763 764 765
        ;; We set a lower bound to how long we accept that the
        ;; readable portion of the page is going to be.
        (when (> (length (split-string (dom-texts highest))) 100)
	  (setq result highest))))
766 767
    result))

768 769
(defvar eww-mode-map
  (let ((map (make-sparse-keymap)))
770
    (define-key map "g" 'eww-reload) ;FIXME: revert-buffer-function instead!
771
    (define-key map "G" 'eww)
772
    (define-key map [?\M-\r] 'eww-open-in-new-buffer)
773 774
    (define-key map [?\t] 'shr-next-link)
    (define-key map [?\M-\t] 'shr-previous-link)
775
    (define-key map [backtab] 'shr-previous-link)
776
    (define-key map [delete] 'scroll-down-command)
777
    (define-key map "l" 'eww-back-url)
778
    (define-key map "r" 'eww-forward-url)
779
    (define-key map "n" 'eww-next-url)
780
    (define-key map "p" 'eww-previous-url)
781 782
    (define-key map "u" 'eww-up-url)
    (define-key map "t" 'eww-top-url)
783
    (define-key map "&" 'eww-browse-with-external-browser)
784
    (define-key map "d" 'eww-download)
785
    (define-key map "w" 'eww-copy-page-url)
786
    (define-key map "C" 'url-cookie-list)
787
    (define-key map "v" 'eww-view-source)
788
    (define-key map "R" 'eww-readable)
789
    (define-key map "H" 'eww-list-histories)
790
    (define-key map "E" 'eww-set-character-encoding)
791
    (define-key map "s" 'eww-switch-to-buffer)
792
    (define-key map "S" 'eww-list-buffers)
793
    (define-key map "F" 'eww-toggle-fonts)
794
    (define-key map "D" 'eww-toggle-paragraph-direction)
795
    (define-key map [(meta C)] 'eww-toggle-colors)
796

797 798 799 800 801
    (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)

802
    (easy-menu-define nil map ""
803
      '("Eww"
804
	["Exit" quit-window t]
805
	["Close browser" quit-window t]
806
	["Reload" eww-reload t]
807
	["Follow URL in new buffer" eww-open-in-new-buffer]
808 809 810 811 812 813
	["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]
814
	["View page source" eww-view-source]
815
	["Copy page URL" eww-copy-page-url t]
816
	["List histories" eww-list-histories t]
817
	["Switch to buffer" eww-switch-to-buffer t]
818
	["List buffers" eww-list-buffers t]
819
	["Add bookmark" eww-add-bookmark t]
Kenjiro NAKAYAMA's avatar
Kenjiro NAKAYAMA committed
820
	["List bookmarks" eww-list-bookmarks t]
821
	["List cookies" url-cookie-list t]
822 823
	["Toggle fonts" eww-toggle-fonts t]
	["Toggle colors" eww-toggle-colors t]
824 825
        ["Character Encoding" eww-set-character-encoding]
        ["Toggle Paragraph Direction" eww-toggle-paragraph-direction]))
826 827
    map))

828 829 830
(defvar eww-tool-bar-map
  (let ((map (make-sparse-keymap)))
    (dolist (tool-bar-item
831
             '((quit-window . "close")
832 833 834 835 836 837 838 839 840 841 842
               (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'.")

Ivan Shmakov's avatar
Ivan Shmakov committed
843 844
;; Autoload cookie needed by desktop.el.
;;;###autoload
845 846
(define-derived-mode eww-mode special-mode "eww"
  "Mode for browsing the web."
847
  (setq-local eww-data (list :title ""))
848 849
  (setq-local browse-url-browser-function #'eww-browse-url)
  (add-hook 'after-change-functions #'eww-process-text-input nil t)
850 851 852
  (setq-local eww-history nil)
  (setq-local eww-history-position 0)
  (when (boundp 'tool-bar-map)
853
    (setq-local tool-bar-map eww-tool-bar-map))
Ivan Shmakov's avatar
Ivan Shmakov committed
854
  ;; desktop support
855
  (setq-local desktop-save-buffer #'eww-desktop-misc-data)
856
  ;; multi-page isearch support
857
  (setq-local multi-isearch-next-buffer-function #'eww-isearch-next-buffer)
858
  (setq truncate-lines t)
859
  (buffer-disable-undo)
860
  (setq buffer-read-only t))
861

862
;;;###autoload
863
(defun eww-browse-url (url &optional new-window)
Lars Ingebrigtsen's avatar
Lars Ingebrigtsen committed
864
  (when new-window
865 866 867 868
    (pop-to-buffer-same-window
     (generate-new-buffer
      (format "*eww-%s*" (url-host (url-generic-parse-url
                                    (eww--dwim-expand-url url))))))
Lars Ingebrigtsen's avatar
Lars Ingebrigtsen committed
869
    (eww-mode))
870
  (eww url))
871

872
(defun eww-back-url ()
873 874
  "Go to the previously displayed page."
  (interactive)
875
  (when (>= eww-history-position (length eww-history))
876
    (user-error "No previous page"))
877 878 879
  (eww-save-history)
  (setq eww-history-position (+ eww-history-position 2))
  (eww-restore-history (elt eww-history (1- eww-history-position))))
880 881 882 883 884

(defun eww-forward-url ()
  "Go to the next displayed page."
  (interactive)
  (when (zerop eww-history-position)
885
    (user-error "No next page"))
886 887
  (eww-save-history)
  (eww-restore-history (elt eww-history (1- eww-history-position))))
888 889

(defun eww-restore-history (elem)
Ivan Shmakov's avatar
Ivan Shmakov committed
890
  (let ((inhibit-read-only t)
891
	(inhibit-modification-hooks t)
Ivan Shmakov's avatar
Ivan Shmakov committed
892
	(text (plist-get elem :text)))
893
    (setq eww-data elem)
Ivan Shmakov's avatar
Ivan Shmakov committed
894 895 896 897 898
    (if (null text)
	(eww-reload)			; FIXME: restore :point?
      (erase-buffer)
      (insert text)
      (goto-char (plist-get elem :point))
899 900
      ;; Make buffer listings more informative.
      (setq list-buffers-directory (plist-get elem :url))
Ivan Shmakov's avatar
Ivan Shmakov committed
901
      (eww-update-header-line-format))))
902

903 904 905 906 907
(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)
908 909 910
  (if (plist-get eww-data :next)
      (eww-browse-url (shr-expand-url (plist-get eww-data :next)
				      (plist-get eww-data :url)))
911
    (user-error "No `next' on this page")))
912 913 914 915 916 917

(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)
918 919
  (if (plist-get eww-data :previous)
      (eww-browse-url (shr-expand-url (plist-get eww-data :previous)
920
				      (plist-get eww-data :url)))
921
    (user-error "No `previous' on this page")))
922 923 924 925 926 927

(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)
928 929 930
  (if (plist-get eww-data :up)
      (eww-browse-url (shr-expand-url (plist-get eww-data :up)
				      (plist-get eww-data :url)))
931
    (user-error "No `up' on this page")))
932 933 934

(defun eww-top-url ()
  "Go to the page marked `top'.
935 936
A page is marked `top' if rel=\"start\", rel=\"home\", or rel=\"contents\"
appears in a <link> or <a> tag."
937
  (interactive)
938 939 940
  (let ((best-url (or (plist-get eww-data :start)
		      (plist-get eww-data :contents)
		      (plist-get eww-data :home))))
941
    (if best-url
942
	(eww-browse-url (shr-expand-url best-url (plist-get eww-data :url)))
943
      (user-error "No `top' for this page"))))
944

945 946
(defun eww-reload (&optional local encode)
  "Reload the current page.
947 948 949
If LOCAL is non-nil (interactively, the command was invoked with
a prefix argument), don't reload the page from the network, but
just re-display the HTML already fetched."
950
  (interactive "P")
951
  (let ((url (plist-get eww-data :url)))
952 953 954 955 956 957 958
    (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)))))
959

960 961 962 963
;; Form support.

(defvar eww-form nil)

964 965 966
(defvar eww-submit-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\r" 'eww-submit)
967
    (define-key map [(control c) (control c)] 'eww-submit)
968 969
    map))

970 971 972 973 974 975
(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))

976 977
(defvar eww-checkbox-map
  (let ((map (make-sparse-keymap)))
Kenjiro NAKAYAMA's avatar
Kenjiro NAKAYAMA committed
978
    (define-key map " " 'eww-toggle-checkbox)
979
    (define-key map "\r" 'eww-toggle-checkbox)
980
    (define-key map [(control c) (control c)] 'eww-submit)
981 982 983 984 985 986 987
    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)
988
    (define-key map [(control c) (control c)] 'eww-submit)
989
    (define-key map [(control e)] 'eww-end-of-text)
990 991
    (define-key map [?\t] 'shr-next-link)
    (define-key map [?\M-\t] 'shr-previous-link)