1 ;;; shr.el --- Simple HTML Renderer
3 ;; Copyright (C) 2010-2016 Free Software Foundation, Inc.
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; This package takes a HTML parse tree (as provided by
26 ;; libxml-parse-html-region) and renders it in the current buffer. It
27 ;; does not do CSS, JavaScript or anything advanced: It's geared
28 ;; towards rendering typical short snippets of HTML, like what you'd
29 ;; find in HTML email and the like.
33 (eval-when-compile (require 'cl))
34 (eval-when-compile (require 'url)) ;For url-filename's setf handler.
43 "Simple HTML Renderer"
47 (defcustom shr-max-image-proportion 0.9
48 "How big pictures displayed are in relation to the window they're in.
49 A value of 0.7 means that they are allowed to take up 70% of the
50 width and height of the window. If they are larger than this,
51 and Emacs supports it, then the images will be rescaled down to
57 (defcustom shr-blocked-images nil
58 "Images that have URLs matching this regexp will be blocked."
61 :type '(choice (const nil) regexp))
63 (defcustom shr-use-fonts t
64 "If non-nil, use proportional fonts for text."
69 (defcustom shr-use-colors t
70 "If non-nil, respect color specifications in the HTML."
75 (defcustom shr-table-horizontal-line nil
76 "Character used to draw horizontal table lines.
77 If nil, don't draw horizontal table lines."
79 :type '(choice (const nil) character))
81 (defcustom shr-table-vertical-line ?\s
82 "Character used to draw vertical table lines."
86 (defcustom shr-table-corner ?\s
87 "Character used to draw table corners."
91 (defcustom shr-hr-line ?-
92 "Character used to draw hr lines."
96 (defcustom shr-width nil
97 "Frame width to use for rendering.
98 May either be an integer specifying a fixed width in characters,
99 or nil, meaning that the full width of the window should be
102 :type '(choice (integer :tag "Fixed width in characters")
103 (const :tag "Use the width of the window" nil))
106 (defcustom shr-bullet "* "
107 "Bullet used for unordered lists.
108 Alternative suggestions are:
115 (defcustom shr-external-browser 'browse-url-default-browser
116 "Function used to launch an external browser."
121 (defcustom shr-image-animate t
122 "Non nil means that images that can be animated will be."
127 (defvar shr-content-function nil
128 "If bound, this should be a function that will return the content.
129 This is used for cid: URLs, and the function is called with the
130 cid: URL as the argument.")
132 (defvar shr-put-image-function 'shr-put-image
133 "Function called to put image and alt string.")
135 (defface shr-strike-through '((t (:strike-through t)))
136 "Font for <s> elements."
140 '((t (:inherit link)))
141 "Font for link elements."
144 (defvar shr-inhibit-images nil
145 "If non-nil, inhibit loading images.")
147 (defvar shr-external-rendering-functions nil
148 "Alist of tag/function pairs used to alter how shr renders certain tags.
149 For instance, eww uses this to alter rendering of title, forms
151 ((title . eww-tag-title)
152 (form . eww-tag-form)
155 ;;; Internal variables.
157 (defvar shr-folding-mode nil)
158 (defvar shr-start nil)
159 (defvar shr-indentation 0)
160 (defvar shr-internal-width nil)
161 (defvar shr-list-mode nil)
162 (defvar shr-content-cache nil)
163 (defvar shr-kinsoku-shorten nil)
164 (defvar shr-table-depth 0)
165 (defvar shr-stylesheet nil)
166 (defvar shr-base nil)
168 (defvar shr-warning nil)
169 (defvar shr-ignore-cache nil)
170 (defvar shr-target-id nil)
171 (defvar shr-table-separator-length 1)
172 (defvar shr-table-separator-pixel-width 0)
173 (defvar shr-table-id nil)
174 (defvar shr-current-font nil)
175 (defvar shr-internal-bullet nil)
178 (let ((map (make-sparse-keymap)))
179 (define-key map "a" 'shr-show-alt-text)
180 (define-key map "i" 'shr-browse-image)
181 (define-key map "z" 'shr-zoom-image)
182 (define-key map [?\t] 'shr-next-link)
183 (define-key map [?\M-\t] 'shr-previous-link)
184 (define-key map [follow-link] 'mouse-face)
185 (define-key map [mouse-2] 'shr-browse-url)
186 (define-key map "I" 'shr-insert-image)
187 (define-key map "w" 'shr-copy-url)
188 (define-key map "u" 'shr-copy-url)
189 (define-key map "v" 'shr-browse-url)
190 (define-key map "O" 'shr-save-contents)
191 (define-key map "\r" 'shr-browse-url)
194 (defvar shr-image-map
195 (let ((map (copy-keymap shr-map)))
196 (when (boundp 'image-map)
197 (set-keymap-parent map image-map))
200 ;; Public functions and commands.
201 (declare-function libxml-parse-html-region "xml.c"
202 (start end &optional base-url discard-comments))
204 (defun shr-render-buffer (buffer)
205 "Display the HTML rendering of the current buffer."
206 (interactive (list (current-buffer)))
207 (or (fboundp 'libxml-parse-html-region)
208 (error "This function requires Emacs to be compiled with libxml2"))
209 (pop-to-buffer "*html*")
212 (with-current-buffer buffer
213 (libxml-parse-html-region (point-min) (point-max))))
214 (goto-char (point-min)))
217 (defun shr-render-region (begin end &optional buffer)
218 "Display the HTML rendering of the region between BEGIN and END."
220 (unless (fboundp 'libxml-parse-html-region)
221 (error "This function requires Emacs to be compiled with libxml2"))
222 (with-current-buffer (or buffer (current-buffer))
223 (let ((dom (libxml-parse-html-region begin end)))
224 (delete-region begin end)
226 (shr-insert-document dom))))
228 (defun shr--have-one-fringe-p ()
229 "Return non-nil if we know at least one of the fringes has non-zero width."
230 (and (fboundp 'fringe-columns)
231 (or (not (zerop (fringe-columns 'right)))
232 (not (zerop (fringe-columns 'left))))))
235 (defun shr-insert-document (dom)
236 "Render the parsed document DOM into the current buffer.
237 DOM should be a parse tree as generated by
238 `libxml-parse-html-region' or similar."
239 (setq shr-content-cache nil)
240 (let ((start (point))
246 (shr-table-separator-pixel-width (shr-string-pixel-width "-"))
247 (shr-internal-bullet (cons shr-bullet
248 (shr-string-pixel-width shr-bullet)))
249 (shr-internal-width (or (and shr-width
250 (if (not shr-use-fonts)
252 (* shr-width (frame-char-width))))
253 ;; We need to adjust the available
254 ;; width for when the user disables
255 ;; the fringes, which will cause the
256 ;; display engine usurp one column for
257 ;; the continuation glyph.
258 (if (not shr-use-fonts)
259 (- (window-body-width) 1
260 (if (and (null shr-width)
261 (not (shr--have-one-fringe-p)))
264 (- (window-body-width nil t)
265 (* 2 (frame-char-width))
266 (if (and (null shr-width)
267 (not (shr--have-one-fringe-p)))
268 (* (frame-char-width) 2)
270 bidi-display-reordering)
271 ;; If the window was hscrolled for some reason, shr-fill-lines
272 ;; below will misbehave, because it silently assumes that it
273 ;; starts with a non-hscrolled window (vertical-motion will move
274 ;; to a wrong place otherwise).
275 (set-window-hscroll nil 0)
277 (shr-fill-lines start (point))
278 (shr--remove-blank-lines-at-the-end start (point))
280 (message "%s" shr-warning))))
282 (defun shr--remove-blank-lines-at-the-end (start end)
285 (narrow-to-region start end)
287 (when (and (re-search-backward "[^ \n]" nil t)
290 (delete-region (point) (point-max))))))
292 (defun shr-copy-url (&optional image-url)
293 "Copy the URL under point to the kill ring.
294 If IMAGE-URL (the prefix) is non-nil, or there is no link under
295 point, but there is an image under point then copy the URL of the
296 image under point instead.
297 If called twice, then try to fetch the URL and see whether it
298 redirects somewhere else."
300 (let ((url (if image-url
301 (get-text-property (point) 'image-url)
302 (or (get-text-property (point) 'shr-url)
303 (get-text-property (point) 'image-url)))))
306 (message "No URL under point"))
307 ;; Resolve redirected URLs.
308 ((equal url (car kill-ring))
313 (eq (car a) :redirect))
316 (goto-char (point-min))
317 ;; Remove common tracking junk from the URL.
318 (when (re-search-forward ".utm_.*" nil t)
319 (replace-match "" t t))
320 (message "Copied %s" (buffer-string))
321 (copy-region-as-kill (point-min) (point-max)))))
323 ;; Copy the URL to the kill ring.
326 (insert (url-encode-url url))
327 (copy-region-as-kill (point-min) (point-max))
328 (message "Copied %s" (buffer-string)))))))
330 (defun shr-next-link ()
331 "Skip to the next link."
333 (let ((current (get-text-property (point) 'shr-url))
336 (while (and (not (eobp))
337 (equal (get-text-property (point) 'shr-url) current))
341 (get-text-property (point) 'shr-url))
342 ;; The next link is adjacent.
343 (message "%s" (get-text-property (point) 'help-echo)))
345 (not (setq skip (text-property-not-all (point) (point-max)
348 (message "No next link"))
351 (message "%s" (get-text-property (point) 'help-echo))))))
353 (defun shr-previous-link ()
354 "Skip to the previous link."
356 (let ((start (point))
358 ;; Skip past the current link.
359 (while (and (not (bobp))
360 (get-text-property (point) 'help-echo))
362 ;; Find the previous link.
363 (while (and (not (bobp))
364 (not (setq found (get-text-property (point) 'help-echo))))
368 (message "No previous link")
370 ;; Put point at the start of the link.
371 (while (and (not (bobp))
372 (get-text-property (point) 'help-echo))
375 (message "%s" (get-text-property (point) 'help-echo)))))
377 (defun shr-show-alt-text ()
378 "Show the ALT text of the image under point."
380 (let ((text (get-text-property (point) 'shr-alt)))
382 (message "No image under point")
383 (message "%s" (shr-fill-text text)))))
385 (defun shr-browse-image (&optional copy-url)
386 "Browse the image under point.
387 If COPY-URL (the prefix if called interactively) is non-nil, copy
388 the URL of the image to the kill buffer instead."
390 (let ((url (get-text-property (point) 'image-url)))
393 (message "No image under point"))
397 (copy-region-as-kill (point-min) (point-max))
398 (message "Copied %s" url)))
400 (message "Browsing %s..." url)
403 (defun shr-insert-image ()
404 "Insert the image under point into the buffer."
406 (let ((url (get-text-property (point) 'image-url)))
408 (message "No image under point")
409 (message "Inserting %s..." url)
410 (url-retrieve url 'shr-image-fetched
411 (list (current-buffer) (1- (point)) (point-marker))
414 (defun shr-zoom-image ()
415 "Toggle the image size.
416 The size will be rotated between the default size, the original
417 size, and full-buffer size."
419 (let ((url (get-text-property (point) 'image-url))
420 (size (get-text-property (point) 'image-size))
421 (buffer-read-only nil))
423 (message "No image under point")
424 ;; Delete the old picture.
425 (while (get-text-property (point) 'image-url)
428 (let ((start (point)))
429 (while (get-text-property (point) 'image-url)
432 (put-text-property start (point) 'display nil)
433 (when (> (- (point) start) 2)
434 (delete-region start (1- (point)))))
435 (message "Inserting %s..." url)
436 (url-retrieve url 'shr-image-fetched
437 (list (current-buffer) (1- (point)) (point-marker)
439 (cond ((or (eq size 'default)
448 ;;; Utility functions.
450 (defsubst shr-generic (dom)
451 (dolist (sub (dom-children dom))
456 (defun shr-descend (dom)
458 (intern (concat "shr-tag-" (symbol-name (dom-tag dom))) obarray))
459 ;; Allow other packages to override (or provide) rendering
461 (external (cdr (assq (dom-tag dom) shr-external-rendering-functions)))
462 (style (dom-attr dom 'style))
463 (shr-stylesheet shr-stylesheet)
464 (shr-depth (1+ shr-depth))
466 ;; shr uses many frames per nested node.
467 (if (> shr-depth (/ max-specpdl-size 15))
468 (setq shr-warning "Too deeply nested to render properly; consider increasing `max-specpdl-size'")
470 (if (string-match "color\\|display\\|border-collapse" style)
471 (setq shr-stylesheet (nconc (shr-parse-style style)
474 ;; If we have a display:none, then just ignore this part of the DOM.
475 (unless (equal (cdr (assq 'display shr-stylesheet)) "none")
477 (funcall external dom))
479 (funcall function dom))
482 (when (and shr-target-id
483 (equal (dom-attr dom 'id) shr-target-id))
484 ;; If the element was empty, we don't have anything to put the
485 ;; anchor on. So just insert a dummy character.
486 (when (= start (point))
488 (put-text-property start (1+ start) 'shr-target-id shr-target-id))
489 ;; If style is set, then this node has set the color.
493 (cdr (assq 'color shr-stylesheet))
494 (cdr (assq 'background-color shr-stylesheet))))))))
496 (defun shr-fill-text (text)
497 (if (zerop (length text))
500 (let ((shr-indentation 0)
502 (shr-internal-width (- (window-body-width nil t)
503 (* 2 (frame-char-width))
504 ;; Adjust the window width for when
505 ;; the user disables the fringes,
506 ;; which causes the display engine
507 ;; to usurp one column for the
508 ;; continuation glyph.
509 (if (and (null shr-width)
510 (not (shr--have-one-fringe-p)))
511 (* (frame-char-width) 2)
516 (define-inline shr-char-breakable-p (char)
517 "Return non-nil if a line can be broken before and after CHAR."
518 (inline-quote (aref fill-find-break-point-function-table ,char)))
519 (define-inline shr-char-nospace-p (char)
520 "Return non-nil if no space is required before and after CHAR."
521 (inline-quote (aref fill-nospace-between-words-table ,char)))
523 ;; KINSOKU is a Japanese word meaning a rule that should not be violated.
524 ;; In Emacs, it is a term used for characters, e.g. punctuation marks,
525 ;; parentheses, and so on, that should not be placed in the beginning
526 ;; of a line or the end of a line.
527 (define-inline shr-char-kinsoku-bol-p (char)
528 "Return non-nil if a line ought not to begin with CHAR."
529 (inline-letevals (char)
530 (inline-quote (and (not (eq ,char ?'))
531 (aref (char-category-set ,char) ?>)))))
532 (define-inline shr-char-kinsoku-eol-p (char)
533 "Return non-nil if a line ought not to end with CHAR."
534 (inline-quote (aref (char-category-set ,char) ?<)))
535 (unless (shr-char-kinsoku-bol-p (make-char 'japanese-jisx0208 33 35))
536 (load "kinsoku" nil t))
538 (defun shr-pixel-column ()
539 (if (not shr-use-fonts)
541 (if (not (get-buffer-window (current-buffer)))
542 (save-window-excursion
543 (set-window-buffer nil (current-buffer))
544 (car (window-text-pixel-size nil (line-beginning-position) (point))))
545 (car (window-text-pixel-size nil (line-beginning-position) (point))))))
547 (defun shr-pixel-region ()
548 (- (shr-pixel-column)
551 (shr-pixel-column))))
553 (defun shr-string-pixel-width (string)
554 (if (not shr-use-fonts)
558 (shr-pixel-column))))
560 (defsubst shr--translate-insertion-chars ()
561 ;; Remove soft hyphens.
562 (goto-char (point-min))
563 (while (search-forward "Â" nil t)
564 (replace-match "" t t))
565 ;; Translate non-breaking spaces into real spaces.
566 (goto-char (point-min))
567 (while (search-forward "Â " nil t)
568 (replace-match " " t t)))
570 (defun shr-insert (text)
571 (when (and (not (bolp))
572 (get-text-property (1- (point)) 'image-url))
575 ((eq shr-folding-mode 'none)
576 (let ((start (point)))
579 (narrow-to-region start (point))
580 (shr--translate-insertion-chars)
581 (goto-char (point-max)))))
583 (let ((font-start (point)))
584 (when (and (string-match "\\`[ \t\n\r]" text)
586 (not (eq (char-after (1- (point))) ? )))
588 (let ((start (point))
592 (narrow-to-region start (point))
594 (when (looking-at "[ \t\n\r]+")
595 (replace-match "" t t))
596 (while (re-search-forward "[ \t\n\r]+" nil t)
597 (replace-match " " t t))
598 (shr--translate-insertion-chars)
599 (goto-char (point-max)))
600 ;; We may have removed everything we inserted if if was just
602 (unless (= font-start (point))
603 ;; Mark all lines that should possibly be folded afterwards.
605 (shr-mark-fill start))
607 (put-text-property font-start (point)
609 (or shr-current-font 'variable-pitch)))))))))
611 (defun shr-fill-lines (start end)
612 (if (<= shr-internal-width 0)
615 (narrow-to-region start end)
617 (when (get-text-property (point) 'shr-indentation)
619 (while (setq start (next-single-property-change start 'shr-indentation))
623 (goto-char (point-max)))))
625 (defun shr-vertical-motion (column)
626 (if (not shr-use-fonts)
627 (move-to-column column)
630 (vertical-motion (cons (/ column (frame-char-width)) 0))
634 (defun shr-fill-line ()
635 (let ((shr-indentation (get-text-property (point) 'shr-indentation))
636 (continuation (get-text-property
637 (point) 'shr-continuation-indentation))
639 (put-text-property (point) (1+ (point)) 'shr-indentation nil)
640 (let ((face (get-text-property (point) 'face))
641 (background-start (point)))
644 (put-text-property background-start (point) 'face
645 `,(shr-face-background face))))
647 (setq shr-indentation (or continuation shr-indentation))
648 (shr-vertical-motion shr-internal-width)
649 (when (looking-at " $")
650 (delete-region (point) (line-end-position)))
652 ;; We have to do some folding. First find the first
653 ;; previous point suitable for folding.
654 (if (or (not (shr-find-fill-point (line-beginning-position)))
656 ;; We had unbreakable text (for this width), so just go to
657 ;; the first space and carry on.
660 (skip-chars-forward " ")
661 (search-forward " " (line-end-position) 'move)))
662 ;; Success; continue.
663 (when (= (preceding-char) ?\s)
665 (let ((face (get-text-property (point) 'face))
666 (background-start (point)))
670 (put-text-property background-start (point) 'face
671 `,(shr-face-background face))))
673 (shr-vertical-motion shr-internal-width)
674 (when (looking-at " $")
675 (delete-region (point) (line-end-position))))))
677 (defun shr-find-fill-point (start)
681 (while (not (or (setq failed (<= (point) start))
682 (eq (preceding-char) ? )
683 (eq (following-char) ? )
684 (shr-char-breakable-p (preceding-char))
685 (shr-char-breakable-p (following-char))
686 (and (shr-char-kinsoku-bol-p (preceding-char))
687 (shr-char-breakable-p (following-char))
688 (not (shr-char-kinsoku-bol-p (following-char))))
689 (shr-char-kinsoku-eol-p (following-char))
693 ;; There's no breakable point, so we give it up.
696 ;; Don't overflow the window edge, even if
697 ;; shr-kinsoku-shorten is nil.
698 (unless (or shr-kinsoku-shorten (null shr-width))
699 (while (setq found (re-search-forward
700 "\\(\\c>\\)\\| \\|\\c<\\|\\c|"
701 (line-end-position) 'move)))
703 (not (match-beginning 1)))
704 (goto-char (match-beginning 0)))))
707 ;; Don't put kinsoku-bol characters at the beginning of a line,
708 ;; or kinsoku-eol characters at the end of a line.
710 ;; Don't overflow the window edge, even if shr-kinsoku-shorten
712 ((or shr-kinsoku-shorten (null shr-width))
713 (while (and (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
714 (or (shr-char-kinsoku-eol-p (preceding-char))
715 (shr-char-kinsoku-bol-p (following-char))))
717 (when (setq failed (<= (point) start))
718 ;; There's no breakable point that doesn't violate kinsoku,
719 ;; so we look for the second best position.
725 (shr-char-kinsoku-eol-p (following-char)))))
727 ((shr-char-kinsoku-eol-p (preceding-char))
728 ;; Find backward the point where kinsoku-eol characters begin.
733 (and (> (setq count (1- count)) 0)
734 (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
735 (or (shr-char-kinsoku-eol-p (preceding-char))
736 (shr-char-kinsoku-bol-p (following-char)))))))
737 (when (setq failed (<= (point) start))
738 ;; There's no breakable point that doesn't violate kinsoku,
739 ;; so we go to the second best position.
740 (if (looking-at "\\(\\c<+\\)\\c<")
741 (goto-char (match-end 1))
743 ((shr-char-kinsoku-bol-p (following-char))
744 ;; Find forward the point where kinsoku-bol characters end.
748 (and (>= (setq count (1- count)) 0)
749 (shr-char-kinsoku-bol-p (following-char))
750 (shr-char-breakable-p (following-char))))))))
751 (when (eq (following-char) ? )
755 (defun shr-parse-base (url)
756 ;; Always chop off anchors.
757 (when (string-match "#.*" url)
758 (setq url (substring url 0 (match-beginning 0))))
759 ;; NB: <base href="" > URI may itself be relative to the document s URI
760 (setq url (shr-expand-url url))
761 (let* ((parsed (url-generic-parse-url url))
762 (local (url-filename parsed)))
763 (setf (url-filename parsed) "")
764 ;; Chop off the bit after the last slash.
765 (when (string-match "\\`\\(.*/\\)[^/]+\\'" local)
766 (setq local (match-string 1 local)))
767 ;; Always make the local bit end with a slash.
768 (when (and (not (zerop (length local)))
769 (not (eq (aref local (1- (length local))) ?/)))
770 (setq local (concat local "/")))
771 (list (url-recreate-url parsed)
776 (autoload 'url-expand-file-name "url-expand")
778 ;; FIXME This needs some tests writing.
779 ;; Does it even need to exist, given that url-expand-file-name does?
780 (defun shr-expand-url (url &optional base)
783 ;; shr-parse-base should never call this with non-nil base!
784 (shr-parse-base base)
785 ;; Bound by the parser.
787 (when (zerop (length url))
789 ;; Strip leading whitespace
790 (and url (string-match "\\`\\s-+" url)
791 (setq url (substring url (match-end 0))))
794 (string-match "\\`[a-z]*:" url))
795 ;; Absolute or empty URI
796 (or url (nth 3 base)))
797 ((eq (aref url 0) ?/)
798 (if (and (> (length url) 1)
799 (eq (aref url 1) ?/))
800 ;; //host...; just use the protocol
801 (concat (nth 2 base) ":" url)
802 ;; Just use the host name part.
803 (concat (car base) url)))
804 ((eq (aref url 0) ?#)
805 ;; A link to an anchor.
806 (concat (nth 3 base) url))
809 (url-expand-file-name url (concat (car base) (cadr base))))))
811 (defun shr-ensure-newline ()
813 (let ((prefix (get-text-property (line-beginning-position)
814 'shr-prefix-length)))
815 (unless (or (zerop (current-column))
817 (= prefix (- (point) (line-beginning-position)))))
820 (defun shr-ensure-paragraph ()
822 (let ((prefix (get-text-property (line-beginning-position)
823 'shr-prefix-length)))
829 ;; We're already at a new paragraph; do nothing.
832 (= prefix (- (point) (line-beginning-position))))
833 ;; Do nothing; we're at the start of a <li>.
837 ;; If the current line is totally blank, and doesn't even
838 ;; have any face properties set, then delete the blank
840 (and (looking-at " *$")
841 (not (get-text-property (point) 'face))
842 (not (= (next-single-property-change (point) 'face nil
844 (line-end-position)))))
845 (delete-region (match-beginning 0) (match-end 0)))
846 ;; We have a single blank line.
849 ;; Insert new paragraph.
854 (when (> shr-indentation 0)
856 (if (not shr-use-fonts)
857 (make-string shr-indentation ?\s)
860 `(space :width (,shr-indentation)))))))
862 (defun shr-fontize-dom (dom &rest types)
863 (let ((start (point)))
866 (shr-add-font start (point) type))))
868 ;; Add face to the region, but avoid putting the font properties on
869 ;; blank text at the start of the line, and the newline at the end, to
871 (defun shr-add-font (start end type)
874 (while (< (point) end)
876 (skip-chars-forward " "))
877 (add-face-text-property (point) (min (line-end-position) end) type t)
878 (if (< (line-end-position) end)
882 (defun shr-mouse-browse-url (ev)
883 "Browse the URL under the mouse cursor."
888 (defun shr-browse-url (&optional external mouse-event)
889 "Browse the URL under point.
890 If EXTERNAL, browse the URL using `shr-external-browser'."
891 (interactive (list current-prefix-arg last-nonmenu-event))
892 (mouse-set-point mouse-event)
893 (let ((url (get-text-property (point) 'shr-url)))
896 (message "No link under point"))
897 ((string-match "^mailto:" url)
898 (browse-url-mail url))
901 (funcall shr-external-browser url)
902 (browse-url url))))))
904 (defun shr-save-contents (directory)
905 "Save the contents from URL in a file."
906 (interactive "DSave contents of URL to directory: ")
907 (let ((url (get-text-property (point) 'shr-url)))
909 (message "No link under point")
910 (url-retrieve (shr-encode-url url)
911 'shr-store-contents (list url directory)
914 (defun shr-store-contents (status url directory)
915 (unless (plist-get status :error)
916 (when (or (search-forward "\n\n" nil t)
917 (search-forward "\r\n\r\n" nil t))
918 (write-region (point) (point-max)
919 (expand-file-name (file-name-nondirectory url)
922 (defun shr-image-fetched (status buffer start end &optional flags)
923 (let ((image-buffer (current-buffer)))
924 (when (and (buffer-name buffer)
925 (not (plist-get status :error)))
926 (url-store-in-cache image-buffer)
927 (when (or (search-forward "\n\n" nil t)
928 (search-forward "\r\n\r\n" nil t))
929 (let ((data (shr-parse-image-data)))
930 (with-current-buffer buffer
932 (let ((alt (buffer-substring start end))
933 (properties (text-properties-at start))
934 (inhibit-read-only t))
935 (delete-region start end)
937 (funcall shr-put-image-function data alt flags)
939 (let ((type (pop properties))
940 (value (pop properties)))
941 (unless (memq type '(display image-size))
942 (put-text-property start (point) type value))))))))))
943 (kill-buffer image-buffer)))
945 (defun shr-image-from-data (data)
946 "Return an image from the data: URI content DATA."
948 "\\(\\([^/;,]+\\(/[^;,]+\\)?\\)\\(;[^;,]+\\)*\\)?,\\(.*\\)"
950 (let ((param (match-string 4 data))
951 (payload (url-unhex-string (match-string 5 data))))
952 (when (string-match "^.*\\(;[ \t]*base64\\)$" param)
953 (setq payload (ignore-errors
954 (base64-decode-string payload))))
957 ;; Behind display-graphic-p test.
958 (declare-function image-size "image.c" (spec &optional pixels frame))
959 (declare-function image-animate "image" (image &optional index limit))
961 (defun shr-put-image (spec alt &optional flags)
962 "Insert image SPEC with a string ALT. Return image.
963 SPEC is either an image data blob, or a list where the first
964 element is the data blob and the second element is the content-type."
965 (if (display-graphic-p)
966 (let* ((size (cdr (assq 'size flags)))
967 (data (if (consp spec)
970 (content-type (and (consp spec)
975 (create-image data nil t :ascent 100
976 :format content-type))
977 ((eq content-type 'image/svg+xml)
978 (create-image data 'svg t :ascent 100))
981 (shr-rescale-image data content-type
982 (plist-get flags :width)
983 (plist-get flags :height))))
986 (shr-rescale-image data content-type
987 (plist-get flags :width)
988 (plist-get flags :height)))))))
990 ;; When inserting big-ish pictures, put them at the
991 ;; beginning of the line.
992 (when (and (> (current-column) 0)
993 (> (car (image-size image t)) 400))
995 (if (eq size 'original)
996 (insert-sliced-image image (or alt "*") nil 20 1)
997 (insert-image image (or alt "*")))
998 (put-text-property start (point) 'image-size size)
999 (when (and shr-image-animate
1000 (cond ((fboundp 'image-multi-frame-p)
1001 ;; Only animate multi-frame things that specify a
1002 ;; delay; eg animated gifs as opposed to
1003 ;; multi-page tiffs. FIXME?
1004 (cdr (image-multi-frame-p image)))
1005 ((fboundp 'image-animated-p)
1006 (image-animated-p image))))
1007 (image-animate image nil 60)))
1009 (insert (or alt ""))))
1011 (defun shr-rescale-image (data content-type width height)
1012 "Rescale DATA, if too big, to fit the current buffer.
1013 WIDTH and HEIGHT are the sizes given in the HTML data, if any."
1014 (if (or (not (fboundp 'imagemagick-types))
1015 (not (get-buffer-window (current-buffer))))
1016 (create-image data nil t :ascent 100)
1017 (let* ((edges (window-inside-pixel-edges
1018 (get-buffer-window (current-buffer))))
1019 (max-width (truncate (* shr-max-image-proportion
1020 (- (nth 2 edges) (nth 0 edges)))))
1021 (max-height (truncate (* shr-max-image-proportion
1022 (- (nth 3 edges) (nth 1 edges)))))
1023 (scaling (image-compute-scaling-factor image-scaling-factor)))
1024 (when (or (and width
1025 (> width max-width))
1027 (> height max-height)))
1030 (if (and width height
1031 (< (* width scaling) max-width)
1032 (< (* height scaling) max-height))
1038 :format content-type)
1042 :max-width max-width
1043 :max-height max-height
1044 :format content-type)))))
1046 ;; url-cache-extract autoloads url-cache.
1047 (declare-function url-cache-create-filename "url-cache" (url))
1048 (autoload 'mm-disable-multibyte "mm-util")
1049 (autoload 'browse-url-mail "browse-url")
1051 (defun shr-get-image-data (url)
1052 "Get image data for URL.
1053 Return a string with image data."
1055 (mm-disable-multibyte)
1056 (when (ignore-errors
1057 (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
1059 (when (or (search-forward "\n\n" nil t)
1060 (search-forward "\r\n\r\n" nil t))
1061 (shr-parse-image-data)))))
1063 (declare-function libxml-parse-xml-region "xml.c"
1064 (start end &optional base-url discard-comments))
1066 (defun shr-parse-image-data ()
1067 (let ((data (buffer-substring (point) (point-max)))
1071 (narrow-to-region (point-min) (point))
1072 (let ((content-type (mail-fetch-field "content-type")))
1074 ;; Remove any comments in the type string.
1075 (intern (replace-regexp-in-string ";.*" "" content-type)
1077 ;; SVG images may contain references to further images that we may
1078 ;; want to block. So special-case these by parsing the XML data
1079 ;; and remove the blocked bits.
1080 (when (eq content-type 'image/svg+xml)
1083 (libxml-parse-xml-region (point) (point-max)))))
1084 (list data content-type)))
1086 (defun shr-image-displayer (content-function)
1087 "Return a function to display an image.
1088 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
1089 is an argument. The function to be returned takes three arguments URL,
1090 START, and END. Note that START and END should be markers."
1091 `(lambda (url start end)
1093 (if (string-match "\\`cid:" url)
1094 ,(when content-function
1095 `(let ((image (funcall ,content-function
1096 (substring url (match-end 0)))))
1099 (funcall shr-put-image-function
1100 image (buffer-substring start end))
1101 (delete-region (point) end))))
1102 (url-retrieve url 'shr-image-fetched
1103 (list (current-buffer) start end)
1106 (defun shr-heading (dom &rest types)
1107 (shr-ensure-paragraph)
1108 (apply #'shr-fontize-dom dom types)
1109 (shr-ensure-paragraph))
1111 (defun shr-urlify (start url &optional title)
1112 (shr-add-font start (point) 'shr-link)
1113 (add-text-properties
1116 'help-echo (let ((iri (or (ignore-errors
1117 (decode-coding-string
1118 (url-unhex-string url)
1121 (if title (format "%s (%s)" iri title) iri))
1123 'mouse-face 'highlight))
1124 ;; Don't overwrite any keymaps that are already in the buffer (i.e.,
1128 (let ((next (next-single-property-change start 'keymap nil (point))))
1129 (if (get-text-property start 'keymap)
1131 (put-text-property start (or next (point)) 'keymap shr-map)))))
1133 (defun shr-encode-url (url)
1135 (browse-url-url-encode-chars url "[)$ ]"))
1137 (autoload 'shr-color-visible "shr-color")
1138 (autoload 'shr-color->hexadecimal "shr-color")
1140 (defun shr-color-check (fg bg)
1141 "Check that FG is visible on BG.
1142 Returns (fg bg) with corrected values.
1143 Returns nil if the colors that would be used are the default
1144 ones, in case fg and bg are nil."
1146 (let ((fixed (cond ((null fg) 'fg)
1148 ;; Convert colors to hexadecimal, or set them to default.
1149 (let ((fg (or (shr-color->hexadecimal fg)
1150 (frame-parameter nil 'foreground-color)))
1151 (bg (or (shr-color->hexadecimal bg)
1152 (frame-parameter nil 'background-color))))
1153 (cond ((eq fixed 'bg)
1154 ;; Only return the new fg
1155 (list nil (cadr (shr-color-visible bg fg t))))
1157 ;; Invert args and results and return only the new bg
1158 (list (cadr (shr-color-visible fg bg t)) nil))
1160 (shr-color-visible bg fg)))))))
1162 (defun shr-colorize-region (start end fg &optional bg)
1163 (when (and shr-use-colors
1165 (>= (display-color-cells) 88))
1166 (let ((new-colors (shr-color-check fg bg)))
1169 (add-face-text-property start end
1170 (list :foreground (cadr new-colors))
1173 (add-face-text-property start end
1174 (list :background (car new-colors))
1178 ;;; Tag-specific rendering rules.
1180 (defun shr-tag-html (dom)
1181 (let ((dir (dom-attr dom 'dir)))
1184 (setq bidi-paragraph-direction 'left-to-right))
1186 (setq bidi-paragraph-direction 'right-to-left))
1188 (setq bidi-paragraph-direction nil))))
1191 (defun shr-tag-body (dom)
1192 (let* ((start (point))
1193 (fgcolor (or (dom-attr dom 'fgcolor) (dom-attr dom 'text)))
1194 (bgcolor (dom-attr dom 'bgcolor))
1195 (shr-stylesheet (list (cons 'color fgcolor)
1196 (cons 'background-color bgcolor))))
1198 (shr-colorize-region start (point) fgcolor bgcolor)))
1200 (defun shr-tag-style (_dom)
1203 (defun shr-tag-script (_dom)
1206 (defun shr-tag-comment (_dom)
1209 (defun shr-dom-to-xml (dom)
1214 (defun shr-dom-print (dom)
1215 "Convert DOM into a string containing the xml representation."
1216 (insert (format "<%s" (dom-tag dom)))
1217 (dolist (attr (dom-attributes dom))
1218 ;; Ignore attributes that start with a colon because they are
1219 ;; private elements.
1220 (unless (= (aref (format "%s" (car attr)) 0) ?:)
1221 (insert (format " %s=\"%s\"" (car attr) (cdr attr)))))
1224 (dolist (elem (dom-children dom))
1228 ((eq (dom-tag elem) 'comment)
1230 ((or (not (eq (dom-tag elem) 'image))
1231 ;; Filter out blocked elements inside the SVG image.
1232 (not (setq url (dom-attr elem ':xlink:href)))
1233 (not shr-blocked-images)
1234 (not (string-match shr-blocked-images url)))
1236 (shr-dom-print elem)))))
1237 (insert (format "</%s>" (dom-tag dom))))
1239 (defun shr-tag-svg (dom)
1240 (when (and (image-type-available-p 'svg)
1241 (not shr-inhibit-images)
1242 (dom-attr dom 'width)
1243 (dom-attr dom 'height))
1244 (funcall shr-put-image-function (list (shr-dom-to-xml dom) 'image/svg+xml)
1247 (defun shr-tag-sup (dom)
1248 (let ((start (point)))
1250 (put-text-property start (point) 'display '(raise 0.5))))
1252 (defun shr-tag-sub (dom)
1253 (let ((start (point)))
1255 (put-text-property start (point) 'display '(raise -0.5))))
1257 (defun shr-tag-label (dom)
1259 (shr-ensure-paragraph))
1261 (defun shr-tag-p (dom)
1262 (shr-ensure-paragraph)
1264 (shr-ensure-paragraph))
1266 (defun shr-tag-div (dom)
1267 (shr-ensure-newline)
1269 (shr-ensure-newline))
1271 (defun shr-tag-s (dom)
1272 (shr-fontize-dom dom 'shr-strike-through))
1274 (defun shr-tag-b (dom)
1275 (shr-fontize-dom dom 'bold))
1277 (defun shr-tag-i (dom)
1278 (shr-fontize-dom dom 'italic))
1280 (defun shr-tag-em (dom)
1281 (shr-fontize-dom dom 'italic))
1283 (defun shr-tag-strong (dom)
1284 (shr-fontize-dom dom 'bold))
1286 (defun shr-tag-u (dom)
1287 (shr-fontize-dom dom 'underline))
1289 (defun shr-tag-tt (dom)
1290 (let ((shr-current-font 'default))
1293 (defun shr-tag-ins (cont)
1294 (let* ((start (point))
1296 (shr-stylesheet (nconc (list (cons 'color color))
1299 (shr-colorize-region start (point) color
1300 (cdr (assq 'background-color shr-stylesheet)))))
1302 (defun shr-tag-del (cont)
1303 (let* ((start (point))
1305 (shr-stylesheet (nconc (list (cons 'color color))
1307 (shr-fontize-dom cont 'shr-strike-through)
1308 (shr-colorize-region start (point) color
1309 (cdr (assq 'background-color shr-stylesheet)))))
1311 (defun shr-parse-style (style)
1314 (when (string-match "\n" style)
1315 (setq style (replace-match " " t t style))))
1317 (dolist (elem (split-string style ";"))
1319 (setq elem (split-string elem ":"))
1320 (when (and (car elem)
1322 (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
1323 (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
1324 (when (string-match " *!important\\'" value)
1325 (setq value (substring value 0 (match-beginning 0))))
1326 (unless (equal value "inherit")
1327 (push (cons (intern name obarray)
1332 (defun shr-tag-base (dom)
1333 (when-let (base (dom-attr dom 'href))
1334 (setq shr-base (shr-parse-base base)))
1337 (defun shr-tag-a (dom)
1338 (let ((url (dom-attr dom 'href))
1339 (title (dom-attr dom 'title))
1343 (when (and shr-target-id
1344 (equal (dom-attr dom 'name) shr-target-id))
1345 ;; We have a zero-length <a name="foo"> element, so just
1346 ;; insert... something.
1347 (when (= start (point))
1348 (shr-ensure-newline)
1350 (put-text-property start (1+ start) 'shr-target-id shr-target-id))
1352 (shr-urlify (or shr-start start) (shr-expand-url url) title))))
1354 (defun shr-tag-object (dom)
1355 (unless shr-inhibit-images
1356 (let ((start (point))
1357 url multimedia image)
1358 (when-let (type (dom-attr dom 'type))
1359 (when (string-match "\\`image/svg" type)
1360 (setq url (dom-attr dom 'data)
1362 (dolist (child (dom-non-text-children dom))
1364 ((eq (dom-tag child) 'embed)
1365 (setq url (or url (dom-attr child 'src))
1367 ((and (eq (dom-tag child) 'param)
1368 (equal (dom-attr child 'name) "movie"))
1369 (setq url (or url (dom-attr child 'value))
1374 (shr-tag-img dom url)
1377 (shr-insert " [multimedia] ")
1378 (shr-urlify start (shr-expand-url url)))))
1380 (shr-generic dom)))))
1382 (defcustom shr-prefer-media-type-alist '(("webm" . 1.0)
1388 "Preferences for media types.
1389 The key element should be a regexp matched against the type of the source or
1390 url if no type is specified. The value should be a float in the range 0.0 to
1391 1.0. Media elements with higher value are preferred."
1394 :type '(alist :key-type regexp :value-type float))
1396 (defun shr--get-media-pref (elem)
1397 "Determine the preference for ELEM.
1398 The preference is a float determined from `shr-prefer-media-type'."
1399 (let ((type (dom-attr elem 'type))
1402 (setq type (dom-attr elem 'src)))
1404 (dolist (pref shr-prefer-media-type-alist)
1407 (string-match-p (car pref) type))
1408 (setq p (cdr pref)))))
1411 (defun shr--extract-best-source (dom &optional url pref)
1412 "Extract the best `:src' property from <source> blocks in DOM."
1413 (setq pref (or pref -1.0))
1415 (dolist (elem (dom-non-text-children dom))
1416 (when (and (eq (dom-tag elem) 'source)
1419 (shr--get-media-pref elem))))
1421 url (dom-attr elem 'src))
1422 ;; libxml's html parser isn't HTML5 compliant and non terminated
1423 ;; source tags might end up as children. So recursion it is...
1424 (dolist (child (dom-non-text-children elem))
1425 (when (eq (dom-tag child) 'source)
1426 (let ((ret (shr--extract-best-source (list child) url pref)))
1427 (when (< pref (cdr ret))
1429 pref (cdr ret)))))))))
1432 (defun shr-tag-video (dom)
1433 (let ((image (dom-attr dom 'poster))
1434 (url (dom-attr dom 'src))
1437 (setq url (car (shr--extract-best-source dom))))
1438 (if (> (length image) 0)
1439 (shr-tag-img nil image)
1440 (shr-insert " [video] "))
1441 (shr-urlify start (shr-expand-url url))))
1443 (defun shr-tag-audio (dom)
1444 (let ((url (dom-attr dom 'src))
1447 (setq url (car (shr--extract-best-source dom))))
1448 (shr-insert " [audio] ")
1449 (shr-urlify start (shr-expand-url url))))
1451 (defun shr-tag-img (dom &optional url)
1454 (or (> (length (dom-attr dom 'src)) 0)
1455 (> (length (dom-attr dom 'srcset)) 0))))
1456 (when (> (current-column) 0)
1458 (let ((alt (dom-attr dom 'alt))
1459 (width (shr-string-number (dom-attr dom 'width)))
1460 (height (shr-string-number (dom-attr dom 'height)))
1461 (url (shr-expand-url (or url (shr--preferred-image dom)))))
1462 (let ((start (point-marker)))
1463 (when (zerop (length alt))
1466 ((or (member (dom-attr dom 'height) '("0" "1"))
1467 (member (dom-attr dom 'width) '("0" "1")))
1468 ;; Ignore zero-sized or single-pixel images.
1470 ((and (not shr-inhibit-images)
1471 (string-match "\\`data:" url))
1472 (let ((image (shr-image-from-data (substring url (match-end 0)))))
1474 (funcall shr-put-image-function image alt
1475 (list :width width :height height))
1477 ((and (not shr-inhibit-images)
1478 (string-match "\\`cid:" url))
1479 (let ((url (substring url (match-end 0)))
1481 (if (or (not shr-content-function)
1482 (not (setq image (funcall shr-content-function url))))
1484 (funcall shr-put-image-function image alt
1485 (list :width width :height height)))))
1486 ((or shr-inhibit-images
1487 (and shr-blocked-images
1488 (string-match shr-blocked-images url)))
1489 (setq shr-start (point))
1491 ((and (not shr-ignore-cache)
1492 (url-is-cached (shr-encode-url url)))
1493 (funcall shr-put-image-function (shr-get-image-data url) alt
1494 (list :width width :height height)))
1496 (when (and shr-ignore-cache
1497 (url-is-cached (shr-encode-url url)))
1498 (let ((file (url-cache-create-filename (shr-encode-url url))))
1499 (when (file-exists-p file)
1500 (delete-file file))))
1501 (when (image-type-available-p 'svg)
1503 (shr-make-placeholder-image dom)
1507 (shr-encode-url url) 'shr-image-fetched
1508 (list (current-buffer) start (set-marker (make-marker) (point))
1509 (list :width width :height height))
1511 (when (zerop shr-table-depth) ;; We are not in a table.
1512 (put-text-property start (point) 'keymap shr-image-map)
1513 (put-text-property start (point) 'shr-alt alt)
1514 (put-text-property start (point) 'image-url url)
1515 (put-text-property start (point) 'image-displayer
1516 (shr-image-displayer shr-content-function))
1517 (put-text-property start (point) 'help-echo
1519 (or (dom-attr dom 'title) alt))))))))
1521 (defun shr--preferred-image (dom)
1522 (let ((srcset (dom-attr dom 'srcset))
1523 (frame-width (frame-pixel-width))
1524 (width (string-to-number (or (dom-attr dom 'width) "100")))
1526 (when (> (length srcset) 0)
1527 ;; srcset consist of a series of URL/size specifications
1528 ;; separated by the ", " string.
1532 (let ((spec (split-string elem " ")))
1534 ((= (length spec) 1)
1535 ;; Make sure it's well formed.
1536 (list (car spec) 0))
1537 ((string-match "\\([0-9]+\\)x\\'" (cadr spec))
1538 ;; If we have an "x" form, then use the width
1539 ;; spec to compute the real width.
1541 (* width (string-to-number
1542 (match-string 1 (cadr spec))))))
1545 (string-to-number (cadr spec)))))))
1546 (split-string srcset ", "))
1548 (> (cadr e1) (cadr e2)))))
1549 ;; Choose the smallest picture that's bigger than the current
1551 (setq candidate (caar srcset))
1553 (> (cadr (car srcset)) frame-width))
1554 (setq candidate (caar srcset))
1556 (or candidate (dom-attr dom 'src))))
1558 (defun shr-string-number (string)
1561 (setq string (replace-regexp-in-string "[^0-9]" "" string))
1562 (if (zerop (length string))
1564 (string-to-number string))))
1566 (defun shr-make-placeholder-image (dom)
1568 (get-buffer-window (current-buffer))
1569 (window-inside-pixel-edges
1570 (get-buffer-window (current-buffer)))))
1571 (scaling (image-compute-scaling-factor image-scaling-factor))
1573 (* (or (shr-string-number (dom-attr dom 'width)) 100)
1576 (* (or (shr-string-number (dom-attr dom 'height)) 100)
1580 (truncate (* shr-max-image-proportion
1581 (- (nth 2 edges) (nth 0 edges))))))
1582 (max-height (and edges
1583 (truncate (* shr-max-image-proportion
1584 (- (nth 3 edges) (nth 1 edges))))))
1586 (when (and max-width
1587 (> width max-width))
1588 (setq height (truncate (* (/ (float max-width) width) height))
1590 (when (and max-height
1591 (> height max-height))
1592 (setq width (truncate (* (/ (float max-height) height) width))
1594 (setq svg (svg-create width height))
1595 (svg-gradient svg "background" 'linear '((0 . "#b0b0b0") (100 . "#808080")))
1596 (svg-rectangle svg 0 0 width height :gradient "background"
1597 :stroke-width 2 :stroke-color "black")
1598 (let ((image (svg-image svg)))
1599 (setf (image-property image :ascent) 100)
1602 (defun shr-tag-pre (dom)
1603 (let ((shr-folding-mode 'none)
1604 (shr-current-font 'default))
1605 (shr-ensure-newline)
1607 (shr-ensure-newline)))
1609 (defun shr-tag-blockquote (dom)
1610 (shr-ensure-paragraph)
1611 (let ((start (point))
1612 (shr-indentation (+ shr-indentation
1613 (* 4 shr-table-separator-pixel-width))))
1615 (shr-ensure-paragraph)
1616 (shr-mark-fill start)))
1618 (defun shr-tag-dl (dom)
1619 (shr-ensure-paragraph)
1621 (shr-ensure-paragraph))
1623 (defun shr-tag-dt (dom)
1624 (shr-ensure-newline)
1626 (shr-ensure-newline))
1628 (defun shr-tag-dd (dom)
1629 (shr-ensure-newline)
1630 (let ((shr-indentation (+ shr-indentation
1631 (* 4 shr-table-separator-pixel-width))))
1634 (defun shr-tag-ul (dom)
1635 (shr-ensure-paragraph)
1636 (let ((shr-list-mode 'ul))
1638 ;; If we end on an empty <li>, then make sure we really end on a new
1642 (shr-ensure-paragraph))
1644 (defun shr-tag-ol (dom)
1645 (shr-ensure-paragraph)
1646 (let ((shr-list-mode 1))
1648 (shr-ensure-paragraph))
1650 (defun shr-tag-li (dom)
1651 (shr-ensure-newline)
1652 (let ((start (point)))
1654 (if (numberp shr-list-mode)
1656 (format "%d " shr-list-mode)
1657 (setq shr-list-mode (1+ shr-list-mode)))
1658 (car shr-internal-bullet)))
1659 (width (if (numberp shr-list-mode)
1660 (shr-string-pixel-width bullet)
1661 (cdr shr-internal-bullet))))
1663 (shr-mark-fill start)
1664 (let ((shr-indentation (+ shr-indentation width)))
1665 (put-text-property start (1+ start)
1666 'shr-continuation-indentation shr-indentation)
1667 (put-text-property start (1+ start) 'shr-prefix-length (length bullet))
1668 (shr-generic dom))))
1672 (defun shr-mark-fill (start)
1673 ;; We may not have inserted any text to fill.
1674 (unless (= start (point))
1675 (put-text-property start (1+ start)
1676 'shr-indentation shr-indentation)))
1678 (defun shr-tag-br (dom)
1679 (when (and (not (bobp))
1680 ;; Only add a newline if we break the current line, or
1681 ;; the previous line isn't a blank line.
1683 (and (> (- (point) 2) (point-min))
1684 (not (= (char-after (- (point) 2)) ?\n)))))
1688 (defun shr-tag-span (dom)
1691 (defun shr-tag-h1 (dom)
1692 (shr-heading dom (if shr-use-fonts
1693 '(variable-pitch (:height 1.3 :weight bold))
1696 (defun shr-tag-h2 (dom)
1697 (shr-heading dom 'bold))
1699 (defun shr-tag-h3 (dom)
1700 (shr-heading dom 'italic))
1702 (defun shr-tag-h4 (dom)
1705 (defun shr-tag-h5 (dom)
1708 (defun shr-tag-h6 (dom)
1711 (defun shr-tag-hr (_dom)
1712 (shr-ensure-newline)
1713 (insert (make-string (if (not shr-use-fonts)
1715 (1+ (/ shr-internal-width
1716 shr-table-separator-pixel-width)))
1720 (defun shr-tag-title (dom)
1721 (shr-heading dom 'bold 'underline))
1723 (defun shr-tag-font (dom)
1724 (let* ((start (point))
1725 (color (dom-attr dom 'color))
1726 (shr-stylesheet (nconc (list (cons 'color color))
1730 (shr-colorize-region start (point) color
1731 (cdr (assq 'background-color shr-stylesheet))))))
1733 (defun shr-tag-bdo (dom)
1734 (let* ((direction (dom-attr dom 'dir))
1736 ((equal direction "ltr")
1737 ?\N{LEFT-TO-RIGHT OVERRIDE})
1738 ((equal direction "rtl")
1739 ?\N{RIGHT-TO-LEFT OVERRIDE}))))
1741 (insert ?\N{FIRST STRONG ISOLATE} char))
1744 (insert ?\N{POP DIRECTIONAL FORMATTING} ?\N{POP DIRECTIONAL ISOLATE}))))
1746 (defun shr-tag-bdi (dom)
1747 (insert ?\N{FIRST STRONG ISOLATE})
1749 (insert ?\N{POP DIRECTIONAL ISOLATE}))
1751 ;;; Table rendering algorithm.
1753 ;; Table rendering is the only complicated thing here. We do this by
1754 ;; first counting how many TDs there are in each TR, and registering
1755 ;; how wide they think they should be ("width=45%", etc). Then we
1756 ;; render each TD separately (this is done in temporary buffers, so
1757 ;; that we can use all the rendering machinery as if we were in the
1758 ;; main buffer). Now we know how much space each TD really takes, so
1759 ;; we then render everything again with the new widths, and finally
1760 ;; insert all these boxes into the main buffer.
1761 (defun shr-tag-table-1 (dom)
1762 (setq dom (or (dom-child-by-tag dom 'tbody) dom))
1763 (let* ((shr-inhibit-images t)
1764 (shr-table-depth (1+ shr-table-depth))
1765 (shr-kinsoku-shorten t)
1766 ;; Find all suggested widths.
1767 (columns (shr-column-specs dom))
1768 ;; Compute how many pixels wide each TD should be.
1769 (suggested-widths (shr-pro-rate-columns columns))
1770 ;; Do a "test rendering" to see how big each TD is (this can
1771 ;; be smaller (if there's little text) or bigger (if there's
1772 ;; unbreakable text).
1773 (elems (or (dom-attr dom 'shr-suggested-widths)
1774 (shr-make-table dom suggested-widths nil
1775 'shr-suggested-widths)))
1776 (sketch (loop for line in elems
1777 collect (mapcar #'car line)))
1778 (natural (loop for line in elems
1779 collect (mapcar #'cdr line)))
1780 (sketch-widths (shr-table-widths sketch natural suggested-widths)))
1781 ;; This probably won't work very well.
1782 (when (> (+ (loop for width across sketch-widths
1784 shr-indentation shr-table-separator-pixel-width)
1786 (setq truncate-lines t))
1787 ;; Then render the table again with these new "hard" widths.
1788 (shr-insert-table (shr-make-table dom sketch-widths t) sketch-widths)))
1790 (defun shr-table-body (dom)
1791 (let ((tbodies (seq-filter (lambda (child)
1792 (eq (dom-tag child) 'tbody))
1793 (dom-non-text-children dom))))
1797 ((= (length tbodies) 1)
1800 ;; Table with multiple tbodies. Convert into a single tbody.
1801 `(tbody nil ,@(cl-reduce 'append
1802 (mapcar 'dom-non-text-children tbodies)))))))
1804 (defun shr-tag-table (dom)
1805 (shr-ensure-paragraph)
1806 (let* ((caption (dom-children (dom-child-by-tag dom 'caption)))
1807 (header (dom-non-text-children (dom-child-by-tag dom 'thead)))
1808 (body (dom-non-text-children (shr-table-body dom)))
1809 (footer (dom-non-text-children (dom-child-by-tag dom 'tfoot)))
1810 (bgcolor (dom-attr dom 'bgcolor))
1812 (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
1814 (nheader (if header (shr-max-columns header)))
1815 (nbody (if body (shr-max-columns body) 0))
1816 (nfooter (if footer (shr-max-columns footer))))
1817 (if (and (not caption)
1819 (not (dom-child-by-tag dom 'tbody))
1820 (not (dom-child-by-tag dom 'tr))
1822 ;; The table is totally invalid and just contains random junk.
1823 ;; Try to output it anyway.
1825 ;; It's a real table, so render it.
1826 (if (dom-attr dom 'shr-fixed-table)
1827 (shr-tag-table-1 dom)
1828 ;; Only fix up the table once.
1832 (if caption `((tr nil (td nil ,@caption))))
1836 ;; header + body + footer
1837 (if (= nheader nbody)
1838 (if (= nbody nfooter)
1839 `((tr nil (td nil (table nil
1841 ,@body ,@footer)))))
1842 (nconc `((tr nil (td nil (table nil
1847 `((tr nil (td nil (table
1849 nil ,@footer))))))))
1850 (nconc `((tr nil (td nil (table nil (tbody
1852 (if (= nbody nfooter)
1853 `((tr nil (td nil (table
1854 nil (tbody nil ,@body
1856 (nconc `((tr nil (td nil (table
1861 `((tr nil (td nil (table
1867 (if (= nheader nbody)
1868 `((tr nil (td nil (table nil (tbody nil ,@header
1871 `(,@header (tr nil (td nil (table
1872 nil (tbody nil ,@body)))))
1873 `((tr nil (td nil (table nil (tbody nil ,@header))))
1874 (tr nil (td nil (table nil (tbody nil ,@body)))))))))
1877 (if (= nbody nfooter)
1878 `((tr nil (td nil (table
1879 nil (tbody nil ,@body ,@footer)))))
1880 (nconc `((tr nil (td nil (table nil (tbody nil ,@body)))))
1883 `((tr nil (td nil (table
1884 nil (tbody nil ,@footer)))))))))
1886 `((tr nil (td nil (table nil (tbody nil ,@body))))))
1888 (dom-set-attribute table 'shr-fixed-table t)
1889 (setcdr dom (cdr table))
1890 (shr-tag-table-1 dom))))
1892 (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
1894 ;; Finally, insert all the images after the table. The Emacs buffer
1895 ;; model isn't strong enough to allow us to put the images actually
1897 (when (zerop shr-table-depth)
1899 (shr-expand-alignments start (point)))
1900 (dolist (elem (dom-by-tag dom 'object))
1901 (shr-tag-object elem))
1902 (dolist (elem (dom-by-tag dom 'img))
1903 (shr-tag-img elem)))))
1905 (defun shr-insert-table (table widths)
1906 (let* ((collapse (equal (cdr (assq 'border-collapse shr-stylesheet))
1908 (shr-table-separator-length (if collapse 0 1))
1909 (shr-table-vertical-line (if collapse "" shr-table-vertical-line))
1911 (setq shr-table-id (1+ shr-table-id))
1913 (shr-insert-table-ruler widths))
1915 (let ((start (point))
1918 (height (let ((max 0))
1919 (dolist (column row)
1920 (setq max (max max (nth 2 column))))
1922 (dotimes (i (max height 1))
1924 (insert shr-table-vertical-line "\n"))
1925 (dolist (column row)
1926 (when (> (nth 2 column) -1)
1928 ;; Sum up all the widths from the column. (There may be
1929 ;; more than one if this is a "colspan" column.)
1930 (dotimes (i (nth 4 column))
1931 ;; The colspan directive may be wrong and there may not be
1932 ;; that number of columns.
1933 (when (<= column-number (1- (length widths)))
1934 (setq align (+ align
1935 (aref widths column-number)
1936 (* 2 shr-table-separator-pixel-width))))
1937 (setq column-number (1+ column-number)))
1938 (let ((lines (nth 3 column))
1939 (pixel-align (if (not shr-use-fonts)
1940 (* align (frame-char-width))
1942 (dolist (line lines)
1944 (let ((start (point))
1945 (background (and (> (length line) 0)
1946 (shr-face-background
1948 (1- (length line)) 'face line))))
1951 'display `(space :align-to (,pixel-align))
1952 'shr-table-indent shr-table-id)))
1954 (setq space (propertize space 'face background)))
1955 (insert line space shr-table-vertical-line)
1956 (shr-colorize-region
1957 start (1- (point)) (nth 5 column) (nth 6 column)))
1959 ;; Add blank lines at padding at the bottom of the TD,
1961 (dotimes (i (- height (length lines)))
1963 (let ((start (point)))
1964 (insert (propertize " "
1965 'display `(space :align-to (,pixel-align))
1966 'shr-table-indent shr-table-id)
1967 shr-table-vertical-line)
1968 (shr-colorize-region
1969 start (1- (point)) (nth 5 column) (nth 6 column)))
1970 (forward-line 1))))))
1972 (shr-insert-table-ruler widths)))
1973 (unless (= start (point))
1974 (put-text-property start (1+ start) 'shr-table-id shr-table-id))))
1976 (defun shr-face-background (face)
1978 (or (and (plist-get face :background)
1979 (list :background (plist-get face :background)))
1980 (let ((background nil))
1982 (when (and (consp elem)
1983 (eq (car elem) :background)
1985 (setq background (cadr elem))))
1987 (list :background background))))))
1989 (defun shr-expand-alignments (start end)
1990 (while (< (setq start (next-single-property-change
1991 start 'shr-table-id nil end))
1994 (let* ((shr-use-fonts t)
1995 (id (get-text-property (point) 'shr-table-id))
1996 (base (shr-pixel-column))
2000 (while (setq elem (text-property-any
2001 (point) end 'shr-table-indent id))
2003 (let ((align (get-text-property (point) 'display)))
2004 (put-text-property (point) (1+ (point)) 'display
2005 `(space :align-to (,(+ (car (nth 2 align))
2007 (forward-char 1)))))
2008 (setq start (1+ start))))
2010 (defun shr-insert-table-ruler (widths)
2011 (when shr-table-horizontal-line
2013 (> shr-indentation 0))
2015 (insert shr-table-corner)
2016 (let ((total-width 0))
2017 (dotimes (i (length widths))
2018 (setq total-width (+ total-width (aref widths i)
2019 (* shr-table-separator-pixel-width 2)))
2020 (insert (make-string (1+ (/ (aref widths i)
2021 shr-table-separator-pixel-width))
2022 shr-table-horizontal-line)
2024 'display `(space :align-to (,total-width))
2025 'shr-table-indent shr-table-id)
2029 (defun shr-table-widths (table natural-table suggested-widths)
2030 (let* ((length (length suggested-widths))
2031 (widths (make-vector length 0))
2032 (natural-widths (make-vector length 0)))
2035 (dolist (column row)
2036 (aset widths i (max (aref widths i) column))
2038 (dolist (row natural-table)
2040 (dolist (column row)
2041 (aset natural-widths i (max (aref natural-widths i) column))
2043 (let ((extra (- (apply '+ (append suggested-widths nil))
2044 (apply '+ (append widths nil))
2045 (* shr-table-separator-pixel-width (1+ (length widths)))))
2046 (expanded-columns 0))
2047 ;; We have extra, unused space, so divide this space amongst the
2050 ;; If the natural width is wider than the rendered width, we
2051 ;; want to allow the column to expand.
2053 (when (> (aref natural-widths i) (aref widths i))
2054 (setq expanded-columns (1+ expanded-columns))))
2056 (when (> (aref natural-widths i) (aref widths i))
2058 (aref natural-widths i)
2059 (+ (/ extra expanded-columns)
2060 (aref widths i))))))))
2063 (defun shr-make-table (dom widths &optional fill storage-attribute)
2064 (or (cadr (assoc (list dom widths fill) shr-content-cache))
2065 (let ((data (shr-make-table-1 dom widths fill)))
2066 (push (list (list dom widths fill) data)
2068 (when storage-attribute
2069 (dom-set-attribute dom storage-attribute data))
2072 (defun shr-make-table-1 (dom widths &optional fill)
2074 (rowspans (make-vector (length widths) 0))
2075 (colspan-remaining 0)
2076 colspan-width colspan-count
2078 (dolist (row (dom-non-text-children dom))
2079 (when (eq (dom-tag row) 'tr)
2081 (columns (dom-non-text-children row))
2085 (while (< i (length widths))
2086 ;; If we previously had a rowspan definition, then that
2087 ;; means that we now have a "missing" td/th element here.
2088 ;; So just insert a dummy, empty one to (sort of) emulate
2091 (if (zerop (aref rowspans i))
2093 (aset rowspans i (1- (aref rowspans i)))
2095 (when (and (not (stringp column))
2096 (or (memq (dom-tag column) '(td th))
2098 (when-let (span (dom-attr column 'rowspan))
2099 (aset rowspans i (+ (aref rowspans i)
2100 (1- (string-to-number span)))))
2101 ;; Sanity check for invalid column-spans.
2102 (when (>= width-column (length widths))
2103 (setq width-column 0))
2106 (aref widths width-column)
2107 (* 10 shr-table-separator-pixel-width)))
2108 (when (setq colspan (dom-attr column 'colspan))
2109 (setq colspan (min (string-to-number colspan)
2110 ;; The colspan may be wrong, so
2111 ;; truncate it to the length of the
2112 ;; remaining columns.
2113 (- (length widths) i)))
2114 (dotimes (j (1- colspan))
2116 (if (> (+ i 1 j) (1- (length widths)))
2117 ;; If we have a colspan spec that's longer
2118 ;; than the table is wide, just use the last
2119 ;; width as the width.
2120 (aref widths (1- (length widths)))
2121 ;; Sum up the widths of the columns we're
2124 shr-table-separator-length
2125 (aref widths (+ i 1 j))))))
2126 (setq width-column (+ width-column (1- colspan))
2127 colspan-count colspan
2128 colspan-remaining colspan))
2130 (let ((data (shr-render-td column width fill)))
2132 (> colspan-remaining 0))
2134 (setq colspan-width (car data))
2135 (let ((this-width (/ colspan-width colspan-count)))
2136 (push (cons this-width (cadr data)) tds)
2137 (setq colspan-remaining (1- colspan-remaining))))
2139 (push (cons (car data) (cadr data)) tds)
2143 (dotimes (c (1- colspan))
2147 (list 0 0 -1 nil 1 nil nil)
2151 width-column (1+ width-column))))
2152 (push (nreverse tds) trs))))
2155 (defun shr-pixel-buffer-width ()
2156 (if (not shr-use-fonts)
2158 (goto-char (point-min))
2162 (setq max (max max (current-column)))
2165 (if (get-buffer-window)
2166 (car (window-text-pixel-size nil (point-min) (point-max)))
2167 (save-window-excursion
2168 (set-window-buffer nil (current-buffer))
2169 (car (window-text-pixel-size nil (point-min) (point-max)))))))
2171 (defun shr-render-td (dom width fill)
2172 (let ((cache (intern (format "shr-td-cache-%s-%s" width fill))))
2173 (or (dom-attr dom cache)
2176 (dolist (attr (dom-attributes dom))
2177 (let ((name (symbol-name (car attr))))
2178 (when (string-match "shr-td-cache-\\([0-9]+\\)-nil" name)
2179 (let ((cache-width (string-to-number
2180 (match-string 1 name))))
2181 (when (and (>= cache-width width)
2182 (<= (car (cdr attr)) width))
2183 (setq result (cdr attr)))))))
2185 (let ((result (shr-render-td-1 dom width fill)))
2186 (dom-set-attribute dom cache result)
2189 (defun shr-render-td-1 (dom width fill)
2191 (let ((bgcolor (dom-attr dom 'bgcolor))
2192 (fgcolor (dom-attr dom 'fgcolor))
2193 (style (dom-attr dom 'style))
2194 (shr-stylesheet shr-stylesheet)
2198 (setq style (and (string-match "color" style)
2199 (shr-parse-style style))))
2201 (setq style (nconc (list (cons 'background-color bgcolor))
2204 (setq style (nconc (list (cons 'color fgcolor)) style)))
2206 (setq shr-stylesheet (append style shr-stylesheet)))
2207 (let ((shr-internal-width width)
2208 (shr-indentation 0))
2210 (save-window-excursion
2211 (set-window-buffer nil (current-buffer))
2214 (or (dom-attr dom 'shr-td-cache-natural)
2215 (let ((natural (max (shr-pixel-buffer-width)
2216 (shr-dom-max-natural-width dom 0))))
2217 (dom-set-attribute dom 'shr-td-cache-natural natural)
2219 (if (and natural-width
2220 (<= natural-width width))
2221 (setq max-width natural-width)
2222 (let ((shr-internal-width width))
2223 (shr-fill-lines (point-min) (point-max))
2224 (setq max-width (shr-pixel-buffer-width)))))
2225 (goto-char (point-max))
2226 ;; Delete padding at the bottom of the TDs.
2230 (skip-chars-backward " \t\n")
2233 (goto-char (point-min))
2236 (count-lines (point-min) (point-max))
2237 (split-string (buffer-string) "\n")
2238 (if (dom-attr dom 'colspan)
2239 (string-to-number (dom-attr dom 'colspan))
2241 (cdr (assq 'color shr-stylesheet))
2242 (cdr (assq 'background-color shr-stylesheet))))))
2244 (defun shr-dom-max-natural-width (dom max)
2245 (if (eq (dom-tag dom) 'table)
2247 (loop for line in (dom-attr dom 'shr-suggested-widths)
2249 shr-table-separator-length
2250 (loop for elem in line
2253 (* 2 shr-table-separator-length)))))
2255 (dolist (child (dom-children dom))
2256 (unless (stringp child)
2257 (setq max (max (shr-dom-max-natural-width child max)))))
2260 (defun shr-buffer-width ()
2261 (goto-char (point-min))
2265 (setq max (max max (current-column)))
2269 (defun shr-pro-rate-columns (columns)
2270 (let ((total-percentage 0)
2271 (widths (make-vector (length columns) 0)))
2272 (dotimes (i (length columns))
2273 (setq total-percentage (+ total-percentage (aref columns i))))
2274 (setq total-percentage (/ 1.0 total-percentage))
2275 (dotimes (i (length columns))
2276 (aset widths i (max (truncate (* (aref columns i)
2278 (- shr-internal-width
2279 (* (1+ (length columns))
2280 shr-table-separator-pixel-width))))
2284 ;; Return a summary of the number and shape of the TDs in the table.
2285 (defun shr-column-specs (dom)
2286 (let ((columns (make-vector (shr-max-columns dom) 1)))
2287 (dolist (row (dom-non-text-children dom))
2288 (when (eq (dom-tag row) 'tr)
2290 (dolist (column (dom-non-text-children row))
2291 (when (memq (dom-tag column) '(td th))
2292 (let ((width (dom-attr column 'width)))
2294 (string-match "\\([0-9]+\\)%" width)
2295 (not (zerop (setq width (string-to-number
2296 (match-string 1 width))))))
2297 (aset columns i (/ width 100.0))))
2298 (setq i (1+ i)))))))
2301 (defun shr-count (dom elem)
2303 (dolist (sub (dom-children dom))
2304 (when (and (not (stringp sub))
2305 (eq (dom-tag sub) elem))
2309 (defun shr-max-columns (dom)
2311 (dolist (row (dom-children dom))
2312 (when (and (not (stringp row))
2313 (eq (dom-tag row) 'tr))
2314 (setq max (max max (+ (shr-count row 'td)
2315 (shr-count row 'th))))))
2320 ;;; shr.el ends here