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