Merge from origin/emacs-24
[emacs.git] / lisp / net / shr.el
bloba0c9eba4144f5bfb665cce6f83b605bffcc1bcbd
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 (let ((iri (or (ignore-errors
898 (decode-coding-string
899 (url-unhex-string url)
900 'utf-8 t))
901 url)))
902 (if title (format "%s (%s)" iri title) iri))
903 'follow-link t
904 'mouse-face 'highlight
905 'keymap shr-map)))
907 (defun shr-encode-url (url)
908 "Encode URL."
909 (browse-url-url-encode-chars url "[)$ ]"))
911 (autoload 'shr-color-visible "shr-color")
912 (autoload 'shr-color->hexadecimal "shr-color")
914 (defun shr-color-check (fg bg)
915 "Check that FG is visible on BG.
916 Returns (fg bg) with corrected values.
917 Returns nil if the colors that would be used are the default
918 ones, in case fg and bg are nil."
919 (when (or fg bg)
920 (let ((fixed (cond ((null fg) 'fg)
921 ((null bg) 'bg))))
922 ;; Convert colors to hexadecimal, or set them to default.
923 (let ((fg (or (shr-color->hexadecimal fg)
924 (frame-parameter nil 'foreground-color)))
925 (bg (or (shr-color->hexadecimal bg)
926 (frame-parameter nil 'background-color))))
927 (cond ((eq fixed 'bg)
928 ;; Only return the new fg
929 (list nil (cadr (shr-color-visible bg fg t))))
930 ((eq fixed 'fg)
931 ;; Invert args and results and return only the new bg
932 (list (cadr (shr-color-visible fg bg t)) nil))
934 (shr-color-visible bg fg)))))))
936 (defun shr-colorize-region (start end fg &optional bg)
937 (when (and (not shr-inhibit-decoration)
938 (or fg bg))
939 (let ((new-colors (shr-color-check fg bg)))
940 (when new-colors
941 (when fg
942 (add-face-text-property start end
943 (list :foreground (cadr new-colors))
945 (when bg
946 (add-face-text-property start end
947 (list :background (car new-colors))
948 t)))
949 new-colors)))
951 (defun shr-expand-newlines (start end color)
952 (save-restriction
953 ;; Skip past all white space at the start and ends.
954 (goto-char start)
955 (skip-chars-forward " \t\n")
956 (beginning-of-line)
957 (setq start (point))
958 (goto-char end)
959 (skip-chars-backward " \t\n")
960 (forward-line 1)
961 (setq end (point))
962 (narrow-to-region start end)
963 (let ((width (shr-buffer-width))
964 column)
965 (goto-char (point-min))
966 (while (not (eobp))
967 (end-of-line)
968 (when (and (< (setq column (current-column)) width)
969 (< (setq column (shr-previous-newline-padding-width column))
970 width))
971 (let ((overlay (make-overlay (point) (1+ (point)))))
972 (overlay-put overlay 'before-string
973 (concat
974 (mapconcat
975 (lambda (overlay)
976 (let ((string (plist-get
977 (overlay-properties overlay)
978 'before-string)))
979 (if (not string)
981 (overlay-put overlay 'before-string "")
982 string)))
983 (overlays-at (point))
985 (propertize (make-string (- width column) ? )
986 'face (list :background color))))))
987 (forward-line 1)))))
989 (defun shr-previous-newline-padding-width (width)
990 (let ((overlays (overlays-at (point)))
991 (previous-width 0))
992 (if (null overlays)
993 width
994 (dolist (overlay overlays)
995 (setq previous-width
996 (+ previous-width
997 (length (plist-get (overlay-properties overlay)
998 'before-string)))))
999 (+ width previous-width))))
1001 ;;; Tag-specific rendering rules.
1003 (defun shr-tag-body (dom)
1004 (let* ((start (point))
1005 (fgcolor (or (dom-attr dom 'fgcolor) (dom-attr dom 'text)))
1006 (bgcolor (dom-attr dom 'bgcolor))
1007 (shr-stylesheet (list (cons 'color fgcolor)
1008 (cons 'background-color bgcolor))))
1009 (shr-generic dom)
1010 (shr-colorize-region start (point) fgcolor bgcolor)))
1012 (defun shr-tag-style (_dom)
1015 (defun shr-tag-script (_dom)
1018 (defun shr-tag-comment (_dom)
1021 (defun shr-dom-to-xml (dom)
1022 (with-temp-buffer
1023 (shr-dom-print dom)
1024 (buffer-string)))
1026 (defun shr-dom-print (dom)
1027 "Convert DOM into a string containing the xml representation."
1028 (insert (format "<%s" (dom-tag dom)))
1029 (dolist (attr (dom-attributes dom))
1030 ;; Ignore attributes that start with a colon because they are
1031 ;; private elements.
1032 (unless (= (aref (format "%s" (car attr)) 0) ?:)
1033 (insert (format " %s=\"%s\"" (car attr) (cdr attr)))))
1034 (insert ">")
1035 (let (url)
1036 (dolist (elem (dom-children dom))
1037 (cond
1038 ((stringp elem)
1039 (insert elem))
1040 ((eq (dom-tag elem) 'comment)
1042 ((or (not (eq (dom-tag elem) 'image))
1043 ;; Filter out blocked elements inside the SVG image.
1044 (not (setq url (dom-attr elem ':xlink:href)))
1045 (not shr-blocked-images)
1046 (not (string-match shr-blocked-images url)))
1047 (insert " ")
1048 (shr-dom-print elem)))))
1049 (insert (format "</%s>" (dom-tag dom))))
1051 (defun shr-tag-svg (dom)
1052 (when (and (image-type-available-p 'svg)
1053 (not shr-inhibit-images))
1054 (funcall shr-put-image-function (list (shr-dom-to-xml dom) 'image/svg+xml)
1055 "SVG Image")))
1057 (defun shr-tag-sup (dom)
1058 (let ((start (point)))
1059 (shr-generic dom)
1060 (put-text-property start (point) 'display '(raise 0.5))))
1062 (defun shr-tag-sub (dom)
1063 (let ((start (point)))
1064 (shr-generic dom)
1065 (put-text-property start (point) 'display '(raise -0.5))))
1067 (defun shr-tag-label (dom)
1068 (shr-generic dom)
1069 (shr-ensure-paragraph))
1071 (defun shr-tag-p (dom)
1072 (shr-ensure-paragraph)
1073 (shr-indent)
1074 (shr-generic dom)
1075 (shr-ensure-paragraph))
1077 (defun shr-tag-div (dom)
1078 (shr-ensure-newline)
1079 (shr-indent)
1080 (shr-generic dom)
1081 (shr-ensure-newline))
1083 (defun shr-tag-s (dom)
1084 (shr-fontize-dom dom 'shr-strike-through))
1086 (defun shr-tag-del (dom)
1087 (shr-fontize-dom dom 'shr-strike-through))
1089 (defun shr-tag-b (dom)
1090 (shr-fontize-dom dom 'bold))
1092 (defun shr-tag-i (dom)
1093 (shr-fontize-dom dom 'italic))
1095 (defun shr-tag-em (dom)
1096 (shr-fontize-dom dom 'italic))
1098 (defun shr-tag-strong (dom)
1099 (shr-fontize-dom dom 'bold))
1101 (defun shr-tag-u (dom)
1102 (shr-fontize-dom dom 'underline))
1104 (defun shr-parse-style (style)
1105 (when style
1106 (save-match-data
1107 (when (string-match "\n" style)
1108 (setq style (replace-match " " t t style))))
1109 (let ((plist nil))
1110 (dolist (elem (split-string style ";"))
1111 (when elem
1112 (setq elem (split-string elem ":"))
1113 (when (and (car elem)
1114 (cadr elem))
1115 (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
1116 (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
1117 (when (string-match " *!important\\'" value)
1118 (setq value (substring value 0 (match-beginning 0))))
1119 (push (cons (intern name obarray)
1120 value)
1121 plist)))))
1122 plist)))
1124 (defun shr-tag-base (dom)
1125 (when-let (base (dom-attr dom 'href))
1126 (setq shr-base (shr-parse-base base)))
1127 (shr-generic dom))
1129 (defun shr-tag-a (dom)
1130 (let ((url (dom-attr dom 'href))
1131 (title (dom-attr dom 'title))
1132 (start (point))
1133 shr-start)
1134 (shr-generic dom)
1135 (when (and shr-target-id
1136 (equal (dom-attr dom 'name) shr-target-id))
1137 ;; We have a zero-length <a name="foo"> element, so just
1138 ;; insert... something.
1139 (when (= start (point))
1140 (shr-ensure-newline)
1141 (insert " "))
1142 (put-text-property start (1+ start) 'shr-target-id shr-target-id))
1143 (when (and url
1144 (not shr-inhibit-decoration))
1145 (shr-urlify (or shr-start start) (shr-expand-url url) title))))
1147 (defun shr-tag-object (dom)
1148 (unless shr-inhibit-images
1149 (let ((start (point))
1150 url multimedia image)
1151 (when-let (type (dom-attr dom 'type))
1152 (when (string-match "\\`image/svg" type)
1153 (setq url (dom-attr dom 'data)
1154 image t)))
1155 (dolist (child (dom-non-text-children dom))
1156 (cond
1157 ((eq (dom-tag child) 'embed)
1158 (setq url (or url (dom-attr child 'src))
1159 multimedia t))
1160 ((and (eq (dom-tag child) 'param)
1161 (equal (dom-attr child 'name) "movie"))
1162 (setq url (or url (dom-attr child 'value))
1163 multimedia t))))
1164 (when url
1165 (cond
1166 (image
1167 (shr-tag-img dom url)
1168 (setq dom nil))
1169 (multimedia
1170 (shr-insert " [multimedia] ")
1171 (shr-urlify start (shr-expand-url url)))))
1172 (when dom
1173 (shr-generic dom)))))
1175 (defcustom shr-prefer-media-type-alist '(("webm" . 1.0)
1176 ("ogv" . 1.0)
1177 ("ogg" . 1.0)
1178 ("opus" . 1.0)
1179 ("flac" . 0.9)
1180 ("wav" . 0.5))
1181 "Preferences for media types.
1182 The key element should be a regexp matched against the type of the source or
1183 url if no type is specified. The value should be a float in the range 0.0 to
1184 1.0. Media elements with higher value are preferred."
1185 :version "24.4"
1186 :group 'shr
1187 :type '(alist :key-type regexp :value-type float))
1189 (defun shr--get-media-pref (elem)
1190 "Determine the preference for ELEM.
1191 The preference is a float determined from `shr-prefer-media-type'."
1192 (let ((type (dom-attr elem 'type))
1193 (p 0.0))
1194 (unless type
1195 (setq type (dom-attr elem 'src)))
1196 (when type
1197 (dolist (pref shr-prefer-media-type-alist)
1198 (when (and
1199 (> (cdr pref) p)
1200 (string-match-p (car pref) type))
1201 (setq p (cdr pref)))))
1204 (defun shr--extract-best-source (dom &optional url pref)
1205 "Extract the best `:src' property from <source> blocks in DOM."
1206 (setq pref (or pref -1.0))
1207 (let (new-pref)
1208 (dolist (elem (dom-non-text-children dom))
1209 (when (and (eq (dom-tag elem) 'source)
1210 (< pref
1211 (setq new-pref
1212 (shr--get-media-pref elem))))
1213 (setq pref new-pref
1214 url (dom-attr elem 'src))
1215 ;; libxml's html parser isn't HTML5 compliant and non terminated
1216 ;; source tags might end up as children. So recursion it is...
1217 (dolist (child (dom-non-text-children elem))
1218 (when (eq (dom-tag child) 'source)
1219 (let ((ret (shr--extract-best-source (list child) url pref)))
1220 (when (< pref (cdr ret))
1221 (setq url (car ret)
1222 pref (cdr ret)))))))))
1223 (cons url pref))
1225 (defun shr-tag-video (dom)
1226 (let ((image (dom-attr dom 'poster))
1227 (url (dom-attr dom 'src))
1228 (start (point)))
1229 (unless url
1230 (setq url (car (shr--extract-best-source dom))))
1231 (if image
1232 (shr-tag-img nil image)
1233 (shr-insert " [video] "))
1234 (shr-urlify start (shr-expand-url url))))
1236 (defun shr-tag-audio (dom)
1237 (let ((url (dom-attr dom 'src))
1238 (start (point)))
1239 (unless url
1240 (setq url (car (shr--extract-best-source dom))))
1241 (shr-insert " [audio] ")
1242 (shr-urlify start (shr-expand-url url))))
1244 (defun shr-tag-img (dom &optional url)
1245 (when (or url
1246 (and dom
1247 (> (length (dom-attr dom 'src)) 0)))
1248 (when (and (> (current-column) 0)
1249 (not (eq shr-state 'image)))
1250 (insert "\n"))
1251 (let ((alt (dom-attr dom 'alt))
1252 (url (shr-expand-url (or url (dom-attr dom 'src)))))
1253 (let ((start (point-marker)))
1254 (when (zerop (length alt))
1255 (setq alt "*"))
1256 (cond
1257 ((or (member (dom-attr dom 'height) '("0" "1"))
1258 (member (dom-attr dom 'width) '("0" "1")))
1259 ;; Ignore zero-sized or single-pixel images.
1261 ((and (not shr-inhibit-images)
1262 (string-match "\\`data:" url))
1263 (let ((image (shr-image-from-data (substring url (match-end 0)))))
1264 (if image
1265 (funcall shr-put-image-function image alt)
1266 (insert alt))))
1267 ((and (not shr-inhibit-images)
1268 (string-match "\\`cid:" url))
1269 (let ((url (substring url (match-end 0)))
1270 image)
1271 (if (or (not shr-content-function)
1272 (not (setq image (funcall shr-content-function url))))
1273 (insert alt)
1274 (funcall shr-put-image-function image alt))))
1275 ((or shr-inhibit-images
1276 (and shr-blocked-images
1277 (string-match shr-blocked-images url)))
1278 (setq shr-start (point))
1279 (let ((shr-state 'space))
1280 (if (> (string-width alt) 8)
1281 (shr-insert (truncate-string-to-width alt 8))
1282 (shr-insert alt))))
1283 ((and (not shr-ignore-cache)
1284 (url-is-cached (shr-encode-url url)))
1285 (funcall shr-put-image-function (shr-get-image-data url) alt))
1287 (insert alt " ")
1288 (when (and shr-ignore-cache
1289 (url-is-cached (shr-encode-url url)))
1290 (let ((file (url-cache-create-filename (shr-encode-url url))))
1291 (when (file-exists-p file)
1292 (delete-file file))))
1293 (url-queue-retrieve
1294 (shr-encode-url url) 'shr-image-fetched
1295 (list (current-buffer) start (set-marker (make-marker) (1- (point))))
1296 t t)))
1297 (when (zerop shr-table-depth) ;; We are not in a table.
1298 (put-text-property start (point) 'keymap shr-map)
1299 (put-text-property start (point) 'shr-alt alt)
1300 (put-text-property start (point) 'image-url url)
1301 (put-text-property start (point) 'image-displayer
1302 (shr-image-displayer shr-content-function))
1303 (put-text-property start (point) 'help-echo
1304 (shr-fold-text (or (dom-attr dom 'title) alt))))
1305 (setq shr-state 'image)))))
1307 (defun shr-tag-pre (dom)
1308 (let ((shr-folding-mode 'none))
1309 (shr-ensure-newline)
1310 (shr-indent)
1311 (shr-generic dom)
1312 (shr-ensure-newline)))
1314 (defun shr-tag-blockquote (dom)
1315 (shr-ensure-paragraph)
1316 (shr-indent)
1317 (let ((shr-indentation (+ shr-indentation 4)))
1318 (shr-generic dom))
1319 (shr-ensure-paragraph))
1321 (defun shr-tag-dl (dom)
1322 (shr-ensure-paragraph)
1323 (shr-generic dom)
1324 (shr-ensure-paragraph))
1326 (defun shr-tag-dt (dom)
1327 (shr-ensure-newline)
1328 (shr-generic dom)
1329 (shr-ensure-newline))
1331 (defun shr-tag-dd (dom)
1332 (shr-ensure-newline)
1333 (let ((shr-indentation (+ shr-indentation 4)))
1334 (shr-generic dom)))
1336 (defun shr-tag-ul (dom)
1337 (shr-ensure-paragraph)
1338 (let ((shr-list-mode 'ul))
1339 (shr-generic dom))
1340 (shr-ensure-paragraph))
1342 (defun shr-tag-ol (dom)
1343 (shr-ensure-paragraph)
1344 (let ((shr-list-mode 1))
1345 (shr-generic dom))
1346 (shr-ensure-paragraph))
1348 (defun shr-tag-li (dom)
1349 (shr-ensure-newline)
1350 (shr-indent)
1351 (let* ((bullet
1352 (if (numberp shr-list-mode)
1353 (prog1
1354 (format "%d " shr-list-mode)
1355 (setq shr-list-mode (1+ shr-list-mode)))
1356 shr-bullet))
1357 (shr-indentation (+ shr-indentation (length bullet))))
1358 (insert bullet)
1359 (shr-generic dom)))
1361 (defun shr-tag-br (dom)
1362 (when (and (not (bobp))
1363 ;; Only add a newline if we break the current line, or
1364 ;; the previous line isn't a blank line.
1365 (or (not (bolp))
1366 (and (> (- (point) 2) (point-min))
1367 (not (= (char-after (- (point) 2)) ?\n)))))
1368 (insert "\n")
1369 (shr-indent))
1370 (shr-generic dom))
1372 (defun shr-tag-span (dom)
1373 (shr-generic dom))
1375 (defun shr-tag-h1 (dom)
1376 (shr-heading dom 'bold 'underline))
1378 (defun shr-tag-h2 (dom)
1379 (shr-heading dom 'bold))
1381 (defun shr-tag-h3 (dom)
1382 (shr-heading dom 'italic))
1384 (defun shr-tag-h4 (dom)
1385 (shr-heading dom))
1387 (defun shr-tag-h5 (dom)
1388 (shr-heading dom))
1390 (defun shr-tag-h6 (dom)
1391 (shr-heading dom))
1393 (defun shr-tag-hr (_dom)
1394 (shr-ensure-newline)
1395 (insert (make-string shr-internal-width shr-hr-line) "\n"))
1397 (defun shr-tag-title (dom)
1398 (shr-heading dom 'bold 'underline))
1400 (defun shr-tag-font (dom)
1401 (let* ((start (point))
1402 (color (dom-attr dom 'color))
1403 (shr-stylesheet (nconc (list (cons 'color color))
1404 shr-stylesheet)))
1405 (shr-generic dom)
1406 (when color
1407 (shr-colorize-region start (point) color
1408 (cdr (assq 'background-color shr-stylesheet))))))
1410 ;;; Table rendering algorithm.
1412 ;; Table rendering is the only complicated thing here. We do this by
1413 ;; first counting how many TDs there are in each TR, and registering
1414 ;; how wide they think they should be ("width=45%", etc). Then we
1415 ;; render each TD separately (this is done in temporary buffers, so
1416 ;; that we can use all the rendering machinery as if we were in the
1417 ;; main buffer). Now we know how much space each TD really takes, so
1418 ;; we then render everything again with the new widths, and finally
1419 ;; insert all these boxes into the main buffer.
1420 (defun shr-tag-table-1 (dom)
1421 (setq dom (or (dom-child-by-tag dom 'tbody) dom))
1422 (let* ((shr-inhibit-images t)
1423 (shr-table-depth (1+ shr-table-depth))
1424 (shr-kinsoku-shorten t)
1425 ;; Find all suggested widths.
1426 (columns (shr-column-specs dom))
1427 ;; Compute how many characters wide each TD should be.
1428 (suggested-widths (shr-pro-rate-columns columns))
1429 ;; Do a "test rendering" to see how big each TD is (this can
1430 ;; be smaller (if there's little text) or bigger (if there's
1431 ;; unbreakable text).
1432 (sketch (shr-make-table dom suggested-widths))
1433 ;; Compute the "natural" width by setting each column to 500
1434 ;; characters and see how wide they really render.
1435 (natural (shr-make-table dom (make-vector (length columns) 500)))
1436 (sketch-widths (shr-table-widths sketch natural suggested-widths)))
1437 ;; This probably won't work very well.
1438 (when (> (+ (loop for width across sketch-widths
1439 summing (1+ width))
1440 shr-indentation 1)
1441 (frame-width))
1442 (setq truncate-lines t))
1443 ;; Then render the table again with these new "hard" widths.
1444 (shr-insert-table (shr-make-table dom sketch-widths t) sketch-widths)))
1446 (defun shr-tag-table (dom)
1447 (shr-ensure-paragraph)
1448 (let* ((caption (dom-children (dom-child-by-tag dom 'caption)))
1449 (header (dom-non-text-children (dom-child-by-tag dom 'thead)))
1450 (body (dom-non-text-children (or (dom-child-by-tag dom 'tbody)
1451 dom)))
1452 (footer (dom-non-text-children (dom-child-by-tag dom 'tfoot)))
1453 (bgcolor (dom-attr dom 'bgcolor))
1454 (start (point))
1455 (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
1456 shr-stylesheet))
1457 (nheader (if header (shr-max-columns header)))
1458 (nbody (if body (shr-max-columns body)))
1459 (nfooter (if footer (shr-max-columns footer))))
1460 (if (and (not caption)
1461 (not header)
1462 (not (dom-child-by-tag dom 'tbody))
1463 (not (dom-child-by-tag dom 'tr))
1464 (not footer))
1465 ;; The table is totally invalid and just contains random junk.
1466 ;; Try to output it anyway.
1467 (shr-generic dom)
1468 ;; It's a real table, so render it.
1469 (shr-tag-table-1
1470 (nconc
1471 (list 'table nil)
1472 (if caption `((tr nil (td nil ,@caption))))
1473 (cond (header
1474 (if footer
1475 ;; header + body + footer
1476 (if (= nheader nbody)
1477 (if (= nbody nfooter)
1478 `((tr nil (td nil (table nil
1479 (tbody nil ,@header
1480 ,@body ,@footer)))))
1481 (nconc `((tr nil (td nil (table nil
1482 (tbody nil ,@header
1483 ,@body)))))
1484 (if (= nfooter 1)
1485 footer
1486 `((tr nil (td nil (table
1487 nil (tbody
1488 nil ,@footer))))))))
1489 (nconc `((tr nil (td nil (table nil (tbody
1490 nil ,@header)))))
1491 (if (= nbody nfooter)
1492 `((tr nil (td nil (table
1493 nil (tbody nil ,@body
1494 ,@footer)))))
1495 (nconc `((tr nil (td nil (table
1496 nil (tbody nil
1497 ,@body)))))
1498 (if (= nfooter 1)
1499 footer
1500 `((tr nil (td nil (table
1502 (tbody
1504 ,@footer))))))))))
1505 ;; header + body
1506 (if (= nheader nbody)
1507 `((tr nil (td nil (table nil (tbody nil ,@header
1508 ,@body)))))
1509 (if (= nheader 1)
1510 `(,@header (tr nil (td nil (table
1511 nil (tbody nil ,@body)))))
1512 `((tr nil (td nil (table nil (tbody nil ,@header))))
1513 (tr nil (td nil (table nil (tbody nil ,@body)))))))))
1514 (footer
1515 ;; body + footer
1516 (if (= nbody nfooter)
1517 `((tr nil (td nil (table
1518 nil (tbody nil ,@body ,@footer)))))
1519 (nconc `((tr nil (td nil (table nil (tbody nil ,@body)))))
1520 (if (= nfooter 1)
1521 footer
1522 `((tr nil (td nil (table
1523 nil (tbody nil ,@footer)))))))))
1524 (caption
1525 `((tr nil (td nil (table nil (tbody nil ,@body))))))
1526 (body)))))
1527 (when bgcolor
1528 (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
1529 bgcolor))
1530 ;; Finally, insert all the images after the table. The Emacs buffer
1531 ;; model isn't strong enough to allow us to put the images actually
1532 ;; into the tables.
1533 (when (zerop shr-table-depth)
1534 (dolist (elem (dom-by-tag dom 'object))
1535 (shr-tag-object elem))
1536 (dolist (elem (dom-by-tag dom 'img))
1537 (shr-tag-img elem)))))
1539 (defun shr-insert-table (table widths)
1540 (let* ((collapse (equal (cdr (assq 'border-collapse shr-stylesheet))
1541 "collapse"))
1542 (shr-table-separator-length (if collapse 0 1))
1543 (shr-table-vertical-line (if collapse "" shr-table-vertical-line)))
1544 (unless collapse
1545 (shr-insert-table-ruler widths))
1546 (dolist (row table)
1547 (let ((start (point))
1548 (height (let ((max 0))
1549 (dolist (column row)
1550 (setq max (max max (cadr column))))
1551 max)))
1552 (dotimes (i height)
1553 (shr-indent)
1554 (insert shr-table-vertical-line "\n"))
1555 (dolist (column row)
1556 (goto-char start)
1557 (let ((lines (nth 2 column)))
1558 (dolist (line lines)
1559 (end-of-line)
1560 (insert line shr-table-vertical-line)
1561 (forward-line 1))
1562 ;; Add blank lines at padding at the bottom of the TD,
1563 ;; possibly.
1564 (dotimes (i (- height (length lines)))
1565 (end-of-line)
1566 (let ((start (point)))
1567 (insert (make-string (string-width (car lines)) ? )
1568 shr-table-vertical-line)
1569 (when (nth 4 column)
1570 (shr-add-font start (1- (point))
1571 (list :background (nth 4 column)))))
1572 (forward-line 1)))))
1573 (unless collapse
1574 (shr-insert-table-ruler widths)))))
1576 (defun shr-insert-table-ruler (widths)
1577 (when shr-table-horizontal-line
1578 (when (and (bolp)
1579 (> shr-indentation 0))
1580 (shr-indent))
1581 (insert shr-table-corner)
1582 (dotimes (i (length widths))
1583 (insert (make-string (aref widths i) shr-table-horizontal-line)
1584 shr-table-corner))
1585 (insert "\n")))
1587 (defun shr-table-widths (table natural-table suggested-widths)
1588 (let* ((length (length suggested-widths))
1589 (widths (make-vector length 0))
1590 (natural-widths (make-vector length 0)))
1591 (dolist (row table)
1592 (let ((i 0))
1593 (dolist (column row)
1594 (aset widths i (max (aref widths i) column))
1595 (setq i (1+ i)))))
1596 (dolist (row natural-table)
1597 (let ((i 0))
1598 (dolist (column row)
1599 (aset natural-widths i (max (aref natural-widths i) column))
1600 (setq i (1+ i)))))
1601 (let ((extra (- (apply '+ (append suggested-widths nil))
1602 (apply '+ (append widths nil))))
1603 (expanded-columns 0))
1604 ;; We have extra, unused space, so divide this space amongst the
1605 ;; columns.
1606 (when (> extra 0)
1607 ;; If the natural width is wider than the rendered width, we
1608 ;; want to allow the column to expand.
1609 (dotimes (i length)
1610 (when (> (aref natural-widths i) (aref widths i))
1611 (setq expanded-columns (1+ expanded-columns))))
1612 (dotimes (i length)
1613 (when (> (aref natural-widths i) (aref widths i))
1614 (aset widths i (min
1615 (aref natural-widths i)
1616 (+ (/ extra expanded-columns)
1617 (aref widths i))))))))
1618 widths))
1620 (defun shr-make-table (dom widths &optional fill)
1621 (or (cadr (assoc (list dom widths fill) shr-content-cache))
1622 (let ((data (shr-make-table-1 dom widths fill)))
1623 (push (list (list dom widths fill) data)
1624 shr-content-cache)
1625 data)))
1627 (defun shr-make-table-1 (dom widths &optional fill)
1628 (let ((trs nil)
1629 (shr-inhibit-decoration (not fill))
1630 (rowspans (make-vector (length widths) 0))
1631 width colspan)
1632 (dolist (row (dom-non-text-children dom))
1633 (when (eq (dom-tag row) 'tr)
1634 (let ((tds nil)
1635 (columns (dom-children row))
1636 (i 0)
1637 (width-column 0)
1638 column)
1639 (while (< i (length widths))
1640 ;; If we previously had a rowspan definition, then that
1641 ;; means that we now have a "missing" td/th element here.
1642 ;; So just insert a dummy, empty one to (sort of) emulate
1643 ;; rowspan.
1644 (setq column
1645 (if (zerop (aref rowspans i))
1646 (pop columns)
1647 (aset rowspans i (1- (aref rowspans i)))
1648 '(td)))
1649 (when (and (not (stringp column))
1650 (or (memq (dom-tag column) '(td th))
1651 (not column)))
1652 (when-let (span (dom-attr column 'rowspan))
1653 (aset rowspans i (+ (aref rowspans i)
1654 (1- (string-to-number span)))))
1655 ;; Sanity check for invalid column-spans.
1656 (when (>= width-column (length widths))
1657 (setq width-column 0))
1658 (setq width
1659 (if column
1660 (aref widths width-column)
1661 10))
1662 (when (and fill
1663 (setq colspan (dom-attr column 'colspan)))
1664 (setq colspan (min (string-to-number colspan)
1665 ;; The colspan may be wrong, so
1666 ;; truncate it to the length of the
1667 ;; remaining columns.
1668 (- (length widths) i)))
1669 (dotimes (j (1- colspan))
1670 (if (> (+ i 1 j) (1- (length widths)))
1671 (setq width (aref widths (1- (length widths))))
1672 (setq width (+ width
1673 shr-table-separator-length
1674 (aref widths (+ i 1 j))))))
1675 (setq width-column (+ width-column (1- colspan))))
1676 (when (or column
1677 (not fill))
1678 (push (shr-render-td column width fill)
1679 tds))
1680 (setq i (1+ i)
1681 width-column (1+ width-column))))
1682 (push (nreverse tds) trs))))
1683 (nreverse trs)))
1685 (defun shr-render-td (dom width fill)
1686 (with-temp-buffer
1687 (let ((bgcolor (dom-attr dom 'bgcolor))
1688 (fgcolor (dom-attr dom 'fgcolor))
1689 (style (dom-attr dom 'style))
1690 (shr-stylesheet shr-stylesheet)
1691 actual-colors)
1692 (when style
1693 (setq style (and (string-match "color" style)
1694 (shr-parse-style style))))
1695 (when bgcolor
1696 (setq style (nconc (list (cons 'background-color bgcolor)) style)))
1697 (when fgcolor
1698 (setq style (nconc (list (cons 'color fgcolor)) style)))
1699 (when style
1700 (setq shr-stylesheet (append style shr-stylesheet)))
1701 (let ((shr-internal-width width)
1702 (shr-indentation 0))
1703 (shr-descend dom))
1704 ;; Delete padding at the bottom of the TDs.
1705 (delete-region
1706 (point)
1707 (progn
1708 (skip-chars-backward " \t\n")
1709 (end-of-line)
1710 (point)))
1711 (goto-char (point-min))
1712 (let ((max 0))
1713 (while (not (eobp))
1714 (end-of-line)
1715 (setq max (max max (current-column)))
1716 (forward-line 1))
1717 (when fill
1718 (goto-char (point-min))
1719 ;; If the buffer is totally empty, then put a single blank
1720 ;; line here.
1721 (if (zerop (buffer-size))
1722 (insert (make-string width ? ))
1723 ;; Otherwise, fill the buffer.
1724 (let ((align (dom-attr dom 'align))
1725 length)
1726 (while (not (eobp))
1727 (end-of-line)
1728 (setq length (- width (current-column)))
1729 (when (> length 0)
1730 (cond
1731 ((equal align "right")
1732 (beginning-of-line)
1733 (insert (make-string length ? )))
1734 ((equal align "center")
1735 (insert (make-string (/ length 2) ? ))
1736 (beginning-of-line)
1737 (insert (make-string (- length (/ length 2)) ? )))
1739 (insert (make-string length ? )))))
1740 (forward-line 1))))
1741 (when style
1742 (setq actual-colors
1743 (shr-colorize-region
1744 (point-min) (point-max)
1745 (cdr (assq 'color shr-stylesheet))
1746 (cdr (assq 'background-color shr-stylesheet))))))
1747 (if fill
1748 (list max
1749 (count-lines (point-min) (point-max))
1750 (split-string (buffer-string) "\n")
1752 (car actual-colors))
1753 max)))))
1755 (defun shr-buffer-width ()
1756 (goto-char (point-min))
1757 (let ((max 0))
1758 (while (not (eobp))
1759 (end-of-line)
1760 (setq max (max max (current-column)))
1761 (forward-line 1))
1762 max))
1764 (defun shr-pro-rate-columns (columns)
1765 (let ((total-percentage 0)
1766 (widths (make-vector (length columns) 0)))
1767 (dotimes (i (length columns))
1768 (setq total-percentage (+ total-percentage (aref columns i))))
1769 (setq total-percentage (/ 1.0 total-percentage))
1770 (dotimes (i (length columns))
1771 (aset widths i (max (truncate (* (aref columns i)
1772 total-percentage
1773 (- shr-internal-width
1774 (1+ (length columns)))))
1775 10)))
1776 widths))
1778 ;; Return a summary of the number and shape of the TDs in the table.
1779 (defun shr-column-specs (dom)
1780 (let ((columns (make-vector (shr-max-columns dom) 1)))
1781 (dolist (row (dom-non-text-children dom))
1782 (when (eq (dom-tag row) 'tr)
1783 (let ((i 0))
1784 (dolist (column (dom-children row))
1785 (when (and (not (stringp column))
1786 (memq (dom-tag column) '(td th)))
1787 (let ((width (dom-attr column 'width)))
1788 (when (and width
1789 (string-match "\\([0-9]+\\)%" width)
1790 (not (zerop (setq width (string-to-number
1791 (match-string 1 width))))))
1792 (aset columns i (/ width 100.0))))
1793 (setq i (1+ i)))))))
1794 columns))
1796 (defun shr-count (dom elem)
1797 (let ((i 0))
1798 (dolist (sub (dom-children dom))
1799 (when (and (not (stringp sub))
1800 (eq (dom-tag sub) elem))
1801 (setq i (1+ i))))
1804 (defun shr-max-columns (dom)
1805 (let ((max 0))
1806 (dolist (row (dom-children dom))
1807 (when (and (not (stringp row))
1808 (eq (dom-tag row) 'tr))
1809 (setq max (max max (+ (shr-count row 'td)
1810 (shr-count row 'th))))))
1811 max))
1813 (provide 'shr)
1815 ;; Local Variables:
1816 ;; coding: utf-8
1817 ;; End:
1819 ;;; shr.el ends here