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