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