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.
40 "Simple HTML Renderer"
44 (defcustom shr-max-image-proportion 0.9
45 "How big pictures displayed are in relation to the window they're in.
46 A value of 0.7 means that they are allowed to take up 70% of the
47 width and height of the window. If they are larger than this,
48 and Emacs supports it, then the images will be rescaled down to
54 (defcustom shr-blocked-images nil
55 "Images that have URLs matching this regexp will be blocked."
58 :type '(choice (const nil) regexp))
60 (defcustom shr-use-fonts t
61 "If non-nil, use proportional fonts for text."
66 (defcustom shr-use-colors t
67 "If non-nil, respect color specifications in the HTML."
72 (defcustom shr-table-horizontal-line nil
73 "Character used to draw horizontal table lines.
74 If nil, don't draw horizontal table lines."
76 :type '(choice (const nil) character))
78 (defcustom shr-table-vertical-line ?\s
79 "Character used to draw vertical table lines."
83 (defcustom shr-table-corner ?\s
84 "Character used to draw table corners."
88 (defcustom shr-hr-line ?-
89 "Character used to draw hr lines."
93 (defcustom shr-width nil
94 "Frame width to use for rendering.
95 May either be an integer specifying a fixed width in characters,
96 or nil, meaning that the full width of the window should be
99 :type '(choice (integer :tag "Fixed width in characters")
100 (const :tag "Use the width of the window" nil))
103 (defcustom shr-bullet "* "
104 "Bullet used for unordered lists.
105 Alternative suggestions are:
112 (defcustom shr-external-browser 'browse-url-default-browser
113 "Function used to launch an external browser."
118 (defcustom shr-image-animate t
119 "Non nil means that images that can be animated will be."
124 (defvar shr-content-function nil
125 "If bound, this should be a function that will return the content.
126 This is used for cid: URLs, and the function is called with the
127 cid: URL as the argument.")
129 (defvar shr-put-image-function 'shr-put-image
130 "Function called to put image and alt string.")
132 (defface shr-strike-through '((t (:strike-through t)))
133 "Font for <s> elements."
137 '((t (:inherit link)))
138 "Font for link elements."
141 (defvar shr-inhibit-images nil
142 "If non-nil, inhibit loading images.")
144 (defvar shr-external-rendering-functions nil
145 "Alist of tag/function pairs used to alter how shr renders certain tags.
146 For instance, eww uses this to alter rendering of title, forms
148 ((title . eww-tag-title)
149 (form . eww-tag-form)
152 ;;; Internal variables.
154 (defvar shr-folding-mode nil)
155 (defvar shr-start nil)
156 (defvar shr-indentation 0)
157 (defvar shr-internal-width nil)
158 (defvar shr-list-mode nil)
159 (defvar shr-content-cache nil)
160 (defvar shr-kinsoku-shorten nil)
161 (defvar shr-table-depth 0)
162 (defvar shr-stylesheet nil)
163 (defvar shr-base nil)
165 (defvar shr-warning nil)
166 (defvar shr-ignore-cache nil)
167 (defvar shr-target-id nil)
168 (defvar shr-table-separator-length 1)
169 (defvar shr-table-separator-pixel-width 0)
170 (defvar shr-table-id nil)
171 (defvar shr-current-font nil)
172 (defvar shr-internal-bullet nil)
175 (let ((map (make-sparse-keymap)))
176 (define-key map "a" 'shr-show-alt-text)
177 (define-key map "i" 'shr-browse-image)
178 (define-key map "z" 'shr-zoom-image)
179 (define-key map [?\t] 'shr-next-link)
180 (define-key map [?\M-\t] 'shr-previous-link)
181 (define-key map [follow-link] 'mouse-face)
182 (define-key map [mouse-2] 'shr-browse-url)
183 (define-key map "I" 'shr-insert-image)
184 (define-key map "w" 'shr-copy-url)
185 (define-key map "u" 'shr-copy-url)
186 (define-key map "v" 'shr-browse-url)
187 (define-key map "o" 'shr-save-contents)
188 (define-key map "\r" 'shr-browse-url)
191 ;; Public functions and commands.
192 (declare-function libxml-parse-html-region "xml.c"
193 (start end &optional base-url discard-comments))
195 (defun shr-render-buffer (buffer)
196 "Display the HTML rendering of the current buffer."
197 (interactive (list (current-buffer)))
198 (or (fboundp 'libxml-parse-html-region)
199 (error "This function requires Emacs to be compiled with libxml2"))
200 (pop-to-buffer "*html*")
203 (with-current-buffer buffer
204 (libxml-parse-html-region (point-min) (point-max))))
205 (goto-char (point-min)))
208 (defun shr-render-region (begin end &optional buffer)
209 "Display the HTML rendering of the region between BEGIN and END."
211 (unless (fboundp 'libxml-parse-html-region)
212 (error "This function requires Emacs to be compiled with libxml2"))
213 (with-current-buffer (or buffer (current-buffer))
214 (let ((dom (libxml-parse-html-region begin end)))
215 (delete-region begin end)
217 (shr-insert-document dom))))
219 (defun shr--have-one-fringe-p ()
220 "Return non-nil if we know at least one of the fringes has non-zero width."
221 (and (fboundp 'fringe-columns)
222 (or (not (zerop (fringe-columns 'right)))
223 (not (zerop (fringe-columns 'left))))))
226 (defun shr-insert-document (dom)
227 "Render the parsed document DOM into the current buffer.
228 DOM should be a parse tree as generated by
229 `libxml-parse-html-region' or similar."
230 (setq shr-content-cache nil)
231 (let ((start (point))
237 (shr-table-separator-pixel-width (shr-string-pixel-width "-"))
238 (shr-internal-bullet (cons shr-bullet
239 (shr-string-pixel-width shr-bullet)))
240 (shr-internal-width (or (and shr-width
241 (if (not shr-use-fonts)
243 (* shr-width (frame-char-width))))
244 ;; We need to adjust the available
245 ;; width for when the user disables
246 ;; the fringes, which will cause the
247 ;; display engine usurp one column for
248 ;; the continuation glyph.
249 (if (not shr-use-fonts)
250 (- (window-body-width) 1
251 (if (and (null shr-width)
252 (not (shr--have-one-fringe-p)))
255 (- (window-body-width nil t)
256 (* 2 (frame-char-width))
257 (if (and (null shr-width)
258 (not (shr--have-one-fringe-p)))
259 (* (frame-char-width) 2)
261 bidi-display-reordering)
262 ;; If the window was hscrolled for some reason, shr-fill-lines
263 ;; below will misbehave, because it silently assumes that it
264 ;; starts with a non-hscrolled window (vertical-motion will move
265 ;; to a wrong place otherwise).
266 (set-window-hscroll nil 0)
268 (shr-fill-lines start (point))
269 (shr-remove-trailing-whitespace start (point))
271 (message "%s" shr-warning))))
273 (defun shr-remove-trailing-whitespace (start end)
274 (let ((width (window-width)))
276 (narrow-to-region start end)
280 (when (> (shr-previous-newline-padding-width (current-column)) width)
281 (dolist (overlay (overlays-at (point)))
282 (when (overlay-get overlay 'before-string)
283 (overlay-put overlay 'before-string nil))))
286 (defun shr-copy-url (&optional image-url)
287 "Copy the URL under point to the kill ring.
288 If IMAGE-URL (the prefix) is non-nil, or there is no link under
289 point, but there is an image under point then copy the URL of the
290 image under point instead.
291 If called twice, then try to fetch the URL and see whether it
292 redirects somewhere else."
294 (let ((url (or (get-text-property (point) 'shr-url)
295 (get-text-property (point) 'image-url))))
298 (message "No URL under point"))
299 ;; Resolve redirected URLs.
300 ((equal url (car kill-ring))
305 (eq (car a) :redirect))
308 (goto-char (point-min))
309 ;; Remove common tracking junk from the URL.
310 (when (re-search-forward ".utm_.*" nil t)
311 (replace-match "" t t))
312 (message "Copied %s" (buffer-string))
313 (copy-region-as-kill (point-min) (point-max)))))
315 ;; Copy the URL to the kill ring.
318 (insert (url-encode-url url))
319 (copy-region-as-kill (point-min) (point-max))
320 (message "Copied %s" (buffer-string)))))))
322 (defun shr-next-link ()
323 "Skip to the next link."
325 (let ((current (get-text-property (point) 'shr-url))
328 (while (and (not (eobp))
329 (equal (get-text-property (point) 'shr-url) current))
333 (get-text-property (point) 'shr-url))
334 ;; The next link is adjacent.
335 (message "%s" (get-text-property (point) 'help-echo)))
337 (not (setq skip (text-property-not-all (point) (point-max)
340 (message "No next link"))
343 (message "%s" (get-text-property (point) 'help-echo))))))
345 (defun shr-previous-link ()
346 "Skip to the previous link."
348 (let ((start (point))
350 ;; Skip past the current link.
351 (while (and (not (bobp))
352 (get-text-property (point) 'help-echo))
354 ;; Find the previous link.
355 (while (and (not (bobp))
356 (not (setq found (get-text-property (point) 'help-echo))))
360 (message "No previous link")
362 ;; Put point at the start of the link.
363 (while (and (not (bobp))
364 (get-text-property (point) 'help-echo))
367 (message "%s" (get-text-property (point) 'help-echo)))))
369 (defun shr-show-alt-text ()
370 "Show the ALT text of the image under point."
372 (let ((text (get-text-property (point) 'shr-alt)))
374 (message "No image under point")
375 (message "%s" (shr-fill-text text)))))
377 (defun shr-browse-image (&optional copy-url)
378 "Browse the image under point.
379 If COPY-URL (the prefix if called interactively) is non-nil, copy
380 the URL of the image to the kill buffer instead."
382 (let ((url (get-text-property (point) 'image-url)))
385 (message "No image under point"))
389 (copy-region-as-kill (point-min) (point-max))
390 (message "Copied %s" url)))
392 (message "Browsing %s..." url)
395 (defun shr-insert-image ()
396 "Insert the image under point into the buffer."
398 (let ((url (get-text-property (point) 'image-url)))
400 (message "No image under point")
401 (message "Inserting %s..." url)
402 (url-retrieve url 'shr-image-fetched
403 (list (current-buffer) (1- (point)) (point-marker))
406 (defun shr-zoom-image ()
407 "Toggle the image size.
408 The size will be rotated between the default size, the original
409 size, and full-buffer size."
411 (let ((url (get-text-property (point) 'image-url))
412 (size (get-text-property (point) 'image-size))
413 (buffer-read-only nil))
415 (message "No image under point")
416 ;; Delete the old picture.
417 (while (get-text-property (point) 'image-url)
420 (let ((start (point)))
421 (while (get-text-property (point) 'image-url)
424 (put-text-property start (point) 'display nil)
425 (when (> (- (point) start) 2)
426 (delete-region start (1- (point)))))
427 (message "Inserting %s..." url)
428 (url-retrieve url 'shr-image-fetched
429 (list (current-buffer) (1- (point)) (point-marker)
431 (cond ((or (eq size 'default)
440 ;;; Utility functions.
442 (defsubst shr-generic (dom)
443 (dolist (sub (dom-children dom))
448 (defun shr-descend (dom)
450 (intern (concat "shr-tag-" (symbol-name (dom-tag dom))) obarray))
451 ;; Allow other packages to override (or provide) rendering
453 (external (cdr (assq (dom-tag dom) shr-external-rendering-functions)))
454 (style (dom-attr dom 'style))
455 (shr-stylesheet shr-stylesheet)
456 (shr-depth (1+ shr-depth))
458 ;; shr uses many frames per nested node.
459 (if (> shr-depth (/ max-specpdl-size 15))
460 (setq shr-warning "Too deeply nested to render properly; consider increasing `max-specpdl-size'")
462 (if (string-match "color\\|display\\|border-collapse" style)
463 (setq shr-stylesheet (nconc (shr-parse-style style)
466 ;; If we have a display:none, then just ignore this part of the DOM.
467 (unless (equal (cdr (assq 'display shr-stylesheet)) "none")
469 (funcall external dom))
471 (funcall function dom))
474 (when (and shr-target-id
475 (equal (dom-attr dom 'id) shr-target-id))
476 ;; If the element was empty, we don't have anything to put the
477 ;; anchor on. So just insert a dummy character.
478 (when (= start (point))
480 (put-text-property start (1+ start) 'shr-target-id shr-target-id))
481 ;; If style is set, then this node has set the color.
485 (cdr (assq 'color shr-stylesheet))
486 (cdr (assq 'background-color shr-stylesheet))))))))
488 (defun shr-fill-text (text)
489 (if (zerop (length text))
492 (let ((shr-indentation 0)
494 (shr-internal-width (- (window-body-width nil t)
495 (* 2 (frame-char-width))
496 ;; Adjust the window width for when
497 ;; the user disables the fringes,
498 ;; which causes the display engine
499 ;; to usurp one column for the
500 ;; continuation glyph.
501 (if (and (null shr-width)
502 (not (shr--have-one-fringe-p)))
503 (* (frame-char-width) 2)
508 (define-inline shr-char-breakable-p (char)
509 "Return non-nil if a line can be broken before and after CHAR."
510 (inline-quote (aref fill-find-break-point-function-table ,char)))
511 (define-inline shr-char-nospace-p (char)
512 "Return non-nil if no space is required before and after CHAR."
513 (inline-quote (aref fill-nospace-between-words-table ,char)))
515 ;; KINSOKU is a Japanese word meaning a rule that should not be violated.
516 ;; In Emacs, it is a term used for characters, e.g. punctuation marks,
517 ;; parentheses, and so on, that should not be placed in the beginning
518 ;; of a line or the end of a line.
519 (define-inline shr-char-kinsoku-bol-p (char)
520 "Return non-nil if a line ought not to begin with CHAR."
521 (inline-letevals (char)
522 (inline-quote (and (not (eq ,char ?'))
523 (aref (char-category-set ,char) ?>)))))
524 (define-inline shr-char-kinsoku-eol-p (char)
525 "Return non-nil if a line ought not to end with CHAR."
526 (inline-quote (aref (char-category-set ,char) ?<)))
527 (unless (shr-char-kinsoku-bol-p (make-char 'japanese-jisx0208 33 35))
528 (load "kinsoku" nil t))
530 (defun shr-pixel-column ()
531 (if (not shr-use-fonts)
533 (if (not (get-buffer-window (current-buffer)))
534 (save-window-excursion
535 (set-window-buffer nil (current-buffer))
536 (car (window-text-pixel-size nil (line-beginning-position) (point))))
537 (car (window-text-pixel-size nil (line-beginning-position) (point))))))
539 (defun shr-pixel-region ()
540 (- (shr-pixel-column)
543 (shr-pixel-column))))
545 (defun shr-string-pixel-width (string)
546 (if (not shr-use-fonts)
550 (shr-pixel-column))))
552 (defun shr-insert (text)
553 (when (and (not (bolp))
554 (get-text-property (1- (point)) 'image-url))
557 ((eq shr-folding-mode 'none)
558 (let ((start (point)))
561 (narrow-to-region start (point))
562 ;; Remove soft hyphens.
563 (goto-char (point-min))
564 (while (search-forward "Â" nil t)
565 (replace-match "" t t))
566 (goto-char (point-max)))))
568 (let ((font-start (point)))
569 (when (and (string-match "\\`[ \t\n\r ]" text)
571 (not (eq (char-after (1- (point))) ? )))
573 (let ((start (point))
577 (narrow-to-region start (point))
579 (when (looking-at "[ \t\n\r ]+")
580 (replace-match "" t t))
581 (while (re-search-forward "[ \t\n\r ]+" nil t)
582 (replace-match " " t t))
583 ;; Remove soft hyphens.
584 (goto-char (point-min))
585 (while (search-forward "Â" nil t)
586 (replace-match "" t t))
587 (goto-char (point-max)))
588 ;; We may have removed everything we inserted if if was just
590 (unless (= font-start (point))
591 ;; Mark all lines that should possibly be folded afterwards.
593 (shr-mark-fill start))
595 (put-text-property font-start (point)
597 (or shr-current-font 'variable-pitch)))))))))
599 (defun shr-fill-lines (start end)
600 (if (<= shr-internal-width 0)
603 (narrow-to-region start end)
605 (when (get-text-property (point) 'shr-indentation)
607 (while (setq start (next-single-property-change start 'shr-indentation))
611 (goto-char (point-max)))))
613 (defun shr-vertical-motion (column)
614 (if (not shr-use-fonts)
615 (move-to-column column)
618 (vertical-motion (cons (/ column (frame-char-width)) 0))
622 (defun shr-fill-line ()
623 (let ((shr-indentation (get-text-property (point) 'shr-indentation))
624 (continuation (get-text-property
625 (point) 'shr-continuation-indentation))
627 (put-text-property (point) (1+ (point)) 'shr-indentation nil)
628 (let ((face (get-text-property (point) 'face))
629 (background-start (point)))
632 (put-text-property background-start (point) 'face
633 `,(shr-face-background face))))
635 (setq shr-indentation (or continuation shr-indentation))
636 (shr-vertical-motion shr-internal-width)
637 (when (looking-at " $")
638 (delete-region (point) (line-end-position)))
640 ;; We have to do some folding. First find the first
641 ;; previous point suitable for folding.
642 (if (or (not (shr-find-fill-point (line-beginning-position)))
644 ;; We had unbreakable text (for this width), so just go to
645 ;; the first space and carry on.
648 (skip-chars-forward " ")
649 (search-forward " " (line-end-position) 'move)))
650 ;; Success; continue.
651 (when (= (preceding-char) ?\s)
653 (let ((face (get-text-property (point) 'face))
654 (background-start (point)))
658 (put-text-property background-start (point) 'face
659 `,(shr-face-background face))))
661 (shr-vertical-motion shr-internal-width)
662 (when (looking-at " $")
663 (delete-region (point) (line-end-position))))))
665 (defun shr-find-fill-point (start)
669 (while (not (or (setq failed (<= (point) start))
670 (eq (preceding-char) ? )
671 (eq (following-char) ? )
672 (shr-char-breakable-p (preceding-char))
673 (shr-char-breakable-p (following-char))
674 (and (shr-char-kinsoku-bol-p (preceding-char))
675 (shr-char-breakable-p (following-char))
676 (not (shr-char-kinsoku-bol-p (following-char))))
677 (shr-char-kinsoku-eol-p (following-char))
681 ;; There's no breakable point, so we give it up.
684 ;; Don't overflow the window edge, even if
685 ;; shr-kinsoku-shorten is nil.
686 (unless (or shr-kinsoku-shorten (null shr-width))
687 (while (setq found (re-search-forward
688 "\\(\\c>\\)\\| \\|\\c<\\|\\c|"
689 (line-end-position) 'move)))
691 (not (match-beginning 1)))
692 (goto-char (match-beginning 0)))))
695 ;; Don't put kinsoku-bol characters at the beginning of a line,
696 ;; or kinsoku-eol characters at the end of a line.
698 ;; Don't overflow the window edge, even if shr-kinsoku-shorten
700 ((or shr-kinsoku-shorten (null shr-width))
701 (while (and (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
702 (or (shr-char-kinsoku-eol-p (preceding-char))
703 (shr-char-kinsoku-bol-p (following-char))))
705 (when (setq failed (<= (point) start))
706 ;; There's no breakable point that doesn't violate kinsoku,
707 ;; so we look for the second best position.
713 (shr-char-kinsoku-eol-p (following-char)))))
715 ((shr-char-kinsoku-eol-p (preceding-char))
716 ;; Find backward the point where kinsoku-eol characters begin.
721 (and (> (setq count (1- count)) 0)
722 (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
723 (or (shr-char-kinsoku-eol-p (preceding-char))
724 (shr-char-kinsoku-bol-p (following-char)))))))
725 (when (setq failed (<= (point) start))
726 ;; There's no breakable point that doesn't violate kinsoku,
727 ;; so we go to the second best position.
728 (if (looking-at "\\(\\c<+\\)\\c<")
729 (goto-char (match-end 1))
731 ((shr-char-kinsoku-bol-p (following-char))
732 ;; Find forward the point where kinsoku-bol characters end.
736 (and (>= (setq count (1- count)) 0)
737 (shr-char-kinsoku-bol-p (following-char))
738 (shr-char-breakable-p (following-char))))))))
739 (when (eq (following-char) ? )
743 (defun shr-parse-base (url)
744 ;; Always chop off anchors.
745 (when (string-match "#.*" url)
746 (setq url (substring url 0 (match-beginning 0))))
747 ;; NB: <base href="" > URI may itself be relative to the document s URI
748 (setq url (shr-expand-url url))
749 (let* ((parsed (url-generic-parse-url url))
750 (local (url-filename parsed)))
751 (setf (url-filename parsed) "")
752 ;; Chop off the bit after the last slash.
753 (when (string-match "\\`\\(.*/\\)[^/]+\\'" local)
754 (setq local (match-string 1 local)))
755 ;; Always make the local bit end with a slash.
756 (when (and (not (zerop (length local)))
757 (not (eq (aref local (1- (length local))) ?/)))
758 (setq local (concat local "/")))
759 (list (url-recreate-url parsed)
764 (autoload 'url-expand-file-name "url-expand")
766 ;; FIXME This needs some tests writing.
767 ;; Does it even need to exist, given that url-expand-file-name does?
768 (defun shr-expand-url (url &optional base)
771 ;; shr-parse-base should never call this with non-nil base!
772 (shr-parse-base base)
773 ;; Bound by the parser.
775 (when (zerop (length url))
777 ;; Strip leading whitespace
778 (and url (string-match "\\`\\s-+" url)
779 (setq url (substring url (match-end 0))))
782 (string-match "\\`[a-z]*:" url))
783 ;; Absolute or empty URI
784 (or url (nth 3 base)))
785 ((eq (aref url 0) ?/)
786 (if (and (> (length url) 1)
787 (eq (aref url 1) ?/))
788 ;; //host...; just use the protocol
789 (concat (nth 2 base) ":" url)
790 ;; Just use the host name part.
791 (concat (car base) url)))
792 ((eq (aref url 0) ?#)
793 ;; A link to an anchor.
794 (concat (nth 3 base) url))
797 (url-expand-file-name url (concat (car base) (cadr base))))))
799 (defun shr-ensure-newline ()
800 (unless (zerop (current-column))
803 (defun shr-ensure-paragraph ()
805 (let ((prefix (get-text-property (line-beginning-position)
806 'shr-prefix-length)))
812 ;; We're already at a new paragraph; do nothing.
815 (= prefix (- (point) (line-beginning-position))))
816 ;; Do nothing; we're at the start of a <li>.
820 ;; If the current line is totally blank, and doesn't even
821 ;; have any face properties set, then delete the blank
823 (and (looking-at " *$")
824 (not (get-text-property (point) 'face))
825 (not (= (next-single-property-change (point) 'face nil
827 (line-end-position)))))
828 (delete-region (match-beginning 0) (match-end 0)))
833 (when (> shr-indentation 0)
835 (if (not shr-use-fonts)
836 (make-string shr-indentation ?\s)
839 `(space :width (,shr-indentation)))))))
841 (defun shr-fontize-dom (dom &rest types)
842 (let ((start (point)))
845 (shr-add-font start (point) type))))
847 ;; Add face to the region, but avoid putting the font properties on
848 ;; blank text at the start of the line, and the newline at the end, to
850 (defun shr-add-font (start end type)
853 (while (< (point) end)
855 (skip-chars-forward " "))
856 (add-face-text-property (point) (min (line-end-position) end) type t)
857 (if (< (line-end-position) end)
861 (defun shr-mouse-browse-url (ev)
862 "Browse the URL under the mouse cursor."
867 (defun shr-browse-url (&optional external mouse-event)
868 "Browse the URL under point.
869 If EXTERNAL, browse the URL using `shr-external-browser'."
870 (interactive (list current-prefix-arg last-nonmenu-event))
871 (mouse-set-point mouse-event)
872 (let ((url (get-text-property (point) 'shr-url)))
875 (message "No link under point"))
876 ((string-match "^mailto:" url)
877 (browse-url-mail url))
880 (funcall shr-external-browser url)
881 (browse-url url))))))
883 (defun shr-save-contents (directory)
884 "Save the contents from URL in a file."
885 (interactive "DSave contents of URL to directory: ")
886 (let ((url (get-text-property (point) 'shr-url)))
888 (message "No link under point")
889 (url-retrieve (shr-encode-url url)
890 'shr-store-contents (list url directory)
893 (defun shr-store-contents (status url directory)
894 (unless (plist-get status :error)
895 (when (or (search-forward "\n\n" nil t)
896 (search-forward "\r\n\r\n" nil t))
897 (write-region (point) (point-max)
898 (expand-file-name (file-name-nondirectory url)
901 (defun shr-image-fetched (status buffer start end &optional flags)
902 (let ((image-buffer (current-buffer)))
903 (when (and (buffer-name buffer)
904 (not (plist-get status :error)))
905 (url-store-in-cache image-buffer)
906 (when (or (search-forward "\n\n" nil t)
907 (search-forward "\r\n\r\n" nil t))
908 (let ((data (shr-parse-image-data)))
909 (with-current-buffer buffer
911 (let ((alt (buffer-substring start end))
912 (properties (text-properties-at start))
913 (inhibit-read-only t))
914 (delete-region start end)
916 (funcall shr-put-image-function data alt flags)
918 (let ((type (pop properties))
919 (value (pop properties)))
920 (unless (memq type '(display image-size))
921 (put-text-property start (point) type value))))))))))
922 (kill-buffer image-buffer)))
924 (defun shr-image-from-data (data)
925 "Return an image from the data: URI content DATA."
927 "\\(\\([^/;,]+\\(/[^;,]+\\)?\\)\\(;[^;,]+\\)*\\)?,\\(.*\\)"
929 (let ((param (match-string 4 data))
930 (payload (url-unhex-string (match-string 5 data))))
931 (when (string-match "^.*\\(;[ \t]*base64\\)$" param)
932 (setq payload (base64-decode-string payload)))
935 ;; Behind display-graphic-p test.
936 (declare-function image-size "image.c" (spec &optional pixels frame))
937 (declare-function image-animate "image" (image &optional index limit))
939 (defun shr-put-image (spec alt &optional flags)
940 "Insert image SPEC with a string ALT. Return image.
941 SPEC is either an image data blob, or a list where the first
942 element is the data blob and the second element is the content-type."
943 (if (display-graphic-p)
944 (let* ((size (cdr (assq 'size flags)))
945 (data (if (consp spec)
948 (content-type (and (consp spec)
953 (create-image data nil t :ascent 100
954 :format content-type))
955 ((eq content-type 'image/svg+xml)
956 (create-image data 'svg t :ascent 100))
959 (shr-rescale-image data content-type)))
962 (shr-rescale-image data content-type))))))
964 ;; When inserting big-ish pictures, put them at the
965 ;; beginning of the line.
966 (when (and (> (current-column) 0)
967 (> (car (image-size image t)) 400))
969 (if (eq size 'original)
970 (insert-sliced-image image (or alt "*") nil 20 1)
971 (insert-image image (or alt "*")))
972 (put-text-property start (point) 'image-size size)
973 (when (and shr-image-animate
974 (cond ((fboundp 'image-multi-frame-p)
975 ;; Only animate multi-frame things that specify a
976 ;; delay; eg animated gifs as opposed to
977 ;; multi-page tiffs. FIXME?
978 (cdr (image-multi-frame-p image)))
979 ((fboundp 'image-animated-p)
980 (image-animated-p image))))
981 (image-animate image nil 60)))
985 (defun shr-rescale-image (data &optional content-type)
986 "Rescale DATA, if too big, to fit the current buffer."
987 (if (not (and (fboundp 'imagemagick-types)
988 (get-buffer-window (current-buffer))))
989 (create-image data nil t :ascent 100)
990 (let ((edges (window-inside-pixel-edges
991 (get-buffer-window (current-buffer)))))
995 :max-width (truncate (* shr-max-image-proportion
996 (- (nth 2 edges) (nth 0 edges))))
997 :max-height (truncate (* shr-max-image-proportion
998 (- (nth 3 edges) (nth 1 edges))))
999 :format content-type))))
1001 ;; url-cache-extract autoloads url-cache.
1002 (declare-function url-cache-create-filename "url-cache" (url))
1003 (autoload 'mm-disable-multibyte "mm-util")
1004 (autoload 'browse-url-mail "browse-url")
1006 (defun shr-get-image-data (url)
1007 "Get image data for URL.
1008 Return a string with image data."
1010 (mm-disable-multibyte)
1011 (when (ignore-errors
1012 (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
1014 (when (or (search-forward "\n\n" nil t)
1015 (search-forward "\r\n\r\n" nil t))
1016 (shr-parse-image-data)))))
1018 (declare-function libxml-parse-xml-region "xml.c"
1019 (start end &optional base-url discard-comments))
1021 (defun shr-parse-image-data ()
1022 (let ((data (buffer-substring (point) (point-max)))
1026 (narrow-to-region (point-min) (point))
1027 (let ((content-type (mail-fetch-field "content-type")))
1029 ;; Remove any comments in the type string.
1030 (intern (replace-regexp-in-string ";.*" "" content-type)
1032 ;; SVG images may contain references to further images that we may
1033 ;; want to block. So special-case these by parsing the XML data
1034 ;; and remove the blocked bits.
1035 (when (eq content-type 'image/svg+xml)
1038 (libxml-parse-xml-region (point) (point-max)))))
1039 (list data content-type)))
1041 (defun shr-image-displayer (content-function)
1042 "Return a function to display an image.
1043 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
1044 is an argument. The function to be returned takes three arguments URL,
1045 START, and END. Note that START and END should be markers."
1046 `(lambda (url start end)
1048 (if (string-match "\\`cid:" url)
1049 ,(when content-function
1050 `(let ((image (funcall ,content-function
1051 (substring url (match-end 0)))))
1054 (funcall shr-put-image-function
1055 image (buffer-substring start end))
1056 (delete-region (point) end))))
1057 (url-retrieve url 'shr-image-fetched
1058 (list (current-buffer) start end)
1061 (defun shr-heading (dom &rest types)
1062 (shr-ensure-paragraph)
1063 (apply #'shr-fontize-dom dom types)
1064 (shr-ensure-paragraph))
1066 (defun shr-urlify (start url &optional title)
1067 (shr-add-font start (point) 'shr-link)
1068 (add-text-properties
1071 'help-echo (let ((iri (or (ignore-errors
1072 (decode-coding-string
1073 (url-unhex-string url)
1076 (if title (format "%s (%s)" iri title) iri))
1078 'mouse-face 'highlight
1081 (defun shr-encode-url (url)
1083 (browse-url-url-encode-chars url "[)$ ]"))
1085 (autoload 'shr-color-visible "shr-color")
1086 (autoload 'shr-color->hexadecimal "shr-color")
1088 (defun shr-color-check (fg bg)
1089 "Check that FG is visible on BG.
1090 Returns (fg bg) with corrected values.
1091 Returns nil if the colors that would be used are the default
1092 ones, in case fg and bg are nil."
1094 (let ((fixed (cond ((null fg) 'fg)
1096 ;; Convert colors to hexadecimal, or set them to default.
1097 (let ((fg (or (shr-color->hexadecimal fg)
1098 (frame-parameter nil 'foreground-color)))
1099 (bg (or (shr-color->hexadecimal bg)
1100 (frame-parameter nil 'background-color))))
1101 (cond ((eq fixed 'bg)
1102 ;; Only return the new fg
1103 (list nil (cadr (shr-color-visible bg fg t))))
1105 ;; Invert args and results and return only the new bg
1106 (list (cadr (shr-color-visible fg bg t)) nil))
1108 (shr-color-visible bg fg)))))))
1110 (defun shr-colorize-region (start end fg &optional bg)
1111 (when (and shr-use-colors
1113 (>= (display-color-cells) 88))
1114 (let ((new-colors (shr-color-check fg bg)))
1117 (add-face-text-property start end
1118 (list :foreground (cadr new-colors))
1121 (add-face-text-property start end
1122 (list :background (car new-colors))
1126 (defun shr-previous-newline-padding-width (width)
1127 (let ((overlays (overlays-at (point)))
1131 (dolist (overlay overlays)
1132 (setq previous-width
1134 (length (plist-get (overlay-properties overlay)
1136 (+ width previous-width))))
1138 ;;; Tag-specific rendering rules.
1140 (defun shr-tag-html (dom)
1141 (let ((dir (dom-attr dom 'dir)))
1144 (setq bidi-paragraph-direction 'left-to-right))
1146 (setq bidi-paragraph-direction 'right-to-left))))
1149 (defun shr-tag-body (dom)
1150 (let* ((start (point))
1151 (fgcolor (or (dom-attr dom 'fgcolor) (dom-attr dom 'text)))
1152 (bgcolor (dom-attr dom 'bgcolor))
1153 (shr-stylesheet (list (cons 'color fgcolor)
1154 (cons 'background-color bgcolor))))
1156 (shr-colorize-region start (point) fgcolor bgcolor)))
1158 (defun shr-tag-style (_dom)
1161 (defun shr-tag-script (_dom)
1164 (defun shr-tag-comment (_dom)
1167 (defun shr-dom-to-xml (dom)
1172 (defun shr-dom-print (dom)
1173 "Convert DOM into a string containing the xml representation."
1174 (insert (format "<%s" (dom-tag dom)))
1175 (dolist (attr (dom-attributes dom))
1176 ;; Ignore attributes that start with a colon because they are
1177 ;; private elements.
1178 (unless (= (aref (format "%s" (car attr)) 0) ?:)
1179 (insert (format " %s=\"%s\"" (car attr) (cdr attr)))))
1182 (dolist (elem (dom-children dom))
1186 ((eq (dom-tag elem) 'comment)
1188 ((or (not (eq (dom-tag elem) 'image))
1189 ;; Filter out blocked elements inside the SVG image.
1190 (not (setq url (dom-attr elem ':xlink:href)))
1191 (not shr-blocked-images)
1192 (not (string-match shr-blocked-images url)))
1194 (shr-dom-print elem)))))
1195 (insert (format "</%s>" (dom-tag dom))))
1197 (defun shr-tag-svg (dom)
1198 (when (and (image-type-available-p 'svg)
1199 (not shr-inhibit-images)
1200 (dom-attr dom 'width)
1201 (dom-attr dom 'height))
1202 (funcall shr-put-image-function (list (shr-dom-to-xml dom) 'image/svg+xml)
1205 (defun shr-tag-sup (dom)
1206 (let ((start (point)))
1208 (put-text-property start (point) 'display '(raise 0.5))))
1210 (defun shr-tag-sub (dom)
1211 (let ((start (point)))
1213 (put-text-property start (point) 'display '(raise -0.5))))
1215 (defun shr-tag-label (dom)
1217 (shr-ensure-paragraph))
1219 (defun shr-tag-p (dom)
1220 (shr-ensure-paragraph)
1222 (shr-ensure-paragraph))
1224 (defun shr-tag-div (dom)
1225 (shr-ensure-newline)
1227 (shr-ensure-newline))
1229 (defun shr-tag-s (dom)
1230 (shr-fontize-dom dom 'shr-strike-through))
1232 (defun shr-tag-del (dom)
1233 (shr-fontize-dom dom 'shr-strike-through))
1235 (defun shr-tag-b (dom)
1236 (shr-fontize-dom dom 'bold))
1238 (defun shr-tag-i (dom)
1239 (shr-fontize-dom dom 'italic))
1241 (defun shr-tag-em (dom)
1242 (shr-fontize-dom dom 'italic))
1244 (defun shr-tag-strong (dom)
1245 (shr-fontize-dom dom 'bold))
1247 (defun shr-tag-u (dom)
1248 (shr-fontize-dom dom 'underline))
1250 (defun shr-tag-tt (dom)
1251 (let ((shr-current-font 'default))
1254 (defun shr-parse-style (style)
1257 (when (string-match "\n" style)
1258 (setq style (replace-match " " t t style))))
1260 (dolist (elem (split-string style ";"))
1262 (setq elem (split-string elem ":"))
1263 (when (and (car elem)
1265 (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
1266 (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
1267 (when (string-match " *!important\\'" value)
1268 (setq value (substring value 0 (match-beginning 0))))
1269 (unless (equal value "inherit")
1270 (push (cons (intern name obarray)
1275 (defun shr-tag-base (dom)
1276 (when-let (base (dom-attr dom 'href))
1277 (setq shr-base (shr-parse-base base)))
1280 (defun shr-tag-a (dom)
1281 (let ((url (dom-attr dom 'href))
1282 (title (dom-attr dom 'title))
1286 (when (and shr-target-id
1287 (equal (dom-attr dom 'name) shr-target-id))
1288 ;; We have a zero-length <a name="foo"> element, so just
1289 ;; insert... something.
1290 (when (= start (point))
1291 (shr-ensure-newline)
1293 (put-text-property start (1+ start) 'shr-target-id shr-target-id))
1295 (shr-urlify (or shr-start start) (shr-expand-url url) title))))
1297 (defun shr-tag-object (dom)
1298 (unless shr-inhibit-images
1299 (let ((start (point))
1300 url multimedia image)
1301 (when-let (type (dom-attr dom 'type))
1302 (when (string-match "\\`image/svg" type)
1303 (setq url (dom-attr dom 'data)
1305 (dolist (child (dom-non-text-children dom))
1307 ((eq (dom-tag child) 'embed)
1308 (setq url (or url (dom-attr child 'src))
1310 ((and (eq (dom-tag child) 'param)
1311 (equal (dom-attr child 'name) "movie"))
1312 (setq url (or url (dom-attr child 'value))
1317 (shr-tag-img dom url)
1320 (shr-insert " [multimedia] ")
1321 (shr-urlify start (shr-expand-url url)))))
1323 (shr-generic dom)))))
1325 (defcustom shr-prefer-media-type-alist '(("webm" . 1.0)
1331 "Preferences for media types.
1332 The key element should be a regexp matched against the type of the source or
1333 url if no type is specified. The value should be a float in the range 0.0 to
1334 1.0. Media elements with higher value are preferred."
1337 :type '(alist :key-type regexp :value-type float))
1339 (defun shr--get-media-pref (elem)
1340 "Determine the preference for ELEM.
1341 The preference is a float determined from `shr-prefer-media-type'."
1342 (let ((type (dom-attr elem 'type))
1345 (setq type (dom-attr elem 'src)))
1347 (dolist (pref shr-prefer-media-type-alist)
1350 (string-match-p (car pref) type))
1351 (setq p (cdr pref)))))
1354 (defun shr--extract-best-source (dom &optional url pref)
1355 "Extract the best `:src' property from <source> blocks in DOM."
1356 (setq pref (or pref -1.0))
1358 (dolist (elem (dom-non-text-children dom))
1359 (when (and (eq (dom-tag elem) 'source)
1362 (shr--get-media-pref elem))))
1364 url (dom-attr elem 'src))
1365 ;; libxml's html parser isn't HTML5 compliant and non terminated
1366 ;; source tags might end up as children. So recursion it is...
1367 (dolist (child (dom-non-text-children elem))
1368 (when (eq (dom-tag child) 'source)
1369 (let ((ret (shr--extract-best-source (list child) url pref)))
1370 (when (< pref (cdr ret))
1372 pref (cdr ret)))))))))
1375 (defun shr-tag-video (dom)
1376 (let ((image (dom-attr dom 'poster))
1377 (url (dom-attr dom 'src))
1380 (setq url (car (shr--extract-best-source dom))))
1381 (if (> (length image) 0)
1382 (shr-tag-img nil image)
1383 (shr-insert " [video] "))
1384 (shr-urlify start (shr-expand-url url))))
1386 (defun shr-tag-audio (dom)
1387 (let ((url (dom-attr dom 'src))
1390 (setq url (car (shr--extract-best-source dom))))
1391 (shr-insert " [audio] ")
1392 (shr-urlify start (shr-expand-url url))))
1394 (defun shr-tag-img (dom &optional url)
1397 (> (length (dom-attr dom 'src)) 0)))
1398 (when (> (current-column) 0)
1400 (let ((alt (dom-attr dom 'alt))
1401 (url (shr-expand-url (or url (dom-attr dom 'src)))))
1402 (let ((start (point-marker)))
1403 (when (zerop (length alt))
1406 ((or (member (dom-attr dom 'height) '("0" "1"))
1407 (member (dom-attr dom 'width) '("0" "1")))
1408 ;; Ignore zero-sized or single-pixel images.
1410 ((and (not shr-inhibit-images)
1411 (string-match "\\`data:" url))
1412 (let ((image (shr-image-from-data (substring url (match-end 0)))))
1414 (funcall shr-put-image-function image alt)
1416 ((and (not shr-inhibit-images)
1417 (string-match "\\`cid:" url))
1418 (let ((url (substring url (match-end 0)))
1420 (if (or (not shr-content-function)
1421 (not (setq image (funcall shr-content-function url))))
1423 (funcall shr-put-image-function image alt))))
1424 ((or shr-inhibit-images
1425 (and shr-blocked-images
1426 (string-match shr-blocked-images url)))
1427 (setq shr-start (point))
1428 (if (> (string-width alt) 8)
1429 (shr-insert (truncate-string-to-width alt 8))
1431 ((and (not shr-ignore-cache)
1432 (url-is-cached (shr-encode-url url)))
1433 (funcall shr-put-image-function (shr-get-image-data url) alt))
1436 (when (and shr-ignore-cache
1437 (url-is-cached (shr-encode-url url)))
1438 (let ((file (url-cache-create-filename (shr-encode-url url))))
1439 (when (file-exists-p file)
1440 (delete-file file))))
1442 (shr-encode-url url) 'shr-image-fetched
1443 (list (current-buffer) start (set-marker (make-marker) (1- (point))))
1445 (when (zerop shr-table-depth) ;; We are not in a table.
1446 (put-text-property start (point) 'keymap shr-map)
1447 (put-text-property start (point) 'shr-alt alt)
1448 (put-text-property start (point) 'image-url url)
1449 (put-text-property start (point) 'image-displayer
1450 (shr-image-displayer shr-content-function))
1451 (put-text-property start (point) 'help-echo
1453 (or (dom-attr dom 'title) alt))))))))
1455 (defun shr-tag-pre (dom)
1456 (let ((shr-folding-mode 'none)
1457 (shr-current-font 'default))
1458 (shr-ensure-newline)
1460 (shr-ensure-newline)))
1462 (defun shr-tag-blockquote (dom)
1463 (shr-ensure-paragraph)
1464 (let ((start (point))
1465 (shr-indentation (+ shr-indentation
1466 (* 4 shr-table-separator-pixel-width))))
1468 (shr-ensure-paragraph)
1469 (shr-mark-fill start)))
1471 (defun shr-tag-dl (dom)
1472 (shr-ensure-paragraph)
1474 (shr-ensure-paragraph))
1476 (defun shr-tag-dt (dom)
1477 (shr-ensure-newline)
1479 (shr-ensure-newline))
1481 (defun shr-tag-dd (dom)
1482 (shr-ensure-newline)
1483 (let ((shr-indentation (+ shr-indentation
1484 (* 4 shr-table-separator-pixel-width))))
1487 (defun shr-tag-ul (dom)
1488 (shr-ensure-paragraph)
1489 (let ((shr-list-mode 'ul))
1491 (shr-ensure-paragraph))
1493 (defun shr-tag-ol (dom)
1494 (shr-ensure-paragraph)
1495 (let ((shr-list-mode 1))
1497 (shr-ensure-paragraph))
1499 (defun shr-tag-li (dom)
1500 (shr-ensure-newline)
1501 (let ((start (point)))
1503 (if (numberp shr-list-mode)
1505 (format "%d " shr-list-mode)
1506 (setq shr-list-mode (1+ shr-list-mode)))
1507 (car shr-internal-bullet)))
1508 (width (if (numberp shr-list-mode)
1509 (shr-string-pixel-width bullet)
1510 (cdr shr-internal-bullet))))
1512 (shr-mark-fill start)
1513 (let ((shr-indentation (+ shr-indentation width)))
1514 (put-text-property start (1+ start)
1515 'shr-continuation-indentation shr-indentation)
1516 (put-text-property start (1+ start) 'shr-prefix-length (length bullet))
1517 (shr-generic dom)))))
1519 (defun shr-mark-fill (start)
1520 ;; We may not have inserted any text to fill.
1521 (unless (= start (point))
1522 (put-text-property start (1+ start)
1523 'shr-indentation shr-indentation)))
1525 (defun shr-tag-br (dom)
1526 (when (and (not (bobp))
1527 ;; Only add a newline if we break the current line, or
1528 ;; the previous line isn't a blank line.
1530 (and (> (- (point) 2) (point-min))
1531 (not (= (char-after (- (point) 2)) ?\n)))))
1535 (defun shr-tag-span (dom)
1538 (defun shr-tag-h1 (dom)
1539 (shr-heading dom (if shr-use-fonts
1540 '(variable-pitch (:height 1.3 :weight bold))
1543 (defun shr-tag-h2 (dom)
1544 (shr-heading dom 'bold))
1546 (defun shr-tag-h3 (dom)
1547 (shr-heading dom 'italic))
1549 (defun shr-tag-h4 (dom)
1552 (defun shr-tag-h5 (dom)
1555 (defun shr-tag-h6 (dom)
1558 (defun shr-tag-hr (_dom)
1559 (shr-ensure-newline)
1560 (insert (make-string (if (not shr-use-fonts)
1562 (1+ (/ shr-internal-width
1563 shr-table-separator-pixel-width)))
1567 (defun shr-tag-title (dom)
1568 (shr-heading dom 'bold 'underline))
1570 (defun shr-tag-font (dom)
1571 (let* ((start (point))
1572 (color (dom-attr dom 'color))
1573 (shr-stylesheet (nconc (list (cons 'color color))
1577 (shr-colorize-region start (point) color
1578 (cdr (assq 'background-color shr-stylesheet))))))
1580 ;;; Table rendering algorithm.
1582 ;; Table rendering is the only complicated thing here. We do this by
1583 ;; first counting how many TDs there are in each TR, and registering
1584 ;; how wide they think they should be ("width=45%", etc). Then we
1585 ;; render each TD separately (this is done in temporary buffers, so
1586 ;; that we can use all the rendering machinery as if we were in the
1587 ;; main buffer). Now we know how much space each TD really takes, so
1588 ;; we then render everything again with the new widths, and finally
1589 ;; insert all these boxes into the main buffer.
1590 (defun shr-tag-table-1 (dom)
1591 (setq dom (or (dom-child-by-tag dom 'tbody) dom))
1592 (let* ((shr-inhibit-images t)
1593 (shr-table-depth (1+ shr-table-depth))
1594 (shr-kinsoku-shorten t)
1595 ;; Find all suggested widths.
1596 (columns (shr-column-specs dom))
1597 ;; Compute how many pixels wide each TD should be.
1598 (suggested-widths (shr-pro-rate-columns columns))
1599 ;; Do a "test rendering" to see how big each TD is (this can
1600 ;; be smaller (if there's little text) or bigger (if there's
1601 ;; unbreakable text).
1602 (elems (or (dom-attr dom 'shr-suggested-widths)
1603 (shr-make-table dom suggested-widths nil
1604 'shr-suggested-widths)))
1605 (sketch (loop for line in elems
1606 collect (mapcar #'car line)))
1607 (natural (loop for line in elems
1608 collect (mapcar #'cdr line)))
1609 (sketch-widths (shr-table-widths sketch natural suggested-widths)))
1610 ;; This probably won't work very well.
1611 (when (> (+ (loop for width across sketch-widths
1613 shr-indentation shr-table-separator-pixel-width)
1615 (setq truncate-lines t))
1616 ;; Then render the table again with these new "hard" widths.
1617 (shr-insert-table (shr-make-table dom sketch-widths t) sketch-widths)))
1619 (defun shr-table-body (dom)
1620 (let ((tbodies (seq-filter (lambda (child)
1621 (eq (dom-tag child) 'tbody))
1622 (dom-non-text-children dom))))
1626 ((= (length tbodies) 1)
1629 ;; Table with multiple tbodies. Convert into a single tbody.
1630 `(tbody nil ,@(cl-reduce 'append
1631 (mapcar 'dom-non-text-children tbodies)))))))
1633 (defun shr-tag-table (dom)
1634 (shr-ensure-paragraph)
1635 (let* ((caption (dom-children (dom-child-by-tag dom 'caption)))
1636 (header (dom-non-text-children (dom-child-by-tag dom 'thead)))
1637 (body (dom-non-text-children (shr-table-body dom)))
1638 (footer (dom-non-text-children (dom-child-by-tag dom 'tfoot)))
1639 (bgcolor (dom-attr dom 'bgcolor))
1641 (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
1643 (nheader (if header (shr-max-columns header)))
1644 (nbody (if body (shr-max-columns body) 0))
1645 (nfooter (if footer (shr-max-columns footer))))
1646 (if (and (not caption)
1648 (not (dom-child-by-tag dom 'tbody))
1649 (not (dom-child-by-tag dom 'tr))
1651 ;; The table is totally invalid and just contains random junk.
1652 ;; Try to output it anyway.
1654 ;; It's a real table, so render it.
1655 (if (dom-attr dom 'shr-fixed-table)
1656 (shr-tag-table-1 dom)
1657 ;; Only fix up the table once.
1661 (if caption `((tr nil (td nil ,@caption))))
1665 ;; header + body + footer
1666 (if (= nheader nbody)
1667 (if (= nbody nfooter)
1668 `((tr nil (td nil (table nil
1670 ,@body ,@footer)))))
1671 (nconc `((tr nil (td nil (table nil
1676 `((tr nil (td nil (table
1678 nil ,@footer))))))))
1679 (nconc `((tr nil (td nil (table nil (tbody
1681 (if (= nbody nfooter)
1682 `((tr nil (td nil (table
1683 nil (tbody nil ,@body
1685 (nconc `((tr nil (td nil (table
1690 `((tr nil (td nil (table
1696 (if (= nheader nbody)
1697 `((tr nil (td nil (table nil (tbody nil ,@header
1700 `(,@header (tr nil (td nil (table
1701 nil (tbody nil ,@body)))))
1702 `((tr nil (td nil (table nil (tbody nil ,@header))))
1703 (tr nil (td nil (table nil (tbody nil ,@body)))))))))
1706 (if (= nbody nfooter)
1707 `((tr nil (td nil (table
1708 nil (tbody nil ,@body ,@footer)))))
1709 (nconc `((tr nil (td nil (table nil (tbody nil ,@body)))))
1712 `((tr nil (td nil (table
1713 nil (tbody nil ,@footer)))))))))
1715 `((tr nil (td nil (table nil (tbody nil ,@body))))))
1717 (dom-set-attribute table 'shr-fixed-table t)
1718 (setcdr dom (cdr table))
1719 (shr-tag-table-1 dom))))
1721 (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
1723 ;; Finally, insert all the images after the table. The Emacs buffer
1724 ;; model isn't strong enough to allow us to put the images actually
1726 (when (zerop shr-table-depth)
1728 (shr-expand-alignments start (point)))
1729 (dolist (elem (dom-by-tag dom 'object))
1730 (shr-tag-object elem))
1731 (dolist (elem (dom-by-tag dom 'img))
1732 (shr-tag-img elem)))))
1734 (defun shr-insert-table (table widths)
1735 (let* ((collapse (equal (cdr (assq 'border-collapse shr-stylesheet))
1737 (shr-table-separator-length (if collapse 0 1))
1738 (shr-table-vertical-line (if collapse "" shr-table-vertical-line))
1740 (setq shr-table-id (1+ shr-table-id))
1742 (shr-insert-table-ruler widths))
1744 (let ((start (point))
1747 (height (let ((max 0))
1748 (dolist (column row)
1749 (setq max (max max (nth 2 column))))
1751 (dotimes (i (max height 1))
1753 (insert shr-table-vertical-line "\n"))
1754 (dolist (column row)
1755 (when (> (nth 2 column) -1)
1757 ;; Sum up all the widths from the column. (There may be
1758 ;; more than one if this is a "colspan" column.)
1759 (dotimes (i (nth 4 column))
1760 ;; The colspan directive may be wrong and there may not be
1761 ;; that number of columns.
1762 (when (<= column-number (1- (length widths)))
1763 (setq align (+ align
1764 (aref widths column-number)
1765 (* 2 shr-table-separator-pixel-width))))
1766 (setq column-number (1+ column-number)))
1767 (let ((lines (nth 3 column))
1768 (pixel-align (if (not shr-use-fonts)
1769 (* align (frame-char-width))
1771 (dolist (line lines)
1773 (let ((start (point)))
1777 'display `(space :align-to (,pixel-align))
1778 'face (and (> (length line) 0)
1779 (shr-face-background
1781 (1- (length line)) 'face line)))
1782 'shr-table-indent shr-table-id)
1783 shr-table-vertical-line)
1784 (shr-colorize-region
1785 start (1- (point)) (nth 5 column) (nth 6 column)))
1787 ;; Add blank lines at padding at the bottom of the TD,
1789 (dotimes (i (- height (length lines)))
1791 (let ((start (point)))
1792 (insert (propertize " "
1793 'display `(space :align-to (,pixel-align))
1794 'shr-table-indent shr-table-id)
1795 shr-table-vertical-line)
1796 (shr-colorize-region
1797 start (1- (point)) (nth 5 column) (nth 6 column)))
1798 (forward-line 1))))))
1800 (shr-insert-table-ruler widths)))
1801 (unless (= start (point))
1802 (put-text-property start (1+ start) 'shr-table-id shr-table-id))))
1804 (defun shr-face-background (face)
1806 (let ((background nil))
1808 (when (and (consp elem)
1809 (eq (car elem) :background))
1810 (setq background (cadr elem))))
1812 (list :background background)))))
1814 (defun shr-expand-alignments (start end)
1815 (while (< (setq start (next-single-property-change
1816 start 'shr-table-id nil end))
1819 (let* ((shr-use-fonts t)
1820 (id (get-text-property (point) 'shr-table-id))
1821 (base (shr-pixel-column))
1825 (while (setq elem (text-property-any
1826 (point) end 'shr-table-indent id))
1828 (let ((align (get-text-property (point) 'display)))
1829 (put-text-property (point) (1+ (point)) 'display
1830 `(space :align-to (,(+ (car (nth 2 align))
1832 (forward-char 1)))))
1833 (setq start (1+ start))))
1835 (defun shr-insert-table-ruler (widths)
1836 (when shr-table-horizontal-line
1838 (> shr-indentation 0))
1840 (insert shr-table-corner)
1841 (let ((total-width 0))
1842 (dotimes (i (length widths))
1843 (setq total-width (+ total-width (aref widths i)
1844 (* shr-table-separator-pixel-width 2)))
1845 (insert (make-string (1+ (/ (aref widths i)
1846 shr-table-separator-pixel-width))
1847 shr-table-horizontal-line)
1849 'display `(space :align-to (,total-width))
1850 'shr-table-indent shr-table-id)
1854 (defun shr-table-widths (table natural-table suggested-widths)
1855 (let* ((length (length suggested-widths))
1856 (widths (make-vector length 0))
1857 (natural-widths (make-vector length 0)))
1860 (dolist (column row)
1861 (aset widths i (max (aref widths i) column))
1863 (dolist (row natural-table)
1865 (dolist (column row)
1866 (aset natural-widths i (max (aref natural-widths i) column))
1868 (let ((extra (- (apply '+ (append suggested-widths nil))
1869 (apply '+ (append widths nil))
1870 (* shr-table-separator-pixel-width (1+ (length widths)))))
1871 (expanded-columns 0))
1872 ;; We have extra, unused space, so divide this space amongst the
1875 ;; If the natural width is wider than the rendered width, we
1876 ;; want to allow the column to expand.
1878 (when (> (aref natural-widths i) (aref widths i))
1879 (setq expanded-columns (1+ expanded-columns))))
1881 (when (> (aref natural-widths i) (aref widths i))
1883 (aref natural-widths i)
1884 (+ (/ extra expanded-columns)
1885 (aref widths i))))))))
1888 (defun shr-make-table (dom widths &optional fill storage-attribute)
1889 (or (cadr (assoc (list dom widths fill) shr-content-cache))
1890 (let ((data (shr-make-table-1 dom widths fill)))
1891 (push (list (list dom widths fill) data)
1893 (when storage-attribute
1894 (dom-set-attribute dom storage-attribute data))
1897 (defun shr-make-table-1 (dom widths &optional fill)
1899 (rowspans (make-vector (length widths) 0))
1900 (colspan-remaining 0)
1901 colspan-width colspan-count
1903 (dolist (row (dom-non-text-children dom))
1904 (when (eq (dom-tag row) 'tr)
1906 (columns (dom-non-text-children row))
1910 (while (< i (length widths))
1911 ;; If we previously had a rowspan definition, then that
1912 ;; means that we now have a "missing" td/th element here.
1913 ;; So just insert a dummy, empty one to (sort of) emulate
1916 (if (zerop (aref rowspans i))
1918 (aset rowspans i (1- (aref rowspans i)))
1920 (when (and (not (stringp column))
1921 (or (memq (dom-tag column) '(td th))
1923 (when-let (span (dom-attr column 'rowspan))
1924 (aset rowspans i (+ (aref rowspans i)
1925 (1- (string-to-number span)))))
1926 ;; Sanity check for invalid column-spans.
1927 (when (>= width-column (length widths))
1928 (setq width-column 0))
1931 (aref widths width-column)
1932 (* 10 shr-table-separator-pixel-width)))
1933 (when (setq colspan (dom-attr column 'colspan))
1934 (setq colspan (min (string-to-number colspan)
1935 ;; The colspan may be wrong, so
1936 ;; truncate it to the length of the
1937 ;; remaining columns.
1938 (- (length widths) i)))
1939 (dotimes (j (1- colspan))
1941 (if (> (+ i 1 j) (1- (length widths)))
1942 ;; If we have a colspan spec that's longer
1943 ;; than the table is wide, just use the last
1944 ;; width as the width.
1945 (aref widths (1- (length widths)))
1946 ;; Sum up the widths of the columns we're
1949 shr-table-separator-length
1950 (aref widths (+ i 1 j))))))
1951 (setq width-column (+ width-column (1- colspan))
1952 colspan-count colspan
1953 colspan-remaining colspan))
1955 (let ((data (shr-render-td column width fill)))
1957 (> colspan-remaining 0))
1959 (setq colspan-width (car data))
1960 (let ((this-width (/ colspan-width colspan-count)))
1961 (push (cons this-width (cadr data)) tds)
1962 (setq colspan-remaining (1- colspan-remaining))))
1964 (push (cons (car data) (cadr data)) tds)
1968 (dotimes (c (1- colspan))
1972 (list 0 0 -1 nil 1 nil nil)
1976 width-column (1+ width-column))))
1977 (push (nreverse tds) trs))))
1980 (defun shr-pixel-buffer-width ()
1981 (if (not shr-use-fonts)
1983 (goto-char (point-min))
1987 (setq max (max max (current-column)))
1990 (if (get-buffer-window)
1991 (car (window-text-pixel-size nil (point-min) (point-max)))
1992 (save-window-excursion
1993 (set-window-buffer nil (current-buffer))
1994 (car (window-text-pixel-size nil (point-min) (point-max)))))))
1996 (defun shr-render-td (dom width fill)
1997 (let ((cache (intern (format "shr-td-cache-%s-%s" width fill))))
1998 (or (dom-attr dom cache)
2001 (dolist (attr (dom-attributes dom))
2002 (let ((name (symbol-name (car attr))))
2003 (when (string-match "shr-td-cache-\\([0-9]+\\)-nil" name)
2004 (let ((cache-width (string-to-number
2005 (match-string 1 name))))
2006 (when (and (>= cache-width width)
2007 (<= (car (cdr attr)) width))
2008 (setq result (cdr attr)))))))
2010 (let ((result (shr-render-td-1 dom width fill)))
2011 (dom-set-attribute dom cache result)
2014 (defun shr-render-td-1 (dom width fill)
2016 (let ((bgcolor (dom-attr dom 'bgcolor))
2017 (fgcolor (dom-attr dom 'fgcolor))
2018 (style (dom-attr dom 'style))
2019 (shr-stylesheet shr-stylesheet)
2023 (setq style (and (string-match "color" style)
2024 (shr-parse-style style))))
2026 (setq style (nconc (list (cons 'background-color bgcolor))
2029 (setq style (nconc (list (cons 'color fgcolor)) style)))
2031 (setq shr-stylesheet (append style shr-stylesheet)))
2032 (let ((shr-internal-width width)
2033 (shr-indentation 0))
2035 (save-window-excursion
2036 (set-window-buffer nil (current-buffer))
2039 (or (dom-attr dom 'shr-td-cache-natural)
2040 (let ((natural (max (shr-pixel-buffer-width)
2041 (shr-dom-max-natural-width dom 0))))
2042 (dom-set-attribute dom 'shr-td-cache-natural natural)
2044 (if (and natural-width
2045 (<= natural-width width))
2046 (setq max-width natural-width)
2047 (let ((shr-internal-width width))
2048 (shr-fill-lines (point-min) (point-max))
2049 (setq max-width (shr-pixel-buffer-width)))))
2050 (goto-char (point-max))
2051 ;; Delete padding at the bottom of the TDs.
2055 (skip-chars-backward " \t\n")
2058 (goto-char (point-min))
2061 (count-lines (point-min) (point-max))
2062 (split-string (buffer-string) "\n")
2063 (if (dom-attr dom 'colspan)
2064 (string-to-number (dom-attr dom 'colspan))
2066 (cdr (assq 'color shr-stylesheet))
2067 (cdr (assq 'background-color shr-stylesheet))))))
2069 (defun shr-dom-max-natural-width (dom max)
2070 (if (eq (dom-tag dom) 'table)
2072 (loop for line in (dom-attr dom 'shr-suggested-widths)
2074 shr-table-separator-length
2075 (loop for elem in line
2078 (* 2 shr-table-separator-length)))))
2080 (dolist (child (dom-children dom))
2081 (unless (stringp child)
2082 (setq max (max (shr-dom-max-natural-width child max)))))
2085 (defun shr-buffer-width ()
2086 (goto-char (point-min))
2090 (setq max (max max (current-column)))
2094 (defun shr-pro-rate-columns (columns)
2095 (let ((total-percentage 0)
2096 (widths (make-vector (length columns) 0)))
2097 (dotimes (i (length columns))
2098 (setq total-percentage (+ total-percentage (aref columns i))))
2099 (setq total-percentage (/ 1.0 total-percentage))
2100 (dotimes (i (length columns))
2101 (aset widths i (max (truncate (* (aref columns i)
2103 (- shr-internal-width
2104 (* (1+ (length columns))
2105 shr-table-separator-pixel-width))))
2109 ;; Return a summary of the number and shape of the TDs in the table.
2110 (defun shr-column-specs (dom)
2111 (let ((columns (make-vector (shr-max-columns dom) 1)))
2112 (dolist (row (dom-non-text-children dom))
2113 (when (eq (dom-tag row) 'tr)
2115 (dolist (column (dom-non-text-children row))
2116 (when (memq (dom-tag column) '(td th))
2117 (let ((width (dom-attr column 'width)))
2119 (string-match "\\([0-9]+\\)%" width)
2120 (not (zerop (setq width (string-to-number
2121 (match-string 1 width))))))
2122 (aset columns i (/ width 100.0))))
2123 (setq i (1+ i)))))))
2126 (defun shr-count (dom elem)
2128 (dolist (sub (dom-children dom))
2129 (when (and (not (stringp sub))
2130 (eq (dom-tag sub) elem))
2134 (defun shr-max-columns (dom)
2136 (dolist (row (dom-children dom))
2137 (when (and (not (stringp row))
2138 (eq (dom-tag row) 'tr))
2139 (setq max (max max (+ (shr-count row 'td)
2140 (shr-count row 'th))))))
2145 ;;; shr.el ends here