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