1 ;;; shr.el --- Simple HTML Renderer
3 ;; Copyright (C) 2010 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-line ?-
57 "Character used to draw table line."
61 (defcustom shr-table-corner ?+
62 "Character used to draw table corner."
66 (defcustom shr-hr-line ?-
67 "Character used to draw hr line."
71 (defcustom shr-width fill-column
72 "Frame width to use for rendering."
76 (defvar shr-content-function nil
77 "If bound, this should be a function that will return the content.
78 This is used for cid: URLs, and the function is called with the
79 cid: URL as the argument.")
81 ;;; Internal variables.
83 (defvar shr-folding-mode nil)
84 (defvar shr-state nil)
85 (defvar shr-start nil)
86 (defvar shr-indentation 0)
87 (defvar shr-inhibit-images nil)
88 (defvar shr-list-mode nil)
89 (defvar shr-content-cache nil)
92 (let ((map (make-sparse-keymap)))
93 (define-key map "a" 'shr-show-alt-text)
94 (define-key map "i" 'shr-browse-image)
95 (define-key map "I" 'shr-insert-image)
96 (define-key map "u" 'shr-copy-url)
97 (define-key map "v" 'shr-browse-url)
98 (define-key map "\r" 'shr-browse-url)
101 ;; Public functions and commands.
104 (defun shr-insert-document (dom)
105 (setq shr-content-cache nil)
106 (let ((shr-state nil)
108 (shr-descend (shr-transform-dom dom))))
110 (defun shr-copy-url ()
111 "Copy the URL under point to the kill ring.
112 If called twice, then try to fetch the URL and see whether it
113 redirects somewhere else."
115 (let ((url (get-text-property (point) 'shr-url)))
118 (message "No URL under point"))
119 ;; Resolve redirected URLs.
120 ((equal url (car kill-ring))
125 (eq (car a) :redirect))
128 (goto-char (point-min))
129 ;; Remove common tracking junk from the URL.
130 (when (re-search-forward ".utm_.*" nil t)
131 (replace-match "" t t))
132 (message "Copied %s" (buffer-string))
133 (copy-region-as-kill (point-min) (point-max)))))))
134 ;; Copy the URL to the kill ring.
138 (copy-region-as-kill (point-min) (point-max))
139 (message "Copied %s" url))))))
141 (defun shr-show-alt-text ()
142 "Show the ALT text of the image under point."
144 (let ((text (get-text-property (point) 'shr-alt)))
146 (message "No image under point")
147 (message "%s" text))))
149 (defun shr-browse-image ()
150 "Browse the image under point."
152 (let ((url (get-text-property (point) 'shr-image)))
154 (message "No image under point")
155 (message "Browsing %s..." url)
158 (defun shr-insert-image ()
159 "Insert the image under point into the buffer."
161 (let ((url (get-text-property (point) 'shr-image)))
163 (message "No image under point")
164 (message "Inserting %s..." url)
165 (url-retrieve url 'shr-image-fetched
166 (list (current-buffer) (1- (point)) (point-marker))
169 ;;; Utility functions.
171 (defun shr-transform-dom (dom)
172 (let ((result (list (pop dom))))
173 (dolist (arg (pop dom))
174 (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
179 (push (cons :text sub) result)
180 (push (shr-transform-dom sub) result)))
183 (defun shr-descend (dom)
184 (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray)))
185 (if (fboundp function)
186 (funcall function (cdr dom))
187 (shr-generic (cdr dom)))))
189 (defun shr-generic (cont)
192 ((eq (car sub) :text)
193 (shr-insert (cdr sub)))
195 (shr-descend sub)))))
197 (defun shr-insert (text)
198 (when (and (eq shr-state 'image)
199 (not (string-match "\\`[ \t\n]+\\'" text)))
201 (setq shr-state nil))
203 ((eq shr-folding-mode 'none)
208 (when (and (string-match "\\`[ \t\n]" text)
210 (not (eq (char-after (1- (point))) ? )))
212 (dolist (elem (split-string text))
214 (> shr-indentation 0))
216 ;; The shr-start is a special variable that is used to pass
217 ;; upwards the first point in the buffer where the text really
220 (setq shr-start (point)))
221 ;; No space is needed before or after a breakable character or
222 ;; at the beginning of a line.
223 (when (and (eq (preceding-char) ? )
224 (or (= (line-beginning-position) (1- (point)))
225 (aref fill-find-break-point-function-table
226 (char-after (- (point) 2)))
227 (aref fill-find-break-point-function-table
231 (while (> (current-column) shr-width)
233 (shr-find-fill-point)
234 (when (eq (preceding-char) ? )
237 (put-text-property (1- (point)) (point) 'shr-break t)
238 ;; No space is needed at the beginning of a line.
239 (if (eq (following-char) ? )
241 (when (> shr-indentation 0)
245 (unless (string-match "[ \t\n]\\'" text)
246 (delete-char -1))))))
248 (eval-and-compile (autoload 'kinsoku-longer "kinsoku"))
250 (defun shr-find-fill-point ()
252 (while (and (not found)
253 (> (current-column) shr-indentation))
254 (when (and (or (eq (preceding-char) ? )
255 (aref fill-find-break-point-function-table
257 (<= (current-column) shr-width))
261 ;; There's no breakable point, so we give it up.
263 (while (aref fill-find-break-point-function-table
266 (setq found 'failed)))
268 ;; Don't put kinsoku-bol characters at the beginning of a line.
271 (not (aref fill-find-break-point-function-table
279 (defun shr-ensure-newline ()
280 (unless (zerop (current-column))
283 (defun shr-ensure-paragraph ()
285 (if (<= (current-column) shr-indentation)
286 (unless (save-excursion
297 (when (> shr-indentation 0)
298 (insert (make-string shr-indentation ? ))))
300 (defun shr-fontize-cont (cont &rest types)
304 (shr-add-font (or shr-start (point)) (point) type))))
306 (defun shr-add-font (start end type)
307 (let ((overlay (make-overlay start end)))
308 (overlay-put overlay 'face type)))
310 (defun shr-browse-url ()
311 "Browse the URL under point."
313 (let ((url (get-text-property (point) 'shr-url)))
315 (message "No link under point")
318 (defun shr-image-fetched (status buffer start end)
319 (when (and (buffer-name buffer)
320 (not (plist-get status :error)))
321 (url-store-in-cache (current-buffer))
322 (when (or (search-forward "\n\n" nil t)
323 (search-forward "\r\n\r\n" nil t))
324 (let ((data (buffer-substring (point) (point-max))))
325 (with-current-buffer buffer
326 (let ((alt (buffer-substring start end))
327 (inhibit-read-only t))
328 (delete-region start end)
329 (shr-put-image data start alt))))))
330 (kill-buffer (current-buffer)))
332 (defun shr-put-image (data point alt)
333 (if (not (display-graphic-p))
335 (let ((image (ignore-errors
336 (shr-rescale-image data))))
338 (put-image image point alt)))))
340 (defun shr-rescale-image (data)
341 (if (or (not (fboundp 'imagemagick-types))
342 (not (get-buffer-window (current-buffer))))
343 (create-image data nil t)
344 (let* ((image (create-image data nil t))
345 (size (image-size image t))
348 (edges (window-inside-pixel-edges
349 (get-buffer-window (current-buffer))))
350 (window-width (truncate (* shr-max-image-proportion
351 (- (nth 2 edges) (nth 0 edges)))))
352 (window-height (truncate (* shr-max-image-proportion
353 (- (nth 3 edges) (nth 1 edges)))))
355 (when (> height window-height)
356 (setq image (or (create-image data 'imagemagick t
357 :height window-height)
359 (setq size (image-size image t)))
360 (when (> (car size) window-width)
362 (create-image data 'imagemagick t
367 (defun shr-get-image-data (url)
368 "Get image data for URL.
369 Return a string with image data."
371 (mm-disable-multibyte)
373 (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
375 (when (or (search-forward "\n\n" nil t)
376 (search-forward "\r\n\r\n" nil t))
377 (buffer-substring (point) (point-max))))))
379 (defun shr-heading (cont &rest types)
380 (shr-ensure-paragraph)
381 (apply #'shr-fontize-cont cont types)
382 (shr-ensure-paragraph))
384 ;;; Tag-specific rendering rules.
386 (defun shr-tag-p (cont)
387 (shr-ensure-paragraph)
390 (shr-ensure-paragraph))
392 (defun shr-tag-b (cont)
393 (shr-fontize-cont cont 'bold))
395 (defun shr-tag-i (cont)
396 (shr-fontize-cont cont 'italic))
398 (defun shr-tag-em (cont)
399 (shr-fontize-cont cont 'bold))
401 (defun shr-tag-u (cont)
402 (shr-fontize-cont cont 'underline))
404 (defun shr-tag-s (cont)
405 (shr-fontize-cont cont 'strike-through))
407 (defun shr-tag-a (cont)
408 (let ((url (cdr (assq :href cont)))
412 (widget-convert-button
413 'url-link (or shr-start start) (point)
417 (put-text-property (or shr-start start) (point) 'shr-url url)))
419 (defun shr-encode-url (url)
421 (browse-url-url-encode-chars url "[)$ ]"))
423 (defun shr-tag-img (cont)
425 (when (and (> (current-column) 0)
426 (not (eq shr-state 'image)))
428 (let ((alt (cdr (assq :alt cont)))
429 (url (cdr (assq :src cont))))
430 (let ((start (point-marker)))
431 (when (zerop (length alt))
434 ((and (not shr-inhibit-images)
435 (string-match "\\`cid:" url))
436 (let ((url (substring url (match-end 0)))
438 (if (or (not shr-content-function)
439 (not (setq image (funcall shr-content-function url))))
441 (shr-put-image image (point) alt))))
442 ((or shr-inhibit-images
443 (and shr-blocked-images
444 (string-match shr-blocked-images url)))
445 (setq shr-start (point))
446 (let ((shr-state 'space))
447 (if (> (length alt) 8)
448 (shr-insert (substring alt 0 8))
450 ((url-is-cached (shr-encode-url url))
451 (shr-put-image (shr-get-image-data url) (point) alt))
455 (url-retrieve (shr-encode-url url) 'shr-image-fetched
456 (list (current-buffer) start (point-marker))
459 (put-text-property start (point) 'keymap shr-map)
460 (put-text-property start (point) 'shr-alt alt)
461 (put-text-property start (point) 'shr-image url)
462 (setq shr-state 'image)))))
464 (defun shr-tag-pre (cont)
465 (let ((shr-folding-mode 'none))
469 (shr-ensure-newline)))
471 (defun shr-tag-blockquote (cont)
472 (shr-ensure-paragraph)
474 (let ((shr-indentation (+ shr-indentation 4)))
476 (shr-ensure-paragraph))
478 (defun shr-tag-ul (cont)
479 (shr-ensure-paragraph)
480 (let ((shr-list-mode 'ul))
482 (shr-ensure-paragraph))
484 (defun shr-tag-ol (cont)
485 (shr-ensure-paragraph)
486 (let ((shr-list-mode 1))
488 (shr-ensure-paragraph))
490 (defun shr-tag-li (cont)
491 (shr-ensure-paragraph)
494 (if (numberp shr-list-mode)
496 (format "%d " shr-list-mode)
497 (setq shr-list-mode (1+ shr-list-mode)))
499 (shr-indentation (+ shr-indentation (length bullet))))
503 (defun shr-tag-br (cont)
509 (defun shr-tag-h1 (cont)
510 (shr-heading cont 'bold 'underline))
512 (defun shr-tag-h2 (cont)
513 (shr-heading cont 'bold))
515 (defun shr-tag-h3 (cont)
516 (shr-heading cont 'italic))
518 (defun shr-tag-h4 (cont)
521 (defun shr-tag-h5 (cont)
524 (defun shr-tag-h6 (cont)
527 (defun shr-tag-hr (cont)
529 (insert (make-string shr-width shr-hr-line) "\n"))
531 ;;; Table rendering algorithm.
533 ;; Table rendering is the only complicated thing here. We do this by
534 ;; first counting how many TDs there are in each TR, and registering
535 ;; how wide they think they should be ("width=45%", etc). Then we
536 ;; render each TD separately (this is done in temporary buffers, so
537 ;; that we can use all the rendering machinery as if we were in the
538 ;; main buffer). Now we know how much space each TD really takes, so
539 ;; we then render everything again with the new widths, and finally
540 ;; insert all these boxes into the main buffer.
541 (defun shr-tag-table (cont)
542 (shr-ensure-paragraph)
543 (setq cont (or (cdr (assq 'tbody cont))
545 (let* ((shr-inhibit-images t)
546 ;; Find all suggested widths.
547 (columns (shr-column-specs cont))
548 ;; Compute how many characters wide each TD should be.
549 (suggested-widths (shr-pro-rate-columns columns))
550 ;; Do a "test rendering" to see how big each TD is (this can
551 ;; be smaller (if there's little text) or bigger (if there's
552 ;; unbreakable text).
553 (sketch (shr-make-table cont suggested-widths))
554 (sketch-widths (shr-table-widths sketch suggested-widths)))
555 ;; This probably won't work very well.
556 (when (> (1+ (loop for width across sketch-widths
559 (setq truncate-lines t))
560 ;; Then render the table again with these new "hard" widths.
561 (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
562 ;; Finally, insert all the images after the table. The Emacs buffer
563 ;; model isn't strong enough to allow us to put the images actually
565 (dolist (elem (shr-find-elements cont 'img))
566 (shr-tag-img (cdr elem))))
568 (defun shr-find-elements (cont type)
571 (cond ((eq (car elem) type)
574 (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
577 (defun shr-insert-table (table widths)
578 (shr-insert-table-ruler widths)
580 (let ((start (point))
581 (height (let ((max 0))
583 (setq max (max max (cadr column))))
590 (let ((lines (nth 2 column))
591 (overlay-lines (nth 3 column))
592 overlay overlay-line)
594 (setq overlay-line (pop overlay-lines))
597 (dolist (overlay overlay-line)
598 (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
599 (- (point) (nth 1 overlay) 1)))
600 (properties (nth 2 overlay)))
602 (overlay-put o (pop properties) (pop properties)))))
604 ;; Add blank lines at padding at the bottom of the TD,
606 (dotimes (i (- height (length lines)))
608 (insert (make-string (length (car lines)) ? ) "|")
610 (shr-insert-table-ruler widths)))
612 (defun shr-insert-table-ruler (widths)
614 (insert shr-table-corner)
615 (dotimes (i (length widths))
616 (insert (make-string (aref widths i) shr-table-line) shr-table-corner))
619 (defun shr-table-widths (table suggested-widths)
620 (let* ((length (length suggested-widths))
621 (widths (make-vector length 0))
622 (natural-widths (make-vector length 0)))
626 (aset widths i (max (aref widths i)
628 (aset natural-widths i (max (aref natural-widths i)
631 (let ((extra (- (apply '+ (append suggested-widths nil))
632 (apply '+ (append widths nil))))
633 (expanded-columns 0))
636 ;; If the natural width is wider than the rendered width, we
637 ;; want to allow the column to expand.
638 (when (> (aref natural-widths i) (aref widths i))
639 (setq expanded-columns (1+ expanded-columns))))
641 (when (> (aref natural-widths i) (aref widths i))
643 (1+ (aref natural-widths i))
644 (+ (/ extra expanded-columns)
645 (aref widths i))))))))
648 (defun shr-make-table (cont widths &optional fill)
651 (when (eq (car row) 'tr)
656 (while (< i (length widths))
657 (setq column (pop columns))
658 (when (or (memq (car column) '(td th))
660 (push (shr-render-td (cdr column) (aref widths i) fill)
663 (push (nreverse tds) trs))))
666 (defun shr-render-td (cont width fill)
668 (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
671 (let ((shr-width width)
677 (skip-chars-backward " \t\n")))
678 (push (cons (cons width cont) (buffer-string))
680 (goto-char (point-min))
684 (setq max (max max (current-column)))
687 (goto-char (point-min))
688 ;; If the buffer is totally empty, then put a single blank
690 (if (zerop (buffer-size))
691 (insert (make-string width ? ))
692 ;; Otherwise, fill the buffer.
695 (when (> (- width (current-column)) 0)
696 (insert (make-string (- width (current-column)) ? )))
700 (count-lines (point-min) (point-max))
701 (split-string (buffer-string) "\n")
702 (shr-collect-overlays))
704 (shr-natural-width))))))
706 (defun shr-natural-width ()
707 (goto-char (point-min))
712 (setq current (+ current (current-column)))
713 (unless (get-text-property (point) 'shr-break)
714 (setq max (max max current)
719 (defun shr-collect-overlays ()
721 (goto-char (point-min))
722 (let ((overlays nil))
724 (push (shr-overlays-in-region (point) (line-end-position))
727 (nreverse overlays))))
729 (defun shr-overlays-in-region (start end)
731 (dolist (overlay (overlays-in start end))
732 (push (list (if (> start (overlay-start overlay))
734 (- end (overlay-start overlay)))
735 (if (< end (overlay-end overlay))
737 (- end (overlay-end overlay)))
738 (overlay-properties overlay))
742 (defun shr-pro-rate-columns (columns)
743 (let ((total-percentage 0)
744 (widths (make-vector (length columns) 0)))
745 (dotimes (i (length columns))
746 (setq total-percentage (+ total-percentage (aref columns i))))
747 (setq total-percentage (/ 1.0 total-percentage))
748 (dotimes (i (length columns))
749 (aset widths i (max (truncate (* (aref columns i)
751 (- shr-width (1+ (length columns)))))
755 ;; Return a summary of the number and shape of the TDs in the table.
756 (defun shr-column-specs (cont)
757 (let ((columns (make-vector (shr-max-columns cont) 1)))
759 (when (eq (car row) 'tr)
761 (dolist (column (cdr row))
762 (when (memq (car column) '(td th))
763 (let ((width (cdr (assq :width (cdr column)))))
765 (string-match "\\([0-9]+\\)%" width))
767 (/ (string-to-number (match-string 1 width))
772 (defun shr-count (cont elem)
775 (when (eq (car sub) elem)
779 (defun shr-max-columns (cont)
782 (when (eq (car row) 'tr)
783 (setq max (max max (+ (shr-count (cdr row) 'td)
784 (shr-count (cdr row) 'th))))))