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