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