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