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