1 ;;; shr.el --- Simple HTML Renderer
3 ;; Copyright (C) 2010-2011 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))
37 "Simple HTML Renderer"
40 (defcustom shr-max-image-proportion 0.9
41 "How big pictures displayed are in relation to the window they're in.
42 A value of 0.7 means that they are allowed to take up 70% of the
43 width and height of the window. If they are larger than this,
44 and Emacs supports it, then the images will be rescaled down to
50 (defcustom shr-blocked-images nil
51 "Images that have URLs matching this regexp will be blocked."
56 (defcustom shr-table-horizontal-line ?
57 "Character used to draw horizontal table lines."
61 (defcustom shr-table-vertical-line ?
62 "Character used to draw vertical table lines."
66 (defcustom shr-table-corner ?
67 "Character used to draw table corners."
71 (defcustom shr-hr-line ?-
72 "Character used to draw hr lines."
76 (defcustom shr-width fill-column
77 "Frame width to use for rendering.
78 May either be an integer specifying a fixed width in characters,
79 or nil, meaning that the full width of the window should be
81 :type '(choice (integer :tag "Fixed width in characters")
82 (const :tag "Use the width of the window" nil))
85 (defvar shr-content-function nil
86 "If bound, this should be a function that will return the content.
87 This is used for cid: URLs, and the function is called with the
88 cid: URL as the argument.")
90 (defvar shr-put-image-function 'shr-put-image
91 "Function called to put image and alt string.")
93 (defface shr-strike-through '((t (:strike-through t)))
94 "Font for <s> elements."
98 '((t (:inherit link)))
99 "Font for link elements."
102 ;;; Internal variables.
104 (defvar shr-folding-mode nil)
105 (defvar shr-state nil)
106 (defvar shr-start nil)
107 (defvar shr-indentation 0)
108 (defvar shr-inhibit-images nil)
109 (defvar shr-list-mode nil)
110 (defvar shr-content-cache nil)
111 (defvar shr-kinsoku-shorten nil)
112 (defvar shr-table-depth 0)
113 (defvar shr-stylesheet nil)
114 (defvar shr-base nil)
117 (let ((map (make-sparse-keymap)))
118 (define-key map "a" 'shr-show-alt-text)
119 (define-key map "i" 'shr-browse-image)
120 (define-key map "I" 'shr-insert-image)
121 (define-key map "u" 'shr-copy-url)
122 (define-key map "v" 'shr-browse-url)
123 (define-key map "o" 'shr-save-contents)
124 (define-key map "\r" 'shr-browse-url)
127 ;; Public functions and commands.
129 (defun shr-visit-file (file)
130 (interactive "fHTML file name: ")
131 (pop-to-buffer "*html*")
135 (insert-file-contents file)
136 (libxml-parse-html-region (point-min) (point-max)))))
139 (defun shr-insert-document (dom)
140 (setq shr-content-cache nil)
141 (let ((shr-state nil)
144 (shr-width (or shr-width (window-width))))
145 (shr-descend (shr-transform-dom dom))))
147 (defun shr-copy-url ()
148 "Copy the URL under point to the kill ring.
149 If called twice, then try to fetch the URL and see whether it
150 redirects somewhere else."
152 (let ((url (get-text-property (point) 'shr-url)))
155 (message "No URL under point"))
156 ;; Resolve redirected URLs.
157 ((equal url (car kill-ring))
162 (eq (car a) :redirect))
165 (goto-char (point-min))
166 ;; Remove common tracking junk from the URL.
167 (when (re-search-forward ".utm_.*" nil t)
168 (replace-match "" t t))
169 (message "Copied %s" (buffer-string))
170 (copy-region-as-kill (point-min) (point-max)))))))
171 ;; Copy the URL to the kill ring.
175 (copy-region-as-kill (point-min) (point-max))
176 (message "Copied %s" url))))))
178 (defun shr-show-alt-text ()
179 "Show the ALT text of the image under point."
181 (let ((text (get-text-property (point) 'shr-alt)))
183 (message "No image under point")
184 (message "%s" text))))
186 (defun shr-browse-image (&optional copy-url)
187 "Browse the image under point.
188 If COPY-URL (the prefix if called interactively) is non-nil, copy
189 the URL of the image to the kill buffer instead."
191 (let ((url (get-text-property (point) 'image-url)))
194 (message "No image under point"))
198 (copy-region-as-kill (point-min) (point-max))
199 (message "Copied %s" url)))
201 (message "Browsing %s..." url)
204 (defun shr-insert-image ()
205 "Insert the image under point into the buffer."
207 (let ((url (get-text-property (point) 'image-url)))
209 (message "No image under point")
210 (message "Inserting %s..." url)
211 (url-retrieve url 'shr-image-fetched
212 (list (current-buffer) (1- (point)) (point-marker))
215 ;;; Utility functions.
217 (defun shr-transform-dom (dom)
218 (let ((result (list (pop dom))))
219 (dolist (arg (pop dom))
220 (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
225 (push (cons 'text sub) result)
226 (push (shr-transform-dom sub) result)))
229 (defun shr-descend (dom)
230 (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray))
231 (style (cdr (assq :style (cdr dom))))
232 (shr-stylesheet shr-stylesheet)
235 (if (string-match "color" style)
236 (setq shr-stylesheet (nconc (shr-parse-style style)
239 (if (fboundp function)
240 (funcall function (cdr dom))
241 (shr-generic (cdr dom)))
242 ;; If style is set, then this node has set the color.
244 (shr-colorize-region start (point)
245 (cdr (assq 'color shr-stylesheet))
246 (cdr (assq 'background-color shr-stylesheet))))))
248 (defun shr-generic (cont)
251 ((eq (car sub) 'text)
252 (shr-insert (cdr sub)))
254 (shr-descend sub)))))
256 (defmacro shr-char-breakable-p (char)
257 "Return non-nil if a line can be broken before and after CHAR."
258 `(aref fill-find-break-point-function-table ,char))
259 (defmacro shr-char-nospace-p (char)
260 "Return non-nil if no space is required before and after CHAR."
261 `(aref fill-nospace-between-words-table ,char))
263 ;; KINSOKU is a Japanese word meaning a rule that should not be violated.
264 ;; In Emacs, it is a term used for characters, e.g. punctuation marks,
265 ;; parentheses, and so on, that should not be placed in the beginning
266 ;; of a line or the end of a line.
267 (defmacro shr-char-kinsoku-bol-p (char)
268 "Return non-nil if a line ought not to begin with CHAR."
269 `(aref (char-category-set ,char) ?>))
270 (defmacro shr-char-kinsoku-eol-p (char)
271 "Return non-nil if a line ought not to end with CHAR."
272 `(aref (char-category-set ,char) ?<))
273 (unless (shr-char-kinsoku-bol-p (make-char 'japanese-jisx0208 33 35))
274 (load "kinsoku" nil t))
276 (defun shr-insert (text)
277 (when (and (eq shr-state 'image)
278 (not (string-match "\\`[ \t\n]+\\'" text)))
280 (setq shr-state nil))
282 ((eq shr-folding-mode 'none)
285 (when (and (string-match "\\`[ \t\n]" text)
287 (not (eq (char-after (1- (point))) ? )))
289 (dolist (elem (split-string text))
291 (> shr-indentation 0))
293 ;; No space is needed behind a wide character categorized as
294 ;; kinsoku-bol, between characters both categorized as nospace,
295 ;; or at the beginning of a line.
297 (when (and (> (current-column) shr-indentation)
298 (eq (preceding-char) ? )
299 (or (= (line-beginning-position) (1- (point)))
300 (and (shr-char-breakable-p
301 (setq prev (char-after (- (point) 2))))
302 (shr-char-kinsoku-bol-p prev))
303 (and (shr-char-nospace-p prev)
304 (shr-char-nospace-p (aref elem 0)))))
306 ;; The shr-start is a special variable that is used to pass
307 ;; upwards the first point in the buffer where the text really
310 (setq shr-start (point)))
313 (while (and (> (current-column) shr-width)
315 (setq found (shr-find-fill-point))
317 (when (eq (preceding-char) ? )
321 (put-text-property (1- (point)) (point) 'shr-break t)
322 ;; No space is needed at the beginning of a line.
323 (when (eq (following-char) ? )
325 (when (> shr-indentation 0)
329 (unless (string-match "[ \t\n]\\'" text)
332 (defun shr-find-fill-point ()
333 (when (> (move-to-column shr-width) shr-width)
337 (while (not (or (setq failed (= (current-column) shr-indentation))
338 (eq (preceding-char) ? )
339 (eq (following-char) ? )
340 (shr-char-breakable-p (preceding-char))
341 (shr-char-breakable-p (following-char))
342 (if (eq (preceding-char) ?')
343 (not (memq (char-after (- (point) 2))
345 (and (shr-char-kinsoku-bol-p (preceding-char))
346 (shr-char-breakable-p (following-char))
347 (not (shr-char-kinsoku-bol-p (following-char)))))
348 (shr-char-kinsoku-eol-p (following-char))))
350 (if (and (not (or failed (eolp)))
351 (eq (preceding-char) ?'))
352 (while (not (or (setq failed (eolp))
353 (eq (following-char) ? )
354 (shr-char-breakable-p (following-char))
355 (shr-char-kinsoku-eol-p (following-char))))
358 ;; There's no breakable point, so we give it up.
361 (unless shr-kinsoku-shorten
362 (while (and (setq found (re-search-forward
363 "\\(\\c>\\)\\| \\|\\c<\\|\\c|"
364 (line-end-position) 'move))
365 (eq (preceding-char) ?')))
366 (if (and found (not (match-beginning 1)))
367 (goto-char (match-beginning 0)))))
370 ;; Don't put kinsoku-bol characters at the beginning of a line,
371 ;; or kinsoku-eol characters at the end of a line.
374 (while (and (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
375 (shr-char-kinsoku-eol-p (preceding-char)))
377 (when (setq failed (= (current-column) shr-indentation))
378 ;; There's no breakable point that doesn't violate kinsoku,
379 ;; so we look for the second best position.
382 (<= (current-column) shr-width))
385 (shr-char-kinsoku-eol-p (following-char)))))
387 ((shr-char-kinsoku-eol-p (preceding-char))
388 (if (shr-char-kinsoku-eol-p (following-char))
389 ;; There are consecutive kinsoku-eol characters.
395 (and (> (setq count (1- count)) 0)
396 (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
397 (or (shr-char-kinsoku-eol-p (preceding-char))
398 (shr-char-kinsoku-bol-p (following-char)))))))
399 (if (setq failed (= (current-column) shr-indentation))
400 ;; There's no breakable point that doesn't violate kinsoku,
401 ;; so we go to the second best position.
402 (if (looking-at "\\(\\c<+\\)\\c<")
403 (goto-char (match-end 1))
406 (if (shr-char-kinsoku-bol-p (preceding-char))
407 ;; There are consecutive kinsoku-bol characters.
410 (while (and (>= (setq count (1- count)) 0)
411 (shr-char-kinsoku-bol-p (following-char))
412 (shr-char-breakable-p (following-char)))
413 (forward-char 1))))))
414 (when (eq (following-char) ? )
418 (defun shr-expand-url (url)
422 (string-match "\\`[a-z]*:" url)
425 ((and (not (string-match "/\\'" shr-base))
426 (not (string-match "\\`/" url)))
427 (concat shr-base "/" url))
429 (concat shr-base url))))
431 (defun shr-ensure-newline ()
432 (unless (zerop (current-column))
435 (defun shr-ensure-paragraph ()
437 (if (<= (current-column) shr-indentation)
438 (unless (save-excursion
449 (when (> shr-indentation 0)
450 (insert (make-string shr-indentation ? ))))
452 (defun shr-fontize-cont (cont &rest types)
456 (shr-add-font (or shr-start (point)) (point) type))))
458 ;; Add an overlay in the region, but avoid putting the font properties
459 ;; on blank text at the start of the line, and the newline at the end,
460 ;; to avoid ugliness.
461 (defun shr-add-font (start end type)
464 (while (< (point) end)
466 (skip-chars-forward " "))
467 (let ((overlay (make-overlay (point) (min (line-end-position) end))))
468 (overlay-put overlay 'face type))
469 (if (< (line-end-position) end)
473 (defun shr-browse-url ()
474 "Browse the URL under point."
476 (let ((url (get-text-property (point) 'shr-url)))
479 (message "No link under point"))
480 ((string-match "^mailto:" url)
481 (browse-url-mailto url))
485 (defun shr-save-contents (directory)
486 "Save the contents from URL in a file."
487 (interactive "DSave contents of URL to directory: ")
488 (let ((url (get-text-property (point) 'shr-url)))
490 (message "No link under point")
491 (url-retrieve (shr-encode-url url)
492 'shr-store-contents (list url directory)))))
494 (defun shr-store-contents (status url directory)
495 (unless (plist-get status :error)
496 (when (or (search-forward "\n\n" nil t)
497 (search-forward "\r\n\r\n" nil t))
498 (write-region (point) (point-max)
499 (expand-file-name (file-name-nondirectory url)
502 (defun shr-image-fetched (status buffer start end)
503 (when (and (buffer-name buffer)
504 (not (plist-get status :error)))
505 (url-store-in-cache (current-buffer))
506 (when (or (search-forward "\n\n" nil t)
507 (search-forward "\r\n\r\n" nil t))
508 (let ((data (buffer-substring (point) (point-max))))
509 (with-current-buffer buffer
511 (let ((alt (buffer-substring start end))
512 (inhibit-read-only t))
513 (delete-region start end)
515 (funcall shr-put-image-function data alt)))))))
516 (kill-buffer (current-buffer)))
518 (defun shr-put-image (data alt)
519 "Put image DATA with a string ALT. Return image."
520 (if (display-graphic-p)
521 (let ((image (ignore-errors
522 (shr-rescale-image data))))
524 ;; When inserting big-ish pictures, put them at the
525 ;; beginning of the line.
526 (when (and (> (current-column) 0)
527 (> (car (image-size image t)) 400))
529 (insert-image image (or alt "*"))
530 (when (image-animated-p image)
531 (image-animate image)))
535 (defun shr-rescale-image (data)
536 (if (or (not (fboundp 'imagemagick-types))
537 (not (get-buffer-window (current-buffer))))
538 (create-image data nil t
540 (let* ((image (create-image data nil t :ascent 100))
541 (size (image-size image t))
544 (edges (window-inside-pixel-edges
545 (get-buffer-window (current-buffer))))
546 (window-width (truncate (* shr-max-image-proportion
547 (- (nth 2 edges) (nth 0 edges)))))
548 (window-height (truncate (* shr-max-image-proportion
549 (- (nth 3 edges) (nth 1 edges)))))
551 (when (> height window-height)
552 (setq image (or (create-image data 'imagemagick t
553 :height window-height)
555 (setq size (image-size image t)))
556 (when (> (car size) window-width)
558 (create-image data 'imagemagick t
564 ;; url-cache-extract autoloads url-cache.
565 (declare-function url-cache-create-filename "url-cache" (url))
566 (autoload 'mm-disable-multibyte "mm-util")
567 (autoload 'browse-url-mailto "browse-url")
569 (defun shr-get-image-data (url)
570 "Get image data for URL.
571 Return a string with image data."
573 (mm-disable-multibyte)
575 (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
577 (when (or (search-forward "\n\n" nil t)
578 (search-forward "\r\n\r\n" nil t))
579 (buffer-substring (point) (point-max))))))
581 (defun shr-image-displayer (content-function)
582 "Return a function to display an image.
583 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
584 is an argument. The function to be returned takes three arguments URL,
585 START, and END. Note that START and END should be merkers."
586 `(lambda (url start end)
588 (if (string-match "\\`cid:" url)
589 ,(when content-function
590 `(let ((image (funcall ,content-function
591 (substring url (match-end 0)))))
594 (funcall shr-put-image-function
595 image (buffer-substring start end))
596 (delete-region (point) end))))
597 (url-retrieve url 'shr-image-fetched
598 (list (current-buffer) start end)
601 (defun shr-heading (cont &rest types)
602 (shr-ensure-paragraph)
603 (apply #'shr-fontize-cont cont types)
604 (shr-ensure-paragraph))
606 (autoload 'widget-convert-button "wid-edit")
608 (defun shr-urlify (start url &optional title)
609 (widget-convert-button
610 'url-link start (point)
611 :help-echo (if title (format "%s (%s)" url title) url)
614 (shr-add-font start (point) 'shr-link)
615 (put-text-property start (point) 'shr-url url))
617 (defun shr-encode-url (url)
619 (browse-url-url-encode-chars url "[)$ ]"))
621 (autoload 'shr-color-visible "shr-color")
622 (autoload 'shr-color->hexadecimal "shr-color")
624 (defun shr-color-check (fg bg)
625 "Check that FG is visible on BG.
626 Returns (fg bg) with corrected values.
627 Returns nil if the colors that would be used are the default
628 ones, in case fg and bg are nil."
630 (let ((fixed (cond ((null fg) 'fg)
632 ;; Convert colors to hexadecimal, or set them to default.
633 (let ((fg (or (shr-color->hexadecimal fg)
634 (frame-parameter nil 'foreground-color)))
635 (bg (or (shr-color->hexadecimal bg)
636 (frame-parameter nil 'background-color))))
637 (cond ((eq fixed 'bg)
638 ;; Only return the new fg
639 (list nil (cadr (shr-color-visible bg fg t))))
641 ;; Invert args and results and return only the new bg
642 (list (cadr (shr-color-visible fg bg t)) nil))
644 (shr-color-visible bg fg)))))))
646 (defun shr-colorize-region (start end fg &optional bg)
648 (let ((new-colors (shr-color-check fg bg)))
651 (shr-put-color start end :foreground (cadr new-colors)))
653 (shr-put-color start end :background (car new-colors))))
656 ;; Put a color in the region, but avoid putting colors on blank
657 ;; text at the start of the line, and the newline at the end, to avoid
658 ;; ugliness. Also, don't overwrite any existing color information,
659 ;; since this can be called recursively, and we want the "inner" color
661 (defun shr-put-color (start end type color)
664 (while (< (point) end)
666 (not (eq type :background)))
667 (skip-chars-forward " "))
668 (when (> (line-end-position) (point))
669 (shr-put-color-1 (point) (min (line-end-position) end) type color))
670 (if (< (line-end-position) end)
673 (when (and (eq type :background)
674 (= shr-table-depth 0))
675 (shr-expand-newlines start end color))))
677 (defun shr-expand-newlines (start end color)
679 ;; Skip past all white space at the start and ends.
681 (skip-chars-forward " \t\n")
685 (skip-chars-backward " \t\n")
688 (narrow-to-region start end)
689 (let ((width (shr-natural-width))
691 (goto-char (point-min))
694 (when (and (< (setq column (current-column)) width)
695 (< (setq column (shr-previous-newline-padding-width column))
697 (let ((overlay (make-overlay (point) (1+ (point)))))
698 (overlay-put overlay 'before-string
702 (let ((string (plist-get
703 (overlay-properties overlay)
707 (overlay-put overlay 'before-string "")
709 (overlays-at (point))
711 (propertize (make-string (- width column) ? )
712 'face (list :background color))))))
715 (defun shr-previous-newline-padding-width (width)
716 (let ((overlays (overlays-at (point)))
720 (dolist (overlay overlays)
723 (length (plist-get (overlay-properties overlay)
725 (+ width previous-width))))
727 (defun shr-put-color-1 (start end type color)
728 (let* ((old-props (get-text-property start 'face))
729 (do-put (and (listp old-props)
730 (not (memq type old-props))))
733 (setq change (next-single-property-change start 'face nil end))
735 (put-text-property start change 'face
736 (nconc (list type color) old-props)))
737 (setq old-props (get-text-property change 'face))
738 (setq do-put (and (listp old-props)
739 (not (memq type old-props))))
743 (put-text-property start end 'face
744 (nconc (list type color old-props))))))
746 ;;; Tag-specific rendering rules.
748 (defun shr-tag-body (cont)
749 (let* ((start (point))
750 (fgcolor (cdr (or (assq :fgcolor cont)
752 (bgcolor (cdr (assq :bgcolor cont)))
753 (shr-stylesheet (list (cons 'color fgcolor)
754 (cons 'background-color bgcolor))))
756 (shr-colorize-region start (point) fgcolor bgcolor)))
758 (defun shr-tag-style (cont)
761 (defun shr-tag-script (cont)
764 (defun shr-tag-sup (cont)
765 (let ((start (point)))
767 (put-text-property start (point) 'display '(raise 0.5))))
769 (defun shr-tag-sub (cont)
770 (let ((start (point)))
772 (put-text-property start (point) 'display '(raise -0.5))))
774 (defun shr-tag-label (cont)
776 (shr-ensure-paragraph))
778 (defun shr-tag-p (cont)
779 (shr-ensure-paragraph)
782 (shr-ensure-paragraph))
784 (defun shr-tag-div (cont)
788 (shr-ensure-newline))
790 (defun shr-tag-s (cont)
791 (shr-fontize-cont cont 'shr-strike-through))
793 (defun shr-tag-del (cont)
794 (shr-fontize-cont cont 'shr-strike-through))
796 (defun shr-tag-b (cont)
797 (shr-fontize-cont cont 'bold))
799 (defun shr-tag-i (cont)
800 (shr-fontize-cont cont 'italic))