Merge branch 'master' of https://git.gnus.org/gnus
[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 (defun shr-tag-img (cont)
195   (when (and (> (current-column) 0)
196              (not (eq shr-state 'image)))
197     (insert "\n"))
198   (let ((start (point-marker)))
199     (let ((alt (cdr (assq :alt cont)))
200           (url (cdr (assq :src cont))))
201       (when (zerop (length alt))
202         (setq alt "[img]"))
203       (cond
204        ((and shr-blocked-images
205              (string-match shr-blocked-images url))
206         (insert alt))
207        ((url-is-cached (browse-url-url-encode-chars url "[&)$ ]"))
208         (shr-put-image (shr-get-image-data url) (point) alt))
209        (t
210         (insert alt)
211         (url-retrieve url 'shr-image-fetched
212                       (list (current-buffer) start (point-marker))
213                       t)))
214       (insert " ")
215       (put-text-property start (point) 'keymap shr-map)
216       (put-text-property start (point) 'shr-alt alt)
217       (put-text-property start (point) 'shr-image url)
218       (setq shr-state 'image))))
219
220 (defun shr-show-alt-text ()
221   "Show the ALT text of the image under point."
222   (interactive)
223   (let ((text (get-text-property (point) 'shr-alt)))
224     (if (not text)
225         (message "No image under point")
226       (message "%s" text))))
227
228 (defun shr-browse-image ()
229   "Browse the image under point."
230   (interactive)
231   (let ((url (get-text-property (point) 'shr-image)))
232     (if (not url)
233         (message "No image under point")
234       (message "Browsing %s..." url)
235       (browse-url url))))
236
237 (defun shr-image-fetched (status buffer start end)
238   (when (and (buffer-name buffer)
239              (not (plist-get status :error)))
240     (url-store-in-cache (current-buffer))
241     (when (or (search-forward "\n\n" nil t)
242               (search-forward "\r\n\r\n" nil t))
243       (let ((data (buffer-substring (point) (point-max))))
244         (with-current-buffer buffer
245           (let ((alt (buffer-substring start end))
246                 (inhibit-read-only t))
247             (delete-region start end)
248             (shr-put-image data start alt))))))
249   (kill-buffer (current-buffer)))
250
251 (defun shr-put-image (data point alt)
252   (if (not (display-graphic-p))
253       (insert alt)
254     (let ((image (ignore-errors
255                    (shr-rescale-image data))))
256       (when image
257         (put-image image point alt)))))
258
259 (defun shr-rescale-image (data)
260   (if (or (not (fboundp 'imagemagick-types))
261           (not (get-buffer-window (current-buffer))))
262       (create-image data nil t)
263     (let* ((image (create-image data nil t))
264            (size (image-size image t))
265            (width (car size))
266            (height (cdr size))
267            (edges (window-inside-pixel-edges
268                    (get-buffer-window (current-buffer))))
269            (window-width (truncate (* shr-max-image-proportion
270                                       (- (nth 2 edges) (nth 0 edges)))))
271            (window-height (truncate (* shr-max-image-proportion
272                                        (- (nth 3 edges) (nth 1 edges)))))
273            scaled-image)
274       (when (> height window-height)
275         (setq image (or (create-image data 'imagemagick t
276                                       :height window-height)
277                         image))
278         (setq size (image-size image t)))
279       (when (> (car size) window-width)
280         (setq image (or
281                      (create-image data 'imagemagick t
282                                    :width window-width)
283                      image)))
284       image)))
285
286 (defun shr-tag-pre (cont)
287   (let ((shr-folding-mode 'none))
288     (shr-ensure-newline)
289     (shr-generic cont)
290     (shr-ensure-newline)))
291
292 (defun shr-tag-blockquote (cont)
293   (shr-ensure-paragraph)
294   (let ((shr-indentation (+ shr-indentation 4)))
295     (shr-generic cont)))
296
297 (defun shr-ensure-newline ()
298   (unless (zerop (current-column))
299     (insert "\n")))
300
301 (defun shr-insert (text)
302   (when (eq shr-state 'image)
303     (insert "\n")
304     (setq shr-state nil))
305   (cond
306    ((eq shr-folding-mode 'none)
307     (insert text))
308    (t
309     (let ((first t)
310           column)
311       (when (and (string-match "\\`[ \t\n]" text)
312                  (not (bolp)))
313         (insert " "))
314       (dolist (elem (split-string text))
315         (setq column (current-column))
316         (when (> column 0)
317           (cond
318            ((and (or (not first)
319                      (eq shr-state 'space))
320                  (> (+ column (length elem) 1) shr-width))
321             (insert "\n"))
322            ((not first)
323             (insert " "))))
324         (setq first nil)
325         (when (and (bolp)
326                    (> shr-indentation 0))
327           (shr-indent))
328         ;; The shr-start is a special variable that is used to pass
329         ;; upwards the first point in the buffer where the text really
330         ;; starts.
331         (unless shr-start
332           (setq shr-start (point)))
333         (insert elem))
334       (setq shr-state nil)
335       (when (and (string-match "[ \t\n]\\'" text)
336                  (not (bolp)))
337         (insert " ")
338         (setq shr-state 'space))))))
339
340 (defun shr-indent ()
341   (insert (make-string shr-indentation ? )))
342
343 (defun shr-get-image-data (url)
344   "Get image data for URL.
345 Return a string with image data."
346   (with-temp-buffer
347     (mm-disable-multibyte)
348     (url-cache-extract (url-cache-create-filename url))
349     (when (or (search-forward "\n\n" nil t)
350               (search-forward "\r\n\r\n" nil t))
351       (buffer-substring (point) (point-max)))))
352
353 (defvar shr-list-mode nil)
354
355 (defun shr-tag-ul (cont)
356   (shr-ensure-paragraph)
357   (let ((shr-list-mode 'ul))
358     (shr-generic cont)))
359
360 (defun shr-tag-ol (cont)
361   (let ((shr-list-mode 1))
362     (shr-generic cont)))
363
364 (defun shr-tag-li (cont)
365   (shr-ensure-newline)
366   (let* ((bullet
367           (if (numberp shr-list-mode)
368               (prog1
369                   (format "%d " shr-list-mode)
370                 (setq shr-list-mode (1+ shr-list-mode)))
371             "* "))
372          (shr-indentation (+ shr-indentation (length bullet))))
373     (insert bullet)
374     (shr-generic cont)))
375
376 (defun shr-tag-br (cont)
377   (unless (bobp)
378     (insert "\n"))
379   (shr-generic cont))
380
381 (defun shr-tag-h1 (cont)
382   (shr-heading cont 'bold 'underline))
383
384 (defun shr-tag-h2 (cont)
385   (shr-heading cont 'bold))
386
387 (defun shr-tag-h3 (cont)
388   (shr-heading cont 'italic))
389
390 (defun shr-tag-h4 (cont)
391   (shr-heading cont))
392
393 (defun shr-tag-h5 (cont)
394   (shr-heading cont))
395
396 (defun shr-tag-h6 (cont)
397   (shr-heading cont))
398
399 (defun shr-heading (cont &rest types)
400   (shr-ensure-paragraph)
401   (apply #'shr-fontize-cont cont types)
402   (shr-ensure-paragraph))
403
404 (defun shr-tag-table (cont)
405   (shr-ensure-paragraph)
406   (setq cont (or (cdr (assq 'tbody cont))
407                  cont))
408   (let* ((columns (shr-column-specs cont))
409          (suggested-widths (shr-pro-rate-columns columns))
410          (sketch (shr-make-table cont suggested-widths))
411          (sketch-widths (shr-table-widths sketch (length suggested-widths))))
412     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths)))
413
414 (defun shr-insert-table (table widths)
415   (shr-insert-table-ruler widths)
416   (dolist (row table)
417     (let ((start (point))
418           (height (let ((max 0))
419                     (dolist (column row)
420                       (setq max (max max (cadr column))))
421                     max)))
422       (dotimes (i height)
423         (shr-indent)
424         (insert "|\n"))
425       (dolist (column row)
426         (goto-char start)
427         (let ((lines (split-string (nth 2 column) "\n")))
428           (dolist (line lines)
429             (when (> (length line) 0)
430               (end-of-line)
431               (insert line "|")
432               (forward-line 1)))
433           ;; Add blank lines at padding at the bottom of the TD,
434           ;; possibly.
435           (dotimes (i (- height (length lines)))
436             (end-of-line)
437             (insert (make-string (length (car lines)) ? ) "|")
438             (forward-line 1)))))
439     (shr-insert-table-ruler widths)))
440
441 (defun shr-insert-table-ruler (widths)
442   (shr-indent)
443   (insert "+")
444   (dotimes (i (length widths))
445     (insert (make-string (aref widths i) ?-) ?+))
446   (insert "\n"))
447
448 (defun shr-table-widths (table length)
449   (let ((widths (make-vector length 0)))
450     (dolist (row table)
451       (let ((i 0))
452         (dolist (column row)
453           (aset widths i (max (aref widths i)
454                               (car column)))
455           (incf i))))
456     widths))
457
458 (defun shr-make-table (cont widths &optional fill)
459   (let ((trs nil))
460     (dolist (row cont)
461       (when (eq (car row) 'tr)
462         (let ((i 0)
463               (tds nil))
464           (dolist (column (cdr row))
465             (when (memq (car column) '(td th))
466               (push (shr-render-td (cdr column) (aref widths i) fill)
467                     tds)
468               (setq i (1+ i))))
469           (push (nreverse tds) trs))))
470     (nreverse trs)))
471
472 (defun shr-render-td (cont width fill)
473   (with-temp-buffer
474     (let ((shr-width width))
475       (shr-generic cont))
476     (while (re-search-backward "\n *$" nil t)
477       (delete-region (match-beginning 0) (match-end 0)))
478     (goto-char (point-min))
479     (let ((max 0))
480       (while (not (eobp))
481         (end-of-line)
482         (setq max (max max (current-column)))
483         (forward-line 1))
484       (when fill
485         (goto-char (point-min))
486         (while (not (eobp))
487           (end-of-line)
488           (insert (make-string (- width (current-column)) ? ))
489           (forward-line 1)))
490       (list max (count-lines (point-min) (point-max)) (buffer-string)))))
491
492 (defun shr-pro-rate-columns (columns)
493   (let ((total-percentage 0)
494         (widths (make-vector (length columns) 0)))
495     (dotimes (i (length columns))
496       (incf total-percentage (aref columns i)))
497     (setq total-percentage (/ 1.0 total-percentage))
498     (dotimes (i (length columns))
499       (aset widths i (max (truncate (* (aref columns i)
500                                        total-percentage
501                                        shr-width))
502                           10)))
503     widths))
504
505 ;; Return a summary of the number and shape of the TDs in the table.
506 (defun shr-column-specs (cont)
507   (let ((columns (make-vector (shr-max-columns cont) 1)))
508     (dolist (row cont)
509       (when (eq (car row) 'tr)
510         (let ((i 0))
511           (dolist (column (cdr row))
512             (when (memq (car column) '(td th))
513               (let ((width (cdr (assq :width (cdr column)))))
514                 (when (and width
515                            (string-match "\\([0-9]+\\)%" width))
516                   (aset columns i
517                         (/ (string-to-number (match-string 1 width))
518                            100.0)))))
519             (setq i (1+ i))))))
520     columns))
521
522 (defun shr-count (cont elem)
523   (let ((i 0))
524     (dolist (sub cont)
525       (when (eq (car sub) elem)
526         (setq i (1+ i))))
527     i))
528
529 (defun shr-max-columns (cont)
530   (let ((max 0))
531     (dolist (row cont)
532       (when (eq (car row) 'tr)
533         (setq max (max max (shr-count (cdr row) 'td)))))
534     max))
535
536 (provide 'shr)
537
538 ;;; shr.el ends here