* shr.el: Rearrange function order to be more logical.
[gnus] / lisp / shr.el
1 ;;; shr.el --- Simple HTML Renderer
2
3 ;; Copyright (C) 2010 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: html
7
8 ;; This file is part of GNU Emacs.
9
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.
14
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.
19
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/>.
22
23 ;;; Commentary:
24
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.
30
31 ;;; Code:
32
33 (require 'browse-url)
34
35 (defgroup shr nil
36   "Simple HTML Renderer"
37   :group 'mail)
38
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
44 fit these criteria."
45   :version "24.1"
46   :group 'shr
47   :type 'float)
48
49 (defcustom shr-blocked-images nil
50   "Images that have URLs matching this regexp will be blocked."
51   :version "24.1"
52   :group 'shr
53   :type 'regexp)
54
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.")
59
60 (defvar shr-width 70
61   "Frame width to use for rendering.")
62
63 ;;; Internal variables.
64
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)
71
72 (defvar shr-map
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)
80     map))
81
82 ;; Public functions and commands.
83
84 ;;;###autoload
85 (defun shr-insert-document (dom)
86   (let ((shr-state nil)
87         (shr-start nil))
88     (shr-descend (shr-transform-dom dom))))
89
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."
94   (interactive)
95   (let ((url (get-text-property (point) 'shr-url)))
96     (cond
97      ((not url)
98       (message "No URL under point"))
99      ;; Resolve redirected URLs.
100      ((equal url (car kill-ring))
101       (url-retrieve
102        url
103        (lambda (a)
104          (when (and (consp a)
105                     (eq (car a) :redirect))
106            (with-temp-buffer
107              (insert (cadr a))
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.
115      (t
116       (with-temp-buffer
117         (insert url)
118         (copy-region-as-kill (point-min) (point-max))
119         (message "Copied %s" url))))))
120
121 (defun shr-show-alt-text ()
122   "Show the ALT text of the image under point."
123   (interactive)
124   (let ((text (get-text-property (point) 'shr-alt)))
125     (if (not text)
126         (message "No image under point")
127       (message "%s" text))))
128
129 (defun shr-browse-image ()
130   "Browse the image under point."
131   (interactive)
132   (let ((url (get-text-property (point) 'shr-image)))
133     (if (not url)
134         (message "No image under point")
135       (message "Browsing %s..." url)
136       (browse-url url))))
137
138 ;;; Utility functions.
139
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)
144                   (cdr arg))
145             result))
146     (dolist (sub dom)
147       (if (stringp sub)
148           (push (cons :text sub) result)
149         (push (shr-transform-dom sub) result)))
150     (nreverse result)))
151
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)))))
157
158 (defun shr-generic (cont)
159   (dolist (sub cont)
160     (cond
161      ((eq (car sub) :text)
162       (shr-insert (cdr sub)))
163      ((listp (cdr sub))
164       (shr-descend sub)))))
165
166 (defun shr-insert (text)
167   (when (eq shr-state 'image)
168     (insert "\n")
169     (setq shr-state nil))
170   (cond
171    ((eq shr-folding-mode 'none)
172     (insert text))
173    (t
174     (let ((first t)
175           column)
176       (when (and (string-match "\\`[ \t\n]" text)
177                  (not (bolp)))
178         (insert " "))
179       (dolist (elem (split-string text))
180         (setq column (current-column))
181         (when (> column 0)
182           (cond
183            ((and (or (not first)
184                      (eq shr-state 'space))
185                  (> (+ column (length elem) 1) shr-width))
186             (insert "\n"))
187            ((not first)
188             (insert " "))))
189         (setq first nil)
190         (when (and (bolp)
191                    (> shr-indentation 0))
192           (shr-indent))
193         ;; The shr-start is a special variable that is used to pass
194         ;; upwards the first point in the buffer where the text really
195         ;; starts.
196         (unless shr-start
197           (setq shr-start (point)))
198         (insert elem))
199       (setq shr-state nil)
200       (when (and (string-match "[ \t\n]\\'" text)
201                  (not (bolp)))
202         (insert " ")
203         (setq shr-state 'space))))))
204
205 (defun shr-ensure-newline ()
206   (unless (zerop (current-column))
207     (insert "\n")))
208
209 (defun shr-ensure-paragraph ()
210   (unless (bobp)
211     (if (bolp)
212         (unless (save-excursion
213                   (forward-line -1)
214                   (looking-at " *$"))
215           (insert "\n"))
216       (if (save-excursion
217             (beginning-of-line)
218             (looking-at " *$"))
219           (insert "\n")
220         (insert "\n\n")))))
221
222 (defun shr-indent ()
223   (insert (make-string shr-indentation ? )))
224
225 (defun shr-fontize-cont (cont &rest types)
226   (let (shr-start)
227     (shr-generic cont)
228     (dolist (type types)
229       (shr-add-font (or shr-start (point)) (point) type))))
230
231 (defun shr-add-font (start end type)
232   (let ((overlay (make-overlay start end)))
233     (overlay-put overlay 'face type)))
234
235 (defun shr-browse-url ()
236   "Browse the URL under point."
237   (interactive)
238   (let ((url (get-text-property (point) 'shr-url)))
239     (if (not url)
240         (message "No link under point")
241       (browse-url url))))
242
243 (defun shr-image-fetched (status buffer start end)
244   (when (and (buffer-name buffer)
245              (not (plist-get status :error)))
246     (url-store-in-cache (current-buffer))
247     (when (or (search-forward "\n\n" nil t)
248               (search-forward "\r\n\r\n" nil t))
249       (let ((data (buffer-substring (point) (point-max))))
250         (with-current-buffer buffer
251           (let ((alt (buffer-substring start end))
252                 (inhibit-read-only t))
253             (delete-region start end)
254             (shr-put-image data start alt))))))
255   (kill-buffer (current-buffer)))
256
257 (defun shr-put-image (data point alt)
258   (if (not (display-graphic-p))
259       (insert alt)
260     (let ((image (ignore-errors
261                    (shr-rescale-image data))))
262       (when image
263         (put-image image point alt)))))
264
265 (defun shr-rescale-image (data)
266   (if (or (not (fboundp 'imagemagick-types))
267           (not (get-buffer-window (current-buffer))))
268       (create-image data nil t)
269     (let* ((image (create-image data nil t))
270            (size (image-size image t))
271            (width (car size))
272            (height (cdr size))
273            (edges (window-inside-pixel-edges
274                    (get-buffer-window (current-buffer))))
275            (window-width (truncate (* shr-max-image-proportion
276                                       (- (nth 2 edges) (nth 0 edges)))))
277            (window-height (truncate (* shr-max-image-proportion
278                                        (- (nth 3 edges) (nth 1 edges)))))
279            scaled-image)
280       (when (> height window-height)
281         (setq image (or (create-image data 'imagemagick t
282                                       :height window-height)
283                         image))
284         (setq size (image-size image t)))
285       (when (> (car size) window-width)
286         (setq image (or
287                      (create-image data 'imagemagick t
288                                    :width window-width)
289                      image)))
290       image)))
291
292 (defun shr-get-image-data (url)
293   "Get image data for URL.
294 Return a string with image data."
295   (with-temp-buffer
296     (mm-disable-multibyte)
297     (when (ignore-errors
298             (url-cache-extract (url-cache-create-filename url))
299             t)
300       (when (or (search-forward "\n\n" nil t)
301                 (search-forward "\r\n\r\n" nil t))
302         (buffer-substring (point) (point-max))))))
303
304 (defun shr-heading (cont &rest types)
305   (shr-ensure-paragraph)
306   (apply #'shr-fontize-cont cont types)
307   (shr-ensure-paragraph))
308
309 ;;; Tag-specific rendering rules.
310
311 (defun shr-tag-p (cont)
312   (shr-ensure-paragraph)
313   (shr-generic cont)
314   (shr-ensure-paragraph))
315
316 (defun shr-tag-b (cont)
317   (shr-fontize-cont cont 'bold))
318
319 (defun shr-tag-i (cont)
320   (shr-fontize-cont cont 'italic))
321
322 (defun shr-tag-em (cont)
323   (shr-fontize-cont cont 'bold))
324
325 (defun shr-tag-u (cont)
326   (shr-fontize-cont cont 'underline))
327
328 (defun shr-tag-s (cont)
329   (shr-fontize-cont cont 'strike-through))
330
331 (defun shr-tag-a (cont)
332   (let ((url (cdr (assq :href cont)))
333         (start (point))
334         shr-start)
335     (shr-generic cont)
336     (widget-convert-button
337      'link (or shr-start start) (point)
338      :help-echo url)
339     (put-text-property (or shr-start start) (point) 'keymap shr-map)
340     (put-text-property (or shr-start start) (point) 'shr-url url)))
341
342 (defun shr-tag-img (cont)
343   (when (and (> (current-column) 0)
344              (not (eq shr-state 'image)))
345     (insert "\n"))
346   (let ((start (point-marker)))
347     (let ((alt (cdr (assq :alt cont)))
348           (url (cdr (assq :src cont))))
349       (when (zerop (length alt))
350         (setq alt "[img]"))
351       (cond
352        ((and (not shr-inhibit-images)
353              (string-match "\\`cid:" url))
354         (let ((url (substring url (match-end 0)))
355               image)
356           (if (or (not shr-content-function)
357                   (not (setq image (funcall shr-content-function url))))
358               (insert alt)
359             (shr-put-image image (point) alt))))
360        ((or shr-inhibit-images
361             (and shr-blocked-images
362                  (string-match shr-blocked-images url)))
363         (setq shr-start (point))
364         (let ((shr-state 'space))
365           (if (> (length alt) 8)
366               (shr-insert (substring alt 0 8))
367             (shr-insert alt))))
368        ((url-is-cached (browse-url-url-encode-chars url "[&)$ ]"))
369         (shr-put-image (shr-get-image-data url) (point) alt))
370        (t
371         (insert alt)
372         (ignore-errors
373           (url-retrieve url 'shr-image-fetched
374                         (list (current-buffer) start (point-marker))
375                         t))))
376       (insert " ")
377       (put-text-property start (point) 'keymap shr-map)
378       (put-text-property start (point) 'shr-alt alt)
379       (put-text-property start (point) 'shr-image url)
380       (setq shr-state 'image))))
381
382 (defun shr-tag-pre (cont)
383   (let ((shr-folding-mode 'none))
384     (shr-ensure-newline)
385     (shr-generic cont)
386     (shr-ensure-newline)))
387
388 (defun shr-tag-blockquote (cont)
389   (shr-ensure-paragraph)
390   (let ((shr-indentation (+ shr-indentation 4)))
391     (shr-generic cont))
392   (shr-ensure-paragraph))
393
394 (defun shr-tag-ul (cont)
395   (shr-ensure-paragraph)
396   (let ((shr-list-mode 'ul))
397     (shr-generic cont)))
398
399 (defun shr-tag-ol (cont)
400   (let ((shr-list-mode 1))
401     (shr-generic cont)))
402
403 (defun shr-tag-li (cont)
404   (shr-ensure-newline)
405   (let* ((bullet
406           (if (numberp shr-list-mode)
407               (prog1
408                   (format "%d " shr-list-mode)
409                 (setq shr-list-mode (1+ shr-list-mode)))
410             "* "))
411          (shr-indentation (+ shr-indentation (length bullet))))
412     (insert bullet)
413     (shr-generic cont)))
414
415 (defun shr-tag-br (cont)
416   (unless (bobp)
417     (insert "\n"))
418   (shr-generic cont))
419
420 (defun shr-tag-h1 (cont)
421   (shr-heading cont 'bold 'underline))
422
423 (defun shr-tag-h2 (cont)
424   (shr-heading cont 'bold))
425
426 (defun shr-tag-h3 (cont)
427   (shr-heading cont 'italic))
428
429 (defun shr-tag-h4 (cont)
430   (shr-heading cont))
431
432 (defun shr-tag-h5 (cont)
433   (shr-heading cont))
434
435 (defun shr-tag-h6 (cont)
436   (shr-heading cont))
437
438 ;;; Table rendering algorithm.
439
440 ;; Table rendering is the only complicated thing here.  We do this by
441 ;; first counting how many TDs there are in each TR, and registering
442 ;; how wide they think they should be ("width=45%", etc).  Then we
443 ;; render each TD separately (this is done in temporary buffers, so
444 ;; that we can use all the rendering machinery as if we were in the
445 ;; main buffer).  Now we know how much space each TD really takes, so
446 ;; we then render everything again with the new widths, and finally
447 ;; insert all these boxes into the main buffer.
448 (defun shr-tag-table (cont)
449   (shr-ensure-paragraph)
450   (setq cont (or (cdr (assq 'tbody cont))
451                  cont))
452   (let* ((shr-inhibit-images t)
453          ;; Find all suggested widths.
454          (columns (shr-column-specs cont))
455          ;; Compute how many characters wide each TD should be.
456          (suggested-widths (shr-pro-rate-columns columns))
457          ;; Do a "test rendering" to see how big each TD is (this can
458          ;; be smaller (if there's little text) or bigger (if there's
459          ;; unbreakable text).
460          (sketch (shr-make-table cont suggested-widths))
461          (sketch-widths (shr-table-widths sketch (length suggested-widths))))
462     ;; Then render the table again with these new "hard" widths.
463     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
464   ;; Finally, insert all the images after the table.  The Emacs buffer
465   ;; model isn't strong enough to allow us to put the images actually
466   ;; into the tables.
467   (dolist (elem (shr-find-elements cont 'img))
468     (shr-tag-img (cdr elem))))
469
470 (defun shr-find-elements (cont type)
471   (let (result)
472     (dolist (elem cont)
473       (cond ((eq (car elem) type)
474              (push elem result))
475             ((consp (cdr elem))
476              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
477     (nreverse result)))
478
479 (defun shr-insert-table (table widths)
480   (shr-insert-table-ruler widths)
481   (dolist (row table)
482     (let ((start (point))
483           (height (let ((max 0))
484                     (dolist (column row)
485                       (setq max (max max (cadr column))))
486                     max)))
487       (dotimes (i height)
488         (shr-indent)
489         (insert "|\n"))
490       (dolist (column row)
491         (goto-char start)
492         (let ((lines (split-string (nth 2 column) "\n"))
493               (overlay-lines (nth 3 column))
494               overlay overlay-line)
495           (dolist (line lines)
496             (setq overlay-line (pop overlay-lines))
497             (when (> (length line) 0)
498               (end-of-line)
499               (insert line "|")
500               (dolist (overlay overlay-line)
501                 (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
502                                        (- (point) (nth 1 overlay) 1)))
503                       (properties (nth 2 overlay)))
504                   (while properties
505                     (overlay-put o (pop properties) (pop properties)))))
506               (forward-line 1)))
507           ;; Add blank lines at padding at the bottom of the TD,
508           ;; possibly.
509           (dotimes (i (- height (length lines)))
510             (end-of-line)
511             (insert (make-string (length (car lines)) ? ) "|")
512             (forward-line 1)))))
513     (shr-insert-table-ruler widths)))
514
515 (defun shr-insert-table-ruler (widths)
516   (shr-indent)
517   (insert "+")
518   (dotimes (i (length widths))
519     (insert (make-string (aref widths i) ?-) ?+))
520   (insert "\n"))
521
522 (defun shr-table-widths (table length)
523   (let ((widths (make-vector length 0)))
524     (dolist (row table)
525       (let ((i 0))
526         (dolist (column row)
527           (aset widths i (max (aref widths i)
528                               (car column)))
529           (incf i))))
530     widths))
531
532 (defun shr-make-table (cont widths &optional fill)
533   (let ((trs nil))
534     (dolist (row cont)
535       (when (eq (car row) 'tr)
536         (let ((tds nil)
537               (columns (cdr row))
538               (i 0)
539               column)
540           (while (< i (length widths))
541             (setq column (pop columns))
542             (when (or (memq (car column) '(td th))
543                       (null column))
544               (push (shr-render-td (cdr column) (aref widths i) fill)
545                     tds)
546               (setq i (1+ i))))
547           (push (nreverse tds) trs))))
548     (nreverse trs)))
549
550 (defun shr-render-td (cont width fill)
551   (with-temp-buffer
552     (let ((shr-width width)
553           (shr-indentation 0))
554       (shr-generic cont))
555     (while (re-search-backward "\n *$" nil t)
556       (delete-region (match-beginning 0) (match-end 0)))
557     (goto-char (point-min))
558     (let ((max 0))
559       (while (not (eobp))
560         (end-of-line)
561         (setq max (max max (current-column)))
562         (forward-line 1))
563       (when fill
564         (goto-char (point-min))
565         ;; If the buffer is totally empty, then put a single blank
566         ;; line here.
567         (if (zerop (buffer-size))
568             (insert (make-string width ? ))
569           ;; Otherwise, fill the buffer.
570           (while (not (eobp))
571             (end-of-line)
572             (when (> (- width (current-column)) 0)
573               (insert (make-string (- width (current-column)) ? )))
574             (forward-line 1))))
575       (list max
576             (count-lines (point-min) (point-max))
577             (buffer-string)
578             (and fill
579                  (shr-collect-overlays))))))
580
581 (defun shr-collect-overlays ()
582   (save-excursion
583     (goto-char (point-min))
584     (let ((overlays nil))
585       (while (not (eobp))
586         (push (shr-overlays-in-region (point) (line-end-position))
587               overlays)
588         (forward-line 1))
589       (nreverse overlays))))
590
591 (defun shr-overlays-in-region (start end)
592   (let (result)
593     (dolist (overlay (overlays-in start end))
594       (push (list (if (> start (overlay-start overlay))
595                       (- end start)
596                     (- end (overlay-start overlay)))
597                   (if (< end (overlay-end overlay))
598                       0
599                     (- end (overlay-end overlay)))
600                   (overlay-properties overlay))
601             result))
602     (nreverse result)))
603
604 (defun shr-pro-rate-columns (columns)
605   (let ((total-percentage 0)
606         (widths (make-vector (length columns) 0)))
607     (dotimes (i (length columns))
608       (incf total-percentage (aref columns i)))
609     (setq total-percentage (/ 1.0 total-percentage))
610     (dotimes (i (length columns))
611       (aset widths i (max (truncate (* (aref columns i)
612                                        total-percentage
613                                        shr-width))
614                           10)))
615     widths))
616
617 ;; Return a summary of the number and shape of the TDs in the table.
618 (defun shr-column-specs (cont)
619   (let ((columns (make-vector (shr-max-columns cont) 1)))
620     (dolist (row cont)
621       (when (eq (car row) 'tr)
622         (let ((i 0))
623           (dolist (column (cdr row))
624             (when (memq (car column) '(td th))
625               (let ((width (cdr (assq :width (cdr column)))))
626                 (when (and width
627                            (string-match "\\([0-9]+\\)%" width))
628                   (aset columns i
629                         (/ (string-to-number (match-string 1 width))
630                            100.0))))
631               (setq i (1+ i)))))))
632     columns))
633
634 (defun shr-count (cont elem)
635   (let ((i 0))
636     (dolist (sub cont)
637       (when (eq (car sub) elem)
638         (setq i (1+ i))))
639     i))
640
641 (defun shr-max-columns (cont)
642   (let ((max 0))
643     (dolist (row cont)
644       (when (eq (car row) 'tr)
645         (setq max (max max (+ (shr-count (cdr row) 'td)
646                               (shr-count (cdr row) 'th))))))
647     max))
648
649 (provide 'shr)
650
651 ;;; shr.el ends here