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