1 ;;; shr.el --- Simple HTML Renderer
3 ;; Copyright (C) 2010-2013 Free Software Foundation, Inc.
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
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/>.
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.
33 (eval-when-compile (require 'cl
))
34 (eval-when-compile (require 'url
)) ;For url-filename's setf handler.
38 "Simple HTML Renderer"
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
52 (defcustom shr-blocked-images nil
53 "Images that have URLs matching this regexp will be blocked."
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."
62 :type
'(choice (const nil
) character
))
64 (defcustom shr-table-vertical-line ?\s
65 "Character used to draw vertical table lines."
69 (defcustom shr-table-corner ?\s
70 "Character used to draw table corners."
74 (defcustom shr-hr-line ?-
75 "Character used to draw hr lines."
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
84 :type
'(choice (integer :tag
"Fixed width in characters")
85 (const :tag
"Use the width of the window" nil
))
88 (defcustom shr-bullet
"* "
89 "Bullet used for unordered lists.
90 Alternative suggestions are:
96 (defcustom shr-external-browser
'browse-url-default-browser
97 "Function used to launch an external browser."
102 (defvar shr-content-function nil
103 "If bound, this should be a function that will return the content.
104 This is used for cid: URLs, and the function is called with the
105 cid: URL as the argument.")
107 (defvar shr-put-image-function
'shr-put-image
108 "Function called to put image and alt string.")
110 (defface shr-strike-through
'((t (:strike-through t
)))
111 "Font for <s> elements."
115 '((t (:inherit link
)))
116 "Font for link elements."
119 ;;; Internal variables.
121 (defvar shr-folding-mode nil
)
122 (defvar shr-state nil
)
123 (defvar shr-start nil
)
124 (defvar shr-indentation
0)
125 (defvar shr-inhibit-images nil
)
126 (defvar shr-list-mode nil
)
127 (defvar shr-content-cache nil
)
128 (defvar shr-kinsoku-shorten nil
)
129 (defvar shr-table-depth
0)
130 (defvar shr-stylesheet nil
)
131 (defvar shr-base nil
)
132 (defvar shr-ignore-cache nil
)
133 (defvar shr-external-rendering-functions nil
)
134 (defvar shr-target-id nil
)
135 (defvar shr-inhibit-decoration nil
)
136 (defvar shr-table-separator-length
1)
139 (let ((map (make-sparse-keymap)))
140 (define-key map
"a" 'shr-show-alt-text
)
141 (define-key map
"i" 'shr-browse-image
)
142 (define-key map
"z" 'shr-zoom-image
)
143 (define-key map
[tab] 'shr-next-link)
144 (define-key map [backtab] 'shr-previous-link)
145 (define-key map [follow-link] 'mouse-face)
146 (define-key map [mouse-2] 'shr-browse-url)
147 (define-key map "I" 'shr-insert-image)
148 (define-key map "w" 'shr-copy-url)
149 (define-key map "u" 'shr-copy-url)
150 (define-key map "v" 'shr-browse-url)
151 (define-key map "o" 'shr-save-contents)
152 (define-key map "\r" 'shr-browse-url)
155 ;; Public functions and commands.
156 (declare-function libxml-parse-html-region "xml.c"
157 (start end &optional base-url))
159 (defun shr-render-buffer (buffer)
160 "Display the HTML rendering of the current buffer."
161 (interactive (list (current-buffer)))
162 (or (fboundp 'libxml-parse-html-region)
163 (error "This function requires Emacs to be compiled with libxml2"))
164 (pop-to-buffer "*html*")
167 (with-current-buffer buffer
168 (libxml-parse-html-region (point-min) (point-max))))
169 (goto-char (point-min)))
171 (defun shr-render-region (begin end &optional buffer)
172 "Display the HTML rendering of the region between BEGIN and END."
174 (unless (fboundp 'libxml-parse-html-region)
175 (error "This function requires Emacs to be compiled with libxml2"))
176 (with-current-buffer (or buffer (current-buffer))
177 (let ((dom (libxml-parse-html-region begin end)))
178 (delete-region begin end)
180 (shr-insert-document dom))))
182 (defun shr-visit-file (file)
183 "Parse FILE as an HTML document, and render it in a new buffer."
184 (interactive "fHTML file name: ")
186 (insert-file-contents file)
187 (shr-render-buffer (current-buffer))))
190 (defun shr-insert-document (dom)
191 "Render the parsed document DOM into the current buffer.
192 DOM should be a parse tree as generated by
193 `libxml-parse-html-region' or similar."
194 (setq shr-content-cache nil)
195 (let ((start (point))
199 (shr-preliminary-table-render 0)
200 (shr-width (or shr-width (1- (window-width)))))
201 (shr-descend (shr-transform-dom dom))
202 (shr-remove-trailing-whitespace start (point))))
204 (defun shr-remove-trailing-whitespace (start end)
205 (let ((width (window-width)))
207 (narrow-to-region start end)
211 (when (> (shr-previous-newline-padding-width (current-column)) width)
212 (dolist (overlay (overlays-at (point)))
213 (when (overlay-get overlay 'before-string)
214 (overlay-put overlay 'before-string nil))))
217 (defun shr-copy-url ()
218 "Copy the URL under point to the kill ring.
219 If called twice, then try to fetch the URL and see whether it
220 redirects somewhere else."
222 (let ((url (get-text-property (point) 'shr-url)))
225 (message "No URL under point"))
226 ;; Resolve redirected URLs.
227 ((equal url (car kill-ring))
232 (eq (car a) :redirect))
235 (goto-char (point-min))
236 ;; Remove common tracking junk from the URL.
237 (when (re-search-forward ".utm_.*" nil t)
238 (replace-match "" t t))
239 (message "Copied %s" (buffer-string))
240 (copy-region-as-kill (point-min) (point-max)))))
242 ;; Copy the URL to the kill ring.
246 (copy-region-as-kill (point-min) (point-max))
247 (message "Copied %s" url))))))
249 (defun shr-next-link ()
250 "Skip to the next link."
252 (let ((skip (text-property-any (point) (point-max) 'help-echo nil)))
253 (if (not (setq skip (text-property-not-all skip (point-max)
255 (message "No next link")
257 (message "%s" (get-text-property (point) 'help-echo)))))
259 (defun shr-previous-link ()
260 "Skip to the previous link."
262 (let ((start (point))
264 ;; Skip past the current link.
265 (while (and (not (bobp))
266 (get-text-property (point) 'help-echo))
268 ;; Find the previous link.
269 (while (and (not (bobp))
270 (not (setq found (get-text-property (point) 'help-echo))))
274 (message "No previous link")
276 ;; Put point at the start of the link.
277 (while (and (not (bobp))
278 (get-text-property (point) 'help-echo))
281 (message "%s" (get-text-property (point) 'help-echo)))))
283 (defun shr-show-alt-text ()
284 "Show the ALT text of the image under point."
286 (let ((text (get-text-property (point) 'shr-alt)))
288 (message "No image under point")
289 (message "%s" text))))
291 (defun shr-browse-image (&optional copy-url)
292 "Browse the image under point.
293 If COPY-URL (the prefix if called interactively) is non-nil, copy
294 the URL of the image to the kill buffer instead."
296 (let ((url (get-text-property (point) 'image-url)))
299 (message "No image under point"))
303 (copy-region-as-kill (point-min) (point-max))
304 (message "Copied %s" url)))
306 (message "Browsing %s..." url)
309 (defun shr-insert-image ()
310 "Insert the image under point into the buffer."
312 (let ((url (get-text-property (point) 'image-url)))
314 (message "No image under point")
315 (message "Inserting %s..." url)
316 (url-retrieve url 'shr-image-fetched
317 (list (current-buffer) (1- (point)) (point-marker))
320 (defun shr-zoom-image ()
321 "Toggle the image size.
322 The size will be rotated between the default size, the original
323 size, and full-buffer size."
325 (let ((url (get-text-property (point) 'image-url))
326 (size (get-text-property (point) 'image-size))
327 (buffer-read-only nil))
329 (message "No image under point")
330 ;; Delete the old picture.
331 (while (get-text-property (point) 'image-url)
334 (let ((start (point)))
335 (while (get-text-property (point) 'image-url)
338 (put-text-property start (point) 'display nil)
339 (when (> (- (point) start) 2)
340 (delete-region start (1- (point)))))
341 (message "Inserting %s..." url)
342 (url-retrieve url 'shr-image-fetched
343 (list (current-buffer) (1- (point)) (point-marker)
345 (cond ((or (eq size 'default)
354 ;;; Utility functions.
356 (defun shr-transform-dom (dom)
357 (let ((result (list (pop dom))))
358 (dolist (arg (pop dom))
359 (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
364 (push (cons 'text sub) result)
365 (push (shr-transform-dom sub) result)))
368 (defun shr-descend (dom)
371 ;; Allow other packages to override (or provide) rendering
373 (cdr (assq (car dom) shr-external-rendering-functions))
374 (intern (concat "shr-tag-" (symbol-name (car dom))) obarray)))
375 (style (cdr (assq :style (cdr dom))))
376 (shr-stylesheet shr-stylesheet)
379 (if (string-match "color\\|display\\|border-collapse" style)
380 (setq shr-stylesheet (nconc (shr-parse-style style)
383 ;; If we have a display:none, then just ignore this part of the
385 (unless (equal (cdr (assq 'display shr-stylesheet)) "none")
386 (if (fboundp function)
387 (funcall function (cdr dom))
388 (shr-generic (cdr dom)))
389 (when (and shr-target-id
390 (equal (cdr (assq :id (cdr dom))) shr-target-id))
391 (put-text-property start (1+ start) 'shr-target-id shr-target-id))
392 ;; If style is set, then this node has set the color.
394 (shr-colorize-region start (point)
395 (cdr (assq 'color shr-stylesheet))
396 (cdr (assq 'background-color shr-stylesheet)))))))
398 (defun shr-generic (cont)
401 ((eq (car sub) 'text)
402 (shr-insert (cdr sub)))
404 (shr-descend sub)))))
406 (defmacro shr-char-breakable-p (char)
407 "Return non-nil if a line can be broken before and after CHAR."
408 `(aref fill-find-break-point-function-table ,char))
409 (defmacro shr-char-nospace-p (char)
410 "Return non-nil if no space is required before and after CHAR."
411 `(aref fill-nospace-between-words-table ,char))
413 ;; KINSOKU is a Japanese word meaning a rule that should not be violated.
414 ;; In Emacs, it is a term used for characters, e.g. punctuation marks,
415 ;; parentheses, and so on, that should not be placed in the beginning
416 ;; of a line or the end of a line.
417 (defmacro shr-char-kinsoku-bol-p (char)
418 "Return non-nil if a line ought not to begin with CHAR."
419 `(aref (char-category-set ,char) ?>))
420 (defmacro shr-char-kinsoku-eol-p (char)
421 "Return non-nil if a line ought not to end with CHAR."
422 `(aref (char-category-set ,char) ?<))
423 (unless (shr-char-kinsoku-bol-p (make-char 'japanese-jisx0208 33 35))
424 (load "kinsoku" nil t))
426 (defun shr-insert (text)
427 (when (and (eq shr-state 'image)
429 (not (string-match "\\`[ \t\n]+\\'" text)))
431 (setq shr-state nil))
433 ((eq shr-folding-mode 'none)
436 (when (and (string-match "\\`[ \t\n ]" text)
438 (not (eq (char-after (1- (point))) ? )))
440 (dolist (elem (split-string text "[ \f\t\n\r\v ]+" t))
442 (> shr-indentation 0))
444 ;; No space is needed behind a wide character categorized as
445 ;; kinsoku-bol, between characters both categorized as nospace,
446 ;; or at the beginning of a line.
448 (when (and (> (current-column) shr-indentation)
449 (eq (preceding-char) ? )
450 (or (= (line-beginning-position) (1- (point)))
451 (and (shr-char-breakable-p
452 (setq prev (char-after (- (point) 2))))
453 (shr-char-kinsoku-bol-p prev))
454 (and (shr-char-nospace-p prev)
455 (shr-char-nospace-p (aref elem 0)))))
457 ;; The shr-start is a special variable that is used to pass
458 ;; upwards the first point in the buffer where the text really
461 (setq shr-start (point)))
465 (while (and (> (current-column) shr-width)
467 (setq found (shr-find-fill-point))
469 (when (eq (preceding-char) ? )
473 ;; No space is needed at the beginning of a line.
474 (when (eq (following-char) ? )
476 (when (> shr-indentation 0)
480 (unless (string-match "[ \t\r\n ]\\'" text)
483 (defun shr-find-fill-point ()
484 (when (> (move-to-column shr-width) shr-width)
488 (while (not (or (setq failed (= (current-column) shr-indentation))
489 (eq (preceding-char) ? )
490 (eq (following-char) ? )
491 (shr-char-breakable-p (preceding-char))
492 (shr-char-breakable-p (following-char))
493 (if (eq (preceding-char) ?')
494 (not (memq (char-after (- (point) 2))
496 (and (shr-char-kinsoku-bol-p (preceding-char))
497 (shr-char-breakable-p (following-char))
498 (not (shr-char-kinsoku-bol-p (following-char)))))
499 (shr-char-kinsoku-eol-p (following-char))))
501 (if (and (not (or failed (eolp)))
502 (eq (preceding-char) ?'))
503 (while (not (or (setq failed (eolp))
504 (eq (following-char) ? )
505 (shr-char-breakable-p (following-char))
506 (shr-char-kinsoku-eol-p (following-char))))
509 ;; There's no breakable point, so we give it up.
512 (unless shr-kinsoku-shorten
513 (while (and (setq found (re-search-forward
514 "\\(\\c>\\)\\| \\|\\c<\\|\\c|"
515 (line-end-position) 'move))
516 (eq (preceding-char) ?')))
517 (if (and found (not (match-beginning 1)))
518 (goto-char (match-beginning 0)))))
521 ;; Don't put kinsoku-bol characters at the beginning of a line,
522 ;; or kinsoku-eol characters at the end of a line.
525 (while (and (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
526 (shr-char-kinsoku-eol-p (preceding-char)))
528 (when (setq failed (= (current-column) shr-indentation))
529 ;; There's no breakable point that doesn't violate kinsoku,
530 ;; so we look for the second best position.
533 (<= (current-column) shr-width))
536 (shr-char-kinsoku-eol-p (following-char)))))
538 ((shr-char-kinsoku-eol-p (preceding-char))
539 ;; Find backward the point where kinsoku-eol characters begin.
544 (and (> (setq count (1- count)) 0)
545 (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
546 (or (shr-char-kinsoku-eol-p (preceding-char))
547 (shr-char-kinsoku-bol-p (following-char)))))))
548 (if (setq failed (= (current-column) shr-indentation))
549 ;; There's no breakable point that doesn't violate kinsoku,
550 ;; so we go to the second best position.
551 (if (looking-at "\\(\\c<+\\)\\c<")
552 (goto-char (match-end 1))
554 ((shr-char-kinsoku-bol-p (following-char))
555 ;; Find forward the point where kinsoku-bol characters end.
559 (and (>= (setq count (1- count)) 0)
560 (shr-char-kinsoku-bol-p (following-char))
561 (shr-char-breakable-p (following-char))))))))
562 (when (eq (following-char) ? )
566 (defun shr-parse-base (url)
567 ;; Always chop off anchors.
568 (when (string-match "#.*" url)
569 (setq url (substring url 0 (match-beginning 0))))
570 (let* ((parsed (url-generic-parse-url url))
571 (local (url-filename parsed)))
572 (setf (url-filename parsed) "")
573 ;; Chop off the bit after the last slash.
574 (when (string-match "\\`\\(.*/\\)[^/]+\\'" local)
575 (setq local (match-string 1 local)))
576 ;; Always make the local bit end with a slash.
577 (when (and (not (zerop (length local)))
578 (not (eq (aref local (1- (length local))) ?/)))
579 (setq local (concat local "/")))
580 (list (url-recreate-url parsed)
585 (defun shr-expand-url (url &optional base)
588 (shr-parse-base base)
589 ;; Bound by the parser.
591 (when (zerop (length url))
595 (string-match "\\`[a-z]*:" url))
598 ((eq (aref url 0) ?/)
599 (if (and (> (length url) 1)
600 (eq (aref url 1) ?/))
601 ;; //host...; just use the protocol
602 (concat (nth 2 base) ":" url)
603 ;; Just use the host name part.
604 (concat (car base) url)))
605 ((eq (aref url 0) ?#)
606 ;; A link to an anchor.
607 (concat (nth 3 base) url))
610 (concat (car base) (cadr base) url))))
612 (defun shr-ensure-newline ()
613 (unless (zerop (current-column))
616 (defun shr-ensure-paragraph ()
618 (if (<= (current-column) shr-indentation)
619 (unless (save-excursion
625 ;; If the current line is totally blank, and doesn't even
626 ;; have any face properties set, then delete the blank
628 (and (looking-at " *$")
629 (not (get-text-property (point) 'face))
630 (not (= (next-single-property-change (point) 'face nil
632 (line-end-position)))))
633 (delete-region (match-beginning 0) (match-end 0))
637 (when (> shr-indentation 0)
638 (insert (make-string shr-indentation ? ))))
640 (defun shr-fontize-cont (cont &rest types)
644 (shr-add-font (or shr-start (point)) (point) type))))
646 ;; Add face to the region, but avoid putting the font properties on
647 ;; blank text at the start of the line, and the newline at the end, to
649 (defun shr-add-font (start end type)
650 (unless shr-inhibit-decoration
653 (while (< (point) end)
655 (skip-chars-forward " "))
656 (add-face-text-property (point) (min (line-end-position) end) type t)
657 (if (< (line-end-position) end)
661 (defun shr-mouse-browse-url (ev)
662 "Browse the URL under the mouse cursor."
667 (defun shr-browse-url (&optional external mouse-event)
668 "Browse the URL under point.
669 If EXTERNAL, browse the URL using `shr-external-browser'."
670 (interactive (list current-prefix-arg last-nonmenu-event))
671 (mouse-set-point mouse-event)
672 (let ((url (get-text-property (point) 'shr-url)))
675 (message "No link under point"))
676 ((string-match "^mailto:" url)
677 (browse-url-mail url))
680 (funcall shr-external-browser url)
681 (browse-url url))))))
683 (defun shr-save-contents (directory)
684 "Save the contents from URL in a file."
685 (interactive "DSave contents of URL to directory: ")
686 (let ((url (get-text-property (point) 'shr-url)))
688 (message "No link under point")
689 (url-retrieve (shr-encode-url url)
690 'shr-store-contents (list url directory)
693 (defun shr-store-contents (status url directory)
694 (unless (plist-get status :error)
695 (when (or (search-forward "\n\n" nil t)
696 (search-forward "\r\n\r\n" nil t))
697 (write-region (point) (point-max)
698 (expand-file-name (file-name-nondirectory url)
701 (defun shr-image-fetched (status buffer start end &optional flags)
702 (let ((image-buffer (current-buffer)))
703 (when (and (buffer-name buffer)
704 (not (plist-get status :error)))
705 (url-store-in-cache image-buffer)
706 (when (or (search-forward "\n\n" nil t)
707 (search-forward "\r\n\r\n" nil t))
708 (let ((data (shr-parse-image-data)))
709 (with-current-buffer buffer
711 (let ((alt (buffer-substring start end))
712 (properties (text-properties-at start))
713 (inhibit-read-only t))
714 (delete-region start end)
716 (funcall shr-put-image-function data alt flags)
718 (let ((type (pop properties))
719 (value (pop properties)))
720 (unless (memq type '(display image-size))
721 (put-text-property start (point) type value))))))))))
722 (kill-buffer image-buffer)))
724 (defun shr-image-from-data (data)
725 "Return an image from the data: URI content DATA."
727 "\\(\\([^/;,]+\\(/[^;,]+\\)?\\)\\(;[^;,]+\\)*\\)?,\\(.*\\)"
729 (let ((param (match-string 4 data))
730 (payload (url-unhex-string (match-string 5 data))))
731 (when (string-match "^.*\\(;[ \t]*base64\\)$" param)
732 (setq payload (base64-decode-string payload)))
735 (defun shr-put-image (spec alt &optional flags)
736 "Insert image SPEC with a string ALT. Return image.
737 SPEC is either an image data blob, or a list where the first
738 element is the data blob and the second element is the content-type."
739 (if (display-graphic-p)
740 (let* ((size (cdr (assq 'size flags)))
741 (data (if (consp spec)
744 (content-type (and (consp spec)
749 (create-image data nil t :ascent 100
750 :format content-type))
753 (shr-rescale-image data t content-type)))
756 (shr-rescale-image data nil content-type))))))
758 ;; When inserting big-ish pictures, put them at the
759 ;; beginning of the line.
760 (when (and (> (current-column) 0)
761 (> (car (image-size image t)) 400))
763 (if (eq size 'original)
764 (insert-sliced-image image (or alt "*") nil 20 1)
765 (insert-image image (or alt "*")))
766 (put-text-property start (point) 'image-size size)
767 (when (cond ((fboundp 'image-multi-frame-p)
768 ;; Only animate multi-frame things that specify a
769 ;; delay; eg animated gifs as opposed to
770 ;; multi-page tiffs. FIXME?
771 (cdr (image-multi-frame-p image)))
772 ((fboundp 'image-animated-p)
773 (image-animated-p image)))
774 (image-animate image nil 60)))
778 (defun shr-rescale-image (data &optional force content-type)
779 "Rescale DATA, if too big, to fit the current buffer.
780 If FORCE, rescale the image anyway."
781 (if (or (not (fboundp 'imagemagick-types))
782 (not (get-buffer-window (current-buffer))))
783 (create-image data nil t :ascent 100)
784 (let ((edges (window-inside-pixel-edges
785 (get-buffer-window (current-buffer)))))
789 :max-width (truncate (* shr-max-image-proportion
790 (- (nth 2 edges) (nth 0 edges))))
791 :max-height (truncate (* shr-max-image-proportion
792 (- (nth 3 edges) (nth 1 edges))))
793 :format content-type))))
795 ;; url-cache-extract autoloads url-cache.
796 (declare-function url-cache-create-filename "url-cache" (url))
797 (autoload 'mm-disable-multibyte "mm-util")
798 (autoload 'browse-url-mail "browse-url")
800 (defun shr-get-image-data (url)
801 "Get image data for URL.
802 Return a string with image data."
804 (mm-disable-multibyte)
806 (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
808 (when (or (search-forward "\n\n" nil t)
809 (search-forward "\r\n\r\n" nil t))
810 (shr-parse-image-data)))))
812 (defun shr-parse-image-data ()
814 (buffer-substring (point) (point-max))
817 (narrow-to-region (point-min) (point))
818 (let ((content-type (mail-fetch-field "content-type")))
820 (intern content-type obarray)))))))
822 (defun shr-image-displayer (content-function)
823 "Return a function to display an image.
824 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
825 is an argument. The function to be returned takes three arguments URL,
826 START, and END. Note that START and END should be markers."
827 `(lambda (url start end)
829 (if (string-match "\\`cid:" url)
830 ,(when content-function
831 `(let ((image (funcall ,content-function
832 (substring url (match-end 0)))))
835 (funcall shr-put-image-function
836 image (buffer-substring start end))
837 (delete-region (point) end))))
838 (url-retrieve url 'shr-image-fetched
839 (list (current-buffer) start end)
842 (defun shr-heading (cont &rest types)
843 (shr-ensure-paragraph)
844 (apply #'shr-fontize-cont cont types)
845 (shr-ensure-paragraph))
847 (defun shr-urlify (start url &optional title)
848 (when (and title (string-match "ctx" title)) (debug))
849 (shr-add-font start (point) 'shr-link)
853 'help-echo (if title (format "%s (%s)" url title) url)
855 'mouse-face 'highlight
858 (defun shr-encode-url (url)
860 (browse-url-url-encode-chars url "[)$ ]"))
862 (autoload 'shr-color-visible "shr-color")
863 (autoload 'shr-color->hexadecimal "shr-color")
865 (defun shr-color-check (fg bg)
866 "Check that FG is visible on BG.
867 Returns (fg bg) with corrected values.
868 Returns nil if the colors that would be used are the default
869 ones, in case fg and bg are nil."
871 (let ((fixed (cond ((null fg) 'fg)
873 ;; Convert colors to hexadecimal, or set them to default.
874 (let ((fg (or (shr-color->hexadecimal fg)
875 (frame-parameter nil 'foreground-color)))
876 (bg (or (shr-color->hexadecimal bg)
877 (frame-parameter nil 'background-color))))
878 (cond ((eq fixed 'bg)
879 ;; Only return the new fg
880 (list nil (cadr (shr-color-visible bg fg t))))
882 ;; Invert args and results and return only the new bg
883 (list (cadr (shr-color-visible fg bg t)) nil))
885 (shr-color-visible bg fg)))))))
887 (defun shr-colorize-region (start end fg &optional bg)
888 (when (and (not shr-inhibit-decoration)
890 (let ((new-colors (shr-color-check fg bg)))
893 (add-face-text-property start end
894 (list :foreground (cadr new-colors))
897 (add-face-text-property start end
898 (list :background (car new-colors))
902 (defun shr-expand-newlines (start end color)
904 ;; Skip past all white space at the start and ends.
906 (skip-chars-forward " \t\n")
910 (skip-chars-backward " \t\n")
913 (narrow-to-region start end)
914 (let ((width (shr-buffer-width))
916 (goto-char (point-min))
919 (when (and (< (setq column (current-column)) width)
920 (< (setq column (shr-previous-newline-padding-width column))
922 (let ((overlay (make-overlay (point) (1+ (point)))))
923 (overlay-put overlay 'before-string
927 (let ((string (plist-get
928 (overlay-properties overlay)
932 (overlay-put overlay 'before-string "")
934 (overlays-at (point))
936 (propertize (make-string (- width column) ? )
937 'face (list :background color))))))
940 (defun shr-previous-newline-padding-width (width)
941 (let ((overlays (overlays-at (point)))
945 (dolist (overlay overlays)
948 (length (plist-get (overlay-properties overlay)
950 (+ width previous-width))))
952 ;;; Tag-specific rendering rules.
954 (defun shr-tag-body (cont)
955 (let* ((start (point))
956 (fgcolor (cdr (or (assq :fgcolor cont)
958 (bgcolor (cdr (assq :bgcolor cont)))
959 (shr-stylesheet (list (cons 'color fgcolor)
960 (cons 'background-color bgcolor))))
962 (shr-colorize-region start (point) fgcolor bgcolor)))
964 (defun shr-tag-style (cont)
967 (defun shr-tag-script (cont)
970 (defun shr-tag-comment (cont)
973 (defun shr-dom-to-xml (dom)
974 "Convert DOM into a string containing the xml representation."
977 (dolist (sub (cdr dom))
980 (setq text (concat text (shr-dom-to-xml sub))))
981 ((eq (car sub) 'text)
982 (setq text (concat text (cdr sub))))
984 (setq arg (concat arg (format "%s=\"%s\" "
985 (substring (symbol-name (car sub)) 1)
987 (format "<%s%s>%s</%s>"
989 (substring arg 0 (1- (length arg)))
993 (defun shr-tag-svg (cont)
994 (when (image-type-available-p 'svg)
995 (funcall shr-put-image-function
996 (shr-dom-to-xml (cons 'svg cont))
999 (defun shr-tag-sup (cont)
1000 (let ((start (point)))
1002 (put-text-property start (point) 'display '(raise 0.5))))
1004 (defun shr-tag-sub (cont)
1005 (let ((start (point)))
1007 (put-text-property start (point) 'display '(raise -0.5))))
1009 (defun shr-tag-label (cont)
1011 (shr-ensure-paragraph))
1013 (defun shr-tag-p (cont)
1014 (shr-ensure-paragraph)
1017 (shr-ensure-paragraph))
1019 (defun shr-tag-div (cont)
1020 (shr-ensure-newline)
1023 (shr-ensure-newline))
1025 (defun shr-tag-s (cont)
1026 (shr-fontize-cont cont 'shr-strike-through))
1028 (defun shr-tag-del (cont)
1029 (shr-fontize-cont cont 'shr-strike-through))
1031 (defun shr-tag-b (cont)
1032 (shr-fontize-cont cont 'bold))
1034 (defun shr-tag-i (cont)
1035 (shr-fontize-cont cont 'italic))
1037 (defun shr-tag-em (cont)
1038 (shr-fontize-cont cont 'italic))
1040 (defun shr-tag-strong (cont)
1041 (shr-fontize-cont cont 'bold))
1043 (defun shr-tag-u (cont)
1044 (shr-fontize-cont cont 'underline))
1046 (defun shr-parse-style (style)
1049 (when (string-match "\n" style)
1050 (setq style (replace-match " " t t style))))
1052 (dolist (elem (split-string style ";"))
1054 (setq elem (split-string elem ":"))
1055 (when (and (car elem)
1057 (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
1058 (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
1059 (when (string-match " *!important\\'" value)
1060 (setq value (substring value 0 (match-beginning 0))))
1061 (push (cons (intern name obarray)
1066 (defun shr-tag-base (cont)
1067 (let ((base (cdr (assq :href cont))))
1069 (setq shr-base (shr-parse-base base))))
1072 (defun shr-tag-a (cont)
1073 (let ((url (cdr (assq :href cont)))
1074 (title (cdr (assq :title cont)))
1079 (not shr-inhibit-decoration))
1080 (shr-urlify (or shr-start start) (shr-expand-url url) title))))
1082 (defun shr-tag-object (cont)
1083 (let ((start (point))
1086 (when (eq (car elem) 'embed)
1087 (setq url (or url (cdr (assq :src (cdr elem))))))
1088 (when (and (eq (car elem) 'param)
1089 (equal (cdr (assq :name (cdr elem))) "movie"))
1090 (setq url (or url (cdr (assq :value (cdr elem)))))))
1092 (shr-insert " [multimedia] ")
1093 (shr-urlify start (shr-expand-url url)))
1094 (shr-generic cont)))
1096 (defun shr-tag-video (cont)
1097 (let ((image (cdr (assq :poster cont)))
1098 (url (cdr (assq :src cont)))
1100 (shr-tag-img nil image)
1101 (shr-urlify start (shr-expand-url url))))
1103 (defun shr-tag-img (cont &optional url)
1106 (cdr (assq :src cont))))
1107 (when (and (> (current-column) 0)
1108 (not (eq shr-state 'image)))
1110 (let ((alt (cdr (assq :alt cont)))
1111 (url (shr-expand-url (or url (cdr (assq :src cont))))))
1112 (let ((start (point-marker)))
1113 (when (zerop (length alt))
1116 ((or (member (cdr (assq :height cont)) '("0" "1"))
1117 (member (cdr (assq :width cont)) '("0" "1")))
1118 ;; Ignore zero-sized or single-pixel images.
1120 ((and (not shr-inhibit-images)
1121 (string-match "\\`data:" url))
1122 (let ((image (shr-image-from-data (substring url (match-end 0)))))
1124 (funcall shr-put-image-function image alt)
1126 ((and (not shr-inhibit-images)
1127 (string-match "\\`cid:" url))
1128 (let ((url (substring url (match-end 0)))
1130 (if (or (not shr-content-function)
1131 (not (setq image (funcall shr-content-function url))))
1133 (funcall shr-put-image-function image alt))))
1134 ((or shr-inhibit-images
1135 (and shr-blocked-images
1136 (string-match shr-blocked-images url)))
1137 (setq shr-start (point))
1138 (let ((shr-state 'space))
1139 (if (> (string-width alt) 8)
1140 (shr-insert (truncate-string-to-width alt 8))
1142 ((and (not shr-ignore-cache)
1143 (url-is-cached (shr-encode-url url)))
1144 (funcall shr-put-image-function (shr-get-image-data url) alt))
1147 (when (and shr-ignore-cache
1148 (url-is-cached (shr-encode-url url)))
1149 (let ((file (url-cache-create-filename (shr-encode-url url))))
1150 (when (file-exists-p file)
1151 (delete-file file))))
1153 (shr-encode-url url) 'shr-image-fetched
1154 (list (current-buffer) start (set-marker (make-marker) (1- (point))))
1156 (when (zerop shr-table-depth) ;; We are not in a table.
1157 (put-text-property start (point) 'keymap shr-map)
1158 (put-text-property start (point) 'shr-alt alt)
1159 (put-text-property start (point) 'image-url url)
1160 (put-text-property start (point) 'image-displayer
1161 (shr-image-displayer shr-content-function))
1162 (put-text-property start (point) 'help-echo alt))
1163 (setq shr-state 'image)))))
1165 (defun shr-tag-pre (cont)
1166 (let ((shr-folding-mode 'none))
1167 (shr-ensure-newline)
1170 (shr-ensure-newline)))
1172 (defun shr-tag-blockquote (cont)
1173 (shr-ensure-paragraph)
1175 (let ((shr-indentation (+ shr-indentation 4)))
1177 (shr-ensure-paragraph))
1179 (defun shr-tag-dl (cont)
1180 (shr-ensure-paragraph)
1182 (shr-ensure-paragraph))
1184 (defun shr-tag-dt (cont)
1185 (shr-ensure-newline)
1187 (shr-ensure-newline))
1189 (defun shr-tag-dd (cont)
1190 (shr-ensure-newline)
1191 (let ((shr-indentation (+ shr-indentation 4)))
1192 (shr-generic cont)))
1194 (defun shr-tag-ul (cont)
1195 (shr-ensure-paragraph)
1196 (let ((shr-list-mode 'ul))
1198 (shr-ensure-paragraph))
1200 (defun shr-tag-ol (cont)
1201 (shr-ensure-paragraph)
1202 (let ((shr-list-mode 1))
1204 (shr-ensure-paragraph))
1206 (defun shr-tag-li (cont)
1207 (shr-ensure-newline)
1210 (if (numberp shr-list-mode)
1212 (format "%d " shr-list-mode)
1213 (setq shr-list-mode (1+ shr-list-mode)))
1215 (shr-indentation (+ shr-indentation (length bullet))))
1217 (shr-generic cont)))
1219 (defun shr-tag-br (cont)
1220 (when (and (not (bobp))
1221 ;; Only add a newline if we break the current line, or
1222 ;; the previous line isn't a blank line.
1224 (and (> (- (point) 2) (point-min))
1225 (not (= (char-after (- (point) 2)) ?\n)))))
1230 (defun shr-tag-span (cont)
1233 (defun shr-tag-h1 (cont)
1234 (shr-heading cont 'bold 'underline))
1236 (defun shr-tag-h2 (cont)
1237 (shr-heading cont 'bold))
1239 (defun shr-tag-h3 (cont)
1240 (shr-heading cont 'italic))
1242 (defun shr-tag-h4 (cont)
1245 (defun shr-tag-h5 (cont)
1248 (defun shr-tag-h6 (cont)
1251 (defun shr-tag-hr (cont)
1252 (shr-ensure-newline)
1253 (insert (make-string shr-width shr-hr-line) "\n"))
1255 (defun shr-tag-title (cont)
1256 (shr-heading cont 'bold 'underline))
1258 (defun shr-tag-font (cont)
1259 (let* ((start (point))
1260 (color (cdr (assq :color cont)))
1261 (shr-stylesheet (nconc (list (cons 'color color))
1265 (shr-colorize-region start (point) color
1266 (cdr (assq 'background-color shr-stylesheet))))))
1268 ;;; Table rendering algorithm.
1270 ;; Table rendering is the only complicated thing here. We do this by
1271 ;; first counting how many TDs there are in each TR, and registering
1272 ;; how wide they think they should be ("width=45%", etc). Then we
1273 ;; render each TD separately (this is done in temporary buffers, so
1274 ;; that we can use all the rendering machinery as if we were in the
1275 ;; main buffer). Now we know how much space each TD really takes, so
1276 ;; we then render everything again with the new widths, and finally
1277 ;; insert all these boxes into the main buffer.
1278 (defun shr-tag-table-1 (cont)
1279 (setq cont (or (cdr (assq 'tbody cont))
1281 (let* ((shr-inhibit-images t)
1282 (shr-table-depth (1+ shr-table-depth))
1283 (shr-kinsoku-shorten t)
1284 ;; Find all suggested widths.
1285 (columns (shr-column-specs cont))
1286 ;; Compute how many characters wide each TD should be.
1287 (suggested-widths (shr-pro-rate-columns columns))
1288 ;; Do a "test rendering" to see how big each TD is (this can
1289 ;; be smaller (if there's little text) or bigger (if there's
1290 ;; unbreakable text).
1291 (sketch (shr-make-table cont suggested-widths))
1292 ;; Compute the "natural" width by setting each column to 500
1293 ;; characters and see how wide they really render.
1294 (natural (shr-make-table cont (make-vector (length columns) 500)))
1295 (sketch-widths (shr-table-widths sketch natural suggested-widths)))
1296 ;; This probably won't work very well.
1297 (when (> (+ (loop for width across sketch-widths
1301 (setq truncate-lines t))
1302 ;; Then render the table again with these new "hard" widths.
1303 (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths)))
1305 (defun shr-tag-table (cont)
1306 (shr-ensure-paragraph)
1307 (let* ((caption (cdr (assq 'caption cont)))
1308 (header (cdr (assq 'thead cont)))
1309 (body (or (cdr (assq 'tbody cont)) cont))
1310 (footer (cdr (assq 'tfoot cont)))
1311 (bgcolor (cdr (assq :bgcolor cont)))
1313 (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
1315 (nheader (if header (shr-max-columns header)))
1316 (nbody (if body (shr-max-columns body)))
1317 (nfooter (if footer (shr-max-columns footer))))
1318 (if (and (not caption)
1320 (not (cdr (assq 'tbody cont)))
1321 (not (cdr (assq 'tr cont)))
1323 ;; The table is totally invalid and just contains random junk.
1324 ;; Try to output it anyway.
1326 ;; It's a real table, so render it.
1329 (if caption `((tr (td ,@caption))))
1332 ;; hader + body + footer
1333 (if (= nheader nbody)
1334 (if (= nbody nfooter)
1335 `((tr (td (table (tbody ,@header ,@body ,@footer)))))
1336 (nconc `((tr (td (table (tbody ,@header ,@body)))))
1339 `((tr (td (table (tbody ,@footer))))))))
1340 (nconc `((tr (td (table (tbody ,@header)))))
1341 (if (= nbody nfooter)
1342 `((tr (td (table (tbody ,@body ,@footer)))))
1343 (nconc `((tr (td (table (tbody ,@body)))))
1346 `((tr (td (table (tbody ,@footer))))))))))
1348 (if (= nheader nbody)
1349 `((tr (td (table (tbody ,@header ,@body)))))
1351 `(,@header (tr (td (table (tbody ,@body)))))
1352 `((tr (td (table (tbody ,@header))))
1353 (tr (td (table (tbody ,@body))))))))
1356 (if (= nbody nfooter)
1357 `((tr (td (table (tbody ,@body ,@footer)))))
1358 (nconc `((tr (td (table (tbody ,@body)))))
1361 `((tr (td (table (tbody ,@footer))))))))
1363 `((tr (td (table (tbody ,@body)))))
1366 (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
1368 ;; Finally, insert all the images after the table. The Emacs buffer
1369 ;; model isn't strong enough to allow us to put the images actually
1371 (when (zerop shr-table-depth)
1372 (dolist (elem (shr-find-elements cont 'img))
1373 (shr-tag-img (cdr elem))))))
1375 (defun shr-find-elements (cont type)
1378 (cond ((eq (car elem) type)
1381 (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
1384 (defun shr-insert-table (table widths)
1385 (let* ((collapse (equal (cdr (assq 'border-collapse shr-stylesheet))
1387 (shr-table-separator-length (if collapse 0 1))
1388 (shr-table-vertical-line (if collapse "" shr-table-vertical-line)))
1390 (shr-insert-table-ruler widths))
1392 (let ((start (point))
1393 (height (let ((max 0))
1394 (dolist (column row)
1395 (setq max (max max (cadr column))))
1399 (insert shr-table-vertical-line "\n"))
1400 (dolist (column row)
1402 (let ((lines (nth 2 column)))
1403 (dolist (line lines)
1405 (insert line shr-table-vertical-line)
1407 ;; Add blank lines at padding at the bottom of the TD,
1409 (dotimes (i (- height (length lines)))
1411 (let ((start (point)))
1412 (insert (make-string (string-width (car lines)) ? )
1413 shr-table-vertical-line)
1414 (when (nth 4 column)
1415 (shr-add-font start (1- (point))
1416 (list :background (nth 4 column)))))
1417 (forward-line 1)))))
1419 (shr-insert-table-ruler widths)))))
1421 (defun shr-insert-table-ruler (widths)
1422 (when shr-table-horizontal-line
1424 (> shr-indentation 0))
1426 (insert shr-table-corner)
1427 (dotimes (i (length widths))
1428 (insert (make-string (aref widths i) shr-table-horizontal-line)
1432 (defun shr-table-widths (table natural-table suggested-widths)
1433 (let* ((length (length suggested-widths))
1434 (widths (make-vector length 0))
1435 (natural-widths (make-vector length 0)))
1438 (dolist (column row)
1439 (aset widths i (max (aref widths i) column))
1441 (dolist (row natural-table)
1443 (dolist (column row)
1444 (aset natural-widths i (max (aref natural-widths i) column))
1446 (let ((extra (- (apply '+ (append suggested-widths nil))
1447 (apply '+ (append widths nil))))
1448 (expanded-columns 0))
1449 ;; We have extra, unused space, so divide this space amongst the
1452 ;; If the natural width is wider than the rendered width, we
1453 ;; want to allow the column to expand.
1455 (when (> (aref natural-widths i) (aref widths i))
1456 (setq expanded-columns (1+ expanded-columns))))
1458 (when (> (aref natural-widths i) (aref widths i))
1460 (aref natural-widths i)
1461 (+ (/ extra expanded-columns)
1462 (aref widths i))))))))
1465 (defun shr-make-table (cont widths &optional fill)
1466 (or (cadr (assoc (list cont widths fill) shr-content-cache))
1467 (let ((data (shr-make-table-1 cont widths fill)))
1468 (push (list (list cont widths fill) data)
1472 (defun shr-make-table-1 (cont widths &optional fill)
1474 (shr-inhibit-decoration (not fill))
1475 (rowspans (make-vector (length widths) 0))
1478 (when (eq (car row) 'tr)
1484 (while (< i (length widths))
1485 ;; If we previously had a rowspan definition, then that
1486 ;; means that we now have a "missing" td/th element here.
1487 ;; So just insert a dummy, empty one to (sort of) emulate
1490 (if (zerop (aref rowspans i))
1492 (aset rowspans i (1- (aref rowspans i)))
1494 (when (or (memq (car column) '(td th))
1496 (when (cdr (assq :rowspan (cdr column)))
1497 (aset rowspans i (+ (aref rowspans i)
1498 (1- (string-to-number
1499 (cdr (assq :rowspan (cdr column))))))))
1500 ;; Sanity check for invalid column-spans.
1501 (when (>= width-column (length widths))
1502 (setq width-column 0))
1505 (aref widths width-column)
1508 (setq colspan (cdr (assq :colspan (cdr column)))))
1509 (setq colspan (min (string-to-number colspan)
1510 ;; The colspan may be wrong, so
1511 ;; truncate it to the length of the
1512 ;; remaining columns.
1513 (- (length widths) i)))
1514 (dotimes (j (1- colspan))
1515 (if (> (+ i 1 j) (1- (length widths)))
1516 (setq width (aref widths (1- (length widths))))
1517 (setq width (+ width
1518 shr-table-separator-length
1519 (aref widths (+ i 1 j))))))
1520 (setq width-column (+ width-column (1- colspan))))
1523 (push (shr-render-td (cdr column) width fill)
1526 width-column (1+ width-column))))
1527 (push (nreverse tds) trs))))
1530 (defun shr-render-td (cont width fill)
1532 (let ((bgcolor (cdr (assq :bgcolor cont)))
1533 (fgcolor (cdr (assq :fgcolor cont)))
1534 (style (cdr (assq :style cont)))
1535 (shr-stylesheet shr-stylesheet)
1538 (setq style (and (string-match "color" style)
1539 (shr-parse-style style))))
1541 (setq style (nconc (list (cons 'background-color bgcolor)) style)))
1543 (setq style (nconc (list (cons 'color fgcolor)) style)))
1545 (setq shr-stylesheet (append style shr-stylesheet)))
1546 (let ((shr-width width)
1547 (shr-indentation 0))
1548 (shr-descend (cons 'td cont)))
1549 ;; Delete padding at the bottom of the TDs.
1553 (skip-chars-backward " \t\n")
1556 (goto-char (point-min))
1560 (setq max (max max (current-column)))
1563 (goto-char (point-min))
1564 ;; If the buffer is totally empty, then put a single blank
1566 (if (zerop (buffer-size))
1567 (insert (make-string width ? ))
1568 ;; Otherwise, fill the buffer.
1569 (let ((align (cdr (assq :align cont)))
1573 (setq length (- width (current-column)))
1576 ((equal align "right")
1578 (insert (make-string length ? )))
1579 ((equal align "center")
1580 (insert (make-string (/ length 2) ? ))
1582 (insert (make-string (- length (/ length 2)) ? )))
1584 (insert (make-string length ? )))))
1588 (shr-colorize-region
1589 (point-min) (point-max)
1590 (cdr (assq 'color shr-stylesheet))
1591 (cdr (assq 'background-color shr-stylesheet))))))
1594 (count-lines (point-min) (point-max))
1595 (split-string (buffer-string) "\n")
1597 (car actual-colors))
1600 (defun shr-buffer-width ()
1601 (goto-char (point-min))
1605 (setq max (max max (current-column)))
1609 (defun shr-pro-rate-columns (columns)
1610 (let ((total-percentage 0)
1611 (widths (make-vector (length columns) 0)))
1612 (dotimes (i (length columns))
1613 (setq total-percentage (+ total-percentage (aref columns i))))
1614 (setq total-percentage (/ 1.0 total-percentage))
1615 (dotimes (i (length columns))
1616 (aset widths i (max (truncate (* (aref columns i)
1618 (- shr-width (1+ (length columns)))))
1622 ;; Return a summary of the number and shape of the TDs in the table.
1623 (defun shr-column-specs (cont)
1624 (let ((columns (make-vector (shr-max-columns cont) 1)))
1626 (when (eq (car row) 'tr)
1628 (dolist (column (cdr row))
1629 (when (memq (car column) '(td th))
1630 (let ((width (cdr (assq :width (cdr column)))))
1632 (string-match "\\([0-9]+\\)%" width)
1633 (not (zerop (setq width (string-to-number
1634 (match-string 1 width))))))
1635 (aset columns i (/ width 100.0))))
1636 (setq i (1+ i)))))))
1639 (defun shr-count (cont elem)
1642 (when (eq (car sub) elem)
1646 (defun shr-max-columns (cont)
1649 (when (eq (car row) 'tr)
1650 (setq max (max max (+ (shr-count (cdr row) 'td)
1651 (shr-count (cdr row) 'th))))))
1660 ;;; shr.el ends here