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