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