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