(gnus-blocked-images): Clarify privacy implications
[emacs.git] / lisp / net / shr.el
blob1103a9302423c6c0600251cd5cf077f4195bdbab
1 ;;; shr.el --- Simple HTML Renderer -*- lexical-binding: t -*-
3 ;; Copyright (C) 2010-2018 Free Software Foundation, Inc.
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: html
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 <https://www.gnu.org/licenses/>.
23 ;;; Commentary:
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.
31 ;;; Code:
33 (require 'cl-lib)
34 (eval-when-compile (require 'url)) ;For url-filename's setf handler.
35 (require 'browse-url)
36 (eval-when-compile (require 'subr-x))
37 (require 'dom)
38 (require 'seq)
39 (require 'svg)
40 (require 'image)
41 (require 'puny)
42 (require 'text-property-search)
44 (defgroup shr nil
45 "Simple HTML Renderer"
46 :version "25.1"
47 :group 'web)
49 (defcustom shr-max-image-proportion 0.9
50 "How big pictures displayed are in relation to the window they're in.
51 A value of 0.7 means that they are allowed to take up 70% of the
52 width and height of the window. If they are larger than this,
53 and Emacs supports it, then the images will be rescaled down to
54 fit these criteria."
55 :version "24.1"
56 :group 'shr
57 :type 'float)
59 (defcustom shr-blocked-images nil
60 "Images that have URLs matching this regexp will be blocked."
61 :version "24.1"
62 :group 'shr
63 :type '(choice (const nil) regexp))
65 (defcustom shr-use-fonts t
66 "If non-nil, use proportional fonts for text."
67 :version "25.1"
68 :group 'shr
69 :type 'boolean)
71 (defcustom shr-use-colors t
72 "If non-nil, respect color specifications in the HTML."
73 :version "26.1"
74 :group 'shr
75 :type 'boolean)
77 (defcustom shr-table-horizontal-line nil
78 "Character used to draw horizontal table lines.
79 If nil, don't draw horizontal table lines."
80 :group 'shr
81 :type '(choice (const nil) character))
83 (defcustom shr-table-vertical-line ?\s
84 "Character used to draw vertical table lines."
85 :group 'shr
86 :type 'character)
88 (defcustom shr-table-corner ?\s
89 "Character used to draw table corners."
90 :group 'shr
91 :type 'character)
93 (defcustom shr-hr-line ?-
94 "Character used to draw hr lines."
95 :group 'shr
96 :type 'character)
98 (defcustom shr-width nil
99 "Frame width to use for rendering.
100 May either be an integer specifying a fixed width in characters,
101 or nil, meaning that the full width of the window should be used.
102 If `shr-use-fonts' is set, the mean character width is used to
103 compute the pixel width, which is used instead."
104 :version "25.1"
105 :type '(choice (integer :tag "Fixed width in characters")
106 (const :tag "Use the width of the window" nil))
107 :group 'shr)
109 (defcustom shr-bullet "* "
110 "Bullet used for unordered lists.
111 Alternative suggestions are:
112 - \" \"
113 - \" \""
114 :version "24.4"
115 :type 'string
116 :group 'shr)
118 (defcustom shr-external-browser 'browse-url-default-browser
119 "Function used to launch an external browser."
120 :version "24.4"
121 :group 'shr
122 :type 'function)
124 (defcustom shr-image-animate t
125 "Non nil means that images that can be animated will be."
126 :version "24.4"
127 :group 'shr
128 :type 'boolean)
130 (defvar shr-content-function nil
131 "If bound, this should be a function that will return the content.
132 This is used for cid: URLs, and the function is called with the
133 cid: URL as the argument.")
135 (defvar shr-put-image-function 'shr-put-image
136 "Function called to put image and alt string.")
138 (defface shr-strike-through '((t :strike-through t))
139 "Face for <s> elements."
140 :version "24.1"
141 :group 'shr)
143 (defface shr-link
144 '((t :inherit link))
145 "Face for link elements."
146 :version "24.1"
147 :group 'shr)
149 (defface shr-selected-link
150 '((t :inherit shr-link :background "red"))
151 "Face for link elements."
152 :version "27.1"
153 :group 'shr)
155 (defvar shr-inhibit-images nil
156 "If non-nil, inhibit loading images.")
158 (defvar shr-external-rendering-functions nil
159 "Alist of tag/function pairs used to alter how shr renders certain tags.
160 For instance, eww uses this to alter rendering of title, forms
161 and other things:
162 \((title . eww-tag-title)
163 (form . eww-tag-form)
164 ...)")
166 ;;; Internal variables.
168 (defvar shr-folding-mode nil)
169 (defvar shr-start nil)
170 (defvar shr-indentation 0)
171 (defvar shr-internal-width nil)
172 (defvar shr-list-mode nil)
173 (defvar shr-content-cache nil)
174 (defvar shr-kinsoku-shorten nil)
175 (defvar shr-table-depth 0)
176 (defvar shr-stylesheet nil)
177 (defvar shr-base nil)
178 (defvar shr-depth 0)
179 (defvar shr-warning nil)
180 (defvar shr-ignore-cache nil)
181 (defvar shr-target-id nil)
182 (defvar shr-table-separator-length 1)
183 (defvar shr-table-separator-pixel-width 0)
184 (defvar shr-table-id nil)
185 (defvar shr-current-font nil)
186 (defvar shr-internal-bullet nil)
188 (defvar shr-map
189 (let ((map (make-sparse-keymap)))
190 (define-key map "a" 'shr-show-alt-text)
191 (define-key map "i" 'shr-browse-image)
192 (define-key map "z" 'shr-zoom-image)
193 (define-key map [?\t] 'shr-next-link)
194 (define-key map [?\M-\t] 'shr-previous-link)
195 (define-key map [follow-link] 'mouse-face)
196 (define-key map [mouse-2] 'shr-browse-url)
197 (define-key map "I" 'shr-insert-image)
198 (define-key map "w" 'shr-maybe-probe-and-copy-url)
199 (define-key map "u" 'shr-maybe-probe-and-copy-url)
200 (define-key map "v" 'shr-browse-url)
201 (define-key map "O" 'shr-save-contents)
202 (define-key map "\r" 'shr-browse-url)
203 map))
205 (defvar shr-image-map
206 (let ((map (copy-keymap shr-map)))
207 (when (boundp 'image-map)
208 (set-keymap-parent map image-map))
209 map))
211 ;; Public functions and commands.
212 (declare-function libxml-parse-html-region "xml.c"
213 (start end &optional base-url discard-comments))
215 (defun shr-render-buffer (buffer)
216 "Display the HTML rendering of the current buffer."
217 (interactive (list (current-buffer)))
218 (or (fboundp 'libxml-parse-html-region)
219 (error "This function requires Emacs to be compiled with libxml2"))
220 (pop-to-buffer "*html*")
221 (erase-buffer)
222 (shr-insert-document
223 (with-current-buffer buffer
224 (libxml-parse-html-region (point-min) (point-max))))
225 (goto-char (point-min)))
227 ;;;###autoload
228 (defun shr-render-region (begin end &optional buffer)
229 "Display the HTML rendering of the region between BEGIN and END."
230 (interactive "r")
231 (unless (fboundp 'libxml-parse-html-region)
232 (error "This function requires Emacs to be compiled with libxml2"))
233 (with-current-buffer (or buffer (current-buffer))
234 (let ((dom (libxml-parse-html-region begin end)))
235 (delete-region begin end)
236 (goto-char begin)
237 (shr-insert-document dom))))
239 (defun shr--have-one-fringe-p ()
240 "Return non-nil if we know at least one of the fringes has non-zero width."
241 (and (fboundp 'fringe-columns)
242 (or (not (zerop (fringe-columns 'right)))
243 (not (zerop (fringe-columns 'left))))))
245 ;;;###autoload
246 (defun shr-insert-document (dom)
247 "Render the parsed document DOM into the current buffer.
248 DOM should be a parse tree as generated by
249 `libxml-parse-html-region' or similar."
250 (setq shr-content-cache nil)
251 (let ((start (point))
252 (shr-start nil)
253 (shr-base nil)
254 (shr-depth 0)
255 (shr-table-id 0)
256 (shr-warning nil)
257 (shr-table-separator-pixel-width (shr-string-pixel-width "-"))
258 (shr-internal-bullet (cons shr-bullet
259 (shr-string-pixel-width shr-bullet)))
260 (shr-internal-width (or (and shr-width
261 (if (not shr-use-fonts)
262 shr-width
263 (* shr-width (frame-char-width))))
264 ;; We need to adjust the available
265 ;; width for when the user disables
266 ;; the fringes, which will cause the
267 ;; display engine usurp one column for
268 ;; the continuation glyph.
269 (if (not shr-use-fonts)
270 (- (window-body-width) 1
271 (if (and (null shr-width)
272 (not (shr--have-one-fringe-p)))
275 (- (window-body-width nil t)
276 (* 2 (frame-char-width))
277 (if (and (null shr-width)
278 (not (shr--have-one-fringe-p)))
279 (* (frame-char-width) 2)
281 1))))
282 (max-specpdl-size max-specpdl-size)
283 bidi-display-reordering)
284 ;; If the window was hscrolled for some reason, shr-fill-lines
285 ;; below will misbehave, because it silently assumes that it
286 ;; starts with a non-hscrolled window (vertical-motion will move
287 ;; to a wrong place otherwise).
288 (set-window-hscroll nil 0)
289 (shr-descend dom)
290 (shr-fill-lines start (point))
291 (shr--remove-blank-lines-at-the-end start (point))
292 (when shr-warning
293 (message "%s" shr-warning))))
295 (defun shr--remove-blank-lines-at-the-end (start end)
296 (save-restriction
297 (save-excursion
298 (narrow-to-region start end)
299 (goto-char end)
300 (when (and (re-search-backward "[^ \n]" nil t)
301 (not (eobp)))
302 (forward-line 1)
303 (delete-region (point) (point-max))))))
305 (defun shr-url-at-point (image-url)
306 "Return the URL under point as a string.
307 If IMAGE-URL is non-nil, or there is no link under point, but
308 there is an image under point then copy the URL of the image
309 under point instead."
310 (if image-url
311 (get-text-property (point) 'image-url)
312 (or (get-text-property (point) 'shr-url)
313 (get-text-property (point) 'image-url))))
315 (defun shr-copy-url (url)
316 "Copy the URL under point to the kill ring.
317 If IMAGE-URL (the prefix) is non-nil, or there is no link under
318 point, but there is an image under point then copy the URL of the
319 image under point instead."
320 (interactive (list (shr-url-at-point current-prefix-arg)))
321 (if (not url)
322 (message "No URL under point")
323 (setq url (url-encode-url url))
324 (kill-new url)
325 (message "Copied %s" url)))
327 (defun shr-probe-url (url cont)
328 "Pass URL's redirect destination to CONT, if it has one.
329 CONT should be a function of one argument, the redirect
330 destination URL. If URL is not redirected, then CONT is never
331 called."
332 (interactive "P")
333 (url-retrieve
334 url (lambda (a)
335 (pcase a
336 (`(:redirect ,destination . ,_)
337 ;; Remove common tracking junk from the URL.
338 (funcall cont (replace-regexp-in-string
339 ".utm_.*" "" destination)))))
340 nil t))
342 (defun shr-probe-and-copy-url (url)
343 "Copy the URL under point to the kill ring.
344 Like `shr-copy-url', but additionally fetch URL and use its
345 redirection destination if it has one."
346 (interactive (list (shr-url-at-point current-prefix-arg)))
347 (if url (shr-probe-url url #'shr-copy-url)
348 (shr-copy-url url)))
350 (defun shr-maybe-probe-and-copy-url (url)
351 "Copy the URL under point to the kill ring.
352 If the URL is already at the front of the kill ring act like
353 `shr-probe-and-copy-url', otherwise like `shr-copy-url'."
354 (interactive (list (shr-url-at-point current-prefix-arg)))
355 (if (equal url (car kill-ring))
356 (shr-probe-and-copy-url url)
357 (shr-copy-url url)))
359 (defun shr--current-link-region ()
360 (let ((current (get-text-property (point) 'shr-url))
361 start)
362 (save-excursion
363 ;; Go to the beginning.
364 (while (and (not (bobp))
365 (equal (get-text-property (point) 'shr-url) current))
366 (forward-char -1))
367 (unless (equal (get-text-property (point) 'shr-url) current)
368 (forward-char 1))
369 (setq start (point))
370 ;; Go to the end.
371 (while (and (not (eobp))
372 (equal (get-text-property (point) 'shr-url) current))
373 (forward-char 1))
374 (list start (point)))))
376 (defun shr--blink-link ()
377 (let* ((region (shr--current-link-region))
378 (overlay (make-overlay (car region) (cadr region))))
379 (overlay-put overlay 'face 'shr-selected-link)
380 (run-at-time 1 nil (lambda ()
381 (delete-overlay overlay)))))
383 (defun shr-next-link ()
384 "Skip to the next link."
385 (interactive)
386 (let ((match (text-property-search-forward 'shr-url nil nil t)))
387 (if (not match)
388 (message "No next link")
389 (goto-char (prop-match-beginning match))
390 (message "%s" (get-text-property (point) 'help-echo)))))
392 (defun shr-previous-link ()
393 "Skip to the previous link."
394 (interactive)
395 (if (not (text-property-search-backward 'shr-url nil nil t))
396 (message "No previous link")
397 (message "%s" (get-text-property (point) 'help-echo))))
399 (defun shr-show-alt-text ()
400 "Show the ALT text of the image under point."
401 (interactive)
402 (let ((text (get-text-property (point) 'shr-alt)))
403 (if (not text)
404 (message "No image under point")
405 (message "%s" (shr-fill-text text)))))
407 (defun shr-browse-image (&optional copy-url)
408 "Browse the image under point.
409 If COPY-URL (the prefix if called interactively) is non-nil, copy
410 the URL of the image to the kill buffer instead."
411 (interactive "P")
412 (let ((url (get-text-property (point) 'image-url)))
413 (cond
414 ((not url)
415 (message "No image under point"))
416 (copy-url
417 (with-temp-buffer
418 (insert url)
419 (copy-region-as-kill (point-min) (point-max))
420 (message "Copied %s" url)))
422 (message "Browsing %s..." url)
423 (browse-url url)))))
425 (defun shr-insert-image ()
426 "Insert the image under point into the buffer."
427 (interactive)
428 (let ((url (get-text-property (point) 'image-url)))
429 (if (not url)
430 (message "No image under point")
431 (message "Inserting %s..." url)
432 (url-retrieve url 'shr-image-fetched
433 (list (current-buffer) (1- (point)) (point-marker))
434 t t))))
436 (defun shr-zoom-image ()
437 "Toggle the image size.
438 The size will be rotated between the default size, the original
439 size, and full-buffer size."
440 (interactive)
441 (let ((url (get-text-property (point) 'image-url))
442 (size (get-text-property (point) 'image-size))
443 (buffer-read-only nil))
444 (if (not url)
445 (message "No image under point")
446 ;; Delete the old picture.
447 (while (get-text-property (point) 'image-url)
448 (forward-char -1))
449 (forward-char 1)
450 (let ((start (point)))
451 (while (get-text-property (point) 'image-url)
452 (forward-char 1))
453 (forward-char -1)
454 (put-text-property start (point) 'display nil)
455 (when (> (- (point) start) 2)
456 (delete-region start (1- (point)))))
457 (message "Inserting %s..." url)
458 (url-retrieve url 'shr-image-fetched
459 (list (current-buffer) (1- (point)) (point-marker)
460 (list (cons 'size
461 (cond ((or (eq size 'default)
462 (null size))
463 'original)
464 ((eq size 'original)
465 'full)
466 ((eq size 'full)
467 'default)))))
468 t))))
470 ;;; Utility functions.
472 (defsubst shr-generic (dom)
473 (dolist (sub (dom-children dom))
474 (if (stringp sub)
475 (shr-insert sub)
476 (shr-descend sub))))
478 (defun shr-indirect-call (tag-name dom &rest args)
479 (let ((function (intern (concat "shr-tag-" (symbol-name tag-name)) obarray))
480 ;; Allow other packages to override (or provide) rendering
481 ;; of elements.
482 (external (cdr (assq tag-name shr-external-rendering-functions))))
483 (cond (external
484 (apply external dom args))
485 ((fboundp function)
486 (apply function dom args))
488 (apply 'shr-generic dom args)))))
490 (defun shr-descend (dom)
491 (let ((function
492 (intern (concat "shr-tag-" (symbol-name (dom-tag dom))) obarray))
493 ;; Allow other packages to override (or provide) rendering
494 ;; of elements.
495 (external (cdr (assq (dom-tag dom) shr-external-rendering-functions)))
496 (style (dom-attr dom 'style))
497 (shr-stylesheet shr-stylesheet)
498 (shr-depth (1+ shr-depth))
499 (start (point)))
500 ;; shr uses many frames per nested node.
501 (if (and (> shr-depth (/ max-specpdl-size 15))
502 (not (and (y-or-n-p "Too deeply nested to render properly; increase `max-specpdl-size'?")
503 (setq max-specpdl-size (* max-specpdl-size 2)))))
504 (setq shr-warning
505 "Not rendering the complete page because of too-deep nesting")
506 (when style
507 (if (string-match "color\\|display\\|border-collapse" style)
508 (setq shr-stylesheet (nconc (shr-parse-style style)
509 shr-stylesheet))
510 (setq style nil)))
511 ;; If we have a display:none, then just ignore this part of the DOM.
512 (unless (equal (cdr (assq 'display shr-stylesheet)) "none")
513 ;; We don't use shr-indirect-call here, since shr-descend is
514 ;; the central bit of shr.el, and should be as fast as
515 ;; possible. Having one more level of indirection with its
516 ;; negative effect on performance is deemed unjustified in
517 ;; this case.
518 (cond (external
519 (funcall external dom))
520 ((fboundp function)
521 (funcall function dom))
523 (shr-generic dom)))
524 (when (and shr-target-id
525 (equal (dom-attr dom 'id) shr-target-id))
526 ;; If the element was empty, we don't have anything to put the
527 ;; anchor on. So just insert a dummy character.
528 (when (= start (point))
529 (insert "*"))
530 (put-text-property start (1+ start) 'shr-target-id shr-target-id))
531 ;; If style is set, then this node has set the color.
532 (when style
533 (shr-colorize-region
534 start (point)
535 (cdr (assq 'color shr-stylesheet))
536 (cdr (assq 'background-color shr-stylesheet))))))))
538 (defun shr-fill-text (text)
539 (if (zerop (length text))
540 text
541 (with-temp-buffer
542 (let ((shr-indentation 0)
543 (shr-start nil)
544 (shr-internal-width (- (window-body-width nil t)
545 (* 2 (frame-char-width))
546 ;; Adjust the window width for when
547 ;; the user disables the fringes,
548 ;; which causes the display engine
549 ;; to usurp one column for the
550 ;; continuation glyph.
551 (if (and (null shr-width)
552 (not (shr--have-one-fringe-p)))
553 (* (frame-char-width) 2)
554 0))))
555 (shr-insert text)
556 (shr-fill-lines (point-min) (point-max))
557 (buffer-string)))))
559 (define-inline shr-char-breakable-p (char)
560 "Return non-nil if a line can be broken before and after CHAR."
561 (inline-quote (aref fill-find-break-point-function-table ,char)))
562 (define-inline shr-char-nospace-p (char)
563 "Return non-nil if no space is required before and after CHAR."
564 (inline-quote (aref fill-nospace-between-words-table ,char)))
566 ;; KINSOKU is a Japanese word meaning a rule that should not be violated.
567 ;; In Emacs, it is a term used for characters, e.g. punctuation marks,
568 ;; parentheses, and so on, that should not be placed in the beginning
569 ;; of a line or the end of a line.
570 (define-inline shr-char-kinsoku-bol-p (char)
571 "Return non-nil if a line ought not to begin with CHAR."
572 (inline-letevals (char)
573 (inline-quote (and (not (eq ,char ?'))
574 (aref (char-category-set ,char) ?>)))))
575 (define-inline shr-char-kinsoku-eol-p (char)
576 "Return non-nil if a line ought not to end with CHAR."
577 (inline-quote (aref (char-category-set ,char) ?<)))
578 (unless (shr-char-kinsoku-bol-p (make-char 'japanese-jisx0208 33 35))
579 (load "kinsoku" nil t))
581 (defun shr-pixel-column ()
582 (if (not shr-use-fonts)
583 (current-column)
584 (if (not (get-buffer-window (current-buffer)))
585 (save-window-excursion
586 ;; Avoid errors if the selected window is a dedicated one,
587 ;; and they just want to insert a document into it.
588 (set-window-dedicated-p nil nil)
589 (set-window-buffer nil (current-buffer))
590 (car (window-text-pixel-size nil (line-beginning-position) (point))))
591 (car (window-text-pixel-size nil (line-beginning-position) (point))))))
593 (defun shr-pixel-region ()
594 (- (shr-pixel-column)
595 (save-excursion
596 (goto-char (mark))
597 (shr-pixel-column))))
599 (defun shr-string-pixel-width (string)
600 (if (not shr-use-fonts)
601 (length string)
602 ;; Save and restore point across with-temp-buffer, since
603 ;; shr-pixel-column uses save-window-excursion, which can reset
604 ;; point to 1.
605 (let ((pt (point)))
606 (prog1
607 (with-temp-buffer
608 (insert string)
609 (shr-pixel-column))
610 (goto-char pt)))))
612 (defsubst shr--translate-insertion-chars ()
613 ;; Remove soft hyphens.
614 (goto-char (point-min))
615 (while (search-forward "­" nil t)
616 (replace-match "" t t))
617 ;; Translate non-breaking spaces into real spaces.
618 (goto-char (point-min))
619 (while (search-forward " " nil t)
620 (replace-match " " t t)))
622 (defun shr-insert (text)
623 (when (and (not (bolp))
624 (get-text-property (1- (point)) 'image-url))
625 (insert "\n"))
626 (cond
627 ((eq shr-folding-mode 'none)
628 (let ((start (point)))
629 (insert text)
630 (save-restriction
631 (narrow-to-region start (point))
632 (shr--translate-insertion-chars)
633 (goto-char (point-max)))))
635 (let ((font-start (point)))
636 (when (and (string-match "\\`[ \t\n\r]" text)
637 (not (bolp))
638 (not (eq (char-after (1- (point))) ? )))
639 (insert " "))
640 (let ((start (point))
641 (bolp (bolp)))
642 (insert text)
643 (save-restriction
644 (narrow-to-region start (point))
645 (goto-char start)
646 (when (looking-at "[ \t\n\r]+")
647 (replace-match "" t t))
648 (while (re-search-forward "[ \t\n\r]+" nil t)
649 (replace-match " " t t))
650 (shr--translate-insertion-chars)
651 (goto-char (point-max)))
652 ;; We may have removed everything we inserted if it was just
653 ;; spaces.
654 (unless (= font-start (point))
655 ;; Mark all lines that should possibly be folded afterwards.
656 (when bolp
657 (shr-mark-fill start))
658 (when shr-use-fonts
659 (put-text-property font-start (point)
660 'face
661 (or shr-current-font 'variable-pitch)))))))))
663 (defun shr-fill-lines (start end)
664 (if (<= shr-internal-width 0)
666 (save-restriction
667 (narrow-to-region start end)
668 (goto-char start)
669 (when (get-text-property (point) 'shr-indentation)
670 (shr-fill-line))
671 (while (setq start (next-single-property-change start 'shr-indentation))
672 (goto-char start)
673 (when (bolp)
674 (shr-fill-line)))
675 (goto-char (point-max)))))
677 (defun shr-vertical-motion (column)
678 (if (not shr-use-fonts)
679 (move-to-column column)
680 (unless (eolp)
681 (forward-char 1))
682 (vertical-motion (cons (/ column (frame-char-width)) 0))
683 (unless (eolp)
684 (forward-char 1))))
686 (defun shr-fill-line ()
687 (let ((shr-indentation (get-text-property (point) 'shr-indentation))
688 (continuation (get-text-property
689 (point) 'shr-continuation-indentation))
690 start)
691 (put-text-property (point) (1+ (point)) 'shr-indentation nil)
692 (let ((face (get-text-property (point) 'face))
693 (background-start (point)))
694 (shr-indent)
695 (when face
696 (put-text-property background-start (point) 'face
697 `,(shr-face-background face))))
698 (setq start (point))
699 (setq shr-indentation (or continuation shr-indentation))
700 ;; If we have an indentation that's wider than the width we're
701 ;; trying to fill to, then just give up and don't do any filling.
702 (when (< shr-indentation shr-internal-width)
703 (shr-vertical-motion shr-internal-width)
704 (when (looking-at " $")
705 (delete-region (point) (line-end-position)))
706 (while (not (eolp))
707 ;; We have to do some folding. First find the first
708 ;; previous point suitable for folding.
709 (if (or (not (shr-find-fill-point (line-beginning-position)))
710 (= (point) start))
711 ;; We had unbreakable text (for this width), so just go to
712 ;; the first space and carry on.
713 (progn
714 (beginning-of-line)
715 (skip-chars-forward " ")
716 (search-forward " " (line-end-position) 'move)))
717 ;; Success; continue.
718 (when (= (preceding-char) ?\s)
719 (delete-char -1))
720 (let ((gap-start (point)))
721 (insert "\n")
722 (shr-indent)
723 (when (and (> (1- gap-start) (point-min))
724 ;; The link on both sides of the newline are the
725 ;; same...
726 (equal (get-text-property (point) 'shr-url)
727 (get-text-property (1- gap-start) 'shr-url)))
728 ;; ... so we join the two bits into one link logically, but
729 ;; not visually. This makes navigation between links work
730 ;; well, but avoids underscores before the link on the next
731 ;; line when indented.
732 (let ((props (copy-sequence (text-properties-at (point)))))
733 ;; We don't want to use the faces on the indentation, because
734 ;; that's ugly.
735 (setq props (plist-put props 'face nil))
736 (add-text-properties gap-start (point) props))))
737 (setq start (point))
738 (shr-vertical-motion shr-internal-width)
739 (when (looking-at " $")
740 (delete-region (point) (line-end-position)))))))
742 (defun shr-find-fill-point (start)
743 (let ((bp (point))
744 (end (point))
745 failed)
746 (while (not (or (setq failed (<= (point) start))
747 (eq (preceding-char) ? )
748 (eq (following-char) ? )
749 (shr-char-breakable-p (preceding-char))
750 (shr-char-breakable-p (following-char))
751 (and (shr-char-kinsoku-bol-p (preceding-char))
752 (shr-char-breakable-p (following-char))
753 (not (shr-char-kinsoku-bol-p (following-char))))
754 (shr-char-kinsoku-eol-p (following-char))
755 (bolp)))
756 (backward-char 1))
757 (if failed
758 ;; There's no breakable point, so we give it up.
759 (let (found)
760 (goto-char bp)
761 ;; Don't overflow the window edge, even if
762 ;; shr-kinsoku-shorten is nil.
763 (unless (or shr-kinsoku-shorten (null shr-width))
764 (while (setq found (re-search-forward
765 "\\(\\c>\\)\\| \\|\\c<\\|\\c|"
766 (line-end-position) 'move)))
767 (if (and found
768 (not (match-beginning 1)))
769 (goto-char (match-beginning 0)))))
771 (eolp)
772 ;; Don't put kinsoku-bol characters at the beginning of a line,
773 ;; or kinsoku-eol characters at the end of a line.
774 (cond
775 ;; Don't overflow the window edge, even if shr-kinsoku-shorten
776 ;; is nil.
777 ((or shr-kinsoku-shorten (null shr-width))
778 (while (and (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
779 (or (shr-char-kinsoku-eol-p (preceding-char))
780 (shr-char-kinsoku-bol-p (following-char))))
781 (backward-char 1))
782 (when (setq failed (<= (point) start))
783 ;; There's no breakable point that doesn't violate kinsoku,
784 ;; so we look for the second best position.
785 (while (and (progn
786 (forward-char 1)
787 (<= (point) end))
788 (progn
789 (setq bp (point))
790 (shr-char-kinsoku-eol-p (following-char)))))
791 (goto-char bp)))
792 ((shr-char-kinsoku-eol-p (preceding-char))
793 ;; Find backward the point where kinsoku-eol characters begin.
794 (let ((count 4))
795 (while
796 (progn
797 (backward-char 1)
798 (and (> (setq count (1- count)) 0)
799 (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
800 (or (shr-char-kinsoku-eol-p (preceding-char))
801 (shr-char-kinsoku-bol-p (following-char)))))))
802 (when (setq failed (<= (point) start))
803 ;; There's no breakable point that doesn't violate kinsoku,
804 ;; so we go to the second best position.
805 (if (looking-at "\\(\\c<+\\)\\c<")
806 (goto-char (match-end 1))
807 (forward-char 1))))
808 ((shr-char-kinsoku-bol-p (following-char))
809 ;; Find forward the point where kinsoku-bol characters end.
810 (let ((count 4))
811 (while (progn
812 (forward-char 1)
813 (and (>= (setq count (1- count)) 0)
814 (shr-char-kinsoku-bol-p (following-char))
815 (shr-char-breakable-p (following-char))))))))
816 (when (eq (following-char) ? )
817 (forward-char 1))))
818 (not failed)))
820 (defun shr-parse-base (url)
821 ;; Always chop off anchors.
822 (when (string-match "#.*" url)
823 (setq url (substring url 0 (match-beginning 0))))
824 ;; NB: <base href="" > URI may itself be relative to the document s URI
825 (setq url (shr-expand-url url))
826 (let* ((parsed (url-generic-parse-url url))
827 (local (url-filename parsed)))
828 (setf (url-filename parsed) "")
829 ;; Chop off the bit after the last slash.
830 (when (string-match "\\`\\(.*/\\)[^/]+\\'" local)
831 (setq local (match-string 1 local)))
832 ;; Always make the local bit end with a slash.
833 (when (and (not (zerop (length local)))
834 (not (eq (aref local (1- (length local))) ?/)))
835 (setq local (concat local "/")))
836 (list (url-recreate-url parsed)
837 local
838 (url-type parsed)
839 url)))
841 (autoload 'url-expand-file-name "url-expand")
843 ;; FIXME This needs some tests writing.
844 ;; Does it even need to exist, given that url-expand-file-name does?
845 (defun shr-expand-url (url &optional base)
846 (setq base
847 (if base
848 ;; shr-parse-base should never call this with non-nil base!
849 (shr-parse-base base)
850 ;; Bound by the parser.
851 shr-base))
852 (when (zerop (length url))
853 (setq url nil))
854 ;; Strip leading whitespace
855 (and url (string-match "\\`\\s-+" url)
856 (setq url (substring url (match-end 0))))
857 (cond ((zerop (length url))
858 (nth 3 base))
859 ((or (not base)
860 (string-match "\\`[a-z]*:" url))
861 ;; Absolute or empty URI
862 url)
863 ((eq (aref url 0) ?/)
864 (if (and (> (length url) 1)
865 (eq (aref url 1) ?/))
866 ;; //host...; just use the protocol
867 (concat (nth 2 base) ":" url)
868 ;; Just use the host name part.
869 (concat (car base) url)))
870 ((eq (aref url 0) ?#)
871 ;; A link to an anchor.
872 (concat (nth 3 base) url))
874 ;; Totally relative.
875 (url-expand-file-name url (concat (car base) (cadr base))))))
877 (defun shr-ensure-newline ()
878 (unless (bobp)
879 (let ((prefix (get-text-property (line-beginning-position)
880 'shr-prefix-length)))
881 (unless (or (zerop (current-column))
882 (and prefix
883 (= prefix (- (point) (line-beginning-position)))))
884 (insert "\n")))))
886 (defun shr-ensure-paragraph ()
887 (unless (bobp)
888 (let ((prefix (get-text-property (line-beginning-position)
889 'shr-prefix-length)))
890 (cond
891 ((and (bolp)
892 (save-excursion
893 (forward-line -1)
894 (looking-at " *$")))
895 ;; We're already at a new paragraph; do nothing.
897 ((and prefix
898 (= prefix (- (point) (line-beginning-position))))
899 ;; Do nothing; we're at the start of a <li>.
901 ((save-excursion
902 (beginning-of-line)
903 ;; If the current line is totally blank, and doesn't even
904 ;; have any face properties set, then delete the blank
905 ;; space.
906 (and (looking-at " *$")
907 (not (get-text-property (point) 'face))
908 (not (= (next-single-property-change (point) 'face nil
909 (line-end-position))
910 (line-end-position)))))
911 (delete-region (match-beginning 0) (match-end 0)))
912 ;; We have a single blank line.
913 ((and (eolp) (bolp))
914 (insert "\n"))
915 ;; Insert new paragraph.
917 (insert "\n\n"))))))
919 (defun shr-indent ()
920 (when (> shr-indentation 0)
921 (insert
922 (if (not shr-use-fonts)
923 (make-string shr-indentation ?\s)
924 (propertize " "
925 'display
926 `(space :width (,shr-indentation)))))))
928 (defun shr-fontize-dom (dom &rest types)
929 (let ((start (point)))
930 (shr-generic dom)
931 (dolist (type types)
932 (shr-add-font start (point) type))))
934 ;; Add face to the region, but avoid putting the font properties on
935 ;; blank text at the start of the line, and the newline at the end, to
936 ;; avoid ugliness.
937 (defun shr-add-font (start end type)
938 (save-excursion
939 (goto-char start)
940 (while (< (point) end)
941 (when (bolp)
942 (skip-chars-forward " "))
943 (add-face-text-property (point) (min (line-end-position) end) type t)
944 (if (< (line-end-position) end)
945 (forward-line 1)
946 (goto-char end)))))
948 (defun shr-mouse-browse-url (ev)
949 "Browse the URL under the mouse cursor."
950 (interactive "e")
951 (mouse-set-point ev)
952 (shr-browse-url))
954 (defun shr-browse-url (&optional external mouse-event)
955 "Browse the URL at point using `browse-url'.
956 If EXTERNAL is non-nil (interactively, the prefix argument), browse
957 the URL using `shr-external-browser'.
958 If this function is invoked by a mouse click, it will browse the URL
959 at the position of the click. Optional argument MOUSE-EVENT describes
960 the mouse click event."
961 (interactive (list current-prefix-arg last-nonmenu-event))
962 (mouse-set-point mouse-event)
963 (let ((url (get-text-property (point) 'shr-url)))
964 (cond
965 ((not url)
966 (message "No link under point"))
967 ((string-match "^mailto:" url)
968 (browse-url-mail url))
970 (if external
971 (progn
972 (funcall shr-external-browser url)
973 (shr--blink-link))
974 (browse-url url))))))
976 (defun shr-save-contents (directory)
977 "Save the contents from URL in a file."
978 (interactive "DSave contents of URL to directory: ")
979 (let ((url (get-text-property (point) 'shr-url)))
980 (if (not url)
981 (message "No link under point")
982 (url-retrieve (shr-encode-url url)
983 'shr-store-contents (list url directory)
984 nil t))))
986 (defun shr-store-contents (status url directory)
987 (unless (plist-get status :error)
988 (when (or (search-forward "\n\n" nil t)
989 (search-forward "\r\n\r\n" nil t))
990 (write-region (point) (point-max)
991 (expand-file-name (file-name-nondirectory url)
992 directory)))))
994 (defun shr-image-fetched (status buffer start end &optional flags)
995 (let ((image-buffer (current-buffer)))
996 (when (and (buffer-name buffer)
997 (not (plist-get status :error)))
998 (url-store-in-cache image-buffer)
999 (goto-char (point-min))
1000 (when (or (search-forward "\n\n" nil t)
1001 (search-forward "\r\n\r\n" nil t))
1002 (let ((data (shr-parse-image-data)))
1003 (with-current-buffer buffer
1004 (save-excursion
1005 (save-restriction
1006 (widen)
1007 (let ((alt (buffer-substring start end))
1008 (properties (text-properties-at start))
1009 (inhibit-read-only t))
1010 (delete-region start end)
1011 (goto-char start)
1012 (funcall shr-put-image-function data alt flags)
1013 (while properties
1014 (let ((type (pop properties))
1015 (value (pop properties)))
1016 (unless (memq type '(display image-size))
1017 (put-text-property start (point) type value)))))))))))
1018 (kill-buffer image-buffer)))
1020 (defun shr-image-from-data (data)
1021 "Return an image from the data: URI content DATA."
1022 (when (string-match
1023 "\\(\\([^/;,]+\\(/[^;,]+\\)?\\)\\(;[^;,]+\\)*\\)?,\\(.*\\)"
1024 data)
1025 (let ((param (match-string 4 data))
1026 (payload (url-unhex-string (match-string 5 data))))
1027 (when (and param
1028 (string-match "^.*\\(;[ \t]*base64\\)$" param))
1029 (setq payload (ignore-errors
1030 (base64-decode-string payload))))
1031 payload)))
1033 ;; Behind display-graphic-p test.
1034 (declare-function image-size "image.c" (spec &optional pixels frame))
1035 (declare-function image-animate "image" (image &optional index limit))
1037 (defun shr-put-image (spec alt &optional flags)
1038 "Insert image SPEC with a string ALT. Return image.
1039 SPEC is either an image data blob, or a list where the first
1040 element is the data blob and the second element is the content-type."
1041 (if (display-graphic-p)
1042 (let* ((size (cdr (assq 'size flags)))
1043 (data (if (consp spec)
1044 (car spec)
1045 spec))
1046 (content-type (and (consp spec)
1047 (cadr spec)))
1048 (start (point))
1049 (image (cond
1050 ((eq size 'original)
1051 (create-image data nil t :ascent 100
1052 :format content-type))
1053 ((eq content-type 'image/svg+xml)
1054 (create-image data 'svg t :ascent 100))
1055 ((eq size 'full)
1056 (ignore-errors
1057 (shr-rescale-image data content-type
1058 (plist-get flags :width)
1059 (plist-get flags :height))))
1061 (ignore-errors
1062 (shr-rescale-image data content-type
1063 (plist-get flags :width)
1064 (plist-get flags :height)))))))
1065 (when image
1066 ;; When inserting big-ish pictures, put them at the
1067 ;; beginning of the line.
1068 (when (and (> (current-column) 0)
1069 (> (car (image-size image t)) 400))
1070 (insert "\n"))
1071 (if (eq size 'original)
1072 (insert-sliced-image image (or alt "*") nil 20 1)
1073 (insert-image image (or alt "*")))
1074 (put-text-property start (point) 'image-size size)
1075 (when (and shr-image-animate
1076 (cond ((fboundp 'image-multi-frame-p)
1077 ;; Only animate multi-frame things that specify a
1078 ;; delay; eg animated gifs as opposed to
1079 ;; multi-page tiffs. FIXME?
1080 (cdr (image-multi-frame-p image)))
1081 ((fboundp 'image-animated-p)
1082 (image-animated-p image))))
1083 (image-animate image nil 60)))
1084 image)
1085 (insert (or alt ""))))
1087 (defun shr-rescale-image (data content-type width height
1088 &optional max-width max-height)
1089 "Rescale DATA, if too big, to fit the current buffer.
1090 WIDTH and HEIGHT are the sizes given in the HTML data, if any.
1092 The size of the displayed image will not exceed
1093 MAX-WIDTH/MAX-HEIGHT. If not given, use the current window
1094 width/height instead."
1095 (if (or (not (fboundp 'imagemagick-types))
1096 (not (get-buffer-window (current-buffer))))
1097 (create-image data nil t :ascent 100)
1098 (let* ((edges (window-inside-pixel-edges
1099 (get-buffer-window (current-buffer))))
1100 (max-width (truncate (* shr-max-image-proportion
1101 (or max-width
1102 (- (nth 2 edges) (nth 0 edges))))))
1103 (max-height (truncate (* shr-max-image-proportion
1104 (or max-height
1105 (- (nth 3 edges) (nth 1 edges))))))
1106 (scaling (image-compute-scaling-factor image-scaling-factor)))
1107 (when (or (and width
1108 (> width max-width))
1109 (and height
1110 (> height max-height)))
1111 (setq width nil
1112 height nil))
1113 (if (and width height
1114 (< (* width scaling) max-width)
1115 (< (* height scaling) max-height))
1116 (create-image
1117 data 'imagemagick t
1118 :ascent 100
1119 :width width
1120 :height height
1121 :format content-type)
1122 (create-image
1123 data 'imagemagick t
1124 :ascent 100
1125 :max-width max-width
1126 :max-height max-height
1127 :format content-type)))))
1129 ;; url-cache-extract autoloads url-cache.
1130 (declare-function url-cache-create-filename "url-cache" (url))
1131 (autoload 'mm-disable-multibyte "mm-util")
1132 (autoload 'browse-url-mail "browse-url")
1134 (defun shr-get-image-data (url)
1135 "Get image data for URL.
1136 Return a string with image data."
1137 (with-temp-buffer
1138 (mm-disable-multibyte)
1139 (when (ignore-errors
1140 (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
1142 (when (re-search-forward "\r?\n\r?\n" nil t)
1143 (shr-parse-image-data)))))
1145 (declare-function libxml-parse-xml-region "xml.c"
1146 (start end &optional base-url discard-comments))
1148 (defun shr-parse-image-data ()
1149 (let ((data (buffer-substring (point) (point-max)))
1150 (content-type
1151 (save-excursion
1152 (save-restriction
1153 (narrow-to-region (point-min) (point))
1154 (let ((content-type (mail-fetch-field "content-type")))
1155 (and content-type
1156 ;; Remove any comments in the type string.
1157 (intern (replace-regexp-in-string ";.*" "" content-type)
1158 obarray)))))))
1159 ;; SVG images may contain references to further images that we may
1160 ;; want to block. So special-case these by parsing the XML data
1161 ;; and remove anything that looks like a blocked bit.
1162 (when (and shr-blocked-images
1163 (eq content-type 'image/svg+xml))
1164 (setq data
1165 ;; Note that libxml2 doesn't parse everything perfectly,
1166 ;; so glitches may occur during this transformation.
1167 (shr-dom-to-xml
1168 (libxml-parse-xml-region (point) (point-max)))))
1169 (list data content-type)))
1171 (defun shr-image-displayer (content-function)
1172 "Return a function to display an image.
1173 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
1174 is an argument. The function to be returned takes three arguments URL,
1175 START, and END. Note that START and END should be markers."
1176 `(lambda (url start end)
1177 (when url
1178 (if (string-match "\\`cid:" url)
1179 ,(when content-function
1180 `(let ((image (funcall ,content-function
1181 (substring url (match-end 0)))))
1182 (when image
1183 (goto-char start)
1184 (funcall shr-put-image-function
1185 image (buffer-substring start end))
1186 (delete-region (point) end))))
1187 (url-retrieve url 'shr-image-fetched
1188 (list (current-buffer) start end)
1189 t t)))))
1191 (defun shr-heading (dom &rest types)
1192 (shr-ensure-paragraph)
1193 (apply #'shr-fontize-dom dom types)
1194 (shr-ensure-paragraph))
1196 (defun shr-urlify (start url &optional title)
1197 (shr-add-font start (point) 'shr-link)
1198 (add-text-properties
1199 start (point)
1200 (list 'shr-url url
1201 'help-echo (let ((parsed (url-generic-parse-url
1202 (or (ignore-errors
1203 (decode-coding-string
1204 (url-unhex-string url)
1205 'utf-8 t))
1206 url)))
1207 iri)
1208 ;; If we have an IDNA domain, then show the
1209 ;; decoded version in the mouseover to let the
1210 ;; user know that there's something possibly
1211 ;; fishy.
1212 (when (url-host parsed)
1213 (setf (url-host parsed)
1214 (puny-encode-domain (url-host parsed))))
1215 (setq iri (url-recreate-url parsed))
1216 (if title
1217 (format "%s (%s)" iri title)
1218 iri))
1219 'follow-link t
1220 'mouse-face 'highlight))
1221 ;; Don't overwrite any keymaps that are already in the buffer (i.e.,
1222 ;; image keymaps).
1223 (while (and start
1224 (< start (point)))
1225 (let ((next (next-single-property-change start 'keymap nil (point))))
1226 (if (get-text-property start 'keymap)
1227 (setq start next)
1228 (put-text-property start (or next (point)) 'keymap shr-map)))))
1230 (defun shr-encode-url (url)
1231 "Encode URL."
1232 (browse-url-url-encode-chars url "[)$ ]"))
1234 (autoload 'shr-color-visible "shr-color")
1235 (autoload 'shr-color->hexadecimal "shr-color")
1237 (defun shr-color-check (fg bg)
1238 "Check that FG is visible on BG.
1239 Returns (fg bg) with corrected values.
1240 Returns nil if the colors that would be used are the default
1241 ones, in case fg and bg are nil."
1242 (when (or fg bg)
1243 (let ((fixed (cond ((null fg) 'fg)
1244 ((null bg) 'bg))))
1245 ;; Convert colors to hexadecimal, or set them to default.
1246 (let ((fg (or (shr-color->hexadecimal fg)
1247 (frame-parameter nil 'foreground-color)))
1248 (bg (or (shr-color->hexadecimal bg)
1249 (frame-parameter nil 'background-color))))
1250 (cond ((eq fixed 'bg)
1251 ;; Only return the new fg
1252 (list nil (cadr (shr-color-visible bg fg t))))
1253 ((eq fixed 'fg)
1254 ;; Invert args and results and return only the new bg
1255 (list (cadr (shr-color-visible fg bg t)) nil))
1257 (shr-color-visible bg fg)))))))
1259 (defun shr-colorize-region (start end fg &optional bg)
1260 (when (and shr-use-colors
1261 (or fg bg)
1262 (>= (display-color-cells) 88))
1263 (let ((new-colors (shr-color-check fg bg)))
1264 (when new-colors
1265 (when fg
1266 (add-face-text-property start end
1267 (list :foreground (cadr new-colors))
1269 (when bg
1270 (add-face-text-property start end
1271 (list :background (car new-colors))
1272 t)))
1273 new-colors)))
1275 ;;; Tag-specific rendering rules.
1277 (defun shr-tag-html (dom)
1278 (let ((dir (dom-attr dom 'dir)))
1279 (cond
1280 ((equal dir "ltr")
1281 (setq bidi-paragraph-direction 'left-to-right))
1282 ((equal dir "rtl")
1283 (setq bidi-paragraph-direction 'right-to-left))
1284 ((equal dir "auto")
1285 (setq bidi-paragraph-direction nil))))
1286 (shr-generic dom))
1288 (defun shr-tag-body (dom)
1289 (let* ((start (point))
1290 (fgcolor (or (dom-attr dom 'fgcolor) (dom-attr dom 'text)))
1291 (bgcolor (dom-attr dom 'bgcolor))
1292 (shr-stylesheet (list (cons 'color fgcolor)
1293 (cons 'background-color bgcolor))))
1294 (shr-generic dom)
1295 (shr-colorize-region start (point) fgcolor bgcolor)))
1297 (defun shr-tag-style (_dom)
1300 (defun shr-tag-script (_dom)
1303 (defun shr-tag-comment (_dom)
1306 (defun shr-dom-to-xml (dom)
1307 (with-temp-buffer
1308 (shr-dom-print dom)
1309 (buffer-string)))
1311 (defun shr-dom-print (dom)
1312 "Convert DOM into a string containing the xml representation."
1313 (insert (format "<%s" (dom-tag dom)))
1314 (dolist (attr (dom-attributes dom))
1315 ;; Ignore attributes that start with a colon because they are
1316 ;; private elements.
1317 (unless (= (aref (format "%s" (car attr)) 0) ?:)
1318 (insert (format " %s=\"%s\"" (car attr) (cdr attr)))))
1319 (insert ">")
1320 (let (url)
1321 (dolist (elem (dom-children dom))
1322 (cond
1323 ((stringp elem)
1324 (insert elem))
1325 ((eq (dom-tag elem) 'comment)
1327 ((or (not (eq (dom-tag elem) 'image))
1328 ;; Filter out blocked elements inside the SVG image.
1329 (not (setq url (dom-attr elem ':xlink:href)))
1330 (not shr-blocked-images)
1331 (not (string-match shr-blocked-images url)))
1332 (insert " ")
1333 (shr-dom-print elem)))))
1334 (insert (format "</%s>" (dom-tag dom))))
1336 (defun shr-tag-svg (dom)
1337 (when (and (image-type-available-p 'svg)
1338 (not shr-inhibit-images)
1339 (dom-attr dom 'width)
1340 (dom-attr dom 'height))
1341 (funcall shr-put-image-function (list (shr-dom-to-xml dom) 'image/svg+xml)
1342 "SVG Image")))
1344 (defun shr-tag-sup (dom)
1345 (let ((start (point)))
1346 (shr-generic dom)
1347 (put-text-property start (point) 'display '(raise 0.5))))
1349 (defun shr-tag-sub (dom)
1350 (let ((start (point)))
1351 (shr-generic dom)
1352 (put-text-property start (point) 'display '(raise -0.5))))
1354 (defun shr-tag-p (dom)
1355 (shr-ensure-paragraph)
1356 (shr-generic dom)
1357 (shr-ensure-paragraph))
1359 (defun shr-tag-div (dom)
1360 (let ((display (cdr (assq 'display shr-stylesheet))))
1361 (if (or (equal display "inline")
1362 (equal display "inline-block"))
1363 (shr-generic dom)
1364 (shr-ensure-newline)
1365 (shr-generic dom)
1366 (shr-ensure-newline))))
1368 (defun shr-tag-s (dom)
1369 (shr-fontize-dom dom 'shr-strike-through))
1371 (defun shr-tag-b (dom)
1372 (shr-fontize-dom dom 'bold))
1374 (defun shr-tag-i (dom)
1375 (shr-fontize-dom dom 'italic))
1377 (defun shr-tag-em (dom)
1378 (shr-fontize-dom dom 'italic))
1380 (defun shr-tag-strong (dom)
1381 (shr-fontize-dom dom 'bold))
1383 (defun shr-tag-u (dom)
1384 (shr-fontize-dom dom 'underline))
1386 (defun shr-tag-tt (dom)
1387 (let ((shr-current-font 'default))
1388 (shr-generic dom)))
1390 (defun shr-tag-ins (cont)
1391 (let* ((start (point))
1392 (color "green")
1393 (shr-stylesheet (nconc (list (cons 'color color))
1394 shr-stylesheet)))
1395 (shr-generic cont)
1396 (shr-colorize-region start (point) color
1397 (cdr (assq 'background-color shr-stylesheet)))))
1399 (defun shr-tag-del (cont)
1400 (let* ((start (point))
1401 (color "red")
1402 (shr-stylesheet (nconc (list (cons 'color color))
1403 shr-stylesheet)))
1404 (shr-fontize-dom cont 'shr-strike-through)
1405 (shr-colorize-region start (point) color
1406 (cdr (assq 'background-color shr-stylesheet)))))
1408 (defun shr-parse-style (style)
1409 (when style
1410 (save-match-data
1411 (when (string-match "\n" style)
1412 (setq style (replace-match " " t t style))))
1413 (let ((plist nil))
1414 (dolist (elem (split-string style ";"))
1415 (when elem
1416 (setq elem (split-string elem ":"))
1417 (when (and (car elem)
1418 (cadr elem))
1419 (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
1420 (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
1421 (when (string-match " *!important\\'" value)
1422 (setq value (substring value 0 (match-beginning 0))))
1423 (unless (equal value "inherit")
1424 (push (cons (intern name obarray)
1425 value)
1426 plist))))))
1427 plist)))
1429 (defun shr-tag-base (dom)
1430 (when-let* ((base (dom-attr dom 'href)))
1431 (setq shr-base (shr-parse-base base)))
1432 (shr-generic dom))
1434 (defun shr-tag-a (dom)
1435 (let ((url (dom-attr dom 'href))
1436 (title (dom-attr dom 'title))
1437 (start (point))
1438 shr-start)
1439 (shr-generic dom)
1440 (when (and shr-target-id
1441 (equal (dom-attr dom 'name) shr-target-id))
1442 ;; We have a zero-length <a name="foo"> element, so just
1443 ;; insert... something.
1444 (when (= start (point))
1445 (shr-ensure-newline)
1446 (insert " "))
1447 (put-text-property start (1+ start) 'shr-target-id shr-target-id))
1448 (when url
1449 (shr-urlify (or shr-start start) (shr-expand-url url) title))))
1451 (defun shr-tag-object (dom)
1452 (unless shr-inhibit-images
1453 (let ((start (point))
1454 url multimedia image)
1455 (when-let* ((type (dom-attr dom 'type)))
1456 (when (string-match "\\`image/svg" type)
1457 (setq url (dom-attr dom 'data)
1458 image t)))
1459 (dolist (child (dom-non-text-children dom))
1460 (cond
1461 ((eq (dom-tag child) 'embed)
1462 (setq url (or url (dom-attr child 'src))
1463 multimedia t))
1464 ((and (eq (dom-tag child) 'param)
1465 (equal (dom-attr child 'name) "movie"))
1466 (setq url (or url (dom-attr child 'value))
1467 multimedia t))))
1468 (when url
1469 (cond
1470 (image
1471 (shr-indirect-call 'img dom url)
1472 (setq dom nil))
1473 (multimedia
1474 (shr-insert " [multimedia] ")
1475 (shr-urlify start (shr-expand-url url)))))
1476 (when dom
1477 (shr-generic dom)))))
1479 (defcustom shr-prefer-media-type-alist '(("webm" . 1.0)
1480 ("ogv" . 1.0)
1481 ("ogg" . 1.0)
1482 ("opus" . 1.0)
1483 ("flac" . 0.9)
1484 ("wav" . 0.5))
1485 "Preferences for media types.
1486 The key element should be a regexp matched against the type of the source or
1487 url if no type is specified. The value should be a float in the range 0.0 to
1488 1.0. Media elements with higher value are preferred."
1489 :version "24.4"
1490 :group 'shr
1491 :type '(alist :key-type regexp :value-type float))
1493 (defun shr--get-media-pref (elem)
1494 "Determine the preference for ELEM.
1495 The preference is a float determined from `shr-prefer-media-type'."
1496 (let ((type (dom-attr elem 'type))
1497 (p 0.0))
1498 (unless type
1499 (setq type (dom-attr elem 'src)))
1500 (when type
1501 (dolist (pref shr-prefer-media-type-alist)
1502 (when (and
1503 (> (cdr pref) p)
1504 (string-match-p (car pref) type))
1505 (setq p (cdr pref)))))
1508 (defun shr--extract-best-source (dom &optional url pref)
1509 "Extract the best `:src' property from <source> blocks in DOM."
1510 (setq pref (or pref -1.0))
1511 (let (new-pref)
1512 (dolist (elem (dom-non-text-children dom))
1513 (when (and (eq (dom-tag elem) 'source)
1514 (< pref
1515 (setq new-pref
1516 (shr--get-media-pref elem))))
1517 (setq pref new-pref
1518 url (dom-attr elem 'src))
1519 ;; libxml's html parser isn't HTML5 compliant and non terminated
1520 ;; source tags might end up as children. So recursion it is...
1521 (dolist (child (dom-non-text-children elem))
1522 (when (eq (dom-tag child) 'source)
1523 (let ((ret (shr--extract-best-source (list child) url pref)))
1524 (when (< pref (cdr ret))
1525 (setq url (car ret)
1526 pref (cdr ret)))))))))
1527 (cons url pref))
1529 (defun shr-tag-video (dom)
1530 (let ((image (dom-attr dom 'poster))
1531 (url (dom-attr dom 'src))
1532 (start (point)))
1533 (unless url
1534 (setq url (car (shr--extract-best-source dom))))
1535 (if (> (length image) 0)
1536 (shr-indirect-call 'img nil image)
1537 (shr-insert " [video] "))
1538 (shr-urlify start (shr-expand-url url))))
1540 (defun shr-tag-audio (dom)
1541 (let ((url (dom-attr dom 'src))
1542 (start (point)))
1543 (unless url
1544 (setq url (car (shr--extract-best-source dom))))
1545 (shr-insert " [audio] ")
1546 (shr-urlify start (shr-expand-url url))))
1548 (defun shr-tag-img (dom &optional url)
1549 (when (or url
1550 (and dom
1551 (or (> (length (dom-attr dom 'src)) 0)
1552 (> (length (dom-attr dom 'srcset)) 0))))
1553 (when (> (current-column) 0)
1554 (insert "\n"))
1555 (let ((alt (dom-attr dom 'alt))
1556 (width (shr-string-number (dom-attr dom 'width)))
1557 (height (shr-string-number (dom-attr dom 'height)))
1558 (url (shr-expand-url (or url (shr--preferred-image dom)))))
1559 (let ((start (point-marker)))
1560 (when (zerop (length alt))
1561 (setq alt "*"))
1562 (cond
1563 ((or (member (dom-attr dom 'height) '("0" "1"))
1564 (member (dom-attr dom 'width) '("0" "1")))
1565 ;; Ignore zero-sized or single-pixel images.
1567 ((and (not shr-inhibit-images)
1568 (string-match "\\`data:" url))
1569 (let ((image (shr-image-from-data (substring url (match-end 0)))))
1570 (if image
1571 (funcall shr-put-image-function image alt
1572 (list :width width :height height))
1573 (insert alt))))
1574 ((and (not shr-inhibit-images)
1575 (string-match "\\`cid:" url))
1576 (let ((url (substring url (match-end 0)))
1577 image)
1578 (if (or (not shr-content-function)
1579 (not (setq image (funcall shr-content-function url))))
1580 (insert alt)
1581 (funcall shr-put-image-function image alt
1582 (list :width width :height height)))))
1583 ((or shr-inhibit-images
1584 (and shr-blocked-images
1585 (string-match shr-blocked-images url)))
1586 (setq shr-start (point))
1587 (shr-insert alt))
1588 ((and (not shr-ignore-cache)
1589 (url-is-cached (shr-encode-url url)))
1590 (funcall shr-put-image-function (shr-get-image-data url) alt
1591 (list :width width :height height)))
1593 (when (and shr-ignore-cache
1594 (url-is-cached (shr-encode-url url)))
1595 (let ((file (url-cache-create-filename (shr-encode-url url))))
1596 (when (file-exists-p file)
1597 (delete-file file))))
1598 (when (image-type-available-p 'svg)
1599 (insert-image
1600 (shr-make-placeholder-image dom)
1601 (or alt "")))
1602 (insert " ")
1603 (url-queue-retrieve
1604 (shr-encode-url url) 'shr-image-fetched
1605 (list (current-buffer) start (set-marker (make-marker) (point))
1606 (list :width width :height height))
1607 t t)))
1608 (when (zerop shr-table-depth) ;; We are not in a table.
1609 (put-text-property start (point) 'keymap shr-image-map)
1610 (put-text-property start (point) 'shr-alt alt)
1611 (put-text-property start (point) 'image-url url)
1612 (put-text-property start (point) 'image-displayer
1613 (shr-image-displayer shr-content-function))
1614 (put-text-property start (point) 'help-echo
1615 (shr-fill-text
1616 (or (dom-attr dom 'title) alt))))))))
1618 (defun shr--preferred-image (dom)
1619 (let ((srcset (dom-attr dom 'srcset))
1620 (frame-width (frame-pixel-width))
1621 (width (string-to-number (or (dom-attr dom 'width) "100")))
1622 candidate)
1623 (when (> (length srcset) 0)
1624 ;; srcset consist of a series of URL/size specifications
1625 ;; separated by the ", " string.
1626 (setq srcset
1627 (sort (mapcar
1628 (lambda (elem)
1629 (let ((spec (split-string elem "[\t\n\r ]+")))
1630 (cond
1631 ((= (length spec) 1)
1632 ;; Make sure it's well formed.
1633 (list (car spec) 0))
1634 ((string-match "\\([0-9]+\\)x\\'" (cadr spec))
1635 ;; If we have an "x" form, then use the width
1636 ;; spec to compute the real width.
1637 (list (car spec)
1638 (* width (string-to-number
1639 (match-string 1 (cadr spec))))))
1641 (list (car spec)
1642 (string-to-number (cadr spec)))))))
1643 (split-string (replace-regexp-in-string
1644 "\\`[\t\n\r ]+\\|[\t\n\r ]+\\'" "" srcset)
1645 "[\t\n\r ]*,[\t\n\r ]*"))
1646 (lambda (e1 e2)
1647 (> (cadr e1) (cadr e2)))))
1648 ;; Choose the smallest picture that's bigger than the current
1649 ;; frame.
1650 (setq candidate (caar srcset))
1651 (while (and srcset
1652 (> (cadr (car srcset)) frame-width))
1653 (setq candidate (caar srcset))
1654 (pop srcset)))
1655 (or candidate (dom-attr dom 'src))))
1657 (defun shr-string-number (string)
1658 (if (null string)
1660 (setq string (replace-regexp-in-string "[^0-9]" "" string))
1661 (if (zerop (length string))
1663 (string-to-number string))))
1665 (defun shr-make-placeholder-image (dom)
1666 (let* ((edges (and
1667 (get-buffer-window (current-buffer))
1668 (window-inside-pixel-edges
1669 (get-buffer-window (current-buffer)))))
1670 (scaling (image-compute-scaling-factor image-scaling-factor))
1671 (width (truncate
1672 (* (or (shr-string-number (dom-attr dom 'width)) 100)
1673 scaling)))
1674 (height (truncate
1675 (* (or (shr-string-number (dom-attr dom 'height)) 100)
1676 scaling)))
1677 (max-width
1678 (and edges
1679 (truncate (* shr-max-image-proportion
1680 (- (nth 2 edges) (nth 0 edges))))))
1681 (max-height (and edges
1682 (truncate (* shr-max-image-proportion
1683 (- (nth 3 edges) (nth 1 edges))))))
1684 svg)
1685 (when (and max-width
1686 (> width max-width))
1687 (setq height (truncate (* (/ (float max-width) width) height))
1688 width max-width))
1689 (when (and max-height
1690 (> height max-height))
1691 (setq width (truncate (* (/ (float max-height) height) width))
1692 height max-height))
1693 (setq svg (svg-create width height))
1694 (svg-gradient svg "background" 'linear '((0 . "#b0b0b0") (100 . "#808080")))
1695 (svg-rectangle svg 0 0 width height :gradient "background"
1696 :stroke-width 2 :stroke-color "black")
1697 (let ((image (svg-image svg)))
1698 (setf (image-property image :ascent) 100)
1699 image)))
1701 (defun shr-tag-pre (dom)
1702 (let ((shr-folding-mode 'none)
1703 (shr-current-font 'default))
1704 (shr-ensure-newline)
1705 (shr-generic dom)
1706 (shr-ensure-newline)))
1708 (defun shr-tag-blockquote (dom)
1709 (shr-ensure-paragraph)
1710 (let ((start (point))
1711 (shr-indentation (+ shr-indentation
1712 (* 4 shr-table-separator-pixel-width))))
1713 (shr-generic dom)
1714 (shr-ensure-paragraph)
1715 (shr-mark-fill start)))
1717 (defun shr-tag-dl (dom)
1718 (shr-ensure-paragraph)
1719 (shr-generic dom)
1720 (shr-ensure-paragraph))
1722 (defun shr-tag-dt (dom)
1723 (shr-ensure-newline)
1724 (shr-generic dom)
1725 (shr-ensure-newline))
1727 (defun shr-tag-dd (dom)
1728 (shr-ensure-newline)
1729 (let ((shr-indentation (+ shr-indentation
1730 (* 4 shr-table-separator-pixel-width))))
1731 (shr-generic dom)))
1733 (defun shr-tag-ul (dom)
1734 (shr-ensure-paragraph)
1735 (let ((shr-list-mode 'ul))
1736 (shr-generic dom))
1737 ;; If we end on an empty <li>, then make sure we really end on a new
1738 ;; paragraph.
1739 (unless (bolp)
1740 (insert "\n"))
1741 (shr-ensure-paragraph))
1743 (defun shr-tag-ol (dom)
1744 (shr-ensure-paragraph)
1745 (let ((shr-list-mode 1))
1746 (shr-generic dom))
1747 (shr-ensure-paragraph))
1749 (defun shr-tag-li (dom)
1750 (shr-ensure-newline)
1751 (let ((start (point)))
1752 (let* ((bullet
1753 (if (numberp shr-list-mode)
1754 (prog1
1755 (format "%d " shr-list-mode)
1756 (setq shr-list-mode (1+ shr-list-mode)))
1757 (car shr-internal-bullet)))
1758 (width (if (numberp shr-list-mode)
1759 (shr-string-pixel-width bullet)
1760 (cdr shr-internal-bullet))))
1761 (insert bullet)
1762 (shr-mark-fill start)
1763 (let ((shr-indentation (+ shr-indentation width)))
1764 (put-text-property start (1+ start)
1765 'shr-continuation-indentation shr-indentation)
1766 (put-text-property start (1+ start) 'shr-prefix-length (length bullet))
1767 (shr-generic dom))))
1768 (unless (bolp)
1769 (insert "\n")))
1771 (defun shr-mark-fill (start)
1772 ;; We may not have inserted any text to fill.
1773 (unless (= start (point))
1774 (put-text-property start (1+ start)
1775 'shr-indentation shr-indentation)))
1777 (defun shr-tag-br (dom)
1778 (when (and (not (bobp))
1779 ;; Only add a newline if we break the current line, or
1780 ;; the previous line isn't a blank line.
1781 (or (not (bolp))
1782 (and (> (- (point) 2) (point-min))
1783 (not (= (char-after (- (point) 2)) ?\n)))))
1784 (insert "\n"))
1785 (shr-generic dom))
1787 (defun shr-tag-span (dom)
1788 (shr-generic dom))
1790 (defun shr-tag-h1 (dom)
1791 (shr-heading dom (if shr-use-fonts
1792 '(variable-pitch (:height 1.3 :weight bold))
1793 'bold)))
1795 (defun shr-tag-h2 (dom)
1796 (shr-heading dom 'bold))
1798 (defun shr-tag-h3 (dom)
1799 (shr-heading dom 'italic))
1801 (defun shr-tag-h4 (dom)
1802 (shr-heading dom))
1804 (defun shr-tag-h5 (dom)
1805 (shr-heading dom))
1807 (defun shr-tag-h6 (dom)
1808 (shr-heading dom))
1810 (defun shr-tag-hr (_dom)
1811 (shr-ensure-newline)
1812 (insert (make-string (if (not shr-use-fonts)
1813 shr-internal-width
1814 (1+ (/ shr-internal-width
1815 shr-table-separator-pixel-width)))
1816 shr-hr-line)
1817 "\n"))
1819 (defun shr-tag-title (dom)
1820 (shr-heading dom 'bold 'underline))
1822 (defun shr-tag-font (dom)
1823 (let* ((start (point))
1824 (color (dom-attr dom 'color))
1825 (shr-stylesheet (nconc (list (cons 'color color))
1826 shr-stylesheet)))
1827 (shr-generic dom)
1828 (when color
1829 (shr-colorize-region start (point) color
1830 (cdr (assq 'background-color shr-stylesheet))))))
1832 (defun shr-tag-bdo (dom)
1833 (let* ((direction (dom-attr dom 'dir))
1834 (char (cond
1835 ((equal direction "ltr")
1836 ?\N{LEFT-TO-RIGHT OVERRIDE})
1837 ((equal direction "rtl")
1838 ?\N{RIGHT-TO-LEFT OVERRIDE}))))
1839 (when char
1840 (insert ?\N{FIRST STRONG ISOLATE} char))
1841 (shr-generic dom)
1842 (when char
1843 (insert ?\N{POP DIRECTIONAL FORMATTING} ?\N{POP DIRECTIONAL ISOLATE}))))
1845 (defun shr-tag-bdi (dom)
1846 (insert ?\N{FIRST STRONG ISOLATE})
1847 (shr-generic dom)
1848 (insert ?\N{POP DIRECTIONAL ISOLATE}))
1850 ;;; Table rendering algorithm.
1852 ;; Table rendering is the only complicated thing here. We do this by
1853 ;; first counting how many TDs there are in each TR, and registering
1854 ;; how wide they think they should be ("width=45%", etc). Then we
1855 ;; render each TD separately (this is done in temporary buffers, so
1856 ;; that we can use all the rendering machinery as if we were in the
1857 ;; main buffer). Now we know how much space each TD really takes, so
1858 ;; we then render everything again with the new widths, and finally
1859 ;; insert all these boxes into the main buffer.
1860 (defun shr-tag-table-1 (dom)
1861 (setq dom (or (dom-child-by-tag dom 'tbody) dom))
1862 (let* ((shr-inhibit-images t)
1863 (shr-table-depth (1+ shr-table-depth))
1864 (shr-kinsoku-shorten t)
1865 ;; Find all suggested widths.
1866 (columns (shr-column-specs dom))
1867 ;; Compute how many pixels wide each TD should be.
1868 (suggested-widths (shr-pro-rate-columns columns))
1869 ;; Do a "test rendering" to see how big each TD is (this can
1870 ;; be smaller (if there's little text) or bigger (if there's
1871 ;; unbreakable text).
1872 (elems (or (dom-attr dom 'shr-suggested-widths)
1873 (shr-make-table dom suggested-widths nil
1874 'shr-suggested-widths)))
1875 (sketch (cl-loop for line in elems
1876 collect (mapcar #'car line)))
1877 (natural (cl-loop for line in elems
1878 collect (mapcar #'cdr line)))
1879 (sketch-widths (shr-table-widths sketch natural suggested-widths)))
1880 ;; This probably won't work very well.
1881 (when (> (+ (cl-loop for width across sketch-widths
1882 summing (1+ width))
1883 shr-indentation shr-table-separator-pixel-width)
1884 (frame-width))
1885 (setq truncate-lines t))
1886 ;; Then render the table again with these new "hard" widths.
1887 (shr-insert-table (shr-make-table dom sketch-widths t) sketch-widths)))
1889 (defun shr-table-body (dom)
1890 (let ((tbodies (seq-filter (lambda (child)
1891 (eq (dom-tag child) 'tbody))
1892 (dom-non-text-children dom))))
1893 (cond
1894 ((null tbodies)
1895 dom)
1896 ((= (length tbodies) 1)
1897 (car tbodies))
1899 ;; Table with multiple tbodies. Convert into a single tbody.
1900 `(tbody nil ,@(cl-reduce 'append
1901 (mapcar 'dom-non-text-children tbodies)))))))
1903 (defun shr-tag-table (dom)
1904 (shr-ensure-paragraph)
1905 (let* ((caption (dom-children (dom-child-by-tag dom 'caption)))
1906 (header (dom-non-text-children (dom-child-by-tag dom 'thead)))
1907 (body (dom-non-text-children (shr-table-body dom)))
1908 (footer (dom-non-text-children (dom-child-by-tag dom 'tfoot)))
1909 (bgcolor (dom-attr dom 'bgcolor))
1910 (start (point))
1911 (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
1912 shr-stylesheet))
1913 (nheader (if header (shr-max-columns header)))
1914 (nbody (if body (shr-max-columns body) 0))
1915 (nfooter (if footer (shr-max-columns footer))))
1916 (if (and (not caption)
1917 (not header)
1918 (not (dom-child-by-tag dom 'tbody))
1919 (not (dom-child-by-tag dom 'tr))
1920 (not footer))
1921 ;; The table is totally invalid and just contains random junk.
1922 ;; Try to output it anyway.
1923 (shr-generic dom)
1924 ;; It's a real table, so render it.
1925 (if (dom-attr dom 'shr-fixed-table)
1926 (shr-tag-table-1 dom)
1927 ;; Only fix up the table once.
1928 (let ((table
1929 (nconc
1930 (list 'table nil)
1931 (if caption `((tr nil (td nil ,@caption))))
1932 (cond
1933 (header
1934 (if footer
1935 ;; header + body + footer
1936 (if (= nheader nbody)
1937 (if (= nbody nfooter)
1938 `((tr nil (td nil (table nil
1939 (tbody nil ,@header
1940 ,@body ,@footer)))))
1941 (nconc `((tr nil (td nil (table nil
1942 (tbody nil ,@header
1943 ,@body)))))
1944 (if (= nfooter 1)
1945 footer
1946 `((tr nil (td nil (table
1947 nil (tbody
1948 nil ,@footer))))))))
1949 (nconc `((tr nil (td nil (table nil (tbody
1950 nil ,@header)))))
1951 (if (= nbody nfooter)
1952 `((tr nil (td nil (table
1953 nil (tbody nil ,@body
1954 ,@footer)))))
1955 (nconc `((tr nil (td nil (table
1956 nil (tbody nil
1957 ,@body)))))
1958 (if (= nfooter 1)
1959 footer
1960 `((tr nil (td nil (table
1962 (tbody
1964 ,@footer))))))))))
1965 ;; header + body
1966 (if (= nheader nbody)
1967 `((tr nil (td nil (table nil (tbody nil ,@header
1968 ,@body)))))
1969 (if (= nheader 1)
1970 `(,@header (tr nil (td nil (table
1971 nil (tbody nil ,@body)))))
1972 `((tr nil (td nil (table nil (tbody nil ,@header))))
1973 (tr nil (td nil (table nil (tbody nil ,@body)))))))))
1974 (footer
1975 ;; body + footer
1976 (if (= nbody nfooter)
1977 `((tr nil (td nil (table
1978 nil (tbody nil ,@body ,@footer)))))
1979 (nconc `((tr nil (td nil (table nil (tbody nil ,@body)))))
1980 (if (= nfooter 1)
1981 footer
1982 `((tr nil (td nil (table
1983 nil (tbody nil ,@footer)))))))))
1984 (caption
1985 `((tr nil (td nil (table nil (tbody nil ,@body))))))
1986 (body)))))
1987 (dom-set-attribute table 'shr-fixed-table t)
1988 (setcdr dom (cdr table))
1989 (shr-tag-table-1 dom))))
1990 (when bgcolor
1991 (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
1992 bgcolor))
1993 ;; Finally, insert all the images after the table. The Emacs buffer
1994 ;; model isn't strong enough to allow us to put the images actually
1995 ;; into the tables. It inserts also non-td/th objects.
1996 (when (zerop shr-table-depth)
1997 (save-excursion
1998 (shr-expand-alignments start (point)))
1999 (let ((strings (shr-collect-extra-strings-in-table dom)))
2000 (when strings
2001 (save-restriction
2002 (narrow-to-region (point) (point))
2003 (insert (mapconcat #'identity strings "\n"))
2004 (shr-fill-lines (point-min) (point-max))))))))
2006 (defun shr-collect-extra-strings-in-table (dom &optional flags)
2007 "Return extra strings in DOM of which the root is a table clause.
2008 Render <img>s and <object>s, and strings and child <table>s of which
2009 the parent <td> or <th> is lacking. FLAGS is a cons of two boolean
2010 flags that control whether to collect or render objects."
2011 ;; This function runs recursively and collects strings if the cdr of
2012 ;; FLAGS is nil and the car is not nil, and it renders also child
2013 ;; <table>s if the cdr is nil. Note: FLAGS may be nil, not a cons.
2014 ;; FLAGS becomes (t . nil) if a <tr> clause is found in the children
2015 ;; of DOM, and becomes (t . t) if a <td> or a <th> clause is found
2016 ;; and the car is t then. When a <table> clause is found, FLAGS
2017 ;; becomes nil if the cdr is t then. But if FLAGS is (t . nil) then,
2018 ;; it renders the <table>.
2019 (cl-loop for child in (dom-children dom) with recurse with tag
2020 do (setq recurse nil)
2021 if (stringp child)
2022 unless (or (not (car flags)) (cdr flags))
2023 when (string-match "\\(?:[^\t\n\r ]+[\t\n\r ]+\\)*[^\t\n\r ]+"
2024 child)
2025 collect (match-string 0 child)
2026 end end
2027 else if (consp child)
2028 do (setq tag (dom-tag child)) and
2029 unless (memq tag '(comment style))
2030 if (eq tag 'img)
2031 do (shr-indirect-call 'img child)
2032 else if (eq tag 'object)
2033 do (shr-indirect-call 'object child)
2034 else
2035 do (setq recurse t) and
2036 if (eq tag 'tr)
2037 do (setq flags '(t . nil))
2038 else if (memq tag '(td th))
2039 when (car flags)
2040 do (setq flags '(t . t))
2042 else if (eq tag 'table)
2043 if (cdr flags)
2044 do (setq flags nil)
2045 else if (car flags)
2046 do (setq recurse nil)
2047 (shr-indirect-call 'table child)
2048 end end end end end end end end end end
2049 when recurse
2050 append (shr-collect-extra-strings-in-table child flags)))
2052 (defun shr-insert-table (table widths)
2053 (let* ((collapse (equal (cdr (assq 'border-collapse shr-stylesheet))
2054 "collapse"))
2055 (shr-table-separator-length (if collapse 0 1))
2056 (shr-table-vertical-line (if collapse "" shr-table-vertical-line))
2057 (start (point)))
2058 (setq shr-table-id (1+ shr-table-id))
2059 (unless collapse
2060 (shr-insert-table-ruler widths))
2061 (dolist (row table)
2062 (let ((start (point))
2063 (align 0)
2064 (column-number 0)
2065 (height (let ((max 0))
2066 (dolist (column row)
2067 (setq max (max max (nth 2 column))))
2068 max)))
2069 (dotimes (_ (max height 1))
2070 (shr-indent)
2071 (insert shr-table-vertical-line "\n"))
2072 (dolist (column row)
2073 (when (> (nth 2 column) -1)
2074 (goto-char start)
2075 ;; Sum up all the widths from the column. (There may be
2076 ;; more than one if this is a "colspan" column.)
2077 (dotimes (_ (nth 4 column))
2078 ;; The colspan directive may be wrong and there may not be
2079 ;; that number of columns.
2080 (when (<= column-number (1- (length widths)))
2081 (setq align (+ align
2082 (aref widths column-number)
2083 (* 2 shr-table-separator-pixel-width))))
2084 (setq column-number (1+ column-number)))
2085 (let ((lines (nth 3 column))
2086 (pixel-align (if (not shr-use-fonts)
2087 (* align (frame-char-width))
2088 align)))
2089 (dolist (line lines)
2090 (end-of-line)
2091 (let ((start (point))
2092 (background (and (> (length line) 0)
2093 (shr-face-background
2094 (get-text-property
2095 (1- (length line)) 'face line))))
2096 (space (propertize
2098 'display `(space :align-to (,pixel-align))
2099 'shr-table-indent shr-table-id)))
2100 (when background
2101 (setq space (propertize space 'face background)))
2102 (insert line space shr-table-vertical-line)
2103 (shr-colorize-region
2104 start (1- (point)) (nth 5 column) (nth 6 column)))
2105 (forward-line 1))
2106 ;; Add blank lines at padding at the bottom of the TD,
2107 ;; possibly.
2108 (dotimes (_ (- height (length lines)))
2109 (end-of-line)
2110 (let ((start (point)))
2111 (insert (propertize " "
2112 'display `(space :align-to (,pixel-align))
2113 'shr-table-indent shr-table-id)
2114 shr-table-vertical-line)
2115 (shr-colorize-region
2116 start (1- (point)) (nth 5 column) (nth 6 column)))
2117 (forward-line 1))))))
2118 (unless collapse
2119 (shr-insert-table-ruler widths)))
2120 (unless (= start (point))
2121 (put-text-property start (1+ start) 'shr-table-id shr-table-id))))
2123 (defun shr-face-background (face)
2124 (and (consp face)
2125 (or (and (plist-get face :background)
2126 (list :background (plist-get face :background)))
2127 (let ((background nil))
2128 (dolist (elem face)
2129 (when (and (consp elem)
2130 (eq (car elem) :background)
2131 (not background))
2132 (setq background (cadr elem))))
2133 (and background
2134 (list :background background))))))
2136 (defun shr-expand-alignments (start end)
2137 (while (< (setq start (next-single-property-change
2138 start 'shr-table-id nil end))
2139 end)
2140 (goto-char start)
2141 (let* ((shr-use-fonts t)
2142 (id (get-text-property (point) 'shr-table-id))
2143 (base (shr-pixel-column))
2144 elem)
2145 (when id
2146 (save-excursion
2147 (while (setq elem (text-property-any
2148 (point) end 'shr-table-indent id))
2149 (goto-char elem)
2150 (let ((align (get-text-property (point) 'display)))
2151 (put-text-property (point) (1+ (point)) 'display
2152 `(space :align-to (,(+ (car (nth 2 align))
2153 base)))))
2154 (forward-char 1)))))
2155 (setq start (1+ start))))
2157 (defun shr-insert-table-ruler (widths)
2158 (when shr-table-horizontal-line
2159 (when (and (bolp)
2160 (> shr-indentation 0))
2161 (shr-indent))
2162 (insert shr-table-corner)
2163 (let ((total-width 0))
2164 (dotimes (i (length widths))
2165 (setq total-width (+ total-width (aref widths i)
2166 (* shr-table-separator-pixel-width 2)))
2167 (insert (make-string (1+ (/ (aref widths i)
2168 shr-table-separator-pixel-width))
2169 shr-table-horizontal-line)
2170 (propertize " "
2171 'display `(space :align-to (,total-width))
2172 'shr-table-indent shr-table-id)
2173 shr-table-corner)))
2174 (insert "\n")))
2176 (defun shr-table-widths (table natural-table suggested-widths)
2177 (let* ((length (length suggested-widths))
2178 (widths (make-vector length 0))
2179 (natural-widths (make-vector length 0)))
2180 (dolist (row table)
2181 (let ((i 0))
2182 (dolist (column row)
2183 (aset widths i (max (aref widths i) column))
2184 (setq i (1+ i)))))
2185 (dolist (row natural-table)
2186 (let ((i 0))
2187 (dolist (column row)
2188 (aset natural-widths i (max (aref natural-widths i) column))
2189 (setq i (1+ i)))))
2190 (let ((extra (- (apply '+ (append suggested-widths nil))
2191 (apply '+ (append widths nil))
2192 (* shr-table-separator-pixel-width (1+ (length widths)))))
2193 (expanded-columns 0))
2194 ;; We have extra, unused space, so divide this space amongst the
2195 ;; columns.
2196 (when (> extra 0)
2197 ;; If the natural width is wider than the rendered width, we
2198 ;; want to allow the column to expand.
2199 (dotimes (i length)
2200 (when (> (aref natural-widths i) (aref widths i))
2201 (setq expanded-columns (1+ expanded-columns))))
2202 (dotimes (i length)
2203 (when (> (aref natural-widths i) (aref widths i))
2204 (aset widths i (min
2205 (aref natural-widths i)
2206 (+ (/ extra expanded-columns)
2207 (aref widths i))))))))
2208 widths))
2210 (defun shr-make-table (dom widths &optional fill storage-attribute)
2211 (or (cadr (assoc (list dom widths fill) shr-content-cache))
2212 (let ((data (shr-make-table-1 dom widths fill)))
2213 (push (list (list dom widths fill) data)
2214 shr-content-cache)
2215 (when storage-attribute
2216 (dom-set-attribute dom storage-attribute data))
2217 data)))
2219 (defun shr-make-table-1 (dom widths &optional fill)
2220 (let ((trs nil)
2221 (rowspans (make-vector (length widths) 0))
2222 (colspan-remaining 0)
2223 colspan-width colspan-count
2224 width colspan)
2225 (dolist (row (dom-non-text-children dom))
2226 (when (eq (dom-tag row) 'tr)
2227 (let ((tds nil)
2228 (columns (dom-non-text-children row))
2229 (i 0)
2230 (width-column 0)
2231 column)
2232 (while (< i (length widths))
2233 ;; If we previously had a rowspan definition, then that
2234 ;; means that we now have a "missing" td/th element here.
2235 ;; So just insert a dummy, empty one to (sort of) emulate
2236 ;; rowspan.
2237 (setq column
2238 (if (zerop (aref rowspans i))
2239 (pop columns)
2240 (aset rowspans i (1- (aref rowspans i)))
2241 '(td)))
2242 (when (and (not (stringp column))
2243 (or (memq (dom-tag column) '(td th))
2244 (not column)))
2245 (when-let* ((span (dom-attr column 'rowspan)))
2246 (aset rowspans i (+ (aref rowspans i)
2247 (1- (string-to-number span)))))
2248 ;; Sanity check for invalid column-spans.
2249 (when (>= width-column (length widths))
2250 (setq width-column 0))
2251 (setq width
2252 (if column
2253 (aref widths width-column)
2254 (* 10 shr-table-separator-pixel-width)))
2255 (when (setq colspan (dom-attr column 'colspan))
2256 (setq colspan (min (string-to-number colspan)
2257 ;; The colspan may be wrong, so
2258 ;; truncate it to the length of the
2259 ;; remaining columns.
2260 (- (length widths) i)))
2261 (dotimes (j (1- colspan))
2262 (setq width
2263 (if (> (+ i 1 j) (1- (length widths)))
2264 ;; If we have a colspan spec that's longer
2265 ;; than the table is wide, just use the last
2266 ;; width as the width.
2267 (aref widths (1- (length widths)))
2268 ;; Sum up the widths of the columns we're
2269 ;; spanning.
2270 (+ width
2271 shr-table-separator-length
2272 (aref widths (+ i 1 j))))))
2273 (setq width-column (+ width-column (1- colspan))
2274 colspan-count colspan
2275 colspan-remaining colspan))
2276 (when column
2277 (let ((data (shr-render-td column width fill)))
2278 (if (and (not fill)
2279 (> colspan-remaining 0))
2280 (progn
2281 (setq colspan-width (car data))
2282 (let ((this-width (/ colspan-width colspan-count)))
2283 (push (cons this-width (cadr data)) tds)
2284 (setq colspan-remaining (1- colspan-remaining))))
2285 (if (not fill)
2286 (push (cons (car data) (cadr data)) tds)
2287 (push data tds)))))
2288 (when (and colspan
2289 (> colspan 1))
2290 (dotimes (_ (1- colspan))
2291 (setq i (1+ i))
2292 (push
2293 (if fill
2294 (list 0 0 -1 nil 1 nil nil)
2295 '(0 . 0))
2296 tds)))
2297 (setq i (1+ i)
2298 width-column (1+ width-column))))
2299 (push (nreverse tds) trs))))
2300 (nreverse trs)))
2302 (defun shr-pixel-buffer-width ()
2303 (if (not shr-use-fonts)
2304 (save-excursion
2305 (goto-char (point-min))
2306 (let ((max 0))
2307 (while (not (eobp))
2308 (end-of-line)
2309 (setq max (max max (current-column)))
2310 (forward-line 1))
2311 max))
2312 (if (get-buffer-window)
2313 (car (window-text-pixel-size nil (point-min) (point-max)))
2314 (save-window-excursion
2315 ;; Avoid errors if the selected window is a dedicated one,
2316 ;; and they just want to insert a document into it.
2317 (set-window-dedicated-p nil nil)
2318 (set-window-buffer nil (current-buffer))
2319 (car (window-text-pixel-size nil (point-min) (point-max)))))))
2321 (defun shr-render-td (dom width fill)
2322 (let ((cache (intern (format "shr-td-cache-%s-%s" width fill))))
2323 (or (dom-attr dom cache)
2324 (and fill
2325 (let (result)
2326 (dolist (attr (dom-attributes dom))
2327 (let ((name (symbol-name (car attr))))
2328 (when (string-match "shr-td-cache-\\([0-9]+\\)-nil" name)
2329 (let ((cache-width (string-to-number
2330 (match-string 1 name))))
2331 (when (and (>= cache-width width)
2332 (<= (car (cdr attr)) width))
2333 (setq result (cdr attr)))))))
2334 result))
2335 (let* ((pt (point))
2336 (result (shr-render-td-1 dom width fill)))
2337 (dom-set-attribute dom cache result)
2338 (goto-char pt)
2339 result))))
2341 (defun shr-render-td-1 (dom width fill)
2342 (with-temp-buffer
2343 (let ((bgcolor (dom-attr dom 'bgcolor))
2344 (fgcolor (dom-attr dom 'fgcolor))
2345 (style (dom-attr dom 'style))
2346 (shr-stylesheet shr-stylesheet)
2347 (max-width 0)
2348 natural-width)
2349 (when style
2350 (setq style (and (string-match "color" style)
2351 (shr-parse-style style))))
2352 (when bgcolor
2353 (setq style (nconc (list (cons 'background-color bgcolor))
2354 style)))
2355 (when fgcolor
2356 (setq style (nconc (list (cons 'color fgcolor)) style)))
2357 (when style
2358 (setq shr-stylesheet (append style shr-stylesheet)))
2359 (let ((shr-internal-width width)
2360 (shr-indentation 0))
2361 (shr-descend dom))
2362 (save-window-excursion
2363 ;; Avoid errors if the selected window is a dedicated one,
2364 ;; and they just want to insert a document into it.
2365 (set-window-dedicated-p nil nil)
2366 (set-window-buffer nil (current-buffer))
2367 (unless fill
2368 (setq natural-width
2369 (or (dom-attr dom 'shr-td-cache-natural)
2370 (let ((natural (max (shr-pixel-buffer-width)
2371 (shr-dom-max-natural-width dom 0))))
2372 (dom-set-attribute dom 'shr-td-cache-natural natural)
2373 natural))))
2374 (if (and natural-width
2375 (<= natural-width width))
2376 (setq max-width natural-width)
2377 (let ((shr-internal-width width))
2378 (shr-fill-lines (point-min) (point-max))
2379 (setq max-width (shr-pixel-buffer-width)))))
2380 (goto-char (point-max))
2381 ;; Delete padding at the bottom of the TDs.
2382 (delete-region
2383 (point)
2384 (progn
2385 (skip-chars-backward " \t\n")
2386 (end-of-line)
2387 (point)))
2388 (goto-char (point-min))
2389 (list max-width
2390 natural-width
2391 (count-lines (point-min) (point-max))
2392 (split-string (buffer-string) "\n")
2393 (if (dom-attr dom 'colspan)
2394 (string-to-number (dom-attr dom 'colspan))
2396 (cdr (assq 'color shr-stylesheet))
2397 (cdr (assq 'background-color shr-stylesheet))))))
2399 (defun shr-dom-max-natural-width (dom max)
2400 (if (eq (dom-tag dom) 'table)
2401 (max max (or
2402 (cl-loop
2403 for line in (dom-attr dom 'shr-suggested-widths)
2404 maximize (+
2405 shr-table-separator-length
2406 (cl-loop for elem in line
2407 summing
2408 (+ (cdr elem)
2409 (* 2 shr-table-separator-length)))))
2411 (dolist (child (dom-children dom))
2412 (unless (stringp child)
2413 (setq max (max (shr-dom-max-natural-width child max)))))
2414 max))
2416 (defun shr-buffer-width ()
2417 (goto-char (point-min))
2418 (let ((max 0))
2419 (while (not (eobp))
2420 (end-of-line)
2421 (setq max (max max (current-column)))
2422 (forward-line 1))
2423 max))
2425 (defun shr-pro-rate-columns (columns)
2426 (let ((total-percentage 0)
2427 (widths (make-vector (length columns) 0)))
2428 (dotimes (i (length columns))
2429 (setq total-percentage (+ total-percentage (aref columns i))))
2430 (setq total-percentage (/ 1.0 total-percentage))
2431 (dotimes (i (length columns))
2432 (aset widths i (max (truncate (* (aref columns i)
2433 total-percentage
2434 (- shr-internal-width
2435 (* (1+ (length columns))
2436 shr-table-separator-pixel-width))))
2437 10)))
2438 widths))
2440 ;; Return a summary of the number and shape of the TDs in the table.
2441 (defun shr-column-specs (dom)
2442 (let ((columns (make-vector (shr-max-columns dom) 1)))
2443 (dolist (row (dom-non-text-children dom))
2444 (when (eq (dom-tag row) 'tr)
2445 (let ((i 0))
2446 (dolist (column (dom-non-text-children row))
2447 (when (memq (dom-tag column) '(td th))
2448 (let ((width (dom-attr column 'width)))
2449 (when (and width
2450 (string-match "\\([0-9]+\\)%" width)
2451 (not (zerop (setq width (string-to-number
2452 (match-string 1 width))))))
2453 (aset columns i (/ width 100.0))))
2454 (setq i (1+ i)))))))
2455 columns))
2457 (defun shr-count (dom elem)
2458 (let ((i 0))
2459 (dolist (sub (dom-children dom))
2460 (when (and (not (stringp sub))
2461 (eq (dom-tag sub) elem))
2462 (setq i (1+ i))))
2465 (defun shr-max-columns (dom)
2466 (let ((max 0))
2467 (dolist (row (dom-children dom))
2468 (when (and (not (stringp row))
2469 (eq (dom-tag row) 'tr))
2470 (setq max (max max (+ (shr-count row 'td)
2471 (shr-count row 'th))))))
2472 max))
2474 (provide 'shr)
2476 ;;; shr.el ends here