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.
36 "Simple HTML Renderer"
39 (defcustom shr-max-image-proportion 0.9
40 "How big pictures displayed are in relation to the window they're in.
41 A value of 0.7 means that they are allowed to take up 70% of the
42 width and height of the window. If they are larger than this,
43 and Emacs supports it, then the images will be rescaled down to
49 (defcustom shr-blocked-images nil
50 "Images that have URLs matching this regexp will be blocked."
55 (defvar shr-content-function nil
56 "If bound, this should be a function that will return the content.
57 This is used for cid: URLs, and the function is called with the
58 cid: URL as the argument.")
61 "Frame width to use for rendering.")
63 ;;; Internal variables.
65 (defvar shr-folding-mode nil)
66 (defvar shr-state nil)
67 (defvar shr-start nil)
68 (defvar shr-indentation 0)
69 (defvar shr-inhibit-images nil)
70 (defvar shr-list-mode nil)
73 (let ((map (make-sparse-keymap)))
74 (define-key map "a" 'shr-show-alt-text)
75 (define-key map "i" 'shr-browse-image)
76 (define-key map "I" 'shr-insert-image)
77 (define-key map "u" 'shr-copy-url)
78 (define-key map "v" 'shr-browse-url)
79 (define-key map "\r" 'shr-browse-url)
82 ;; Public functions and commands.
85 (defun shr-insert-document (dom)
88 (shr-descend (shr-transform-dom dom))))
90 (defun shr-copy-url ()
91 "Copy the URL under point to the kill ring.
92 If called twice, then try to fetch the URL and see whether it
93 redirects somewhere else."
95 (let ((url (get-text-property (point) 'shr-url)))
98 (message "No URL under point"))
99 ;; Resolve redirected URLs.
100 ((equal url (car kill-ring))
105 (eq (car a) :redirect))
108 (goto-char (point-min))
109 ;; Remove common tracking junk from the URL.
110 (when (re-search-forward ".utm_.*" nil t)
111 (replace-match "" t t))
112 (message "Copied %s" (buffer-string))
113 (copy-region-as-kill (point-min) (point-max)))))))
114 ;; Copy the URL to the kill ring.
118 (copy-region-as-kill (point-min) (point-max))
119 (message "Copied %s" url))))))
121 (defun shr-show-alt-text ()
122 "Show the ALT text of the image under point."
124 (let ((text (get-text-property (point) 'shr-alt)))
126 (message "No image under point")
127 (message "%s" text))))
129 (defun shr-browse-image ()
130 "Browse the image under point."
132 (let ((url (get-text-property (point) 'shr-image)))
134 (message "No image under point")
135 (message "Browsing %s..." url)
138 ;;; Utility functions.
140 (defun shr-transform-dom (dom)
141 (let ((result (list (pop dom))))
142 (dolist (arg (pop dom))
143 (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
148 (push (cons :text sub) result)
149 (push (shr-transform-dom sub) result)))
152 (defun shr-descend (dom)
153 (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray)))
154 (if (fboundp function)
155 (funcall function (cdr dom))
156 (shr-generic (cdr dom)))))
158 (defun shr-generic (cont)
161 ((eq (car sub) :text)
162 (shr-insert (cdr sub)))
164 (shr-descend sub)))))
166 (defun shr-insert (text)
167 (when (eq shr-state 'image)
169 (setq shr-state nil))
171 ((eq shr-folding-mode 'none)
176 (when (and (string-match "\\`[ \t\n]" text)
179 (setq shr-state 'space))
180 (dolist (elem (split-string text))
181 (setq column (current-column))
184 ((and (or (not first)
185 (eq shr-state 'space))
186 (> (+ column (length elem) 1) shr-width))
192 (> shr-indentation 0))
194 ;; The shr-start is a special variable that is used to pass
195 ;; upwards the first point in the buffer where the text really
198 (setq shr-start (point)))
201 (when (and (string-match "[ \t\n]\\'" text)
204 (setq shr-state 'space))))))
206 (defun shr-ensure-newline ()
207 (unless (zerop (current-column))
210 (defun shr-ensure-paragraph ()
213 (unless (save-excursion
224 (insert (make-string shr-indentation ? )))
226 (defun shr-fontize-cont (cont &rest types)
230 (shr-add-font (or shr-start (point)) (point) type))))
232 (defun shr-add-font (start end type)
233 (let ((overlay (make-overlay start end)))
234 (overlay-put overlay 'face type)))
236 (defun shr-browse-url ()
237 "Browse the URL under point."
239 (let ((url (get-text-property (point) 'shr-url)))
241 (message "No link under point")
244 (defun shr-image-fetched (status buffer start end)
245 (when (and (buffer-name buffer)
246 (not (plist-get status :error)))
247 (url-store-in-cache (current-buffer))
248 (when (or (search-forward "\n\n" nil t)
249 (search-forward "\r\n\r\n" nil t))
250 (let ((data (buffer-substring (point) (point-max))))
251 (with-current-buffer buffer
252 (let ((alt (buffer-substring start end))
253 (inhibit-read-only t))
254 (delete-region start end)
255 (shr-put-image data start alt))))))
256 (kill-buffer (current-buffer)))
258 (defun shr-put-image (data point alt)
259 (if (not (display-graphic-p))
261 (let ((image (ignore-errors
262 (shr-rescale-image data))))
264 (put-image image point alt)))))
266 (defun shr-rescale-image (data)
267 (if (or (not (fboundp 'imagemagick-types))
268 (not (get-buffer-window (current-buffer))))
269 (create-image data nil t)
270 (let* ((image (create-image data nil t))
271 (size (image-size image t))
274 (edges (window-inside-pixel-edges
275 (get-buffer-window (current-buffer))))
276 (window-width (truncate (* shr-max-image-proportion
277 (- (nth 2 edges) (nth 0 edges)))))
278 (window-height (truncate (* shr-max-image-proportion
279 (- (nth 3 edges) (nth 1 edges)))))
281 (when (> height window-height)
282 (setq image (or (create-image data 'imagemagick t
283 :height window-height)
285 (setq size (image-size image t)))
286 (when (> (car size) window-width)
288 (create-image data 'imagemagick t
293 (defun shr-get-image-data (url)
294 "Get image data for URL.
295 Return a string with image data."
297 (mm-disable-multibyte)
299 (url-cache-extract (url-cache-create-filename url))
301 (when (or (search-forward "\n\n" nil t)
302 (search-forward "\r\n\r\n" nil t))
303 (buffer-substring (point) (point-max))))))
305 (defun shr-heading (cont &rest types)
306 (shr-ensure-paragraph)
307 (apply #'shr-fontize-cont cont types)
308 (shr-ensure-paragraph))
310 ;;; Tag-specific rendering rules.
312 (defun shr-tag-p (cont)
313 (shr-ensure-paragraph)
315 (shr-ensure-paragraph))
317 (defun shr-tag-b (cont)
318 (shr-fontize-cont cont 'bold))
320 (defun shr-tag-i (cont)
321 (shr-fontize-cont cont 'italic))
323 (defun shr-tag-em (cont)
324 (shr-fontize-cont cont 'bold))
326 (defun shr-tag-u (cont)
327 (shr-fontize-cont cont 'underline))
329 (defun shr-tag-s (cont)
330 (shr-fontize-cont cont 'strike-through))
332 (defun shr-tag-a (cont)
333 (let ((url (cdr (assq :href cont)))
337 (widget-convert-button
338 'link (or shr-start start) (point)
340 (put-text-property (or shr-start start) (point) 'keymap shr-map)
341 (put-text-property (or shr-start start) (point) 'shr-url url)))
343 (defun shr-tag-img (cont)
344 (when (and (> (current-column) 0)
345 (not (eq shr-state 'image)))
347 (let ((start (point-marker)))
348 (let ((alt (cdr (assq :alt cont)))
349 (url (cdr (assq :src cont))))
350 (when (zerop (length alt))
353 ((and (not shr-inhibit-images)
354 (string-match "\\`cid:" url))
355 (let ((url (substring url (match-end 0)))
357 (if (or (not shr-content-function)
358 (not (setq image (funcall shr-content-function url))))
360 (shr-put-image image (point) alt))))
361 ((or shr-inhibit-images
362 (and shr-blocked-images
363 (string-match shr-blocked-images url)))
364 (setq shr-start (point))
365 (let ((shr-state 'space))
366 (if (> (length alt) 8)
367 (shr-insert (substring alt 0 8))
369 ((url-is-cached (browse-url-url-encode-chars url "[&)$ ]"))
370 (shr-put-image (shr-get-image-data url) (point) alt))
374 (url-retrieve url 'shr-image-fetched
375 (list (current-buffer) start (point-marker))
378 (put-text-property start (point) 'keymap shr-map)
379 (put-text-property start (point) 'shr-alt alt)
380 (put-text-property start (point) 'shr-image url)
381 (setq shr-state 'image))))
383 (defun shr-tag-pre (cont)
384 (let ((shr-folding-mode 'none))
387 (shr-ensure-newline)))
389 (defun shr-tag-blockquote (cont)
390 (shr-ensure-paragraph)
391 (let ((shr-indentation (+ shr-indentation 4)))
393 (shr-ensure-paragraph))
395 (defun shr-tag-ul (cont)
396 (shr-ensure-paragraph)
397 (let ((shr-list-mode 'ul))
400 (defun shr-tag-ol (cont)
401 (let ((shr-list-mode 1))
404 (defun shr-tag-li (cont)
407 (if (numberp shr-list-mode)
409 (format "%d " shr-list-mode)
410 (setq shr-list-mode (1+ shr-list-mode)))
412 (shr-indentation (+ shr-indentation (length bullet))))
416 (defun shr-tag-br (cont)
421 (defun shr-tag-h1 (cont)
422 (shr-heading cont 'bold 'underline))
424 (defun shr-tag-h2 (cont)
425 (shr-heading cont 'bold))
427 (defun shr-tag-h3 (cont)
428 (shr-heading cont 'italic))
430 (defun shr-tag-h4 (cont)
433 (defun shr-tag-h5 (cont)
436 (defun shr-tag-h6 (cont)
439 ;;; Table rendering algorithm.
441 ;; Table rendering is the only complicated thing here. We do this by
442 ;; first counting how many TDs there are in each TR, and registering
443 ;; how wide they think they should be ("width=45%", etc). Then we
444 ;; render each TD separately (this is done in temporary buffers, so
445 ;; that we can use all the rendering machinery as if we were in the
446 ;; main buffer). Now we know how much space each TD really takes, so
447 ;; we then render everything again with the new widths, and finally
448 ;; insert all these boxes into the main buffer.
449 (defun shr-tag-table (cont)
450 (shr-ensure-paragraph)
451 (setq cont (or (cdr (assq 'tbody cont))
453 (let* ((shr-inhibit-images t)
454 ;; Find all suggested widths.
455 (columns (shr-column-specs cont))
456 ;; Compute how many characters wide each TD should be.
457 (suggested-widths (shr-pro-rate-columns columns))
458 ;; Do a "test rendering" to see how big each TD is (this can
459 ;; be smaller (if there's little text) or bigger (if there's
460 ;; unbreakable text).
461 (sketch (shr-make-table cont suggested-widths))
462 (sketch-widths (shr-table-widths sketch (length suggested-widths))))
463 ;; Then render the table again with these new "hard" widths.
464 (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
465 ;; Finally, insert all the images after the table. The Emacs buffer
466 ;; model isn't strong enough to allow us to put the images actually
468 (dolist (elem (shr-find-elements cont 'img))
469 (shr-tag-img (cdr elem))))
471 (defun shr-find-elements (cont type)
474 (cond ((eq (car elem) type)
477 (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
480 (defun shr-insert-table (table widths)
481 (shr-insert-table-ruler widths)
483 (let ((start (point))
484 (height (let ((max 0))
486 (setq max (max max (cadr column))))
493 (let ((lines (split-string (nth 2 column) "\n"))
494 (overlay-lines (nth 3 column))
495 overlay overlay-line)
497 (setq overlay-line (pop overlay-lines))
498 (when (> (length line) 0)
501 (dolist (overlay overlay-line)
502 (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
503 (- (point) (nth 1 overlay) 1)))
504 (properties (nth 2 overlay)))
506 (overlay-put o (pop properties) (pop properties)))))
508 ;; Add blank lines at padding at the bottom of the TD,
510 (dotimes (i (- height (length lines)))
512 (insert (make-string (length (car lines)) ? ) "|")
514 (shr-insert-table-ruler widths)))
516 (defun shr-insert-table-ruler (widths)
519 (dotimes (i (length widths))
520 (insert (make-string (aref widths i) ?-) ?+))
523 (defun shr-table-widths (table length)
524 (let ((widths (make-vector length 0)))
528 (aset widths i (max (aref widths i)
533 (defun shr-make-table (cont widths &optional fill)
536 (when (eq (car row) 'tr)
541 (while (< i (length widths))
542 (setq column (pop columns))
543 (when (or (memq (car column) '(td th))
545 (push (shr-render-td (cdr column) (aref widths i) fill)
548 (push (nreverse tds) trs))))
551 (defun shr-render-td (cont width fill)
553 (let ((shr-width width)
559 (skip-chars-backward " \t\n")))
560 (goto-char (point-min))
564 (setq max (max max (current-column)))
567 (goto-char (point-min))
568 ;; If the buffer is totally empty, then put a single blank
570 (if (zerop (buffer-size))
571 (insert (make-string width ? ))
572 ;; Otherwise, fill the buffer.
575 (when (> (- width (current-column)) 0)
576 (insert (make-string (- width (current-column)) ? )))
579 (count-lines (point-min) (point-max))
582 (shr-collect-overlays))))))
584 (defun shr-collect-overlays ()
586 (goto-char (point-min))
587 (let ((overlays nil))
589 (push (shr-overlays-in-region (point) (line-end-position))
592 (nreverse overlays))))
594 (defun shr-overlays-in-region (start end)
596 (dolist (overlay (overlays-in start end))
597 (push (list (if (> start (overlay-start overlay))
599 (- end (overlay-start overlay)))
600 (if (< end (overlay-end overlay))
602 (- end (overlay-end overlay)))
603 (overlay-properties overlay))
607 (defun shr-pro-rate-columns (columns)
608 (let ((total-percentage 0)
609 (widths (make-vector (length columns) 0)))
610 (dotimes (i (length columns))
611 (incf total-percentage (aref columns i)))
612 (setq total-percentage (/ 1.0 total-percentage))
613 (dotimes (i (length columns))
614 (aset widths i (max (truncate (* (aref columns i)
620 ;; Return a summary of the number and shape of the TDs in the table.
621 (defun shr-column-specs (cont)
622 (let ((columns (make-vector (shr-max-columns cont) 1)))
624 (when (eq (car row) 'tr)
626 (dolist (column (cdr row))
627 (when (memq (car column) '(td th))
628 (let ((width (cdr (assq :width (cdr column)))))
630 (string-match "\\([0-9]+\\)%" width))
632 (/ (string-to-number (match-string 1 width))
637 (defun shr-count (cont elem)
640 (when (eq (car sub) elem)
644 (defun shr-max-columns (cont)
647 (when (eq (car row) 'tr)
648 (setq max (max max (+ (shr-count (cdr row) 'td)
649 (shr-count (cdr row) 'th))))))