Make inline SVGs work in shr again
[emacs.git] / lisp / net / shr.el
blob186c9f5757d7fd0ac3d29fc2489115462e43dee3
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 (define-inline shr-char-breakable-p (char)
416 "Return non-nil if a line can be broken before and after CHAR."
417 (inline-quote (aref fill-find-break-point-function-table ,char)))
418 (define-inline shr-char-nospace-p (char)
419 "Return non-nil if no space is required before and after CHAR."
420 (inline-quote (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 (define-inline shr-char-kinsoku-bol-p (char)
427 "Return non-nil if a line ought not to begin with CHAR."
428 (inline-letevals (char)
429 (inline-quote (and (not (eq ,char ?'))
430 (aref (char-category-set ,char) ?>)))))
431 (define-inline shr-char-kinsoku-eol-p (char)
432 "Return non-nil if a line ought not to end with CHAR."
433 (inline-quote (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 ((eq (dom-tag elem) 'comment)
1024 ((or (not (eq (dom-tag elem) 'image))
1025 ;; Filter out blocked elements inside the SVG image.
1026 (not (setq url (dom-attr elem ':xlink:href)))
1027 (not shr-blocked-images)
1028 (not (string-match shr-blocked-images url)))
1029 (insert " ")
1030 (shr-dom-print elem)))))
1031 (insert (format "</%s>" (dom-tag dom))))
1033 (defun shr-tag-svg (dom)
1034 (when (and (image-type-available-p 'svg)
1035 (not shr-inhibit-images))
1036 (funcall shr-put-image-function (list (shr-dom-to-xml dom) 'image/svg+xml)
1037 "SVG Image")))
1039 (defun shr-tag-sup (dom)
1040 (let ((start (point)))
1041 (shr-generic dom)
1042 (put-text-property start (point) 'display '(raise 0.5))))
1044 (defun shr-tag-sub (dom)
1045 (let ((start (point)))
1046 (shr-generic dom)
1047 (put-text-property start (point) 'display '(raise -0.5))))
1049 (defun shr-tag-label (dom)
1050 (shr-generic dom)
1051 (shr-ensure-paragraph))
1053 (defun shr-tag-p (dom)
1054 (shr-ensure-paragraph)
1055 (shr-indent)
1056 (shr-generic dom)
1057 (shr-ensure-paragraph))
1059 (defun shr-tag-div (dom)
1060 (shr-ensure-newline)
1061 (shr-indent)
1062 (shr-generic dom)
1063 (shr-ensure-newline))
1065 (defun shr-tag-s (dom)
1066 (shr-fontize-dom dom 'shr-strike-through))
1068 (defun shr-tag-del (dom)
1069 (shr-fontize-dom dom 'shr-strike-through))
1071 (defun shr-tag-b (dom)
1072 (shr-fontize-dom dom 'bold))
1074 (defun shr-tag-i (dom)
1075 (shr-fontize-dom dom 'italic))
1077 (defun shr-tag-em (dom)
1078 (shr-fontize-dom dom 'italic))
1080 (defun shr-tag-strong (dom)
1081 (shr-fontize-dom dom 'bold))
1083 (defun shr-tag-u (dom)
1084 (shr-fontize-dom dom 'underline))
1086 (defun shr-parse-style (style)
1087 (when style
1088 (save-match-data
1089 (when (string-match "\n" style)
1090 (setq style (replace-match " " t t style))))
1091 (let ((plist nil))
1092 (dolist (elem (split-string style ";"))
1093 (when elem
1094 (setq elem (split-string elem ":"))
1095 (when (and (car elem)
1096 (cadr elem))
1097 (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
1098 (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
1099 (when (string-match " *!important\\'" value)
1100 (setq value (substring value 0 (match-beginning 0))))
1101 (push (cons (intern name obarray)
1102 value)
1103 plist)))))
1104 plist)))
1106 (defun shr-tag-base (dom)
1107 (when-let (base (dom-attr dom 'href))
1108 (setq shr-base (shr-parse-base base)))
1109 (shr-generic dom))
1111 (defun shr-tag-a (dom)
1112 (let ((url (dom-attr dom 'href))
1113 (title (dom-attr dom 'title))
1114 (start (point))
1115 shr-start)
1116 (shr-generic dom)
1117 (when (and shr-target-id
1118 (equal (dom-attr dom 'name) shr-target-id))
1119 ;; We have a zero-length <a name="foo"> element, so just
1120 ;; insert... something.
1121 (when (= start (point))
1122 (shr-ensure-newline)
1123 (insert " "))
1124 (put-text-property start (1+ start) 'shr-target-id shr-target-id))
1125 (when (and url
1126 (not shr-inhibit-decoration))
1127 (shr-urlify (or shr-start start) (shr-expand-url url) title))))
1129 (defun shr-tag-object (dom)
1130 (unless shr-inhibit-images
1131 (let ((start (point))
1132 url multimedia image)
1133 (when-let (type (dom-attr dom 'type))
1134 (when (string-match "\\`image/svg" type)
1135 (setq url (dom-attr dom 'data)
1136 image t)))
1137 (dolist (child (dom-children dom))
1138 (cond
1139 ((eq (dom-tag child) 'embed)
1140 (setq url (or url (dom-attr child 'src))
1141 multimedia t))
1142 ((and (eq (dom-tag child) 'param)
1143 (equal (dom-attr child 'name) "movie"))
1144 (setq url (or url (dom-attr child 'value))
1145 multimedia t))))
1146 (when url
1147 (cond
1148 (image
1149 (shr-tag-img dom url)
1150 (setq dom nil))
1151 (multimedia
1152 (shr-insert " [multimedia] ")
1153 (shr-urlify start (shr-expand-url url)))))
1154 (when dom
1155 (shr-generic dom)))))
1157 (defcustom shr-prefer-media-type-alist '(("webm" . 1.0)
1158 ("ogv" . 1.0)
1159 ("ogg" . 1.0)
1160 ("opus" . 1.0)
1161 ("flac" . 0.9)
1162 ("wav" . 0.5))
1163 "Preferences for media types.
1164 The key element should be a regexp matched against the type of the source or
1165 url if no type is specified. The value should be a float in the range 0.0 to
1166 1.0. Media elements with higher value are preferred."
1167 :version "24.4"
1168 :group 'shr
1169 :type '(alist :key-type regexp :value-type float))
1171 (defun shr--get-media-pref (elem)
1172 "Determine the preference for ELEM.
1173 The preference is a float determined from `shr-prefer-media-type'."
1174 (let ((type (dom-attr elem 'type))
1175 (p 0.0))
1176 (unless type
1177 (setq type (dom-attr elem 'src)))
1178 (when type
1179 (dolist (pref shr-prefer-media-type-alist)
1180 (when (and
1181 (> (cdr pref) p)
1182 (string-match-p (car pref) type))
1183 (setq p (cdr pref)))))
1186 (defun shr--extract-best-source (dom &optional url pref)
1187 "Extract the best `:src' property from <source> blocks in DOM."
1188 (setq pref (or pref -1.0))
1189 (let (new-pref)
1190 (dolist (elem (dom-non-text-children dom))
1191 (when (and (eq (dom-tag elem) 'source)
1192 (< pref
1193 (setq new-pref
1194 (shr--get-media-pref elem))))
1195 (setq pref new-pref
1196 url (dom-attr elem 'src))
1197 ;; libxml's html parser isn't HTML5 compliant and non terminated
1198 ;; source tags might end up as children. So recursion it is...
1199 (dolist (child (dom-non-text-children elem))
1200 (when (eq (dom-tag child) 'source)
1201 (let ((ret (shr--extract-best-source (list child) url pref)))
1202 (when (< pref (cdr ret))
1203 (setq url (car ret)
1204 pref (cdr ret)))))))))
1205 (cons url pref))
1207 (defun shr-tag-video (dom)
1208 (let ((image (dom-attr dom 'poster))
1209 (url (dom-attr dom 'src))
1210 (start (point)))
1211 (unless url
1212 (setq url (car (shr--extract-best-source dom))))
1213 (if image
1214 (shr-tag-img nil image)
1215 (shr-insert " [video] "))
1216 (shr-urlify start (shr-expand-url url))))
1218 (defun shr-tag-audio (dom)
1219 (let ((url (dom-attr dom 'src))
1220 (start (point)))
1221 (unless url
1222 (setq url (car (shr--extract-best-source dom))))
1223 (shr-insert " [audio] ")
1224 (shr-urlify start (shr-expand-url url))))
1226 (defun shr-tag-img (dom &optional url)
1227 (when (or url
1228 (and dom
1229 (> (length (dom-attr dom 'src)) 0)))
1230 (when (and (> (current-column) 0)
1231 (not (eq shr-state 'image)))
1232 (insert "\n"))
1233 (let ((alt (dom-attr dom 'alt))
1234 (url (shr-expand-url (or url (dom-attr dom 'src)))))
1235 (let ((start (point-marker)))
1236 (when (zerop (length alt))
1237 (setq alt "*"))
1238 (cond
1239 ((or (member (dom-attr dom 'height) '("0" "1"))
1240 (member (dom-attr dom 'width) '("0" "1")))
1241 ;; Ignore zero-sized or single-pixel images.
1243 ((and (not shr-inhibit-images)
1244 (string-match "\\`data:" url))
1245 (let ((image (shr-image-from-data (substring url (match-end 0)))))
1246 (if image
1247 (funcall shr-put-image-function image alt)
1248 (insert alt))))
1249 ((and (not shr-inhibit-images)
1250 (string-match "\\`cid:" url))
1251 (let ((url (substring url (match-end 0)))
1252 image)
1253 (if (or (not shr-content-function)
1254 (not (setq image (funcall shr-content-function url))))
1255 (insert alt)
1256 (funcall shr-put-image-function image alt))))
1257 ((or shr-inhibit-images
1258 (and shr-blocked-images
1259 (string-match shr-blocked-images url)))
1260 (setq shr-start (point))
1261 (let ((shr-state 'space))
1262 (if (> (string-width alt) 8)
1263 (shr-insert (truncate-string-to-width alt 8))
1264 (shr-insert alt))))
1265 ((and (not shr-ignore-cache)
1266 (url-is-cached (shr-encode-url url)))
1267 (funcall shr-put-image-function (shr-get-image-data url) alt))
1269 (insert alt " ")
1270 (when (and shr-ignore-cache
1271 (url-is-cached (shr-encode-url url)))
1272 (let ((file (url-cache-create-filename (shr-encode-url url))))
1273 (when (file-exists-p file)
1274 (delete-file file))))
1275 (url-queue-retrieve
1276 (shr-encode-url url) 'shr-image-fetched
1277 (list (current-buffer) start (set-marker (make-marker) (1- (point))))
1278 t t)))
1279 (when (zerop shr-table-depth) ;; We are not in a table.
1280 (put-text-property start (point) 'keymap shr-map)
1281 (put-text-property start (point) 'shr-alt alt)
1282 (put-text-property start (point) 'image-url url)
1283 (put-text-property start (point) 'image-displayer
1284 (shr-image-displayer shr-content-function))
1285 (put-text-property start (point) 'help-echo
1286 (or (dom-attr dom 'title) alt)))
1287 (setq shr-state 'image)))))
1289 (defun shr-tag-pre (dom)
1290 (let ((shr-folding-mode 'none))
1291 (shr-ensure-newline)
1292 (shr-indent)
1293 (shr-generic dom)
1294 (shr-ensure-newline)))
1296 (defun shr-tag-blockquote (dom)
1297 (shr-ensure-paragraph)
1298 (shr-indent)
1299 (let ((shr-indentation (+ shr-indentation 4)))
1300 (shr-generic dom))
1301 (shr-ensure-paragraph))
1303 (defun shr-tag-dl (dom)
1304 (shr-ensure-paragraph)
1305 (shr-generic dom)
1306 (shr-ensure-paragraph))
1308 (defun shr-tag-dt (dom)
1309 (shr-ensure-newline)
1310 (shr-generic dom)
1311 (shr-ensure-newline))
1313 (defun shr-tag-dd (dom)
1314 (shr-ensure-newline)
1315 (let ((shr-indentation (+ shr-indentation 4)))
1316 (shr-generic dom)))
1318 (defun shr-tag-ul (dom)
1319 (shr-ensure-paragraph)
1320 (let ((shr-list-mode 'ul))
1321 (shr-generic dom))
1322 (shr-ensure-paragraph))
1324 (defun shr-tag-ol (dom)
1325 (shr-ensure-paragraph)
1326 (let ((shr-list-mode 1))
1327 (shr-generic dom))
1328 (shr-ensure-paragraph))
1330 (defun shr-tag-li (dom)
1331 (shr-ensure-newline)
1332 (shr-indent)
1333 (let* ((bullet
1334 (if (numberp shr-list-mode)
1335 (prog1
1336 (format "%d " shr-list-mode)
1337 (setq shr-list-mode (1+ shr-list-mode)))
1338 shr-bullet))
1339 (shr-indentation (+ shr-indentation (length bullet))))
1340 (insert bullet)
1341 (shr-generic dom)))
1343 (defun shr-tag-br (dom)
1344 (when (and (not (bobp))
1345 ;; Only add a newline if we break the current line, or
1346 ;; the previous line isn't a blank line.
1347 (or (not (bolp))
1348 (and (> (- (point) 2) (point-min))
1349 (not (= (char-after (- (point) 2)) ?\n)))))
1350 (insert "\n")
1351 (shr-indent))
1352 (shr-generic dom))
1354 (defun shr-tag-span (dom)
1355 (shr-generic dom))
1357 (defun shr-tag-h1 (dom)
1358 (shr-heading dom 'bold 'underline))
1360 (defun shr-tag-h2 (dom)
1361 (shr-heading dom 'bold))
1363 (defun shr-tag-h3 (dom)
1364 (shr-heading dom 'italic))
1366 (defun shr-tag-h4 (dom)
1367 (shr-heading dom))
1369 (defun shr-tag-h5 (dom)
1370 (shr-heading dom))
1372 (defun shr-tag-h6 (dom)
1373 (shr-heading dom))
1375 (defun shr-tag-hr (_dom)
1376 (shr-ensure-newline)
1377 (insert (make-string shr-internal-width shr-hr-line) "\n"))
1379 (defun shr-tag-title (dom)
1380 (shr-heading dom 'bold 'underline))
1382 (defun shr-tag-font (dom)
1383 (let* ((start (point))
1384 (color (dom-attr dom 'color))
1385 (shr-stylesheet (nconc (list (cons 'color color))
1386 shr-stylesheet)))
1387 (shr-generic dom)
1388 (when color
1389 (shr-colorize-region start (point) color
1390 (cdr (assq 'background-color shr-stylesheet))))))
1392 ;;; Table rendering algorithm.
1394 ;; Table rendering is the only complicated thing here. We do this by
1395 ;; first counting how many TDs there are in each TR, and registering
1396 ;; how wide they think they should be ("width=45%", etc). Then we
1397 ;; render each TD separately (this is done in temporary buffers, so
1398 ;; that we can use all the rendering machinery as if we were in the
1399 ;; main buffer). Now we know how much space each TD really takes, so
1400 ;; we then render everything again with the new widths, and finally
1401 ;; insert all these boxes into the main buffer.
1402 (defun shr-tag-table-1 (dom)
1403 (setq dom (or (dom-child-by-tag dom 'tbody) dom))
1404 (let* ((shr-inhibit-images t)
1405 (shr-table-depth (1+ shr-table-depth))
1406 (shr-kinsoku-shorten t)
1407 ;; Find all suggested widths.
1408 (columns (shr-column-specs dom))
1409 ;; Compute how many characters wide each TD should be.
1410 (suggested-widths (shr-pro-rate-columns columns))
1411 ;; Do a "test rendering" to see how big each TD is (this can
1412 ;; be smaller (if there's little text) or bigger (if there's
1413 ;; unbreakable text).
1414 (sketch (shr-make-table dom suggested-widths))
1415 ;; Compute the "natural" width by setting each column to 500
1416 ;; characters and see how wide they really render.
1417 (natural (shr-make-table dom (make-vector (length columns) 500)))
1418 (sketch-widths (shr-table-widths sketch natural suggested-widths)))
1419 ;; This probably won't work very well.
1420 (when (> (+ (loop for width across sketch-widths
1421 summing (1+ width))
1422 shr-indentation 1)
1423 (frame-width))
1424 (setq truncate-lines t))
1425 ;; Then render the table again with these new "hard" widths.
1426 (shr-insert-table (shr-make-table dom sketch-widths t) sketch-widths)))
1428 (defun shr-tag-table (dom)
1429 (shr-ensure-paragraph)
1430 (let* ((caption (dom-child-by-tag dom 'caption))
1431 (header (dom-child-by-tag dom 'thead))
1432 (body (or (dom-child-by-tag dom 'tbody) dom))
1433 (footer (dom-child-by-tag dom 'tfoot))
1434 (bgcolor (dom-attr dom 'bgcolor))
1435 (start (point))
1436 (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
1437 shr-stylesheet))
1438 (nheader (if header (shr-max-columns header)))
1439 (nbody (if body (shr-max-columns body)))
1440 (nfooter (if footer (shr-max-columns footer))))
1441 (if (and (not caption)
1442 (not header)
1443 (not (dom-child-by-tag dom 'tbody))
1444 (not (dom-child-by-tag dom 'tr))
1445 (not footer))
1446 ;; The table is totally invalid and just contains random junk.
1447 ;; Try to output it anyway.
1448 (shr-generic dom)
1449 ;; It's a real table, so render it.
1450 (shr-tag-table-1
1451 (nconc
1452 (if caption `((tr (td ,@caption))))
1453 (if header
1454 (if footer
1455 ;; header + body + footer
1456 (if (= nheader nbody)
1457 (if (= nbody nfooter)
1458 `((tr (td (table (tbody ,@header ,@body ,@footer)))))
1459 (nconc `((tr (td (table (tbody ,@header ,@body)))))
1460 (if (= nfooter 1)
1461 footer
1462 `((tr (td (table (tbody ,@footer))))))))
1463 (nconc `((tr (td (table (tbody ,@header)))))
1464 (if (= nbody nfooter)
1465 `((tr (td (table (tbody ,@body ,@footer)))))
1466 (nconc `((tr (td (table (tbody ,@body)))))
1467 (if (= nfooter 1)
1468 footer
1469 `((tr (td (table (tbody ,@footer))))))))))
1470 ;; header + body
1471 (if (= nheader nbody)
1472 `((tr (td (table (tbody ,@header ,@body)))))
1473 (if (= nheader 1)
1474 `(,@header (tr (td (table (tbody ,@body)))))
1475 `((tr (td (table (tbody ,@header))))
1476 (tr (td (table (tbody ,@body))))))))
1477 (if footer
1478 ;; body + footer
1479 (if (= nbody nfooter)
1480 `((tr (td (table (tbody ,@body ,@footer)))))
1481 (nconc `((tr (td (table (tbody ,@body)))))
1482 (if (= nfooter 1)
1483 footer
1484 `((tr (td (table (tbody ,@footer))))))))
1485 (if caption
1486 `((tr (td (table (tbody ,@body)))))
1487 body))))))
1488 (when bgcolor
1489 (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
1490 bgcolor))
1491 ;; Finally, insert all the images after the table. The Emacs buffer
1492 ;; model isn't strong enough to allow us to put the images actually
1493 ;; into the tables.
1494 (when (zerop shr-table-depth)
1495 (dolist (elem (dom-by-tag dom 'object))
1496 (shr-tag-object elem))
1497 (dolist (elem (dom-by-tag dom 'img))
1498 (shr-tag-img elem)))))
1500 (defun shr-insert-table (table widths)
1501 (let* ((collapse (equal (cdr (assq 'border-collapse shr-stylesheet))
1502 "collapse"))
1503 (shr-table-separator-length (if collapse 0 1))
1504 (shr-table-vertical-line (if collapse "" shr-table-vertical-line)))
1505 (unless collapse
1506 (shr-insert-table-ruler widths))
1507 (dolist (row table)
1508 (let ((start (point))
1509 (height (let ((max 0))
1510 (dolist (column row)
1511 (setq max (max max (cadr column))))
1512 max)))
1513 (dotimes (i height)
1514 (shr-indent)
1515 (insert shr-table-vertical-line "\n"))
1516 (dolist (column row)
1517 (goto-char start)
1518 (let ((lines (nth 2 column)))
1519 (dolist (line lines)
1520 (end-of-line)
1521 (insert line shr-table-vertical-line)
1522 (forward-line 1))
1523 ;; Add blank lines at padding at the bottom of the TD,
1524 ;; possibly.
1525 (dotimes (i (- height (length lines)))
1526 (end-of-line)
1527 (let ((start (point)))
1528 (insert (make-string (string-width (car lines)) ? )
1529 shr-table-vertical-line)
1530 (when (nth 4 column)
1531 (shr-add-font start (1- (point))
1532 (list :background (nth 4 column)))))
1533 (forward-line 1)))))
1534 (unless collapse
1535 (shr-insert-table-ruler widths)))))
1537 (defun shr-insert-table-ruler (widths)
1538 (when shr-table-horizontal-line
1539 (when (and (bolp)
1540 (> shr-indentation 0))
1541 (shr-indent))
1542 (insert shr-table-corner)
1543 (dotimes (i (length widths))
1544 (insert (make-string (aref widths i) shr-table-horizontal-line)
1545 shr-table-corner))
1546 (insert "\n")))
1548 (defun shr-table-widths (table natural-table suggested-widths)
1549 (let* ((length (length suggested-widths))
1550 (widths (make-vector length 0))
1551 (natural-widths (make-vector length 0)))
1552 (dolist (row table)
1553 (let ((i 0))
1554 (dolist (column row)
1555 (aset widths i (max (aref widths i) column))
1556 (setq i (1+ i)))))
1557 (dolist (row natural-table)
1558 (let ((i 0))
1559 (dolist (column row)
1560 (aset natural-widths i (max (aref natural-widths i) column))
1561 (setq i (1+ i)))))
1562 (let ((extra (- (apply '+ (append suggested-widths nil))
1563 (apply '+ (append widths nil))))
1564 (expanded-columns 0))
1565 ;; We have extra, unused space, so divide this space amongst the
1566 ;; columns.
1567 (when (> extra 0)
1568 ;; If the natural width is wider than the rendered width, we
1569 ;; want to allow the column to expand.
1570 (dotimes (i length)
1571 (when (> (aref natural-widths i) (aref widths i))
1572 (setq expanded-columns (1+ expanded-columns))))
1573 (dotimes (i length)
1574 (when (> (aref natural-widths i) (aref widths i))
1575 (aset widths i (min
1576 (aref natural-widths i)
1577 (+ (/ extra expanded-columns)
1578 (aref widths i))))))))
1579 widths))
1581 (defun shr-make-table (dom widths &optional fill)
1582 (or (cadr (assoc (list dom widths fill) shr-content-cache))
1583 (let ((data (shr-make-table-1 dom widths fill)))
1584 (push (list (list dom widths fill) data)
1585 shr-content-cache)
1586 data)))
1588 (defun shr-make-table-1 (dom widths &optional fill)
1589 (let ((trs nil)
1590 (shr-inhibit-decoration (not fill))
1591 (rowspans (make-vector (length widths) 0))
1592 width colspan)
1593 (dolist (row (dom-non-text-children dom))
1594 (when (eq (dom-tag row) 'tr)
1595 (let ((tds nil)
1596 (columns (dom-children row))
1597 (i 0)
1598 (width-column 0)
1599 column)
1600 (while (< i (length widths))
1601 ;; If we previously had a rowspan definition, then that
1602 ;; means that we now have a "missing" td/th element here.
1603 ;; So just insert a dummy, empty one to (sort of) emulate
1604 ;; rowspan.
1605 (setq column
1606 (if (zerop (aref rowspans i))
1607 (pop columns)
1608 (aset rowspans i (1- (aref rowspans i)))
1609 '(td)))
1610 (when (and (not (stringp column))
1611 (or (memq (dom-tag column) '(td th))
1612 (not column)))
1613 (when-let (span (dom-attr column 'rowspan))
1614 (aset rowspans i (+ (aref rowspans i)
1615 (1- (string-to-number span)))))
1616 ;; Sanity check for invalid column-spans.
1617 (when (>= width-column (length widths))
1618 (setq width-column 0))
1619 (setq width
1620 (if column
1621 (aref widths width-column)
1622 10))
1623 (when (and fill
1624 (setq colspan (dom-attr column colspan)))
1625 (setq colspan (min (string-to-number colspan)
1626 ;; The colspan may be wrong, so
1627 ;; truncate it to the length of the
1628 ;; remaining columns.
1629 (- (length widths) i)))
1630 (dotimes (j (1- colspan))
1631 (if (> (+ i 1 j) (1- (length widths)))
1632 (setq width (aref widths (1- (length widths))))
1633 (setq width (+ width
1634 shr-table-separator-length
1635 (aref widths (+ i 1 j))))))
1636 (setq width-column (+ width-column (1- colspan))))
1637 (when (or column
1638 (not fill))
1639 (push (shr-render-td column width fill)
1640 tds))
1641 (setq i (1+ i)
1642 width-column (1+ width-column))))
1643 (push (nreverse tds) trs))))
1644 (nreverse trs)))
1646 (defun shr-render-td (dom width fill)
1647 (with-temp-buffer
1648 (let ((bgcolor (dom-attr dom 'bgcolor))
1649 (fgcolor (dom-attr dom 'fgcolor))
1650 (style (dom-attr dom 'style))
1651 (shr-stylesheet shr-stylesheet)
1652 actual-colors)
1653 (when style
1654 (setq style (and (string-match "color" style)
1655 (shr-parse-style style))))
1656 (when bgcolor
1657 (setq style (nconc (list (cons 'background-color bgcolor)) style)))
1658 (when fgcolor
1659 (setq style (nconc (list (cons 'color fgcolor)) style)))
1660 (when style
1661 (setq shr-stylesheet (append style shr-stylesheet)))
1662 (let ((shr-internal-width width)
1663 (shr-indentation 0))
1664 (shr-descend dom))
1665 ;; Delete padding at the bottom of the TDs.
1666 (delete-region
1667 (point)
1668 (progn
1669 (skip-chars-backward " \t\n")
1670 (end-of-line)
1671 (point)))
1672 (goto-char (point-min))
1673 (let ((max 0))
1674 (while (not (eobp))
1675 (end-of-line)
1676 (setq max (max max (current-column)))
1677 (forward-line 1))
1678 (when fill
1679 (goto-char (point-min))
1680 ;; If the buffer is totally empty, then put a single blank
1681 ;; line here.
1682 (if (zerop (buffer-size))
1683 (insert (make-string width ? ))
1684 ;; Otherwise, fill the buffer.
1685 (let ((align (dom-attr dom 'align))
1686 length)
1687 (while (not (eobp))
1688 (end-of-line)
1689 (setq length (- width (current-column)))
1690 (when (> length 0)
1691 (cond
1692 ((equal align "right")
1693 (beginning-of-line)
1694 (insert (make-string length ? )))
1695 ((equal align "center")
1696 (insert (make-string (/ length 2) ? ))
1697 (beginning-of-line)
1698 (insert (make-string (- length (/ length 2)) ? )))
1700 (insert (make-string length ? )))))
1701 (forward-line 1))))
1702 (when style
1703 (setq actual-colors
1704 (shr-colorize-region
1705 (point-min) (point-max)
1706 (cdr (assq 'color shr-stylesheet))
1707 (cdr (assq 'background-color shr-stylesheet))))))
1708 (if fill
1709 (list max
1710 (count-lines (point-min) (point-max))
1711 (split-string (buffer-string) "\n")
1713 (car actual-colors))
1714 max)))))
1716 (defun shr-buffer-width ()
1717 (goto-char (point-min))
1718 (let ((max 0))
1719 (while (not (eobp))
1720 (end-of-line)
1721 (setq max (max max (current-column)))
1722 (forward-line 1))
1723 max))
1725 (defun shr-pro-rate-columns (columns)
1726 (let ((total-percentage 0)
1727 (widths (make-vector (length columns) 0)))
1728 (dotimes (i (length columns))
1729 (setq total-percentage (+ total-percentage (aref columns i))))
1730 (setq total-percentage (/ 1.0 total-percentage))
1731 (dotimes (i (length columns))
1732 (aset widths i (max (truncate (* (aref columns i)
1733 total-percentage
1734 (- shr-internal-width
1735 (1+ (length columns)))))
1736 10)))
1737 widths))
1739 ;; Return a summary of the number and shape of the TDs in the table.
1740 (defun shr-column-specs (dom)
1741 (let ((columns (make-vector (shr-max-columns dom) 1)))
1742 (dolist (row (dom-non-text-children dom))
1743 (when (eq (dom-tag row) 'tr)
1744 (let ((i 0))
1745 (dolist (column (dom-children row))
1746 (when (and (not (stringp column))
1747 (memq (dom-tag column) '(td th)))
1748 (let ((width (dom-attr column 'width)))
1749 (when (and width
1750 (string-match "\\([0-9]+\\)%" width)
1751 (not (zerop (setq width (string-to-number
1752 (match-string 1 width))))))
1753 (aset columns i (/ width 100.0))))
1754 (setq i (1+ i)))))))
1755 columns))
1757 (defun shr-count (dom elem)
1758 (let ((i 0))
1759 (dolist (sub (dom-children dom))
1760 (when (and (not (stringp sub))
1761 (eq (dom-tag sub) elem))
1762 (setq i (1+ i))))
1765 (defun shr-max-columns (dom)
1766 (let ((max 0))
1767 (dolist (row (dom-children dom))
1768 (when (and (not (stringp row))
1769 (eq (dom-tag row) 'tr))
1770 (setq max (max max (+ (shr-count row 'td)
1771 (shr-count row 'th))))))
1772 max))
1774 (provide 'shr)
1776 ;; Local Variables:
1777 ;; coding: utf-8
1778 ;; End:
1780 ;;; shr.el ends here