* net/shr.el (shr--extract-best-source): Ignore non-text children.
[emacs.git] / lisp / net / shr.el
bloba2a122cf5d8eee1104940a5f79067a5eb56d433f
1 ;;; shr.el --- Simple HTML Renderer
3 ;; Copyright (C) 2010-2014 Free Software Foundation, Inc.
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: html
8 ;; This file is part of GNU Emacs.
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.
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.
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/>.
23 ;;; Commentary:
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.
31 ;;; Code:
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)
39 (defgroup shr nil
40 "Simple HTML Renderer"
41 :version "25.1"
42 :group 'web)
44 (defcustom shr-max-image-proportion 0.9
45 "How big pictures displayed are in relation to the window they're in.
46 A value of 0.7 means that they are allowed to take up 70% of the
47 width and height of the window. If they are larger than this,
48 and Emacs supports it, then the images will be rescaled down to
49 fit these criteria."
50 :version "24.1"
51 :group 'shr
52 :type 'float)
54 (defcustom shr-blocked-images nil
55 "Images that have URLs matching this regexp will be blocked."
56 :version "24.1"
57 :group 'shr
58 :type '(choice (const nil) regexp))
60 (defcustom shr-table-horizontal-line nil
61 "Character used to draw horizontal table lines.
62 If nil, don't draw horizontal table lines."
63 :group 'shr
64 :type '(choice (const nil) character))
66 (defcustom shr-table-vertical-line ?\s
67 "Character used to draw vertical table lines."
68 :group 'shr
69 :type 'character)
71 (defcustom shr-table-corner ?\s
72 "Character used to draw table corners."
73 :group 'shr
74 :type 'character)
76 (defcustom shr-hr-line ?-
77 "Character used to draw hr lines."
78 :group 'shr
79 :type 'character)
81 (defcustom shr-width fill-column
82 "Frame width to use for rendering.
83 May either be an integer specifying a fixed width in characters,
84 or nil, meaning that the full width of the window should be
85 used."
86 :type '(choice (integer :tag "Fixed width in characters")
87 (const :tag "Use the width of the window" nil))
88 :group 'shr)
90 (defcustom shr-bullet "* "
91 "Bullet used for unordered lists.
92 Alternative suggestions are:
93 - \" \"
94 - \" \""
95 :version "24.4"
96 :type 'string
97 :group 'shr)
99 (defcustom shr-external-browser 'browse-url-default-browser
100 "Function used to launch an external browser."
101 :version "24.4"
102 :group 'shr
103 :type 'function)
105 (defcustom shr-image-animate t
106 "Non nil means that images that can be animated will be."
107 :version "24.4"
108 :group 'shr
109 :type 'boolean)
111 (defvar shr-content-function nil
112 "If bound, this should be a function that will return the content.
113 This is used for cid: URLs, and the function is called with the
114 cid: URL as the argument.")
116 (defvar shr-put-image-function 'shr-put-image
117 "Function called to put image and alt string.")
119 (defface shr-strike-through '((t (:strike-through t)))
120 "Font for <s> elements."
121 :group 'shr)
123 (defface shr-link
124 '((t (:inherit link)))
125 "Font for link elements."
126 :group 'shr)
128 (defvar shr-inhibit-images nil
129 "If non-nil, inhibit loading images.")
131 ;;; Internal variables.
133 (defvar shr-folding-mode nil)
134 (defvar shr-state nil)
135 (defvar shr-start nil)
136 (defvar shr-indentation 0)
137 (defvar shr-internal-width (or shr-width (1- (window-width))))
138 (defvar shr-list-mode nil)
139 (defvar shr-content-cache nil)
140 (defvar shr-kinsoku-shorten nil)
141 (defvar shr-table-depth 0)
142 (defvar shr-stylesheet nil)
143 (defvar shr-base nil)
144 (defvar shr-depth 0)
145 (defvar shr-warning nil)
146 (defvar shr-ignore-cache nil)
147 (defvar shr-external-rendering-functions nil)
148 (defvar shr-target-id nil)
149 (defvar shr-inhibit-decoration nil)
150 (defvar shr-table-separator-length 1)
152 (defvar shr-map
153 (let ((map (make-sparse-keymap)))
154 (define-key map "a" 'shr-show-alt-text)
155 (define-key map "i" 'shr-browse-image)
156 (define-key map "z" 'shr-zoom-image)
157 (define-key map [?\t] 'shr-next-link)
158 (define-key map [?\M-\t] 'shr-previous-link)
159 (define-key map [follow-link] 'mouse-face)
160 (define-key map [mouse-2] 'shr-browse-url)
161 (define-key map "I" 'shr-insert-image)
162 (define-key map "w" 'shr-copy-url)
163 (define-key map "u" 'shr-copy-url)
164 (define-key map "v" 'shr-browse-url)
165 (define-key map "o" 'shr-save-contents)
166 (define-key map "\r" 'shr-browse-url)
167 map))
169 ;; Public functions and commands.
170 (declare-function libxml-parse-html-region "xml.c"
171 (start end &optional base-url))
173 (defun shr-render-buffer (buffer)
174 "Display the HTML rendering of the current buffer."
175 (interactive (list (current-buffer)))
176 (or (fboundp 'libxml-parse-html-region)
177 (error "This function requires Emacs to be compiled with libxml2"))
178 (pop-to-buffer "*html*")
179 (erase-buffer)
180 (shr-insert-document
181 (with-current-buffer buffer
182 (libxml-parse-html-region (point-min) (point-max))))
183 (goto-char (point-min)))
185 ;;;###autoload
186 (defun shr-render-region (begin end &optional buffer)
187 "Display the HTML rendering of the region between BEGIN and END."
188 (interactive "r")
189 (unless (fboundp 'libxml-parse-html-region)
190 (error "This function requires Emacs to be compiled with libxml2"))
191 (with-current-buffer (or buffer (current-buffer))
192 (let ((dom (libxml-parse-html-region begin end)))
193 (delete-region begin end)
194 (goto-char begin)
195 (shr-insert-document dom))))
197 ;;;###autoload
198 (defun shr-insert-document (dom)
199 "Render the parsed document DOM into the current buffer.
200 DOM should be a parse tree as generated by
201 `libxml-parse-html-region' or similar."
202 (setq shr-content-cache nil)
203 (let ((start (point))
204 (shr-state nil)
205 (shr-start nil)
206 (shr-base nil)
207 (shr-depth 0)
208 (shr-warning nil)
209 (shr-internal-width (or shr-width (1- (window-width)))))
210 (shr-descend dom)
211 (shr-remove-trailing-whitespace start (point))
212 (when shr-warning
213 (message "%s" shr-warning))))
215 (defun shr-remove-trailing-whitespace (start end)
216 (let ((width (window-width)))
217 (save-restriction
218 (narrow-to-region start end)
219 (goto-char start)
220 (while (not (eobp))
221 (end-of-line)
222 (when (> (shr-previous-newline-padding-width (current-column)) width)
223 (dolist (overlay (overlays-at (point)))
224 (when (overlay-get overlay 'before-string)
225 (overlay-put overlay 'before-string nil))))
226 (forward-line 1)))))
228 (defun shr-copy-url (&optional image-url)
229 "Copy the URL under point to the kill ring.
230 If IMAGE-URL (the prefix) is non-nil, or there is no link under
231 point, but there is an image under point then copy the URL of the
232 image under point instead.
233 If called twice, then try to fetch the URL and see whether it
234 redirects somewhere else."
235 (interactive "P")
236 (let ((url (or (get-text-property (point) 'shr-url)
237 (get-text-property (point) 'image-url))))
238 (cond
239 ((not url)
240 (message "No URL under point"))
241 ;; Resolve redirected URLs.
242 ((equal url (car kill-ring))
243 (url-retrieve
245 (lambda (a)
246 (when (and (consp a)
247 (eq (car a) :redirect))
248 (with-temp-buffer
249 (insert (cadr a))
250 (goto-char (point-min))
251 ;; Remove common tracking junk from the URL.
252 (when (re-search-forward ".utm_.*" nil t)
253 (replace-match "" t t))
254 (message "Copied %s" (buffer-string))
255 (copy-region-as-kill (point-min) (point-max)))))
256 nil t))
257 ;; Copy the URL to the kill ring.
259 (with-temp-buffer
260 (insert (url-encode-url url))
261 (copy-region-as-kill (point-min) (point-max))
262 (message "Copied %s" (buffer-string)))))))
264 (defun shr-next-link ()
265 "Skip to the next link."
266 (interactive)
267 (let ((skip (text-property-any (point) (point-max) 'help-echo nil)))
268 (if (not (setq skip (text-property-not-all skip (point-max)
269 'help-echo nil)))
270 (message "No next link")
271 (goto-char skip)
272 (message "%s" (get-text-property (point) 'help-echo)))))
274 (defun shr-previous-link ()
275 "Skip to the previous link."
276 (interactive)
277 (let ((start (point))
278 (found nil))
279 ;; Skip past the current link.
280 (while (and (not (bobp))
281 (get-text-property (point) 'help-echo))
282 (forward-char -1))
283 ;; Find the previous link.
284 (while (and (not (bobp))
285 (not (setq found (get-text-property (point) 'help-echo))))
286 (forward-char -1))
287 (if (not found)
288 (progn
289 (message "No previous link")
290 (goto-char start))
291 ;; Put point at the start of the link.
292 (while (and (not (bobp))
293 (get-text-property (point) 'help-echo))
294 (forward-char -1))
295 (forward-char 1)
296 (message "%s" (get-text-property (point) 'help-echo)))))
298 (defun shr-show-alt-text ()
299 "Show the ALT text of the image under point."
300 (interactive)
301 (let ((text (get-text-property (point) 'shr-alt)))
302 (if (not text)
303 (message "No image under point")
304 (message "%s" text))))
306 (defun shr-browse-image (&optional copy-url)
307 "Browse the image under point.
308 If COPY-URL (the prefix if called interactively) is non-nil, copy
309 the URL of the image to the kill buffer instead."
310 (interactive "P")
311 (let ((url (get-text-property (point) 'image-url)))
312 (cond
313 ((not url)
314 (message "No image under point"))
315 (copy-url
316 (with-temp-buffer
317 (insert url)
318 (copy-region-as-kill (point-min) (point-max))
319 (message "Copied %s" url)))
321 (message "Browsing %s..." url)
322 (browse-url url)))))
324 (defun shr-insert-image ()
325 "Insert the image under point into the buffer."
326 (interactive)
327 (let ((url (get-text-property (point) 'image-url)))
328 (if (not url)
329 (message "No image under point")
330 (message "Inserting %s..." url)
331 (url-retrieve url 'shr-image-fetched
332 (list (current-buffer) (1- (point)) (point-marker))
333 t t))))
335 (defun shr-zoom-image ()
336 "Toggle the image size.
337 The size will be rotated between the default size, the original
338 size, and full-buffer size."
339 (interactive)
340 (let ((url (get-text-property (point) 'image-url))
341 (size (get-text-property (point) 'image-size))
342 (buffer-read-only nil))
343 (if (not url)
344 (message "No image under point")
345 ;; Delete the old picture.
346 (while (get-text-property (point) 'image-url)
347 (forward-char -1))
348 (forward-char 1)
349 (let ((start (point)))
350 (while (get-text-property (point) 'image-url)
351 (forward-char 1))
352 (forward-char -1)
353 (put-text-property start (point) 'display nil)
354 (when (> (- (point) start) 2)
355 (delete-region start (1- (point)))))
356 (message "Inserting %s..." url)
357 (url-retrieve url 'shr-image-fetched
358 (list (current-buffer) (1- (point)) (point-marker)
359 (list (cons 'size
360 (cond ((or (eq size 'default)
361 (null size))
362 'original)
363 ((eq size 'original)
364 'full)
365 ((eq size 'full)
366 'default)))))
367 t))))
369 ;;; Utility functions.
371 (defsubst shr-generic (dom)
372 (dolist (sub (dom-children dom))
373 (if (stringp sub)
374 (shr-insert sub)
375 (shr-descend sub))))
377 (defun shr-descend (dom)
378 (let ((function
380 ;; Allow other packages to override (or provide) rendering
381 ;; of elements.
382 (cdr (assq (dom-tag dom) shr-external-rendering-functions))
383 (intern (concat "shr-tag-" (symbol-name (dom-tag dom))) obarray)))
384 (style (dom-attr dom 'style))
385 (shr-stylesheet shr-stylesheet)
386 (shr-depth (1+ shr-depth))
387 (start (point)))
388 ;; shr uses about 12 frames per nested node.
389 (if (> shr-depth (/ max-specpdl-size 12))
390 (setq shr-warning "Too deeply nested to render properly; consider increasing `max-specpdl-size'")
391 (when style
392 (if (string-match "color\\|display\\|border-collapse" style)
393 (setq shr-stylesheet (nconc (shr-parse-style style)
394 shr-stylesheet))
395 (setq style nil)))
396 ;; If we have a display:none, then just ignore this part of the DOM.
397 (unless (equal (cdr (assq 'display shr-stylesheet)) "none")
398 (if (fboundp function)
399 (funcall function dom)
400 (shr-generic dom))
401 (when (and shr-target-id
402 (equal (dom-attr dom 'id) shr-target-id))
403 ;; If the element was empty, we don't have anything to put the
404 ;; anchor on. So just insert a dummy character.
405 (when (= start (point))
406 (insert "*"))
407 (put-text-property start (1+ start) 'shr-target-id shr-target-id))
408 ;; If style is set, then this node has set the color.
409 (when style
410 (shr-colorize-region
411 start (point)
412 (cdr (assq 'color shr-stylesheet))
413 (cdr (assq 'background-color shr-stylesheet))))))))
415 (defmacro shr-char-breakable-p (char)
416 "Return non-nil if a line can be broken before and after CHAR."
417 `(aref fill-find-break-point-function-table ,char))
418 (defmacro shr-char-nospace-p (char)
419 "Return non-nil if no space is required before and after CHAR."
420 `(aref fill-nospace-between-words-table ,char))
422 ;; KINSOKU is a Japanese word meaning a rule that should not be violated.
423 ;; In Emacs, it is a term used for characters, e.g. punctuation marks,
424 ;; parentheses, and so on, that should not be placed in the beginning
425 ;; of a line or the end of a line.
426 (defmacro shr-char-kinsoku-bol-p (char)
427 "Return non-nil if a line ought not to begin with CHAR."
428 `(let ((char ,char))
429 (and (not (eq char ?'))
430 (aref (char-category-set char) ?>))))
431 (defmacro shr-char-kinsoku-eol-p (char)
432 "Return non-nil if a line ought not to end with CHAR."
433 `(aref (char-category-set ,char) ?<))
434 (unless (shr-char-kinsoku-bol-p (make-char 'japanese-jisx0208 33 35))
435 (load "kinsoku" nil t))
437 (defun shr-insert (text)
438 (when (and (eq shr-state 'image)
439 (not (bolp))
440 (not (string-match "\\`[ \t\n]+\\'" text)))
441 (insert "\n")
442 (setq shr-state nil))
443 (cond
444 ((eq shr-folding-mode 'none)
445 (insert text))
447 (when (and (string-match "\\`[ \t\n ]" text)
448 (not (bolp))
449 (not (eq (char-after (1- (point))) ? )))
450 (insert " "))
451 (dolist (elem (split-string text "[ \f\t\n\r\v ]+" t))
452 (when (and (bolp)
453 (> shr-indentation 0))
454 (shr-indent))
455 ;; No space is needed behind a wide character categorized as
456 ;; kinsoku-bol, between characters both categorized as nospace,
457 ;; or at the beginning of a line.
458 (let (prev)
459 (when (and (> (current-column) shr-indentation)
460 (eq (preceding-char) ? )
461 (or (= (line-beginning-position) (1- (point)))
462 (and (shr-char-breakable-p
463 (setq prev (char-after (- (point) 2))))
464 (shr-char-kinsoku-bol-p prev))
465 (and (shr-char-nospace-p prev)
466 (shr-char-nospace-p (aref elem 0)))))
467 (delete-char -1)))
468 ;; The shr-start is a special variable that is used to pass
469 ;; upwards the first point in the buffer where the text really
470 ;; starts.
471 (unless shr-start
472 (setq shr-start (point)))
473 (insert elem)
474 (setq shr-state nil)
475 (let (found)
476 (while (and (> (current-column) shr-internal-width)
477 (> shr-internal-width 0)
478 (progn
479 (setq found (shr-find-fill-point))
480 (not (eolp))))
481 (when (eq (preceding-char) ? )
482 (delete-char -1))
483 (insert "\n")
484 (unless found
485 ;; No space is needed at the beginning of a line.
486 (when (eq (following-char) ? )
487 (delete-char 1)))
488 (when (> shr-indentation 0)
489 (shr-indent))
490 (end-of-line))
491 (if (<= (current-column) shr-internal-width)
492 (insert " ")
493 ;; In case we couldn't get a valid break point (because of a
494 ;; word that's longer than `shr-internal-width'), just break anyway.
495 (insert "\n")
496 (when (> shr-indentation 0)
497 (shr-indent)))))
498 (unless (string-match "[ \t\r\n ]\\'" text)
499 (delete-char -1)))))
501 (defun shr-find-fill-point ()
502 (when (> (move-to-column shr-internal-width) shr-internal-width)
503 (backward-char 1))
504 (let ((bp (point))
505 failed)
506 (while (not (or (setq failed (<= (current-column) shr-indentation))
507 (eq (preceding-char) ? )
508 (eq (following-char) ? )
509 (shr-char-breakable-p (preceding-char))
510 (shr-char-breakable-p (following-char))
511 (and (shr-char-kinsoku-bol-p (preceding-char))
512 (shr-char-breakable-p (following-char))
513 (not (shr-char-kinsoku-bol-p (following-char))))
514 (shr-char-kinsoku-eol-p (following-char))
515 (bolp)))
516 (backward-char 1))
517 (if failed
518 ;; There's no breakable point, so we give it up.
519 (let (found)
520 (goto-char bp)
521 (unless shr-kinsoku-shorten
522 (while (setq found (re-search-forward
523 "\\(\\c>\\)\\| \\|\\c<\\|\\c|"
524 (line-end-position) 'move)))
525 (if (and found
526 (not (match-beginning 1)))
527 (goto-char (match-beginning 0)))))
529 (eolp)
530 ;; Don't put kinsoku-bol characters at the beginning of a line,
531 ;; or kinsoku-eol characters at the end of a line.
532 (cond
533 (shr-kinsoku-shorten
534 (while (and (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
535 (shr-char-kinsoku-eol-p (preceding-char)))
536 (backward-char 1))
537 (when (setq failed (<= (current-column) shr-indentation))
538 ;; There's no breakable point that doesn't violate kinsoku,
539 ;; so we look for the second best position.
540 (while (and (progn
541 (forward-char 1)
542 (<= (current-column) shr-internal-width))
543 (progn
544 (setq bp (point))
545 (shr-char-kinsoku-eol-p (following-char)))))
546 (goto-char bp)))
547 ((shr-char-kinsoku-eol-p (preceding-char))
548 ;; Find backward the point where kinsoku-eol characters begin.
549 (let ((count 4))
550 (while
551 (progn
552 (backward-char 1)
553 (and (> (setq count (1- count)) 0)
554 (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
555 (or (shr-char-kinsoku-eol-p (preceding-char))
556 (shr-char-kinsoku-bol-p (following-char)))))))
557 (when (setq failed (<= (current-column) shr-indentation))
558 ;; There's no breakable point that doesn't violate kinsoku,
559 ;; so we go to the second best position.
560 (if (looking-at "\\(\\c<+\\)\\c<")
561 (goto-char (match-end 1))
562 (forward-char 1))))
563 ((shr-char-kinsoku-bol-p (following-char))
564 ;; Find forward the point where kinsoku-bol characters end.
565 (let ((count 4))
566 (while (progn
567 (forward-char 1)
568 (and (>= (setq count (1- count)) 0)
569 (shr-char-kinsoku-bol-p (following-char))
570 (shr-char-breakable-p (following-char))))))))
571 (when (eq (following-char) ? )
572 (forward-char 1))))
573 (not failed)))
575 (defun shr-parse-base (url)
576 ;; Always chop off anchors.
577 (when (string-match "#.*" url)
578 (setq url (substring url 0 (match-beginning 0))))
579 ;; NB: <base href="" > URI may itself be relative to the document s URI
580 (setq url (shr-expand-url url))
581 (let* ((parsed (url-generic-parse-url url))
582 (local (url-filename parsed)))
583 (setf (url-filename parsed) "")
584 ;; Chop off the bit after the last slash.
585 (when (string-match "\\`\\(.*/\\)[^/]+\\'" local)
586 (setq local (match-string 1 local)))
587 ;; Always make the local bit end with a slash.
588 (when (and (not (zerop (length local)))
589 (not (eq (aref local (1- (length local))) ?/)))
590 (setq local (concat local "/")))
591 (list (url-recreate-url parsed)
592 local
593 (url-type parsed)
594 url)))
596 (autoload 'url-expand-file-name "url-expand")
598 ;; FIXME This needs some tests writing.
599 ;; Does it even need to exist, given that url-expand-file-name does?
600 (defun shr-expand-url (url &optional base)
601 (setq base
602 (if base
603 ;; shr-parse-base should never call this with non-nil base!
604 (shr-parse-base base)
605 ;; Bound by the parser.
606 shr-base))
607 (when (zerop (length url))
608 (setq url nil))
609 (cond ((or (not url)
610 (not base)
611 (string-match "\\`[a-z]*:" url))
612 ;; Absolute or empty URI
613 (or url (nth 3 base)))
614 ((eq (aref url 0) ?/)
615 (if (and (> (length url) 1)
616 (eq (aref url 1) ?/))
617 ;; //host...; just use the protocol
618 (concat (nth 2 base) ":" url)
619 ;; Just use the host name part.
620 (concat (car base) url)))
621 ((eq (aref url 0) ?#)
622 ;; A link to an anchor.
623 (concat (nth 3 base) url))
625 ;; Totally relative.
626 (url-expand-file-name url (concat (car base) (cadr base))))))
628 (defun shr-ensure-newline ()
629 (unless (zerop (current-column))
630 (insert "\n")))
632 (defun shr-ensure-paragraph ()
633 (unless (bobp)
634 (if (<= (current-column) shr-indentation)
635 (unless (save-excursion
636 (forward-line -1)
637 (looking-at " *$"))
638 (insert "\n"))
639 (if (save-excursion
640 (beginning-of-line)
641 ;; If the current line is totally blank, and doesn't even
642 ;; have any face properties set, then delete the blank
643 ;; space.
644 (and (looking-at " *$")
645 (not (get-text-property (point) 'face))
646 (not (= (next-single-property-change (point) 'face nil
647 (line-end-position))
648 (line-end-position)))))
649 (delete-region (match-beginning 0) (match-end 0))
650 (insert "\n\n")))))
652 (defun shr-indent ()
653 (when (> shr-indentation 0)
654 (insert (make-string shr-indentation ? ))))
656 (defun shr-fontize-dom (dom &rest types)
657 (let (shr-start)
658 (shr-generic dom)
659 (dolist (type types)
660 (shr-add-font (or shr-start (point)) (point) type))))
662 ;; Add face to the region, but avoid putting the font properties on
663 ;; blank text at the start of the line, and the newline at the end, to
664 ;; avoid ugliness.
665 (defun shr-add-font (start end type)
666 (unless shr-inhibit-decoration
667 (save-excursion
668 (goto-char start)
669 (while (< (point) end)
670 (when (bolp)
671 (skip-chars-forward " "))
672 (add-face-text-property (point) (min (line-end-position) end) type t)
673 (if (< (line-end-position) end)
674 (forward-line 1)
675 (goto-char end))))))
677 (defun shr-mouse-browse-url (ev)
678 "Browse the URL under the mouse cursor."
679 (interactive "e")
680 (mouse-set-point ev)
681 (shr-browse-url))
683 (defun shr-browse-url (&optional external mouse-event)
684 "Browse the URL under point.
685 If EXTERNAL, browse the URL using `shr-external-browser'."
686 (interactive (list current-prefix-arg last-nonmenu-event))
687 (mouse-set-point mouse-event)
688 (let ((url (get-text-property (point) 'shr-url)))
689 (cond
690 ((not url)
691 (message "No link under point"))
692 ((string-match "^mailto:" url)
693 (browse-url-mail url))
695 (if external
696 (funcall shr-external-browser url)
697 (browse-url url))))))
699 (defun shr-save-contents (directory)
700 "Save the contents from URL in a file."
701 (interactive "DSave contents of URL to directory: ")
702 (let ((url (get-text-property (point) 'shr-url)))
703 (if (not url)
704 (message "No link under point")
705 (url-retrieve (shr-encode-url url)
706 'shr-store-contents (list url directory)
707 nil t))))
709 (defun shr-store-contents (status url directory)
710 (unless (plist-get status :error)
711 (when (or (search-forward "\n\n" nil t)
712 (search-forward "\r\n\r\n" nil t))
713 (write-region (point) (point-max)
714 (expand-file-name (file-name-nondirectory url)
715 directory)))))
717 (defun shr-image-fetched (status buffer start end &optional flags)
718 (let ((image-buffer (current-buffer)))
719 (when (and (buffer-name buffer)
720 (not (plist-get status :error)))
721 (url-store-in-cache image-buffer)
722 (when (or (search-forward "\n\n" nil t)
723 (search-forward "\r\n\r\n" nil t))
724 (let ((data (shr-parse-image-data)))
725 (with-current-buffer buffer
726 (save-excursion
727 (let ((alt (buffer-substring start end))
728 (properties (text-properties-at start))
729 (inhibit-read-only t))
730 (delete-region start end)
731 (goto-char start)
732 (funcall shr-put-image-function data alt flags)
733 (while properties
734 (let ((type (pop properties))
735 (value (pop properties)))
736 (unless (memq type '(display image-size))
737 (put-text-property start (point) type value))))))))))
738 (kill-buffer image-buffer)))
740 (defun shr-image-from-data (data)
741 "Return an image from the data: URI content DATA."
742 (when (string-match
743 "\\(\\([^/;,]+\\(/[^;,]+\\)?\\)\\(;[^;,]+\\)*\\)?,\\(.*\\)"
744 data)
745 (let ((param (match-string 4 data))
746 (payload (url-unhex-string (match-string 5 data))))
747 (when (string-match "^.*\\(;[ \t]*base64\\)$" param)
748 (setq payload (base64-decode-string payload)))
749 payload)))
751 ;; Behind display-graphic-p test.
752 (declare-function image-size "image.c" (spec &optional pixels frame))
753 (declare-function image-animate "image" (image &optional index limit))
755 (defun shr-put-image (spec alt &optional flags)
756 "Insert image SPEC with a string ALT. Return image.
757 SPEC is either an image data blob, or a list where the first
758 element is the data blob and the second element is the content-type."
759 (if (display-graphic-p)
760 (let* ((size (cdr (assq 'size flags)))
761 (data (if (consp spec)
762 (car spec)
763 spec))
764 (content-type (and (consp spec)
765 (cadr spec)))
766 (start (point))
767 (image (cond
768 ((eq size 'original)
769 (create-image data nil t :ascent 100
770 :format content-type))
771 ((eq content-type 'image/svg+xml)
772 (create-image data 'svg t :ascent 100))
773 ((eq size 'full)
774 (ignore-errors
775 (shr-rescale-image data content-type)))
777 (ignore-errors
778 (shr-rescale-image data content-type))))))
779 (when image
780 ;; When inserting big-ish pictures, put them at the
781 ;; beginning of the line.
782 (when (and (> (current-column) 0)
783 (> (car (image-size image t)) 400))
784 (insert "\n"))
785 (if (eq size 'original)
786 (insert-sliced-image image (or alt "*") nil 20 1)
787 (insert-image image (or alt "*")))
788 (put-text-property start (point) 'image-size size)
789 (when (and shr-image-animate
790 (cond ((fboundp 'image-multi-frame-p)
791 ;; Only animate multi-frame things that specify a
792 ;; delay; eg animated gifs as opposed to
793 ;; multi-page tiffs. FIXME?
794 (cdr (image-multi-frame-p image)))
795 ((fboundp 'image-animated-p)
796 (image-animated-p image))))
797 (image-animate image nil 60)))
798 image)
799 (insert alt)))
801 (defun shr-rescale-image (data &optional content-type)
802 "Rescale DATA, if too big, to fit the current buffer."
803 (if (not (and (fboundp 'imagemagick-types)
804 (get-buffer-window (current-buffer))))
805 (create-image data nil t :ascent 100)
806 (let ((edges (window-inside-pixel-edges
807 (get-buffer-window (current-buffer)))))
808 (create-image
809 data 'imagemagick t
810 :ascent 100
811 :max-width (truncate (* shr-max-image-proportion
812 (- (nth 2 edges) (nth 0 edges))))
813 :max-height (truncate (* shr-max-image-proportion
814 (- (nth 3 edges) (nth 1 edges))))
815 :format content-type))))
817 ;; url-cache-extract autoloads url-cache.
818 (declare-function url-cache-create-filename "url-cache" (url))
819 (autoload 'mm-disable-multibyte "mm-util")
820 (autoload 'browse-url-mail "browse-url")
822 (defun shr-get-image-data (url)
823 "Get image data for URL.
824 Return a string with image data."
825 (with-temp-buffer
826 (mm-disable-multibyte)
827 (when (ignore-errors
828 (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
830 (when (or (search-forward "\n\n" nil t)
831 (search-forward "\r\n\r\n" nil t))
832 (shr-parse-image-data)))))
834 (defun shr-parse-image-data ()
835 (let ((data (buffer-substring (point) (point-max)))
836 (content-type
837 (save-excursion
838 (save-restriction
839 (narrow-to-region (point-min) (point))
840 (let ((content-type (mail-fetch-field "content-type")))
841 (and content-type
842 ;; Remove any comments in the type string.
843 (intern (replace-regexp-in-string ";.*" "" content-type)
844 obarray)))))))
845 ;; SVG images may contain references to further images that we may
846 ;; want to block. So special-case these by parsing the XML data
847 ;; and remove the blocked bits.
848 (when (eq content-type 'image/svg+xml)
849 (setq data
850 (shr-dom-to-xml
851 (libxml-parse-xml-region (point) (point-max)))))
852 (list data content-type)))
854 (defun shr-image-displayer (content-function)
855 "Return a function to display an image.
856 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
857 is an argument. The function to be returned takes three arguments URL,
858 START, and END. Note that START and END should be markers."
859 `(lambda (url start end)
860 (when url
861 (if (string-match "\\`cid:" url)
862 ,(when content-function
863 `(let ((image (funcall ,content-function
864 (substring url (match-end 0)))))
865 (when image
866 (goto-char start)
867 (funcall shr-put-image-function
868 image (buffer-substring start end))
869 (delete-region (point) end))))
870 (url-retrieve url 'shr-image-fetched
871 (list (current-buffer) start end)
872 t t)))))
874 (defun shr-heading (dom &rest types)
875 (shr-ensure-paragraph)
876 (apply #'shr-fontize-dom dom types)
877 (shr-ensure-paragraph))
879 (defun shr-urlify (start url &optional title)
880 (shr-add-font start (point) 'shr-link)
881 (add-text-properties
882 start (point)
883 (list 'shr-url url
884 'help-echo (if title (format "%s (%s)" url title) url)
885 'follow-link t
886 'mouse-face 'highlight
887 'keymap shr-map)))
889 (defun shr-encode-url (url)
890 "Encode URL."
891 (browse-url-url-encode-chars url "[)$ ]"))
893 (autoload 'shr-color-visible "shr-color")
894 (autoload 'shr-color->hexadecimal "shr-color")
896 (defun shr-color-check (fg bg)
897 "Check that FG is visible on BG.
898 Returns (fg bg) with corrected values.
899 Returns nil if the colors that would be used are the default
900 ones, in case fg and bg are nil."
901 (when (or fg bg)
902 (let ((fixed (cond ((null fg) 'fg)
903 ((null bg) 'bg))))
904 ;; Convert colors to hexadecimal, or set them to default.
905 (let ((fg (or (shr-color->hexadecimal fg)
906 (frame-parameter nil 'foreground-color)))
907 (bg (or (shr-color->hexadecimal bg)
908 (frame-parameter nil 'background-color))))
909 (cond ((eq fixed 'bg)
910 ;; Only return the new fg
911 (list nil (cadr (shr-color-visible bg fg t))))
912 ((eq fixed 'fg)
913 ;; Invert args and results and return only the new bg
914 (list (cadr (shr-color-visible fg bg t)) nil))
916 (shr-color-visible bg fg)))))))
918 (defun shr-colorize-region (start end fg &optional bg)
919 (when (and (not shr-inhibit-decoration)
920 (or fg bg))
921 (let ((new-colors (shr-color-check fg bg)))
922 (when new-colors
923 (when fg
924 (add-face-text-property start end
925 (list :foreground (cadr new-colors))
927 (when bg
928 (add-face-text-property start end
929 (list :background (car new-colors))
930 t)))
931 new-colors)))
933 (defun shr-expand-newlines (start end color)
934 (save-restriction
935 ;; Skip past all white space at the start and ends.
936 (goto-char start)
937 (skip-chars-forward " \t\n")
938 (beginning-of-line)
939 (setq start (point))
940 (goto-char end)
941 (skip-chars-backward " \t\n")
942 (forward-line 1)
943 (setq end (point))
944 (narrow-to-region start end)
945 (let ((width (shr-buffer-width))
946 column)
947 (goto-char (point-min))
948 (while (not (eobp))
949 (end-of-line)
950 (when (and (< (setq column (current-column)) width)
951 (< (setq column (shr-previous-newline-padding-width column))
952 width))
953 (let ((overlay (make-overlay (point) (1+ (point)))))
954 (overlay-put overlay 'before-string
955 (concat
956 (mapconcat
957 (lambda (overlay)
958 (let ((string (plist-get
959 (overlay-properties overlay)
960 'before-string)))
961 (if (not string)
963 (overlay-put overlay 'before-string "")
964 string)))
965 (overlays-at (point))
967 (propertize (make-string (- width column) ? )
968 'face (list :background color))))))
969 (forward-line 1)))))
971 (defun shr-previous-newline-padding-width (width)
972 (let ((overlays (overlays-at (point)))
973 (previous-width 0))
974 (if (null overlays)
975 width
976 (dolist (overlay overlays)
977 (setq previous-width
978 (+ previous-width
979 (length (plist-get (overlay-properties overlay)
980 'before-string)))))
981 (+ width previous-width))))
983 ;;; Tag-specific rendering rules.
985 (defun shr-tag-body (dom)
986 (let* ((start (point))
987 (fgcolor (or (dom-attr dom 'fgcolor) (dom-attr dom 'text)))
988 (bgcolor (dom-attr dom 'bgcolor))
989 (shr-stylesheet (list (cons 'color fgcolor)
990 (cons 'background-color bgcolor))))
991 (shr-generic dom)
992 (shr-colorize-region start (point) fgcolor bgcolor)))
994 (defun shr-tag-style (_dom)
997 (defun shr-tag-script (_dom)
1000 (defun shr-tag-comment (_dom)
1003 (defun shr-dom-to-xml (dom)
1004 (with-temp-buffer
1005 (shr-dom-print dom)
1006 (buffer-string)))
1008 (defun shr-dom-print (dom)
1009 "Convert DOM into a string containing the xml representation."
1010 (insert (format "<%s" (dom-tag dom)))
1011 (dolist (attr (dom-attributes dom))
1012 ;; Ignore attributes that start with a colon because they are
1013 ;; private elements.
1014 (unless (= (aref (format "%s" (car attr)) 0) ?:)
1015 (insert (format " %s=\"%s\"" (car attr) (cdr attr)))))
1016 (insert ">")
1017 (let (url)
1018 (dolist (elem (dom-children dom))
1019 (cond
1020 ((stringp elem)
1021 (insert elem))
1022 ((or (not (eq (dom-tag elem) 'image))
1023 ;; Filter out blocked elements inside the SVG image.
1024 (not (setq url (dom-attr elem ':xlink:href)))
1025 (not shr-blocked-images)
1026 (not (string-match shr-blocked-images url)))
1027 (insert " ")
1028 (shr-dom-print elem)))))
1029 (insert (format "</%s>" (dom-tag dom))))
1031 (defun shr-tag-svg (dom)
1032 (when (and (image-type-available-p 'svg)
1033 (not shr-inhibit-images))
1034 (funcall shr-put-image-function (shr-dom-to-xml dom) "SVG Image")))
1036 (defun shr-tag-sup (dom)
1037 (let ((start (point)))
1038 (shr-generic dom)
1039 (put-text-property start (point) 'display '(raise 0.5))))
1041 (defun shr-tag-sub (dom)
1042 (let ((start (point)))
1043 (shr-generic dom)
1044 (put-text-property start (point) 'display '(raise -0.5))))
1046 (defun shr-tag-label (dom)
1047 (shr-generic dom)
1048 (shr-ensure-paragraph))
1050 (defun shr-tag-p (dom)
1051 (shr-ensure-paragraph)
1052 (shr-indent)
1053 (shr-generic dom)
1054 (shr-ensure-paragraph))
1056 (defun shr-tag-div (dom)
1057 (shr-ensure-newline)
1058 (shr-indent)
1059 (shr-generic dom)
1060 (shr-ensure-newline))
1062 (defun shr-tag-s (dom)
1063 (shr-fontize-dom dom 'shr-strike-through))
1065 (defun shr-tag-del (dom)
1066 (shr-fontize-dom dom 'shr-strike-through))
1068 (defun shr-tag-b (dom)
1069 (shr-fontize-dom dom 'bold))
1071 (defun shr-tag-i (dom)
1072 (shr-fontize-dom dom 'italic))
1074 (defun shr-tag-em (dom)
1075 (shr-fontize-dom dom 'italic))
1077 (defun shr-tag-strong (dom)
1078 (shr-fontize-dom dom 'bold))
1080 (defun shr-tag-u (dom)
1081 (shr-fontize-dom dom 'underline))
1083 (defun shr-parse-style (style)
1084 (when style
1085 (save-match-data
1086 (when (string-match "\n" style)
1087 (setq style (replace-match " " t t style))))
1088 (let ((plist nil))
1089 (dolist (elem (split-string style ";"))
1090 (when elem
1091 (setq elem (split-string elem ":"))
1092 (when (and (car elem)
1093 (cadr elem))
1094 (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
1095 (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
1096 (when (string-match " *!important\\'" value)
1097 (setq value (substring value 0 (match-beginning 0))))
1098 (push (cons (intern name obarray)
1099 value)
1100 plist)))))
1101 plist)))
1103 (defun shr-tag-base (dom)
1104 (when-let (base (dom-attr dom 'href))
1105 (setq shr-base (shr-parse-base base)))
1106 (shr-generic dom))
1108 (defun shr-tag-a (dom)
1109 (let ((url (dom-attr dom 'href))
1110 (title (dom-attr dom 'title))
1111 (start (point))
1112 shr-start)
1113 (shr-generic dom)
1114 (when (and shr-target-id
1115 (equal (dom-attr dom 'name) shr-target-id))
1116 ;; We have a zero-length <a name="foo"> element, so just
1117 ;; insert... something.
1118 (when (= start (point))
1119 (shr-ensure-newline)
1120 (insert " "))
1121 (put-text-property start (1+ start) 'shr-target-id shr-target-id))
1122 (when (and url
1123 (not shr-inhibit-decoration))
1124 (shr-urlify (or shr-start start) (shr-expand-url url) title))))
1126 (defun shr-tag-object (dom)
1127 (unless shr-inhibit-images
1128 (let ((start (point))
1129 url multimedia image)
1130 (when-let (type (dom-attr dom 'type))
1131 (when (string-match "\\`image/svg" type)
1132 (setq url (dom-attr dom 'data)
1133 image t)))
1134 (dolist (child (dom-children dom))
1135 (cond
1136 ((eq (dom-tag child) 'embed)
1137 (setq url (or url (dom-attr child 'src))
1138 multimedia t))
1139 ((and (eq (dom-tag child) 'param)
1140 (equal (dom-attr child 'name) "movie"))
1141 (setq url (or url (dom-attr child 'value))
1142 multimedia t))))
1143 (when url
1144 (cond
1145 (image
1146 (shr-tag-img dom url)
1147 (setq dom nil))
1148 (multimedia
1149 (shr-insert " [multimedia] ")
1150 (shr-urlify start (shr-expand-url url)))))
1151 (when dom
1152 (shr-generic dom)))))
1154 (defcustom shr-prefer-media-type-alist '(("webm" . 1.0)
1155 ("ogv" . 1.0)
1156 ("ogg" . 1.0)
1157 ("opus" . 1.0)
1158 ("flac" . 0.9)
1159 ("wav" . 0.5))
1160 "Preferences for media types.
1161 The key element should be a regexp matched against the type of the source or
1162 url if no type is specified. The value should be a float in the range 0.0 to
1163 1.0. Media elements with higher value are preferred."
1164 :version "24.4"
1165 :group 'shr
1166 :type '(alist :key-type regexp :value-type float))
1168 (defun shr--get-media-pref (elem)
1169 "Determine the preference for ELEM.
1170 The preference is a float determined from `shr-prefer-media-type'."
1171 (let ((type (dom-attr elem 'type))
1172 (p 0.0))
1173 (unless type
1174 (setq type (dom-attr elem 'src)))
1175 (when type
1176 (dolist (pref shr-prefer-media-type-alist)
1177 (when (and
1178 (> (cdr pref) p)
1179 (string-match-p (car pref) type))
1180 (setq p (cdr pref)))))
1183 (defun shr--extract-best-source (dom &optional url pref)
1184 "Extract the best `:src' property from <source> blocks in DOM."
1185 (setq pref (or pref -1.0))
1186 (let (new-pref)
1187 (dolist (elem (dom-non-text-children dom))
1188 (when (and (eq (dom-tag elem) 'source)
1189 (< pref
1190 (setq new-pref
1191 (shr--get-media-pref elem))))
1192 (setq pref new-pref
1193 url (dom-attr elem 'src))
1194 ;; libxml's html parser isn't HTML5 compliant and non terminated
1195 ;; source tags might end up as children. So recursion it is...
1196 (dolist (child (dom-non-text-children elem))
1197 (when (eq (dom-tag child) 'source)
1198 (let ((ret (shr--extract-best-source (list child) url pref)))
1199 (when (< pref (cdr ret))
1200 (setq url (car ret)
1201 pref (cdr ret)))))))))
1202 (cons url pref))
1204 (defun shr-tag-video (dom)
1205 (let ((image (dom-attr dom 'poster))
1206 (url (dom-attr dom 'src))
1207 (start (point)))
1208 (unless url
1209 (setq url (car (shr--extract-best-source dom))))
1210 (if image
1211 (shr-tag-img nil image)
1212 (shr-insert " [video] "))
1213 (shr-urlify start (shr-expand-url url))))
1215 (defun shr-tag-audio (dom)
1216 (let ((url (dom-attr dom 'src))
1217 (start (point)))
1218 (unless url
1219 (setq url (car (shr--extract-best-source dom))))
1220 (shr-insert " [audio] ")
1221 (shr-urlify start (shr-expand-url url))))
1223 (defun shr-tag-img (dom &optional url)
1224 (when (or url
1225 (and dom
1226 (> (length (dom-attr dom 'src)) 0)))
1227 (when (and (> (current-column) 0)
1228 (not (eq shr-state 'image)))
1229 (insert "\n"))
1230 (let ((alt (dom-attr dom 'alt))
1231 (url (shr-expand-url (or url (dom-attr dom 'src)))))
1232 (let ((start (point-marker)))
1233 (when (zerop (length alt))
1234 (setq alt "*"))
1235 (cond
1236 ((or (member (dom-attr dom 'height) '("0" "1"))
1237 (member (dom-attr dom 'width) '("0" "1")))
1238 ;; Ignore zero-sized or single-pixel images.
1240 ((and (not shr-inhibit-images)
1241 (string-match "\\`data:" url))
1242 (let ((image (shr-image-from-data (substring url (match-end 0)))))
1243 (if image
1244 (funcall shr-put-image-function image alt)
1245 (insert alt))))
1246 ((and (not shr-inhibit-images)
1247 (string-match "\\`cid:" url))
1248 (let ((url (substring url (match-end 0)))
1249 image)
1250 (if (or (not shr-content-function)
1251 (not (setq image (funcall shr-content-function url))))
1252 (insert alt)
1253 (funcall shr-put-image-function image alt))))
1254 ((or shr-inhibit-images
1255 (and shr-blocked-images
1256 (string-match shr-blocked-images url)))
1257 (setq shr-start (point))
1258 (let ((shr-state 'space))
1259 (if (> (string-width alt) 8)
1260 (shr-insert (truncate-string-to-width alt 8))
1261 (shr-insert alt))))
1262 ((and (not shr-ignore-cache)
1263 (url-is-cached (shr-encode-url url)))
1264 (funcall shr-put-image-function (shr-get-image-data url) alt))
1266 (insert alt " ")
1267 (when (and shr-ignore-cache
1268 (url-is-cached (shr-encode-url url)))
1269 (let ((file (url-cache-create-filename (shr-encode-url url))))
1270 (when (file-exists-p file)
1271 (delete-file file))))
1272 (url-queue-retrieve
1273 (shr-encode-url url) 'shr-image-fetched
1274 (list (current-buffer) start (set-marker (make-marker) (1- (point))))
1275 t t)))
1276 (when (zerop shr-table-depth) ;; We are not in a table.
1277 (put-text-property start (point) 'keymap shr-map)
1278 (put-text-property start (point) 'shr-alt alt)
1279 (put-text-property start (point) 'image-url url)
1280 (put-text-property start (point) 'image-displayer
1281 (shr-image-displayer shr-content-function))
1282 (put-text-property start (point) 'help-echo
1283 (or (dom-attr dom 'title) alt)))
1284 (setq shr-state 'image)))))
1286 (defun shr-tag-pre (dom)
1287 (let ((shr-folding-mode 'none))
1288 (shr-ensure-newline)
1289 (shr-indent)
1290 (shr-generic dom)
1291 (shr-ensure-newline)))
1293 (defun shr-tag-blockquote (dom)
1294 (shr-ensure-paragraph)
1295 (shr-indent)
1296 (let ((shr-indentation (+ shr-indentation 4)))
1297 (shr-generic dom))
1298 (shr-ensure-paragraph))
1300 (defun shr-tag-dl (dom)
1301 (shr-ensure-paragraph)
1302 (shr-generic dom)
1303 (shr-ensure-paragraph))
1305 (defun shr-tag-dt (dom)
1306 (shr-ensure-newline)
1307 (shr-generic dom)
1308 (shr-ensure-newline))
1310 (defun shr-tag-dd (dom)
1311 (shr-ensure-newline)
1312 (let ((shr-indentation (+ shr-indentation 4)))
1313 (shr-generic dom)))
1315 (defun shr-tag-ul (dom)
1316 (shr-ensure-paragraph)
1317 (let ((shr-list-mode 'ul))
1318 (shr-generic dom))
1319 (shr-ensure-paragraph))
1321 (defun shr-tag-ol (dom)
1322 (shr-ensure-paragraph)
1323 (let ((shr-list-mode 1))
1324 (shr-generic dom))
1325 (shr-ensure-paragraph))
1327 (defun shr-tag-li (dom)
1328 (shr-ensure-newline)
1329 (shr-indent)
1330 (let* ((bullet
1331 (if (numberp shr-list-mode)
1332 (prog1
1333 (format "%d " shr-list-mode)
1334 (setq shr-list-mode (1+ shr-list-mode)))
1335 shr-bullet))
1336 (shr-indentation (+ shr-indentation (length bullet))))
1337 (insert bullet)
1338 (shr-generic dom)))
1340 (defun shr-tag-br (dom)
1341 (when (and (not (bobp))
1342 ;; Only add a newline if we break the current line, or
1343 ;; the previous line isn't a blank line.
1344 (or (not (bolp))
1345 (and (> (- (point) 2) (point-min))
1346 (not (= (char-after (- (point) 2)) ?\n)))))
1347 (insert "\n")
1348 (shr-indent))
1349 (shr-generic dom))
1351 (defun shr-tag-span (dom)
1352 (shr-generic dom))
1354 (defun shr-tag-h1 (dom)
1355 (shr-heading dom 'bold 'underline))
1357 (defun shr-tag-h2 (dom)
1358 (shr-heading dom 'bold))
1360 (defun shr-tag-h3 (dom)
1361 (shr-heading dom 'italic))
1363 (defun shr-tag-h4 (dom)
1364 (shr-heading dom))
1366 (defun shr-tag-h5 (dom)
1367 (shr-heading dom))
1369 (defun shr-tag-h6 (dom)
1370 (shr-heading dom))
1372 (defun shr-tag-hr (_dom)
1373 (shr-ensure-newline)
1374 (insert (make-string shr-internal-width shr-hr-line) "\n"))
1376 (defun shr-tag-title (dom)
1377 (shr-heading dom 'bold 'underline))
1379 (defun shr-tag-font (dom)
1380 (let* ((start (point))
1381 (color (dom-attr dom 'color))
1382 (shr-stylesheet (nconc (list (cons 'color color))
1383 shr-stylesheet)))
1384 (shr-generic dom)
1385 (when color
1386 (shr-colorize-region start (point) color
1387 (cdr (assq 'background-color shr-stylesheet))))))
1389 ;;; Table rendering algorithm.
1391 ;; Table rendering is the only complicated thing here. We do this by
1392 ;; first counting how many TDs there are in each TR, and registering
1393 ;; how wide they think they should be ("width=45%", etc). Then we
1394 ;; render each TD separately (this is done in temporary buffers, so
1395 ;; that we can use all the rendering machinery as if we were in the
1396 ;; main buffer). Now we know how much space each TD really takes, so
1397 ;; we then render everything again with the new widths, and finally
1398 ;; insert all these boxes into the main buffer.
1399 (defun shr-tag-table-1 (dom)
1400 (setq dom (or (dom-child-by-tag dom 'tbody) dom))
1401 (let* ((shr-inhibit-images t)
1402 (shr-table-depth (1+ shr-table-depth))
1403 (shr-kinsoku-shorten t)
1404 ;; Find all suggested widths.
1405 (columns (shr-column-specs dom))
1406 ;; Compute how many characters wide each TD should be.
1407 (suggested-widths (shr-pro-rate-columns columns))
1408 ;; Do a "test rendering" to see how big each TD is (this can
1409 ;; be smaller (if there's little text) or bigger (if there's
1410 ;; unbreakable text).
1411 (sketch (shr-make-table dom suggested-widths))
1412 ;; Compute the "natural" width by setting each column to 500
1413 ;; characters and see how wide they really render.
1414 (natural (shr-make-table dom (make-vector (length columns) 500)))
1415 (sketch-widths (shr-table-widths sketch natural suggested-widths)))
1416 ;; This probably won't work very well.
1417 (when (> (+ (loop for width across sketch-widths
1418 summing (1+ width))
1419 shr-indentation 1)
1420 (frame-width))
1421 (setq truncate-lines t))
1422 ;; Then render the table again with these new "hard" widths.
1423 (shr-insert-table (shr-make-table dom sketch-widths t) sketch-widths)))
1425 (defun shr-tag-table (dom)
1426 (shr-ensure-paragraph)
1427 (let* ((caption (dom-child-by-tag dom 'caption))
1428 (header (dom-child-by-tag dom 'thead))
1429 (body (or (dom-child-by-tag dom 'tbody) dom))
1430 (footer (dom-child-by-tag dom 'tfoot))
1431 (bgcolor (dom-attr dom 'bgcolor))
1432 (start (point))
1433 (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
1434 shr-stylesheet))
1435 (nheader (if header (shr-max-columns header)))
1436 (nbody (if body (shr-max-columns body)))
1437 (nfooter (if footer (shr-max-columns footer))))
1438 (if (and (not caption)
1439 (not header)
1440 (not (dom-child-by-tag dom 'tbody))
1441 (not (dom-child-by-tag dom 'tr))
1442 (not footer))
1443 ;; The table is totally invalid and just contains random junk.
1444 ;; Try to output it anyway.
1445 (shr-generic dom)
1446 ;; It's a real table, so render it.
1447 (shr-tag-table-1
1448 (nconc
1449 (if caption `((tr (td ,@caption))))
1450 (if header
1451 (if footer
1452 ;; header + body + footer
1453 (if (= nheader nbody)
1454 (if (= nbody nfooter)
1455 `((tr (td (table (tbody ,@header ,@body ,@footer)))))
1456 (nconc `((tr (td (table (tbody ,@header ,@body)))))
1457 (if (= nfooter 1)
1458 footer
1459 `((tr (td (table (tbody ,@footer))))))))
1460 (nconc `((tr (td (table (tbody ,@header)))))
1461 (if (= nbody nfooter)
1462 `((tr (td (table (tbody ,@body ,@footer)))))
1463 (nconc `((tr (td (table (tbody ,@body)))))
1464 (if (= nfooter 1)
1465 footer
1466 `((tr (td (table (tbody ,@footer))))))))))
1467 ;; header + body
1468 (if (= nheader nbody)
1469 `((tr (td (table (tbody ,@header ,@body)))))
1470 (if (= nheader 1)
1471 `(,@header (tr (td (table (tbody ,@body)))))
1472 `((tr (td (table (tbody ,@header))))
1473 (tr (td (table (tbody ,@body))))))))
1474 (if footer
1475 ;; body + footer
1476 (if (= nbody nfooter)
1477 `((tr (td (table (tbody ,@body ,@footer)))))
1478 (nconc `((tr (td (table (tbody ,@body)))))
1479 (if (= nfooter 1)
1480 footer
1481 `((tr (td (table (tbody ,@footer))))))))
1482 (if caption
1483 `((tr (td (table (tbody ,@body)))))
1484 body))))))
1485 (when bgcolor
1486 (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
1487 bgcolor))
1488 ;; Finally, insert all the images after the table. The Emacs buffer
1489 ;; model isn't strong enough to allow us to put the images actually
1490 ;; into the tables.
1491 (when (zerop shr-table-depth)
1492 (dolist (elem (dom-by-tag dom 'object))
1493 (shr-tag-object elem))
1494 (dolist (elem (dom-by-tag dom 'img))
1495 (shr-tag-img elem)))))
1497 (defun shr-insert-table (table widths)
1498 (let* ((collapse (equal (cdr (assq 'border-collapse shr-stylesheet))
1499 "collapse"))
1500 (shr-table-separator-length (if collapse 0 1))
1501 (shr-table-vertical-line (if collapse "" shr-table-vertical-line)))
1502 (unless collapse
1503 (shr-insert-table-ruler widths))
1504 (dolist (row table)
1505 (let ((start (point))
1506 (height (let ((max 0))
1507 (dolist (column row)
1508 (setq max (max max (cadr column))))
1509 max)))
1510 (dotimes (i height)
1511 (shr-indent)
1512 (insert shr-table-vertical-line "\n"))
1513 (dolist (column row)
1514 (goto-char start)
1515 (let ((lines (nth 2 column)))
1516 (dolist (line lines)
1517 (end-of-line)
1518 (insert line shr-table-vertical-line)
1519 (forward-line 1))
1520 ;; Add blank lines at padding at the bottom of the TD,
1521 ;; possibly.
1522 (dotimes (i (- height (length lines)))
1523 (end-of-line)
1524 (let ((start (point)))
1525 (insert (make-string (string-width (car lines)) ? )
1526 shr-table-vertical-line)
1527 (when (nth 4 column)
1528 (shr-add-font start (1- (point))
1529 (list :background (nth 4 column)))))
1530 (forward-line 1)))))
1531 (unless collapse
1532 (shr-insert-table-ruler widths)))))
1534 (defun shr-insert-table-ruler (widths)
1535 (when shr-table-horizontal-line
1536 (when (and (bolp)
1537 (> shr-indentation 0))
1538 (shr-indent))
1539 (insert shr-table-corner)
1540 (dotimes (i (length widths))
1541 (insert (make-string (aref widths i) shr-table-horizontal-line)
1542 shr-table-corner))
1543 (insert "\n")))
1545 (defun shr-table-widths (table natural-table suggested-widths)
1546 (let* ((length (length suggested-widths))
1547 (widths (make-vector length 0))
1548 (natural-widths (make-vector length 0)))
1549 (dolist (row table)
1550 (let ((i 0))
1551 (dolist (column row)
1552 (aset widths i (max (aref widths i) column))
1553 (setq i (1+ i)))))
1554 (dolist (row natural-table)
1555 (let ((i 0))
1556 (dolist (column row)
1557 (aset natural-widths i (max (aref natural-widths i) column))
1558 (setq i (1+ i)))))
1559 (let ((extra (- (apply '+ (append suggested-widths nil))
1560 (apply '+ (append widths nil))))
1561 (expanded-columns 0))
1562 ;; We have extra, unused space, so divide this space amongst the
1563 ;; columns.
1564 (when (> extra 0)
1565 ;; If the natural width is wider than the rendered width, we
1566 ;; want to allow the column to expand.
1567 (dotimes (i length)
1568 (when (> (aref natural-widths i) (aref widths i))
1569 (setq expanded-columns (1+ expanded-columns))))
1570 (dotimes (i length)
1571 (when (> (aref natural-widths i) (aref widths i))
1572 (aset widths i (min
1573 (aref natural-widths i)
1574 (+ (/ extra expanded-columns)
1575 (aref widths i))))))))
1576 widths))
1578 (defun shr-make-table (dom widths &optional fill)
1579 (or (cadr (assoc (list dom widths fill) shr-content-cache))
1580 (let ((data (shr-make-table-1 dom widths fill)))
1581 (push (list (list dom widths fill) data)
1582 shr-content-cache)
1583 data)))
1585 (defun shr-make-table-1 (dom widths &optional fill)
1586 (let ((trs nil)
1587 (shr-inhibit-decoration (not fill))
1588 (rowspans (make-vector (length widths) 0))
1589 width colspan)
1590 (dolist (row (dom-non-text-children dom))
1591 (when (eq (dom-tag row) 'tr)
1592 (let ((tds nil)
1593 (columns (dom-children row))
1594 (i 0)
1595 (width-column 0)
1596 column)
1597 (while (< i (length widths))
1598 ;; If we previously had a rowspan definition, then that
1599 ;; means that we now have a "missing" td/th element here.
1600 ;; So just insert a dummy, empty one to (sort of) emulate
1601 ;; rowspan.
1602 (setq column
1603 (if (zerop (aref rowspans i))
1604 (pop columns)
1605 (aset rowspans i (1- (aref rowspans i)))
1606 '(td)))
1607 (when (and (not (stringp column))
1608 (or (memq (dom-tag column) '(td th))
1609 (not column)))
1610 (when-let (span (dom-attr column 'rowspan))
1611 (aset rowspans i (+ (aref rowspans i)
1612 (1- (string-to-number span)))))
1613 ;; Sanity check for invalid column-spans.
1614 (when (>= width-column (length widths))
1615 (setq width-column 0))
1616 (setq width
1617 (if column
1618 (aref widths width-column)
1619 10))
1620 (when (and fill
1621 (setq colspan (dom-attr column colspan)))
1622 (setq colspan (min (string-to-number colspan)
1623 ;; The colspan may be wrong, so
1624 ;; truncate it to the length of the
1625 ;; remaining columns.
1626 (- (length widths) i)))
1627 (dotimes (j (1- colspan))
1628 (if (> (+ i 1 j) (1- (length widths)))
1629 (setq width (aref widths (1- (length widths))))
1630 (setq width (+ width
1631 shr-table-separator-length
1632 (aref widths (+ i 1 j))))))
1633 (setq width-column (+ width-column (1- colspan))))
1634 (when (or column
1635 (not fill))
1636 (push (shr-render-td column width fill)
1637 tds))
1638 (setq i (1+ i)
1639 width-column (1+ width-column))))
1640 (push (nreverse tds) trs))))
1641 (nreverse trs)))
1643 (defun shr-render-td (dom width fill)
1644 (with-temp-buffer
1645 (let ((bgcolor (dom-attr dom 'bgcolor))
1646 (fgcolor (dom-attr dom 'fgcolor))
1647 (style (dom-attr dom 'style))
1648 (shr-stylesheet shr-stylesheet)
1649 actual-colors)
1650 (when style
1651 (setq style (and (string-match "color" style)
1652 (shr-parse-style style))))
1653 (when bgcolor
1654 (setq style (nconc (list (cons 'background-color bgcolor)) style)))
1655 (when fgcolor
1656 (setq style (nconc (list (cons 'color fgcolor)) style)))
1657 (when style
1658 (setq shr-stylesheet (append style shr-stylesheet)))
1659 (let ((shr-internal-width width)
1660 (shr-indentation 0))
1661 (shr-descend dom))
1662 ;; Delete padding at the bottom of the TDs.
1663 (delete-region
1664 (point)
1665 (progn
1666 (skip-chars-backward " \t\n")
1667 (end-of-line)
1668 (point)))
1669 (goto-char (point-min))
1670 (let ((max 0))
1671 (while (not (eobp))
1672 (end-of-line)
1673 (setq max (max max (current-column)))
1674 (forward-line 1))
1675 (when fill
1676 (goto-char (point-min))
1677 ;; If the buffer is totally empty, then put a single blank
1678 ;; line here.
1679 (if (zerop (buffer-size))
1680 (insert (make-string width ? ))
1681 ;; Otherwise, fill the buffer.
1682 (let ((align (dom-attr dom 'align))
1683 length)
1684 (while (not (eobp))
1685 (end-of-line)
1686 (setq length (- width (current-column)))
1687 (when (> length 0)
1688 (cond
1689 ((equal align "right")
1690 (beginning-of-line)
1691 (insert (make-string length ? )))
1692 ((equal align "center")
1693 (insert (make-string (/ length 2) ? ))
1694 (beginning-of-line)
1695 (insert (make-string (- length (/ length 2)) ? )))
1697 (insert (make-string length ? )))))
1698 (forward-line 1))))
1699 (when style
1700 (setq actual-colors
1701 (shr-colorize-region
1702 (point-min) (point-max)
1703 (cdr (assq 'color shr-stylesheet))
1704 (cdr (assq 'background-color shr-stylesheet))))))
1705 (if fill
1706 (list max
1707 (count-lines (point-min) (point-max))
1708 (split-string (buffer-string) "\n")
1710 (car actual-colors))
1711 max)))))
1713 (defun shr-buffer-width ()
1714 (goto-char (point-min))
1715 (let ((max 0))
1716 (while (not (eobp))
1717 (end-of-line)
1718 (setq max (max max (current-column)))
1719 (forward-line 1))
1720 max))
1722 (defun shr-pro-rate-columns (columns)
1723 (let ((total-percentage 0)
1724 (widths (make-vector (length columns) 0)))
1725 (dotimes (i (length columns))
1726 (setq total-percentage (+ total-percentage (aref columns i))))
1727 (setq total-percentage (/ 1.0 total-percentage))
1728 (dotimes (i (length columns))
1729 (aset widths i (max (truncate (* (aref columns i)
1730 total-percentage
1731 (- shr-internal-width
1732 (1+ (length columns)))))
1733 10)))
1734 widths))
1736 ;; Return a summary of the number and shape of the TDs in the table.
1737 (defun shr-column-specs (dom)
1738 (let ((columns (make-vector (shr-max-columns dom) 1)))
1739 (dolist (row (dom-non-text-children dom))
1740 (when (eq (dom-tag row) 'tr)
1741 (let ((i 0))
1742 (dolist (column (dom-children row))
1743 (when (and (not (stringp column))
1744 (memq (dom-tag column) '(td th)))
1745 (let ((width (dom-attr column 'width)))
1746 (when (and width
1747 (string-match "\\([0-9]+\\)%" width)
1748 (not (zerop (setq width (string-to-number
1749 (match-string 1 width))))))
1750 (aset columns i (/ width 100.0))))
1751 (setq i (1+ i)))))))
1752 columns))
1754 (defun shr-count (dom elem)
1755 (let ((i 0))
1756 (dolist (sub (dom-children dom))
1757 (when (and (not (stringp sub))
1758 (eq (dom-tag sub) elem))
1759 (setq i (1+ i))))
1762 (defun shr-max-columns (dom)
1763 (let ((max 0))
1764 (dolist (row (dom-children dom))
1765 (when (and (not (stringp row))
1766 (eq (dom-tag row) 'tr))
1767 (setq max (max max (+ (shr-count row 'td)
1768 (shr-count row 'th))))))
1769 max))
1771 (provide 'shr)
1773 ;; Local Variables:
1774 ;; coding: utf-8
1775 ;; End:
1777 ;;; shr.el ends here