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