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