e97ca1da47a85df57d7f1bee44618f6257be6fae
[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-folding-mode nil)
56 (defvar shr-state nil)
57 (defvar shr-start nil)
58 (defvar shr-indentation 0)
59
60 (defvar shr-width 70)
61
62 (defvar shr-map
63   (let ((map (make-sparse-keymap)))
64     (define-key map "a" 'shr-show-alt-text)
65     (define-key map "i" 'shr-browse-image)
66     (define-key map "I" 'shr-insert-image)
67     (define-key map "u" 'shr-copy-url)
68     (define-key map "v" 'shr-browse-url)
69     (define-key map "\r" 'shr-browse-url)
70     map))
71
72 (defun shr-transform-dom (dom)
73   (let ((result (list (pop dom))))
74     (dolist (arg (pop dom))
75       (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
76                   (cdr arg))
77             result))
78     (dolist (sub dom)
79       (if (stringp sub)
80           (push (cons :text sub) result)
81         (push (shr-transform-dom sub) result)))
82     (nreverse result)))
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-descend (dom)
91   (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray)))
92     (if (fboundp function)
93         (funcall function (cdr dom))
94       (shr-generic (cdr dom)))))
95
96 (defun shr-generic (cont)
97   (dolist (sub cont)
98     (cond
99      ((eq (car sub) :text)
100       (shr-insert (cdr sub)))
101      ((listp (cdr sub))
102       (shr-descend sub)))))
103
104 (defun shr-tag-p (cont)
105   (shr-ensure-paragraph)
106   (shr-generic cont)
107   (shr-ensure-paragraph))
108
109 (defun shr-ensure-paragraph ()
110   (unless (bobp)
111     (if (bolp)
112         (unless (save-excursion
113                   (forward-line -1)
114                   (looking-at " *$"))
115           (insert "\n"))
116       (if (save-excursion
117             (beginning-of-line)
118             (looking-at " *$"))
119           (insert "\n")
120         (insert "\n\n")))))
121
122 (defun shr-tag-b (cont)
123   (shr-fontize-cont cont 'bold))
124
125 (defun shr-tag-i (cont)
126   (shr-fontize-cont cont 'italic))
127
128 (defun shr-tag-u (cont)
129   (shr-fontize-cont cont 'underline))
130
131 (defun shr-tag-s (cont)
132   (shr-fontize-cont cont 'strike-through))
133
134 (defun shr-fontize-cont (cont &rest types)
135   (let (shr-start)
136     (shr-generic cont)
137     (dolist (type types)
138       (shr-add-font (or shr-start (point)) (point) type))))
139
140 (defun shr-add-font (start end type)
141   (let ((overlay (make-overlay start end)))
142     (overlay-put overlay 'face type)))
143
144 (defun shr-tag-a (cont)
145   (let ((url (cdr (assq :href cont)))
146         (start (point))
147         shr-start)
148     (shr-generic cont)
149     (widget-convert-button
150      'link (or shr-start start) (point)
151      :help-echo url)
152     (put-text-property (or shr-start start) (point) 'keymap shr-map)
153     (put-text-property (or shr-start start) (point) 'shr-url url)))
154
155 (defun shr-browse-url ()
156   "Browse the URL under point."
157   (interactive)
158   (let ((url (get-text-property (point) 'shr-url)))
159     (if (not url)
160         (message "No link under point")
161       (browse-url url))))
162
163 (defun shr-copy-url ()
164   "Copy the URL under point to the kill ring.
165 If called twice, then try to fetch the URL and see whether it
166 redirects somewhere else."
167   (interactive)
168   (let ((url (get-text-property (point) 'shr-url)))
169     (cond
170      ((not url)
171       (message "No URL under point"))
172      ;; Resolve redirected URLs.
173      ((equal url (car kill-ring))
174       (url-retrieve
175        url
176        (lambda (a)
177          (when (and (consp a)
178                     (eq (car a) :redirect))
179            (with-temp-buffer
180              (insert (cadr a))
181              (goto-char (point-min))
182              ;; Remove common tracking junk from the URL.
183              (when (re-search-forward ".utm_.*" nil t)
184                (replace-match "" t t))
185              (message "Copied %s" (buffer-string))
186              (copy-region-as-kill (point-min) (point-max)))))))
187      ;; Copy the URL to the kill ring.
188      (t
189       (with-temp-buffer
190         (insert url)
191         (copy-region-as-kill (point-min) (point-max))
192         (message "Copied %s" url))))))
193
194 (eval-and-compile
195   (defalias 'shr-encode-url-chars
196     ;; Neither Emacs 22 nor XEmacs provides this function.
197     (if (fboundp 'browse-url-url-encode-chars)
198         'browse-url-url-encode-chars
199       (lambda (text chars)
200         "URL-encode the chars in TEXT that match CHARS.
201 CHARS is a regexp-like character alternative (e.g., \"[)$]\")."
202         (let ((encoded-text (copy-sequence text))
203               (s 0))
204           (while (setq s (string-match chars encoded-text s))
205             (setq encoded-text
206                   (replace-match (format "%%%x"
207                                          (string-to-char
208                                           (match-string 0 encoded-text)))
209                                  t t encoded-text)
210                   s (1+ s)))
211           encoded-text)))))
212
213 (defun shr-tag-img (cont)
214   (when (and (> (current-column) 0)
215              (not (eq shr-state 'image)))
216     (insert "\n"))
217   (let ((start (point-marker)))
218     (let ((alt (cdr (assq :alt cont)))
219           (url (cdr (assq :src cont))))
220       (when (zerop (length alt))
221         (setq alt "[img]"))
222       (cond
223        ((and shr-blocked-images
224              (string-match shr-blocked-images url))
225         (insert alt))
226        ((url-is-cached (shr-encode-url-chars url "[&)$ ]"))
227         (shr-put-image (shr-get-image-data url) (point) alt))
228        (t
229         (insert alt)
230         (url-retrieve url 'shr-image-fetched
231                       (list (current-buffer) start (point-marker))
232                       t)))
233       (insert " ")
234       (put-text-property start (point) 'keymap shr-map)
235       (put-text-property start (point) 'shr-alt alt)
236       (put-text-property start (point) 'shr-image url)
237       (setq shr-state 'image))))
238
239 (defun shr-show-alt-text ()
240   "Show the ALT text of the image under point."
241   (interactive)
242   (let ((text (get-text-property (point) 'shr-alt)))
243     (if (not text)
244         (message "No image under point")
245       (message "%s" text))))
246
247 (defun shr-browse-image ()
248   "Browse the image under point."
249   (interactive)
250   (let ((url (get-text-property (point) 'shr-image)))
251     (if (not url)
252         (message "No image under point")
253       (message "Browsing %s..." url)
254       (browse-url url))))
255
256 (defun shr-image-fetched (status buffer start end)
257   (when (and (buffer-name buffer)
258              (not (plist-get status :error)))
259     (url-store-in-cache (current-buffer))
260     (when (or (search-forward "\n\n" nil t)
261               (search-forward "\r\n\r\n" nil t))
262       (let ((data (buffer-substring (point) (point-max))))
263         (with-current-buffer buffer
264           (let ((alt (buffer-substring start end))
265                 (inhibit-read-only t))
266             (delete-region start end)
267             (shr-put-image data start alt))))))
268   (kill-buffer (current-buffer)))
269
270 (defun shr-put-image (data point alt)
271   (if (not (display-graphic-p))
272       (insert alt)
273     (let ((image (ignore-errors
274                    (shr-rescale-image data))))
275       (when image
276         (put-image image point alt)))))
277
278 (defun shr-rescale-image (data)
279   (if (or (not (fboundp 'imagemagick-types))
280           (not (get-buffer-window (current-buffer))))
281       (create-image data nil t)
282     (let* ((image (create-image data nil t))
283            (size (image-size image t))
284            (width (car size))
285            (height (cdr size))
286            (edges (window-inside-pixel-edges
287                    (get-buffer-window (current-buffer))))
288            (window-width (truncate (* shr-max-image-proportion
289                                       (- (nth 2 edges) (nth 0 edges)))))
290            (window-height (truncate (* shr-max-image-proportion
291                                        (- (nth 3 edges) (nth 1 edges)))))
292            scaled-image)
293       (when (> height window-height)
294         (setq image (or (create-image data 'imagemagick t
295                                       :height window-height)
296                         image))
297         (setq size (image-size image t)))
298       (when (> (car size) window-width)
299         (setq image (or
300                      (create-image data 'imagemagick t
301                                    :width window-width)
302                      image)))
303       image)))
304
305 (defun shr-tag-pre (cont)
306   (let ((shr-folding-mode 'none))
307     (shr-ensure-newline)
308     (shr-generic cont)
309     (shr-ensure-newline)))
310
311 (defun shr-tag-blockquote (cont)
312   (shr-ensure-paragraph)
313   (let ((shr-indentation (+ shr-indentation 4)))
314     (shr-generic cont))
315   (shr-ensure-paragraph))
316
317 (defun shr-ensure-newline ()
318   (unless (zerop (current-column))
319     (insert "\n")))
320
321 (defun shr-insert (text)
322   (when (eq shr-state 'image)
323     (insert "\n")
324     (setq shr-state nil))
325   (cond
326    ((eq shr-folding-mode 'none)
327     (insert text))
328    (t
329     (let ((first t)
330           column)
331       (when (and (string-match "\\`[ \t\n]" text)
332                  (not (bolp)))
333         (insert " "))
334       (dolist (elem (split-string text))
335         (setq column (current-column))
336         (when (> column 0)
337           (cond
338            ((and (or (not first)
339                      (eq shr-state 'space))
340                  (> (+ column (length elem) 1) shr-width))
341             (insert "\n"))
342            ((not first)
343             (insert " "))))
344         (setq first nil)
345         (when (and (bolp)
346                    (> shr-indentation 0))
347           (shr-indent))
348         ;; The shr-start is a special variable that is used to pass
349         ;; upwards the first point in the buffer where the text really
350         ;; starts.
351         (unless shr-start
352           (setq shr-start (point)))
353         (insert elem))
354       (setq shr-state nil)
355       (when (and (string-match "[ \t\n]\\'" text)
356                  (not (bolp)))
357         (insert " ")
358         (setq shr-state 'space))))))
359
360 (defun shr-indent ()
361   (insert (make-string shr-indentation ? )))
362
363 (defun shr-get-image-data (url)
364   "Get image data for URL.
365 Return a string with image data."
366   (with-temp-buffer
367     (mm-disable-multibyte)
368     (when (ignore-errors
369             (url-cache-extract (url-cache-create-filename url))
370             t)
371       (when (or (search-forward "\n\n" nil t)
372                 (search-forward "\r\n\r\n" nil t))
373         (buffer-substring (point) (point-max))))))
374
375 (defvar shr-list-mode nil)
376
377 (defun shr-tag-ul (cont)
378   (shr-ensure-paragraph)
379   (let ((shr-list-mode 'ul))
380     (shr-generic cont)))
381
382 (defun shr-tag-ol (cont)
383   (let ((shr-list-mode 1))
384     (shr-generic cont)))
385
386 (defun shr-tag-li (cont)
387   (shr-ensure-newline)
388   (let* ((bullet
389           (if (numberp shr-list-mode)
390               (prog1
391                   (format "%d " shr-list-mode)
392                 (setq shr-list-mode (1+ shr-list-mode)))
393             "* "))
394          (shr-indentation (+ shr-indentation (length bullet))))
395     (insert bullet)
396     (shr-generic cont)))
397
398 (defun shr-tag-br (cont)
399   (unless (bobp)
400     (insert "\n"))
401   (shr-generic cont))
402
403 (defun shr-tag-h1 (cont)
404   (shr-heading cont 'bold 'underline))
405
406 (defun shr-tag-h2 (cont)
407   (shr-heading cont 'bold))
408
409 (defun shr-tag-h3 (cont)
410   (shr-heading cont 'italic))
411
412 (defun shr-tag-h4 (cont)
413   (shr-heading cont))
414
415 (defun shr-tag-h5 (cont)
416   (shr-heading cont))
417
418 (defun shr-tag-h6 (cont)
419   (shr-heading cont))
420
421 (defun shr-heading (cont &rest types)
422   (shr-ensure-paragraph)
423   (apply #'shr-fontize-cont cont types)
424   (shr-ensure-paragraph))
425
426 (defun shr-tag-table (cont)
427   (shr-ensure-paragraph)
428   (setq cont (or (cdr (assq 'tbody cont))
429                  cont))
430   (let* ((columns (shr-column-specs cont))
431          (suggested-widths (shr-pro-rate-columns columns))
432          (sketch (shr-make-table cont suggested-widths))
433          (sketch-widths (shr-table-widths sketch (length suggested-widths))))
434     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths)))
435
436 (defun shr-insert-table (table widths)
437   (shr-insert-table-ruler widths)
438   (dolist (row table)
439     (let ((start (point))
440           (height (let ((max 0))
441                     (dolist (column row)
442                       (setq max (max max (cadr column))))
443                     max)))
444       (dotimes (i height)
445         (shr-indent)
446         (insert "|\n"))
447       (dolist (column row)
448         (goto-char start)
449         (let ((lines (split-string (nth 2 column) "\n")))
450           (dolist (line lines)
451             (when (> (length line) 0)
452               (end-of-line)
453               (insert line "|")
454               (forward-line 1)))
455           ;; Add blank lines at padding at the bottom of the TD,
456           ;; possibly.
457           (dotimes (i (- height (length lines)))
458             (end-of-line)
459             (insert (make-string (length (car lines)) ? ) "|")
460             (forward-line 1)))))
461     (shr-insert-table-ruler widths)))
462
463 (defun shr-insert-table-ruler (widths)
464   (shr-indent)
465   (insert "+")
466   (dotimes (i (length widths))
467     (insert (make-string (aref widths i) ?-) ?+))
468   (insert "\n"))
469
470 (defun shr-table-widths (table length)
471   (let ((widths (make-vector length 0)))
472     (dolist (row table)
473       (let ((i 0))
474         (dolist (column row)
475           (aset widths i (max (aref widths i)
476                               (car column)))
477           (incf i))))
478     widths))
479
480 (defun shr-make-table (cont widths &optional fill)
481   (let ((trs nil))
482     (dolist (row cont)
483       (when (eq (car row) 'tr)
484         (let ((i 0)
485               (tds nil))
486           (dolist (column (cdr row))
487             (when (memq (car column) '(td th))
488               (push (shr-render-td (cdr column) (aref widths i) fill)
489                     tds)
490               (setq i (1+ i))))
491           (push (nreverse tds) trs))))
492     (nreverse trs)))
493
494 (defun shr-render-td (cont width fill)
495   (with-temp-buffer
496     (let ((shr-width width)
497           (shr-indentation 0))
498       (shr-generic cont))
499     (while (re-search-backward "\n *$" nil t)
500       (delete-region (match-beginning 0) (match-end 0)))
501     (goto-char (point-min))
502     (let ((max 0))
503       (while (not (eobp))
504         (end-of-line)
505         (setq max (max max (current-column)))
506         (forward-line 1))
507       (when fill
508         (goto-char (point-min))
509         (while (not (eobp))
510           (end-of-line)
511           (when (> (- width (current-column)) 0)
512             (insert (make-string (- width (current-column)) ? )))
513           (forward-line 1)))
514       (list max (count-lines (point-min) (point-max)) (buffer-string)))))
515
516 (defun shr-pro-rate-columns (columns)
517   (let ((total-percentage 0)
518         (widths (make-vector (length columns) 0)))
519     (dotimes (i (length columns))
520       (incf total-percentage (aref columns i)))
521     (setq total-percentage (/ 1.0 total-percentage))
522     (dotimes (i (length columns))
523       (aset widths i (max (truncate (* (aref columns i)
524                                        total-percentage
525                                        shr-width))
526                           10)))
527     widths))
528
529 ;; Return a summary of the number and shape of the TDs in the table.
530 (defun shr-column-specs (cont)
531   (let ((columns (make-vector (shr-max-columns cont) 1)))
532     (dolist (row cont)
533       (when (eq (car row) 'tr)
534         (let ((i 0))
535           (dolist (column (cdr row))
536             (when (memq (car column) '(td th))
537               (let ((width (cdr (assq :width (cdr column)))))
538                 (when (and width
539                            (string-match "\\([0-9]+\\)%" width))
540                   (aset columns i
541                         (/ (string-to-number (match-string 1 width))
542                            100.0)))))
543             (setq i (1+ i))))))
544     columns))
545
546 (defun shr-count (cont elem)
547   (let ((i 0))
548     (dolist (sub cont)
549       (when (eq (car sub) elem)
550         (setq i (1+ i))))
551     i))
552
553 (defun shr-max-columns (cont)
554   (let ((max 0))
555     (dolist (row cont)
556       (when (eq (car row) 'tr)
557         (setq max (max max (shr-count (cdr row) 'td)))))
558     max))
559
560 (provide 'shr)
561
562 ;;; shr.el ends here