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