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   (shr-ensure-paragraph))
297
298 (defun shr-ensure-newline ()
299   (unless (zerop (current-column))
300     (insert "\n")))
301
302 (defun shr-insert (text)
303   (when (eq shr-state 'image)
304     (insert "\n")
305     (setq shr-state nil))
306   (cond
307    ((eq shr-folding-mode 'none)
308     (insert text))
309    (t
310     (let ((first t)
311           column)
312       (when (and (string-match "\\`[ \t\n]" text)
313                  (not (bolp)))
314         (insert " "))
315       (dolist (elem (split-string text))
316         (setq column (current-column))
317         (when (> column 0)
318           (cond
319            ((and (or (not first)
320                      (eq shr-state 'space))
321                  (> (+ column (length elem) 1) shr-width))
322             (insert "\n"))
323            ((not first)
324             (insert " "))))
325         (setq first nil)
326         (when (and (bolp)
327                    (> shr-indentation 0))
328           (shr-indent))
329         ;; The shr-start is a special variable that is used to pass
330         ;; upwards the first point in the buffer where the text really
331         ;; starts.
332         (unless shr-start
333           (setq shr-start (point)))
334         (insert elem))
335       (setq shr-state nil)
336       (when (and (string-match "[ \t\n]\\'" text)
337                  (not (bolp)))
338         (insert " ")
339         (setq shr-state 'space))))))
340
341 (defun shr-indent ()
342   (insert (make-string shr-indentation ? )))
343
344 (defun shr-get-image-data (url)
345   "Get image data for URL.
346 Return a string with image data."
347   (with-temp-buffer
348     (mm-disable-multibyte)
349     (when (ignore-errors
350             (url-cache-extract (url-cache-create-filename url))
351             t)
352       (when (or (search-forward "\n\n" nil t)
353                 (search-forward "\r\n\r\n" nil t))
354         (buffer-substring (point) (point-max))))))
355
356 (defvar shr-list-mode nil)
357
358 (defun shr-tag-ul (cont)
359   (shr-ensure-paragraph)
360   (let ((shr-list-mode 'ul))
361     (shr-generic cont)))
362
363 (defun shr-tag-ol (cont)
364   (let ((shr-list-mode 1))
365     (shr-generic cont)))
366
367 (defun shr-tag-li (cont)
368   (shr-ensure-newline)
369   (let* ((bullet
370           (if (numberp shr-list-mode)
371               (prog1
372                   (format "%d " shr-list-mode)
373                 (setq shr-list-mode (1+ shr-list-mode)))
374             "* "))
375          (shr-indentation (+ shr-indentation (length bullet))))
376     (insert bullet)
377     (shr-generic cont)))
378
379 (defun shr-tag-br (cont)
380   (unless (bobp)
381     (insert "\n"))
382   (shr-generic cont))
383
384 (defun shr-tag-h1 (cont)
385   (shr-heading cont 'bold 'underline))
386
387 (defun shr-tag-h2 (cont)
388   (shr-heading cont 'bold))
389
390 (defun shr-tag-h3 (cont)
391   (shr-heading cont 'italic))
392
393 (defun shr-tag-h4 (cont)
394   (shr-heading cont))
395
396 (defun shr-tag-h5 (cont)
397   (shr-heading cont))
398
399 (defun shr-tag-h6 (cont)
400   (shr-heading cont))
401
402 (defun shr-heading (cont &rest types)
403   (shr-ensure-paragraph)
404   (apply #'shr-fontize-cont cont types)
405   (shr-ensure-paragraph))
406
407 (defun shr-tag-table (cont)
408   (shr-ensure-paragraph)
409   (setq cont (or (cdr (assq 'tbody cont))
410                  cont))
411   (let* ((columns (shr-column-specs cont))
412          (suggested-widths (shr-pro-rate-columns columns))
413          (sketch (shr-make-table cont suggested-widths))
414          (sketch-widths (shr-table-widths sketch (length suggested-widths))))
415     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths)))
416
417 (defun shr-insert-table (table widths)
418   (shr-insert-table-ruler widths)
419   (dolist (row table)
420     (let ((start (point))
421           (height (let ((max 0))
422                     (dolist (column row)
423                       (setq max (max max (cadr column))))
424                     max)))
425       (dotimes (i height)
426         (shr-indent)
427         (insert "|\n"))
428       (dolist (column row)
429         (goto-char start)
430         (let ((lines (split-string (nth 2 column) "\n")))
431           (dolist (line lines)
432             (when (> (length line) 0)
433               (end-of-line)
434               (insert line "|")
435               (forward-line 1)))
436           ;; Add blank lines at padding at the bottom of the TD,
437           ;; possibly.
438           (dotimes (i (- height (length lines)))
439             (end-of-line)
440             (insert (make-string (length (car lines)) ? ) "|")
441             (forward-line 1)))))
442     (shr-insert-table-ruler widths)))
443
444 (defun shr-insert-table-ruler (widths)
445   (shr-indent)
446   (insert "+")
447   (dotimes (i (length widths))
448     (insert (make-string (aref widths i) ?-) ?+))
449   (insert "\n"))
450
451 (defun shr-table-widths (table length)
452   (let ((widths (make-vector length 0)))
453     (dolist (row table)
454       (let ((i 0))
455         (dolist (column row)
456           (aset widths i (max (aref widths i)
457                               (car column)))
458           (incf i))))
459     widths))
460
461 (defun shr-make-table (cont widths &optional fill)
462   (let ((trs nil))
463     (dolist (row cont)
464       (when (eq (car row) 'tr)
465         (let ((i 0)
466               (tds nil))
467           (dolist (column (cdr row))
468             (when (memq (car column) '(td th))
469               (push (shr-render-td (cdr column) (aref widths i) fill)
470                     tds)
471               (setq i (1+ i))))
472           (push (nreverse tds) trs))))
473     (nreverse trs)))
474
475 (defun shr-render-td (cont width fill)
476   (with-temp-buffer
477     (let ((shr-width width)
478           (shr-indentation 0))
479       (shr-generic cont))
480     (while (re-search-backward "\n *$" nil t)
481       (delete-region (match-beginning 0) (match-end 0)))
482     (goto-char (point-min))
483     (let ((max 0))
484       (while (not (eobp))
485         (end-of-line)
486         (setq max (max max (current-column)))
487         (forward-line 1))
488       (when fill
489         (goto-char (point-min))
490         (while (not (eobp))
491           (end-of-line)
492           (when (> (- width (current-column)) 0)
493             (insert (make-string (- width (current-column)) ? )))
494           (forward-line 1)))
495       (list max (count-lines (point-min) (point-max)) (buffer-string)))))
496
497 (defun shr-pro-rate-columns (columns)
498   (let ((total-percentage 0)
499         (widths (make-vector (length columns) 0)))
500     (dotimes (i (length columns))
501       (incf total-percentage (aref columns i)))
502     (setq total-percentage (/ 1.0 total-percentage))
503     (dotimes (i (length columns))
504       (aset widths i (max (truncate (* (aref columns i)
505                                        total-percentage
506                                        shr-width))
507                           10)))
508     widths))
509
510 ;; Return a summary of the number and shape of the TDs in the table.
511 (defun shr-column-specs (cont)
512   (let ((columns (make-vector (shr-max-columns cont) 1)))
513     (dolist (row cont)
514       (when (eq (car row) 'tr)
515         (let ((i 0))
516           (dolist (column (cdr row))
517             (when (memq (car column) '(td th))
518               (let ((width (cdr (assq :width (cdr column)))))
519                 (when (and width
520                            (string-match "\\([0-9]+\\)%" width))
521                   (aset columns i
522                         (/ (string-to-number (match-string 1 width))
523                            100.0)))))
524             (setq i (1+ i))))))
525     columns))
526
527 (defun shr-count (cont elem)
528   (let ((i 0))
529     (dolist (sub cont)
530       (when (eq (car sub) elem)
531         (setq i (1+ i))))
532     i))
533
534 (defun shr-max-columns (cont)
535   (let ((max 0))
536     (dolist (row cont)
537       (when (eq (car row) 'tr)
538         (setq max (max max (shr-count (cdr row) 'td)))))
539     max))
540
541 (provide 'shr)
542
543 ;;; shr.el ends here