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 (defvar shr-content-function nil
57 "If bound, this should be a function that will return the content.
58 This is used for cid: URLs, and the function is called with the
59 cid: URL as the argument.")
62 "Frame width to use for rendering.")
64 ;;; Internal variables.
66 (defvar shr-folding-mode nil)
67 (defvar shr-state nil)
68 (defvar shr-start nil)
69 (defvar shr-indentation 0)
70 (defvar shr-inhibit-images nil)
71 (defvar shr-list-mode nil)
72 (defvar shr-content-cache nil)
75 (let ((map (make-sparse-keymap)))
76 (define-key map "a" 'shr-show-alt-text)
77 (define-key map "i" 'shr-browse-image)
78 (define-key map "I" 'shr-insert-image)
79 (define-key map "u" 'shr-copy-url)
80 (define-key map "v" 'shr-browse-url)
81 (define-key map "\r" 'shr-browse-url)
84 ;; Public functions and commands.
87 (defun shr-insert-document (dom)
88 (setq shr-content-cache nil)
91 (shr-descend (shr-transform-dom dom))))
93 (defun shr-copy-url ()
94 "Copy the URL under point to the kill ring.
95 If called twice, then try to fetch the URL and see whether it
96 redirects somewhere else."
98 (let ((url (get-text-property (point) 'shr-url)))
101 (message "No URL under point"))
102 ;; Resolve redirected URLs.
103 ((equal url (car kill-ring))
108 (eq (car a) :redirect))
111 (goto-char (point-min))
112 ;; Remove common tracking junk from the URL.
113 (when (re-search-forward ".utm_.*" nil t)
114 (replace-match "" t t))
115 (message "Copied %s" (buffer-string))
116 (copy-region-as-kill (point-min) (point-max)))))))
117 ;; Copy the URL to the kill ring.
121 (copy-region-as-kill (point-min) (point-max))
122 (message "Copied %s" url))))))
124 (defun shr-show-alt-text ()
125 "Show the ALT text of the image under point."
127 (let ((text (get-text-property (point) 'shr-alt)))
129 (message "No image under point")
130 (message "%s" text))))
132 (defun shr-browse-image ()
133 "Browse the image under point."
135 (let ((url (get-text-property (point) 'shr-image)))
137 (message "No image under point")
138 (message "Browsing %s..." url)
141 (defun shr-insert-image ()
142 "Insert the image under point into the buffer."
144 (let ((url (get-text-property (point) 'shr-image)))
146 (message "No image under point")
147 (message "Inserting %s..." url)
148 (url-retrieve url 'shr-image-fetched
149 (list (current-buffer) (1- (point)) (point-marker))
152 ;;; Utility functions.
154 (defun shr-transform-dom (dom)
155 (let ((result (list (pop dom))))
156 (dolist (arg (pop dom))
157 (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
162 (push (cons :text sub) result)
163 (push (shr-transform-dom sub) result)))
166 (defun shr-descend (dom)
167 (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray)))
168 (if (fboundp function)
169 (funcall function (cdr dom))
170 (shr-generic (cdr dom)))))
172 (defun shr-generic (cont)
175 ((eq (car sub) :text)
176 (shr-insert (cdr sub)))
178 (shr-descend sub)))))
180 (defun shr-insert (text)
181 (when (eq shr-state 'image)
183 (setq shr-state nil))
185 ((eq shr-folding-mode 'none)
190 (when (and (string-match "\\`[ \t\n]" text)
193 (dolist (elem (split-string text))
195 (> shr-indentation 0))
197 ;; The shr-start is a special variable that is used to pass
198 ;; upwards the first point in the buffer where the text really
201 (setq shr-start (point)))
203 (when (> (current-column) shr-width)
204 (if (not (search-backward " " (line-beginning-position) t))
208 (put-text-property (1- (point)) (point) 'shr-break t)
209 (when (> shr-indentation 0)
213 (unless (string-match "[ \t\n]\\'" text)
214 (delete-char -1))))))
216 (defun shr-ensure-newline ()
217 (unless (zerop (current-column))
220 (defun shr-ensure-paragraph ()
223 (unless (save-excursion
234 (insert (make-string shr-indentation ? )))
236 (defun shr-fontize-cont (cont &rest types)
240 (shr-add-font (or shr-start (point)) (point) type))))
242 (defun shr-add-font (start end type)
243 (let ((overlay (make-overlay start end)))
244 (overlay-put overlay 'face type)))
246 (defun shr-browse-url ()
247 "Browse the URL under point."
249 (let ((url (get-text-property (point) 'shr-url)))
251 (message "No link under point")
254 (defun shr-image-fetched (status buffer start end)
255 (when (and (buffer-name buffer)
256 (not (plist-get status :error)))
257 (url-store-in-cache (current-buffer))
258 (when (or (search-forward "\n\n" nil t)
259 (search-forward "\r\n\r\n" nil t))
260 (let ((data (buffer-substring (point) (point-max))))
261 (with-current-buffer buffer
262 (let ((alt (buffer-substring start end))
263 (inhibit-read-only t))
264 (delete-region start end)
265 (shr-put-image data start alt))))))
266 (kill-buffer (current-buffer)))
268 (defun shr-put-image (data point alt)
269 (if (not (display-graphic-p))
271 (let ((image (ignore-errors
272 (shr-rescale-image data))))
274 (put-image image point alt)))))
276 (defun shr-rescale-image (data)
277 (if (or (not (fboundp 'imagemagick-types))
278 (not (get-buffer-window (current-buffer))))
279 (create-image data nil t)
280 (let* ((image (create-image data nil t))
281 (size (image-size image t))
284 (edges (window-inside-pixel-edges
285 (get-buffer-window (current-buffer))))
286 (window-width (truncate (* shr-max-image-proportion
287 (- (nth 2 edges) (nth 0 edges)))))
288 (window-height (truncate (* shr-max-image-proportion
289 (- (nth 3 edges) (nth 1 edges)))))
291 (when (> height window-height)
292 (setq image (or (create-image data 'imagemagick t
293 :height window-height)
295 (setq size (image-size image t)))
296 (when (> (car size) window-width)
298 (create-image data 'imagemagick t
303 (defun shr-get-image-data (url)
304 "Get image data for URL.
305 Return a string with image data."
307 (mm-disable-multibyte)
309 (url-cache-extract (url-cache-create-filename url))
311 (when (or (search-forward "\n\n" nil t)
312 (search-forward "\r\n\r\n" nil t))
313 (buffer-substring (point) (point-max))))))
315 (defun shr-heading (cont &rest types)
316 (shr-ensure-paragraph)
317 (apply #'shr-fontize-cont cont types)
318 (shr-ensure-paragraph))
320 ;;; Tag-specific rendering rules.
322 (defun shr-tag-p (cont)
323 (shr-ensure-paragraph)
325 (shr-ensure-paragraph))
327 (defun shr-tag-b (cont)
328 (shr-fontize-cont cont 'bold))
330 (defun shr-tag-i (cont)
331 (shr-fontize-cont cont 'italic))
333 (defun shr-tag-em (cont)
334 (shr-fontize-cont cont 'bold))
336 (defun shr-tag-u (cont)
337 (shr-fontize-cont cont 'underline))
339 (defun shr-tag-s (cont)
340 (shr-fontize-cont cont 'strike-through))
342 (defun shr-tag-a (cont)
343 (let ((url (cdr (assq :href cont)))
347 (widget-convert-button
348 'link (or shr-start start) (point)
350 (put-text-property (or shr-start start) (point) 'keymap shr-map)
351 (put-text-property (or shr-start start) (point) 'shr-url url)))
353 (defun shr-tag-img (cont)
354 (when (and (> (current-column) 0)
355 (not (eq shr-state 'image)))
357 (let ((start (point-marker)))
358 (let ((alt (cdr (assq :alt cont)))
359 (url (cdr (assq :src cont))))
360 (when (zerop (length alt))
363 ((and (not shr-inhibit-images)
364 (string-match "\\`cid:" url))
365 (let ((url (substring url (match-end 0)))
367 (if (or (not shr-content-function)
368 (not (setq image (funcall shr-content-function url))))
370 (shr-put-image image (point) alt))))
371 ((or shr-inhibit-images
372 (and shr-blocked-images
373 (string-match shr-blocked-images url)))
374 (setq shr-start (point))
375 (let ((shr-state 'space))
376 (if (> (length alt) 8)
377 (shr-insert (substring alt 0 8))
379 ((url-is-cached (browse-url-url-encode-chars url "[&)$ ]"))
380 (shr-put-image (shr-get-image-data url) (point) alt))
384 (url-retrieve url 'shr-image-fetched
385 (list (current-buffer) start (point-marker))
388 (put-text-property start (point) 'keymap shr-map)
389 (put-text-property start (point) 'shr-alt alt)
390 (put-text-property start (point) 'shr-image url)
391 (setq shr-state 'image))))
393 (defun shr-tag-pre (cont)
394 (let ((shr-folding-mode 'none))
397 (shr-ensure-newline)))
399 (defun shr-tag-blockquote (cont)
400 (shr-ensure-paragraph)
401 (let ((shr-indentation (+ shr-indentation 4)))
403 (shr-ensure-paragraph))
405 (defun shr-tag-ul (cont)
406 (shr-ensure-paragraph)
407 (let ((shr-list-mode 'ul))
409 (shr-ensure-paragraph))
411 (defun shr-tag-ol (cont)
412 (shr-ensure-paragraph)
413 (let ((shr-list-mode 1))
415 (shr-ensure-paragraph))
417 (defun shr-tag-li (cont)
420 (if (numberp shr-list-mode)
422 (format "%d " shr-list-mode)
423 (setq shr-list-mode (1+ shr-list-mode)))
425 (shr-indentation (+ shr-indentation (length bullet))))
429 (defun shr-tag-br (cont)
434 (defun shr-tag-h1 (cont)
435 (shr-heading cont 'bold 'underline))
437 (defun shr-tag-h2 (cont)
438 (shr-heading cont 'bold))
440 (defun shr-tag-h3 (cont)
441 (shr-heading cont 'italic))
443 (defun shr-tag-h4 (cont)
446 (defun shr-tag-h5 (cont)
449 (defun shr-tag-h6 (cont)
452 ;;; Table rendering algorithm.
454 ;; Table rendering is the only complicated thing here. We do this by
455 ;; first counting how many TDs there are in each TR, and registering
456 ;; how wide they think they should be ("width=45%", etc). Then we
457 ;; render each TD separately (this is done in temporary buffers, so
458 ;; that we can use all the rendering machinery as if we were in the
459 ;; main buffer). Now we know how much space each TD really takes, so
460 ;; we then render everything again with the new widths, and finally
461 ;; insert all these boxes into the main buffer.
462 (defun shr-tag-table (cont)
463 (shr-ensure-paragraph)
464 (setq cont (or (cdr (assq 'tbody cont))
466 (let* ((shr-inhibit-images t)
467 ;; Find all suggested widths.
468 (columns (shr-column-specs cont))
469 ;; Compute how many characters wide each TD should be.
470 (suggested-widths (shr-pro-rate-columns columns))
471 ;; Do a "test rendering" to see how big each TD is (this can
472 ;; be smaller (if there's little text) or bigger (if there's
473 ;; unbreakable text).
474 (sketch (shr-make-table cont suggested-widths))
475 (sketch-widths (shr-table-widths sketch suggested-widths)))
476 ;; Then render the table again with these new "hard" widths.
477 (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
478 ;; Finally, insert all the images after the table. The Emacs buffer
479 ;; model isn't strong enough to allow us to put the images actually
481 (dolist (elem (shr-find-elements cont 'img))
482 (shr-tag-img (cdr elem))))
484 (defun shr-find-elements (cont type)
487 (cond ((eq (car elem) type)
490 (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
493 (defun shr-insert-table (table widths)
494 (shr-insert-table-ruler widths)
496 (let ((start (point))
497 (height (let ((max 0))
499 (setq max (max max (cadr column))))
506 (let ((lines (nth 2 column))
507 (overlay-lines (nth 3 column))
508 overlay overlay-line)
510 (setq overlay-line (pop overlay-lines))
513 (dolist (overlay overlay-line)
514 (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
515 (- (point) (nth 1 overlay) 1)))
516 (properties (nth 2 overlay)))
518 (overlay-put o (pop properties) (pop properties)))))
520 ;; Add blank lines at padding at the bottom of the TD,
522 (dotimes (i (- height (length lines)))
524 (insert (make-string (length (car lines)) ? ) "|")
526 (shr-insert-table-ruler widths)))
528 (defun shr-insert-table-ruler (widths)
531 (dotimes (i (length widths))
532 (insert (make-string (aref widths i) ?-) ?+))
535 (defun shr-table-widths (table suggested-widths)
536 (let* ((length (length suggested-widths))
537 (widths (make-vector length 0))
538 (natural-widths (make-vector length 0)))
542 (aset widths i (max (aref widths i)
544 (aset natural-widths i (max (aref natural-widths i)
547 (let ((extra (- (reduce '+ suggested-widths)
549 (expanded-columns 0))
552 ;; If the natural width is wider than the rendered width, we
553 ;; want to allow the column to expand.
554 (when (> (aref natural-widths i) (aref widths i))
555 (setq expanded-columns (1+ expanded-columns))))
557 (when (> (aref natural-widths i) (aref widths i))
559 (1+ (aref natural-widths i))
560 (+ (/ extra expanded-columns)
561 (aref widths i))))))))
564 (defun shr-make-table (cont widths &optional fill)
567 (when (eq (car row) 'tr)
572 (while (< i (length widths))
573 (setq column (pop columns))
574 (when (or (memq (car column) '(td th))
576 (push (shr-render-td (cdr column) (aref widths i) fill)
579 (push (nreverse tds) trs))))
582 (defun shr-render-td (cont width fill)
584 (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
587 (let ((shr-width width)
593 (skip-chars-backward " \t\n")))
594 (push (cons (cons width cont) (buffer-string))
596 (goto-char (point-min))
600 (setq max (max max (current-column)))
603 (goto-char (point-min))
604 ;; If the buffer is totally empty, then put a single blank
606 (if (zerop (buffer-size))
607 (insert (make-string width ? ))
608 ;; Otherwise, fill the buffer.
611 (when (> (- width (current-column)) 0)
612 (insert (make-string (- width (current-column)) ? )))
616 (count-lines (point-min) (point-max))
617 (split-string (buffer-string) "\n")
618 (shr-collect-overlays))
620 (shr-natural-width))))))
622 (defun shr-natural-width ()
623 (goto-char (point-min))
628 (setq current (+ current (current-column)))
629 (unless (get-text-property (point) 'shr-break)
630 (setq max (max max current)
635 (defun shr-collect-overlays ()
637 (goto-char (point-min))
638 (let ((overlays nil))
640 (push (shr-overlays-in-region (point) (line-end-position))
643 (nreverse overlays))))
645 (defun shr-overlays-in-region (start end)
647 (dolist (overlay (overlays-in start end))
648 (push (list (if (> start (overlay-start overlay))
650 (- end (overlay-start overlay)))
651 (if (< end (overlay-end overlay))
653 (- end (overlay-end overlay)))
654 (overlay-properties overlay))
658 (defun shr-pro-rate-columns (columns)
659 (let ((total-percentage 0)
660 (widths (make-vector (length columns) 0)))
661 (dotimes (i (length columns))
662 (setq total-percentage (+ total-percentage (aref columns i))))
663 (setq total-percentage (/ 1.0 total-percentage))
664 (dotimes (i (length columns))
665 (aset widths i (max (truncate (* (aref columns i)
667 (- shr-width (1+ (length columns)))))
671 ;; Return a summary of the number and shape of the TDs in the table.
672 (defun shr-column-specs (cont)
673 (let ((columns (make-vector (shr-max-columns cont) 1)))
675 (when (eq (car row) 'tr)
677 (dolist (column (cdr row))
678 (when (memq (car column) '(td th))
679 (let ((width (cdr (assq :width (cdr column)))))
681 (string-match "\\([0-9]+\\)%" width))
683 (/ (string-to-number (match-string 1 width))
688 (defun shr-count (cont elem)
691 (when (eq (car sub) elem)
695 (defun shr-max-columns (cont)
698 (when (eq (car row) 'tr)
699 (setq max (max max (+ (shr-count (cdr row) 'td)
700 (shr-count (cdr row) 'th))))))