Proof of concept implemantation of boxy backgrounds.
[gnus] / lisp / shr.el
1 ;;; shr.el --- Simple HTML Renderer
2
3 ;; Copyright (C) 2010, 2011 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 (defcustom shr-table-horizontal-line ?-
57   "Character used to draw horizontal table lines."
58   :group 'shr
59   :type 'character)
60
61 (defcustom shr-table-vertical-line ?|
62   "Character used to draw vertical table lines."
63   :group 'shr
64   :type 'character)
65
66 (defcustom shr-table-corner ?+
67   "Character used to draw table corners."
68   :group 'shr
69   :type 'character)
70
71 (defcustom shr-hr-line ?-
72   "Character used to draw hr lines."
73   :group 'shr
74   :type 'character)
75
76 (defcustom shr-width fill-column
77   "Frame width to use for rendering.
78 May either be an integer specifying a fixed width in characters,
79 or nil, meaning that the full width of the window should be
80 used."
81   :type '(choice (integer :tag "Fixed width in characters")
82                  (const   :tag "Use the width of the window" nil))
83   :group 'shr)
84
85 (defface shr-tag-h1 '((t (:bold t :height 2.2)))
86   "Face used for H1 tags."
87   :group 'shr)
88
89 (defface shr-tag-h2 '((t (:bold t :height 2.0)))
90   "Face used for H2 tags."
91   :group 'shr)
92
93 (defface shr-tag-h3 '((t (:bold t :height 1.8)))
94   "Face used for H3 tags."
95   :group 'shr)
96
97 (defface shr-tag-h4 '((t (:bold t :height 1.6)))
98   "Face used for H4 tags."
99   :group 'shr)
100
101 (defface shr-tag-h5 '((t (:bold t :height 1.4)))
102   "Face used for H5 tags."
103   :group 'shr)
104
105 (defface shr-tag-h6 '((t (:bold t :height 1.2)))
106   "Face used for H6 tags."
107   :group 'shr)
108
109 (defvar shr-content-function nil
110   "If bound, this should be a function that will return the content.
111 This is used for cid: URLs, and the function is called with the
112 cid: URL as the argument.")
113
114 ;;; Internal variables.
115
116 (defvar shr-folding-mode nil)
117 (defvar shr-state nil)
118 (defvar shr-start nil)
119 (defvar shr-indentation 0)
120 (defvar shr-inhibit-images nil)
121 (defvar shr-list-mode nil)
122 (defvar shr-content-cache nil)
123 (defvar shr-kinsoku-shorten nil)
124 (defvar shr-table-depth 0)
125 (defvar shr-stylesheet nil)
126
127 (defvar shr-map
128   (let ((map (make-sparse-keymap)))
129     (define-key map "a" 'shr-show-alt-text)
130     (define-key map "i" 'shr-browse-image)
131     (define-key map "I" 'shr-insert-image)
132     (define-key map "u" 'shr-copy-url)
133     (define-key map "v" 'shr-browse-url)
134     (define-key map "o" 'shr-save-contents)
135     (define-key map "\r" 'shr-browse-url)
136     map))
137
138 ;; Public functions and commands.
139
140 ;;;###autoload
141 (defun shr-insert-document (dom)
142   (setq shr-content-cache nil)
143   (let ((shr-state nil)
144         (shr-start nil)
145         (shr-width (or shr-width (window-width))))
146     (shr-descend (shr-transform-dom dom))))
147
148 (defun shr-copy-url ()
149   "Copy the URL under point to the kill ring.
150 If called twice, then try to fetch the URL and see whether it
151 redirects somewhere else."
152   (interactive)
153   (let ((url (get-text-property (point) 'shr-url)))
154     (cond
155      ((not url)
156       (message "No URL under point"))
157      ;; Resolve redirected URLs.
158      ((equal url (car kill-ring))
159       (url-retrieve
160        url
161        (lambda (a)
162          (when (and (consp a)
163                     (eq (car a) :redirect))
164            (with-temp-buffer
165              (insert (cadr a))
166              (goto-char (point-min))
167              ;; Remove common tracking junk from the URL.
168              (when (re-search-forward ".utm_.*" nil t)
169                (replace-match "" t t))
170              (message "Copied %s" (buffer-string))
171              (copy-region-as-kill (point-min) (point-max)))))))
172      ;; Copy the URL to the kill ring.
173      (t
174       (with-temp-buffer
175         (insert url)
176         (copy-region-as-kill (point-min) (point-max))
177         (message "Copied %s" url))))))
178
179 (defun shr-show-alt-text ()
180   "Show the ALT text of the image under point."
181   (interactive)
182   (let ((text (get-text-property (point) 'shr-alt)))
183     (if (not text)
184         (message "No image under point")
185       (message "%s" text))))
186
187 (defun shr-browse-image ()
188   "Browse the image under point."
189   (interactive)
190   (let ((url (get-text-property (point) 'image-url)))
191     (if (not url)
192         (message "No image under point")
193       (message "Browsing %s..." url)
194       (browse-url url))))
195
196 (defun shr-insert-image ()
197   "Insert the image under point into the buffer."
198   (interactive)
199   (let ((url (get-text-property (point) 'image-url)))
200     (if (not url)
201         (message "No image under point")
202       (message "Inserting %s..." url)
203       (url-retrieve url 'shr-image-fetched
204                     (list (current-buffer) (1- (point)) (point-marker))
205                     t))))
206
207 ;;; Utility functions.
208
209 (defun shr-transform-dom (dom)
210   (let ((result (list (pop dom))))
211     (dolist (arg (pop dom))
212       (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
213                   (cdr arg))
214             result))
215     (dolist (sub dom)
216       (if (stringp sub)
217           (push (cons 'text sub) result)
218         (push (shr-transform-dom sub) result)))
219     (nreverse result)))
220
221 (defun shr-descend (dom)
222   (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray))
223         (style (cdr (assq :style (cdr dom))))
224         (shr-stylesheet shr-stylesheet)
225         (start (point)))
226     (when style
227       (if (string-match "color" style)
228           (setq shr-stylesheet (nconc (shr-parse-style style)
229                                       shr-stylesheet))
230         (setq style nil)))
231     (if (fboundp function)
232         (funcall function (cdr dom))
233       (shr-generic (cdr dom)))
234     ;; If style is set, then this node has set the color.
235     (when style
236       (shr-colorize-region start (point)
237                            (cdr (assq 'color shr-stylesheet))
238                            (cdr (assq 'background-color shr-stylesheet))))))
239
240 (defun shr-generic (cont)
241   (dolist (sub cont)
242     (cond
243      ((eq (car sub) 'text)
244       (shr-insert (cdr sub)))
245      ((listp (cdr sub))
246       (shr-descend sub)))))
247
248 (defmacro shr-char-breakable-p (char)
249   "Return non-nil if a line can be broken before and after CHAR."
250   `(aref fill-find-break-point-function-table ,char))
251 (defmacro shr-char-nospace-p (char)
252   "Return non-nil if no space is required before and after CHAR."
253   `(aref fill-nospace-between-words-table ,char))
254
255 ;; KINSOKU is a Japanese word meaning a rule that should not be violated.
256 ;; In Emacs, it is a term used for characters, e.g. punctuation marks,
257 ;; parentheses, and so on, that should not be placed in the beginning
258 ;; of a line or the end of a line.
259 (defmacro shr-char-kinsoku-bol-p (char)
260   "Return non-nil if a line ought not to begin with CHAR."
261   `(aref (char-category-set ,char) ?>))
262 (defmacro shr-char-kinsoku-eol-p (char)
263   "Return non-nil if a line ought not to end with CHAR."
264   `(aref (char-category-set ,char) ?<))
265 (unless (shr-char-kinsoku-bol-p (make-char 'japanese-jisx0208 33 35))
266   (load "kinsoku" nil t))
267
268 (defun shr-insert (text)
269   (when (and (eq shr-state 'image)
270              (not (string-match "\\`[ \t\n]+\\'" text)))
271     (insert "\n")
272     (setq shr-state nil))
273   (cond
274    ((eq shr-folding-mode 'none)
275     (insert text))
276    (t
277     (when (and (string-match "\\`[ \t\n]" text)
278                (not (bolp))
279                (not (eq (char-after (1- (point))) ? )))
280       (insert " "))
281     (dolist (elem (split-string text))
282       (when (and (bolp)
283                  (> shr-indentation 0))
284         (shr-indent))
285       ;; No space is needed behind a wide character categorized as
286       ;; kinsoku-bol, between characters both categorized as nospace,
287       ;; or at the beginning of a line.
288       (let (prev)
289         (when (and (> (current-column) shr-indentation)
290                    (eq (preceding-char) ? )
291                    (or (= (line-beginning-position) (1- (point)))
292                        (and (shr-char-breakable-p
293                              (setq prev (char-after (- (point) 2))))
294                             (shr-char-kinsoku-bol-p prev))
295                        (and (shr-char-nospace-p prev)
296                             (shr-char-nospace-p (aref elem 0)))))
297           (delete-char -1)))
298       ;; The shr-start is a special variable that is used to pass
299       ;; upwards the first point in the buffer where the text really
300       ;; starts.
301       (unless shr-start
302         (setq shr-start (point)))
303       (insert elem)
304       (let (found)
305         (while (and (> (current-column) shr-width)
306                     (progn
307                       (setq found (shr-find-fill-point))
308                       (not (eolp))))
309           (when (eq (preceding-char) ? )
310             (delete-char -1))
311           (insert "\n")
312           (unless found
313             (put-text-property (1- (point)) (point) 'shr-break t)
314             ;; No space is needed at the beginning of a line.
315             (when (eq (following-char) ? )
316               (delete-char 1)))
317           (when (> shr-indentation 0)
318             (shr-indent))
319           (end-of-line))
320         (insert " ")))
321     (unless (string-match "[ \t\n]\\'" text)
322       (delete-char -1)))))
323
324 (defun shr-find-fill-point ()
325   (when (> (move-to-column shr-width) shr-width)
326     (backward-char 1))
327   (let ((bp (point))
328         failed)
329     (while (not (or (setq failed (= (current-column) shr-indentation))
330                     (eq (preceding-char) ? )
331                     (eq (following-char) ? )
332                     (shr-char-breakable-p (preceding-char))
333                     (shr-char-breakable-p (following-char))
334                     (if (eq (preceding-char) ?')
335                         (not (memq (char-after (- (point) 2))
336                                    (list nil ?\n ? )))
337                       (and (shr-char-kinsoku-bol-p (preceding-char))
338                            (shr-char-breakable-p (following-char))
339                            (not (shr-char-kinsoku-bol-p (following-char)))))
340                     (shr-char-kinsoku-eol-p (following-char))))
341       (backward-char 1))
342     (if (and (not (or failed (eolp)))
343              (eq (preceding-char) ?'))
344         (while (not (or (setq failed (eolp))
345                         (eq (following-char) ? )
346                         (shr-char-breakable-p (following-char))
347                         (shr-char-kinsoku-eol-p (following-char))))
348           (forward-char 1)))
349     (if failed
350         ;; There's no breakable point, so we give it up.
351         (let (found)
352           (goto-char bp)
353           (unless shr-kinsoku-shorten
354             (while (and (setq found (re-search-forward
355                                      "\\(\\c>\\)\\| \\|\\c<\\|\\c|"
356                                      (line-end-position) 'move))
357                         (eq (preceding-char) ?')))
358             (if (and found (not (match-beginning 1)))
359                 (goto-char (match-beginning 0)))))
360       (or
361        (eolp)
362        ;; Don't put kinsoku-bol characters at the beginning of a line,
363        ;; or kinsoku-eol characters at the end of a line.
364        (cond
365         (shr-kinsoku-shorten
366          (while (and (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
367                      (shr-char-kinsoku-eol-p (preceding-char)))
368            (backward-char 1))
369          (when (setq failed (= (current-column) shr-indentation))
370            ;; There's no breakable point that doesn't violate kinsoku,
371            ;; so we look for the second best position.
372            (while (and (progn
373                          (forward-char 1)
374                          (<= (current-column) shr-width))
375                        (progn
376                          (setq bp (point))
377                          (shr-char-kinsoku-eol-p (following-char)))))
378            (goto-char bp)))
379         ((shr-char-kinsoku-eol-p (preceding-char))
380          (if (shr-char-kinsoku-eol-p (following-char))
381              ;; There are consecutive kinsoku-eol characters.
382              (setq failed t)
383            (let ((count 4))
384              (while
385                  (progn
386                    (backward-char 1)
387                    (and (> (setq count (1- count)) 0)
388                         (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
389                         (or (shr-char-kinsoku-eol-p (preceding-char))
390                             (shr-char-kinsoku-bol-p (following-char)))))))
391            (if (setq failed (= (current-column) shr-indentation))
392                ;; There's no breakable point that doesn't violate kinsoku,
393                ;; so we go to the second best position.
394                (if (looking-at "\\(\\c<+\\)\\c<")
395                    (goto-char (match-end 1))
396                  (forward-char 1)))))
397         (t
398          (if (shr-char-kinsoku-bol-p (preceding-char))
399              ;; There are consecutive kinsoku-bol characters.
400              (setq failed t)
401            (let ((count 4))
402              (while (and (>= (setq count (1- count)) 0)
403                          (shr-char-kinsoku-bol-p (following-char))
404                          (shr-char-breakable-p (following-char)))
405                (forward-char 1))))))
406        (when (eq (following-char) ? )
407          (forward-char 1))))
408     (not failed)))
409
410 (defun shr-ensure-newline ()
411   (unless (zerop (current-column))
412     (insert "\n")))
413
414 (defun shr-ensure-paragraph ()
415   (unless (bobp)
416     (if (<= (current-column) shr-indentation)
417         (unless (save-excursion
418                   (forward-line -1)
419                   (looking-at " *$"))
420           (insert "\n"))
421       (if (save-excursion
422             (beginning-of-line)
423             (looking-at " *$"))
424           (insert "\n")
425         (insert "\n\n")))))
426
427 (defun shr-indent ()
428   (when (> shr-indentation 0)
429     (insert (make-string shr-indentation ? ))))
430
431 (defun shr-fontize-cont (cont &rest types)
432   (let (shr-start)
433     (shr-generic cont)
434     (dolist (type types)
435       (shr-add-font (or shr-start (point)) (point) type))))
436
437 ;; Add an overlay in the region, but avoid putting the font properties
438 ;; on blank text at the start of the line, and the newline at the end,
439 ;; to avoid ugliness.
440 (defun shr-add-font (start end type)
441   (save-excursion
442     (goto-char start)
443     (while (< (point) end)
444       (when (bolp)
445         (skip-chars-forward " "))
446       (let ((overlay (make-overlay (point) (min (line-end-position) end))))
447         (overlay-put overlay 'face type))
448       (if (< (line-end-position) end)
449           (forward-line 1)
450         (goto-char end)))))
451
452 (defun shr-browse-url ()
453   "Browse the URL under point."
454   (interactive)
455   (let ((url (get-text-property (point) 'shr-url)))
456     (cond
457      ((not url)
458       (message "No link under point"))
459      ((string-match "^mailto:" url)
460       (browse-url-mailto url))
461      (t
462       (browse-url url)))))
463
464 (defun shr-save-contents (directory)
465   "Save the contents from URL in a file."
466   (interactive "DSave contents of URL to directory: ")
467   (let ((url (get-text-property (point) 'shr-url)))
468     (if (not url)
469         (message "No link under point")
470       (url-retrieve (shr-encode-url url)
471                     'shr-store-contents (list url directory)))))
472
473 (defun shr-store-contents (status url directory)
474   (unless (plist-get status :error)
475     (when (or (search-forward "\n\n" nil t)
476               (search-forward "\r\n\r\n" nil t))
477       (write-region (point) (point-max)
478                     (expand-file-name (file-name-nondirectory url)
479                                       directory)))))
480
481 (defun shr-image-fetched (status buffer start end)
482   (when (and (buffer-name buffer)
483              (not (plist-get status :error)))
484     (url-store-in-cache (current-buffer))
485     (when (or (search-forward "\n\n" nil t)
486               (search-forward "\r\n\r\n" nil t))
487       (let ((data (buffer-substring (point) (point-max))))
488         (with-current-buffer buffer
489           (save-excursion
490             (let ((alt (buffer-substring start end))
491                   (inhibit-read-only t))
492               (delete-region start end)
493               (goto-char start)
494               (shr-put-image data alt)))))))
495   (kill-buffer (current-buffer)))
496
497 (defun shr-put-image (data alt)
498   (if (display-graphic-p)
499       (let ((image (ignore-errors
500                      (shr-rescale-image data))))
501         (when image
502           ;; When inserting big-ish pictures, put them at the
503           ;; beginning of the line.
504           (when (and (> (current-column) 0)
505                      (> (car (image-size image t)) 400))
506             (insert "\n"))
507           (insert-image image (or alt "*"))))
508     (insert alt)))
509
510 (defun shr-rescale-image (data)
511   (if (or (not (fboundp 'imagemagick-types))
512           (not (get-buffer-window (current-buffer))))
513       (create-image data nil t)
514     (let* ((image (create-image data nil t))
515            (size (image-size image t))
516            (width (car size))
517            (height (cdr size))
518            (edges (window-inside-pixel-edges
519                    (get-buffer-window (current-buffer))))
520            (window-width (truncate (* shr-max-image-proportion
521                                       (- (nth 2 edges) (nth 0 edges)))))
522            (window-height (truncate (* shr-max-image-proportion
523                                        (- (nth 3 edges) (nth 1 edges)))))
524            scaled-image)
525       (when (> height window-height)
526         (setq image (or (create-image data 'imagemagick t
527                                       :height window-height)
528                         image))
529         (setq size (image-size image t)))
530       (when (> (car size) window-width)
531         (setq image (or
532                      (create-image data 'imagemagick t
533                                    :width window-width)
534                      image)))
535       (when (and (fboundp 'create-animated-image)
536                  (eq (image-type data nil t) 'gif))
537         (setq image (create-animated-image data 'gif t)))
538       image)))
539
540 ;; url-cache-extract autoloads url-cache.
541 (declare-function url-cache-create-filename "url-cache" (url))
542 (autoload 'mm-disable-multibyte "mm-util")
543 (autoload 'browse-url-mailto "browse-url")
544
545 (defun shr-get-image-data (url)
546   "Get image data for URL.
547 Return a string with image data."
548   (with-temp-buffer
549     (mm-disable-multibyte)
550     (when (ignore-errors
551             (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
552             t)
553       (when (or (search-forward "\n\n" nil t)
554                 (search-forward "\r\n\r\n" nil t))
555         (buffer-substring (point) (point-max))))))
556
557 (defun shr-image-displayer (content-function)
558   "Return a function to display an image.
559 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
560 is an argument.  The function to be returned takes three arguments URL,
561 START, and END.  Note that START and END should be merkers."
562   `(lambda (url start end)
563      (when url
564        (if (string-match "\\`cid:" url)
565            ,(when content-function
566               `(let ((image (funcall ,content-function
567                                      (substring url (match-end 0)))))
568                  (when image
569                    (goto-char start)
570                    (shr-put-image image
571                                   (buffer-substring-no-properties start end))
572                    (delete-region (point) end))))
573          (url-retrieve url 'shr-image-fetched
574                        (list (current-buffer) start end)
575                        t)))))
576
577 (defun shr-heading (cont &rest types)
578   (shr-ensure-paragraph)
579   (apply #'shr-fontize-cont cont types)
580   (shr-ensure-paragraph))
581
582 (autoload 'widget-convert-button "wid-edit")
583
584 (defun shr-urlify (start url &optional title)
585   (widget-convert-button
586    'url-link start (point)
587    :help-echo (if title (format "%s (%s)" url title) url)
588    :keymap shr-map
589    url)
590   (put-text-property start (point) 'shr-url url))
591
592 (defun shr-encode-url (url)
593   "Encode URL."
594   (browse-url-url-encode-chars url "[)$ ]"))
595
596 (autoload 'shr-color-visible "shr-color")
597 (autoload 'shr-color->hexadecimal "shr-color")
598
599 (defun shr-color-check (fg bg)
600   "Check that FG is visible on BG.
601 Returns (fg bg) with corrected values.
602 Returns nil if the colors that would be used are the default
603 ones, in case fg and bg are nil."
604   (when (or fg bg)
605     (let ((fixed (cond ((null fg) 'fg)
606                        ((null bg) 'bg))))
607       ;; Convert colors to hexadecimal, or set them to default.
608       (let ((fg (or (shr-color->hexadecimal fg)
609                     (frame-parameter nil 'foreground-color)))
610             (bg (or (shr-color->hexadecimal bg)
611                     (frame-parameter nil 'background-color))))
612         (cond ((eq fixed 'bg)
613                ;; Only return the new fg
614                (list nil (cadr (shr-color-visible bg fg t))))
615               ((eq fixed 'fg)
616                ;; Invert args and results and return only the new bg
617                (list (cadr (shr-color-visible fg bg t)) nil))
618               (t
619                (shr-color-visible bg fg)))))))
620
621 (defun shr-colorize-region (start end fg &optional bg)
622   (when (or fg bg)
623     (let ((new-colors (shr-color-check fg bg)))
624       (when new-colors
625         (when fg
626           (shr-put-color start end :foreground (cadr new-colors)))
627         (when bg
628           (shr-put-color start end :background (car new-colors)))))))
629
630 ;; Put a color in the region, but avoid putting colors on on blank
631 ;; text at the start of the line, and the newline at the end, to avoid
632 ;; ugliness.  Also, don't overwrite any existing color information,
633 ;; since this can be called recursively, and we want the "inner" color
634 ;; to win.
635 (defun shr-put-color (start end type color)
636   (save-excursion
637     (goto-char start)
638     (while (< (point) end)
639       (when (bolp)
640         (skip-chars-forward " "))
641       (when (> (line-end-position) (point))
642         (shr-put-color-1 (point) (min (line-end-position) end) type color))
643       (if (< (line-end-position) end)
644           (forward-line 1)
645         (goto-char end)))
646     (when (eq type :background)
647       (shr-expand-newlines start end color))))
648
649 (defun shr-expand-newlines (start end color)
650   (save-restriction
651     (narrow-to-region start end)
652     (let ((width (shr-natural-width))
653           column)
654       (goto-char (point-min))
655       (while (not (eobp))
656         (end-of-line)
657         (when (and (< (setq current-column (current-column)) width)
658                    (not (get-text-property (point) 'display)))
659           (put-text-property
660            (point) (1+ (point)) 'display
661            (concat (propertize (make-string (- width current-column) ? )
662                                'face (list :background color))
663                    "\n")))
664         (forward-line 1)))))
665
666 (defun shr-put-color-1 (start end type color)
667   (let* ((old-props (get-text-property start 'face))
668          (do-put (not (memq type old-props)))
669          change)
670     (while (< start end)
671       (setq change (next-single-property-change start 'face nil end))
672       (when do-put
673         (put-text-property start change 'face
674                            (nconc (list type color) old-props)))
675       (setq old-props (get-text-property change 'face))
676       (setq do-put (not (memq type old-props)))
677       (setq start change))
678     (when (and do-put
679                (> end start))
680       (put-text-property start end 'face
681                          (nconc (list type color old-props))))))
682
683 ;;; Tag-specific rendering rules.
684
685 (defun shr-tag-body (cont)
686   (let* ((start (point))
687          (fgcolor (cdr (assq :fgcolor cont)))
688          (bgcolor (cdr (assq :bgcolor cont)))
689          (shr-stylesheet (list (cons 'color fgcolor)
690                                (cons 'background-color bgcolor))))
691     (shr-generic cont)
692     (shr-colorize-region start (point) fgcolor bgcolor)))
693
694 (defun shr-tag-style (cont)
695   )
696
697 (defun shr-tag-script (cont)
698   )
699
700 (defun shr-tag-label (cont)
701   (shr-generic cont)
702   (shr-ensure-paragraph))
703
704 (defun shr-tag-p (cont)
705   (shr-ensure-paragraph)
706   (shr-indent)
707   (shr-generic cont)
708   (shr-ensure-paragraph))
709
710 (defun shr-tag-div (cont)
711   (shr-ensure-newline)
712   (shr-indent)
713   (shr-generic cont)
714   (shr-ensure-newline))
715
716 (defun shr-tag-b (cont)
717   (shr-fontize-cont cont 'bold))
718
719 (defun shr-tag-i (cont)
720   (shr-fontize-cont cont 'italic))
721
722 (defun shr-tag-em (cont)
723   (shr-fontize-cont cont 'bold))
724
725 (defun shr-tag-strong (cont)
726   (shr-fontize-cont cont 'bold))
727
728 (defun shr-tag-u (cont)
729   (shr-fontize-cont cont 'underline))
730
731 (defun shr-tag-s (cont)
732   (shr-fontize-cont cont 'strike-through))
733
734 (defun shr-parse-style (style)
735   (when style
736     (save-match-data
737       (when (string-match "\n" style)
738         (setq style (replace-match " " t t style))))
739     (let ((plist nil))
740       (dolist (elem (split-string style ";"))
741         (when elem
742           (setq elem (split-string elem ":"))
743           (when (and (car elem)
744                      (cadr elem))
745             (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
746                   (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
747               (when (string-match " *!important\\'" value)
748                 (setq value (substring value 0 (match-beginning 0))))
749               (push (cons (intern name obarray)
750                           value)
751                     plist)))))
752       plist)))
753
754 (defun shr-tag-a (cont)
755   (let ((url (cdr (assq :href cont)))
756         (title (cdr (assq :title cont)))
757         (start (point))
758         shr-start)
759     (shr-generic cont)
760     (shr-urlify (or shr-start start) url title)))
761
762 (defun shr-tag-object (cont)
763   (let ((start (point))
764         url)
765     (dolist (elem cont)
766       (when (eq (car elem) 'embed)
767         (setq url (or url (cdr (assq :src (cdr elem))))))
768       (when (and (eq (car elem) 'param)
769                  (equal (cdr (assq :name (cdr elem))) "movie"))
770         (setq url (or url (cdr (assq :value (cdr elem)))))))
771     (when url
772       (shr-insert " [multimedia] ")
773       (shr-urlify start url))
774     (shr-generic cont)))
775
776 (defun shr-tag-video (cont)
777   (let ((image (cdr (assq :poster cont)))
778         (url (cdr (assq :src cont)))
779         (start (point)))
780     (shr-tag-img nil image)
781     (shr-urlify start url)))
782
783 (defun shr-tag-img (cont &optional url)
784   (when (or url
785             (and cont
786                  (cdr (assq :src cont))))
787     (when (and (> (current-column) 0)
788                (not (eq shr-state 'image)))
789       (insert "\n"))
790     (let ((alt (cdr (assq :alt cont)))
791           (url (or url (cdr (assq :src cont)))))
792       (let ((start (point-marker)))
793         (when (zerop (length alt))
794           (setq alt "*"))
795         (cond
796          ((or (member (cdr (assq :height cont)) '("0" "1"))
797               (member (cdr (assq :width cont)) '("0" "1")))
798           ;; Ignore zero-sized or single-pixel images.
799           )
800          ((and (not shr-inhibit-images)
801                (string-match "\\`cid:" url))
802           (let ((url (substring url (match-end 0)))
803                 image)
804             (if (or (not shr-content-function)
805                     (not (setq image (funcall shr-content-function url))))
806                 (insert alt)
807               (shr-put-image image alt))))
808          ((or shr-inhibit-images
809               (and shr-blocked-images
810                    (string-match shr-blocked-images url)))
811           (setq shr-start (point))
812           (let ((shr-state 'space))
813             (if (> (string-width alt) 8)
814                 (shr-insert (truncate-string-to-width alt 8))
815               (shr-insert alt))))
816          ((url-is-cached (shr-encode-url url))
817           (shr-put-image (shr-get-image-data url) alt))
818          (t
819           (insert alt)
820           (ignore-errors
821             (url-retrieve (shr-encode-url url) 'shr-image-fetched
822                           (list (current-buffer) start (point-marker))
823                           t))))
824         (put-text-property start (point) 'keymap shr-map)
825         (put-text-property start (point) 'shr-alt alt)
826         (put-text-property start (point) 'image-url url)
827         (put-text-property start (point) 'image-displayer
828                            (shr-image-displayer shr-content-function))
829         (put-text-property start (point) 'help-echo alt)
830         (setq shr-state 'image)))))
831
832 (defun shr-tag-pre (cont)
833   (let ((shr-folding-mode 'none))
834     (shr-ensure-newline)
835     (shr-indent)
836     (shr-generic cont)
837     (shr-ensure-newline)))
838
839 (defun shr-tag-blockquote (cont)
840   (shr-ensure-paragraph)
841   (shr-indent)
842   (let ((shr-indentation (+ shr-indentation 4)))
843     (shr-generic cont))
844   (shr-ensure-paragraph))
845
846 (defun shr-tag-ul (cont)
847   (shr-ensure-paragraph)
848   (let ((shr-list-mode 'ul))
849     (shr-generic cont))
850   (shr-ensure-paragraph))
851
852 (defun shr-tag-ol (cont)
853   (shr-ensure-paragraph)
854   (let ((shr-list-mode 1))
855     (shr-generic cont))
856   (shr-ensure-paragraph))
857
858 (defun shr-tag-li (cont)
859   (shr-ensure-paragraph)
860   (shr-indent)
861   (let* ((bullet
862           (if (numberp shr-list-mode)
863               (prog1
864                   (format "%d " shr-list-mode)
865                 (setq shr-list-mode (1+ shr-list-mode)))
866             "* "))
867          (shr-indentation (+ shr-indentation (length bullet))))
868     (insert bullet)
869     (shr-generic cont)))
870
871 (defun shr-tag-br (cont)
872   (unless (bobp)
873     (insert "\n")
874     (shr-indent))
875   (shr-generic cont))
876
877 (defun shr-tag-h1 (cont)
878   (shr-heading cont 'shr-tag-h1))
879
880 (defun shr-tag-h2 (cont)
881   (shr-heading cont 'shr-tag-h2))
882
883 (defun shr-tag-h3 (cont)
884   (shr-heading cont 'shr-tag-h3))
885
886 (defun shr-tag-h4 (cont)
887   (shr-heading cont 'shr-tag-h4))
888
889 (defun shr-tag-h5 (cont)
890   (shr-heading cont 'shr-tag-h5))
891
892 (defun shr-tag-h6 (cont)
893   (shr-heading cont 'shr-tag-h6))
894
895 (defun shr-tag-hr (cont)
896   (shr-ensure-newline)
897   (insert (make-string shr-width shr-hr-line) "\n"))
898
899 (defun shr-tag-title (cont)
900   (shr-heading cont 'bold 'underline))
901
902 (defun shr-tag-font (cont)
903   (let* ((start (point))
904          (color (cdr (assq :color cont)))
905          (shr-stylesheet (nconc (list (cons 'color color))
906                                 shr-stylesheet)))
907     (shr-generic cont)
908     (when color
909       (shr-colorize-region start (point) color
910                            (cdr (assq 'background-color shr-stylesheet))))))
911
912 ;;; Table rendering algorithm.
913
914 ;; Table rendering is the only complicated thing here.  We do this by
915 ;; first counting how many TDs there are in each TR, and registering
916 ;; how wide they think they should be ("width=45%", etc).  Then we
917 ;; render each TD separately (this is done in temporary buffers, so
918 ;; that we can use all the rendering machinery as if we were in the
919 ;; main buffer).  Now we know how much space each TD really takes, so
920 ;; we then render everything again with the new widths, and finally
921 ;; insert all these boxes into the main buffer.
922 (defun shr-tag-table-1 (cont)
923   (setq cont (or (cdr (assq 'tbody cont))
924                  cont))
925   (let* ((shr-inhibit-images t)
926          (shr-table-depth (1+ shr-table-depth))
927          (shr-kinsoku-shorten t)
928          ;; Find all suggested widths.
929          (columns (shr-column-specs cont))
930          ;; Compute how many characters wide each TD should be.
931          (suggested-widths (shr-pro-rate-columns columns))
932          ;; Do a "test rendering" to see how big each TD is (this can
933          ;; be smaller (if there's little text) or bigger (if there's
934          ;; unbreakable text).
935          (sketch (shr-make-table cont suggested-widths))
936          (sketch-widths (shr-table-widths sketch suggested-widths)))
937     ;; This probably won't work very well.
938     (when (> (+ (loop for width across sketch-widths
939                       summing (1+ width))
940                 shr-indentation 1)
941              (frame-width))
942       (setq truncate-lines t))
943     ;; Then render the table again with these new "hard" widths.
944     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
945   ;; Finally, insert all the images after the table.  The Emacs buffer
946   ;; model isn't strong enough to allow us to put the images actually
947   ;; into the tables.
948   (when (zerop shr-table-depth)
949     (dolist (elem (shr-find-elements cont 'img))
950       (shr-tag-img (cdr elem)))))
951
952 (defun shr-tag-table (cont)
953   (shr-ensure-paragraph)
954   (let* ((caption (cdr (assq 'caption cont)))
955          (header (cdr (assq 'thead cont)))
956          (body (or (cdr (assq 'tbody cont)) cont))
957          (footer (cdr (assq 'tfoot cont)))
958          (bgcolor (cdr (assq :bgcolor cont)))
959          (start (point))
960          (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
961                                 shr-stylesheet))
962          (nheader (if header (shr-max-columns header)))
963          (nbody (if body (shr-max-columns body)))
964          (nfooter (if footer (shr-max-columns footer))))
965     (shr-tag-table-1
966      (nconc
967       (if caption `((tr (td ,@caption))))
968       (if header
969           (if footer
970               ;; hader + body + footer
971               (if (= nheader nbody)
972                   (if (= nbody nfooter)
973                       `((tr (td (table (tbody ,@header ,@body ,@footer)))))
974                     (nconc `((tr (td (table (tbody ,@header ,@body)))))
975                            (if (= nfooter 1)
976                                footer
977                              `((tr (td (table (tbody ,@footer))))))))
978                 (nconc `((tr (td (table (tbody ,@header)))))
979                        (if (= nbody nfooter)
980                            `((tr (td (table (tbody ,@body ,@footer)))))
981                          (nconc `((tr (td (table (tbody ,@body)))))
982                                 (if (= nfooter 1)
983                                     footer
984                                   `((tr (td (table (tbody ,@footer))))))))))
985             ;; header + body
986             (if (= nheader nbody)
987                 `((tr (td (table (tbody ,@header ,@body)))))
988               (if (= nheader 1)
989                   `(,@header (tr (td (table (tbody ,@body)))))
990                 `((tr (td (table (tbody ,@header))))
991                   (tr (td (table (tbody ,@body))))))))
992         (if footer
993             ;; body + footer
994             (if (= nbody nfooter)
995                 `((tr (td (table (tbody ,@body ,@footer)))))
996               (nconc `((tr (td (table (tbody ,@body)))))
997                      (if (= nfooter 1)
998                          footer
999                        `((tr (td (table (tbody ,@footer))))))))
1000           (if caption
1001               `((tr (td (table (tbody ,@body)))))
1002             body)))))
1003     (when bgcolor
1004       (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
1005                            bgcolor))))
1006
1007 (defun shr-find-elements (cont type)
1008   (let (result)
1009     (dolist (elem cont)
1010       (cond ((eq (car elem) type)
1011              (push elem result))
1012             ((consp (cdr elem))
1013              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
1014     (nreverse result)))
1015
1016 (defun shr-insert-table (table widths)
1017   (shr-insert-table-ruler widths)
1018   (dolist (row table)
1019     (let ((start (point))
1020           (height (let ((max 0))
1021                     (dolist (column row)
1022                       (setq max (max max (cadr column))))
1023                     max)))
1024       (dotimes (i height)
1025         (shr-indent)
1026         (insert shr-table-vertical-line "\n"))
1027       (dolist (column row)
1028         (goto-char start)
1029         (let ((lines (nth 2 column))
1030               (overlay-lines (nth 3 column))
1031               overlay overlay-line)
1032           (dolist (line lines)
1033             (setq overlay-line (pop overlay-lines))
1034             (end-of-line)
1035             (insert line shr-table-vertical-line)
1036             (dolist (overlay overlay-line)
1037               (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
1038                                      (- (point) (nth 1 overlay) 1)))
1039                     (properties (nth 2 overlay)))
1040                 (while properties
1041                   (overlay-put o (pop properties) (pop properties)))))
1042             (forward-line 1))
1043           ;; Add blank lines at padding at the bottom of the TD,
1044           ;; possibly.
1045           (dotimes (i (- height (length lines)))
1046             (end-of-line)
1047             (insert (make-string (string-width (car lines)) ? )
1048                     shr-table-vertical-line)
1049             (forward-line 1)))))
1050     (shr-insert-table-ruler widths)))
1051
1052 (defun shr-insert-table-ruler (widths)
1053   (when (and (bolp)
1054              (> shr-indentation 0))
1055     (shr-indent))
1056   (insert shr-table-corner)
1057   (dotimes (i (length widths))
1058     (insert (make-string (aref widths i) shr-table-horizontal-line)
1059             shr-table-corner))
1060   (insert "\n"))
1061
1062 (defun shr-table-widths (table suggested-widths)
1063   (let* ((length (length suggested-widths))
1064          (widths (make-vector length 0))
1065          (natural-widths (make-vector length 0)))
1066     (dolist (row table)
1067       (let ((i 0))
1068         (dolist (column row)
1069           (aset widths i (max (aref widths i)
1070                               (car column)))
1071           (aset natural-widths i (max (aref natural-widths i)
1072                                       (cadr column)))
1073           (setq i (1+ i)))))
1074     (let ((extra (- (apply '+ (append suggested-widths nil))
1075                     (apply '+ (append widths nil))))
1076           (expanded-columns 0))
1077       (when (> extra 0)
1078         (dotimes (i length)
1079           ;; If the natural width is wider than the rendered width, we
1080           ;; want to allow the column to expand.
1081           (when (> (aref natural-widths i) (aref widths i))
1082             (setq expanded-columns (1+ expanded-columns))))
1083         (dotimes (i length)
1084           (when (> (aref natural-widths i) (aref widths i))
1085             (aset widths i (min
1086                             (1+ (aref natural-widths i))
1087                             (+ (/ extra expanded-columns)
1088                                (aref widths i))))))))
1089     widths))
1090
1091 (defun shr-make-table (cont widths &optional fill)
1092   (let ((trs nil))
1093     (dolist (row cont)
1094       (when (eq (car row) 'tr)
1095         (let ((tds nil)
1096               (columns (cdr row))
1097               (i 0)
1098               column)
1099           (while (< i (length widths))
1100             (setq column (pop columns))
1101             (when (or (memq (car column) '(td th))
1102                       (null column))
1103               (push (shr-render-td (cdr column) (aref widths i) fill)
1104                     tds)
1105               (setq i (1+ i))))
1106           (push (nreverse tds) trs))))
1107     (nreverse trs)))
1108
1109 (defun shr-render-td (cont width fill)
1110   (with-temp-buffer
1111     (let ((bgcolor (cdr (assq :bgcolor cont)))
1112           (fgcolor (cdr (assq :fgcolor cont)))
1113           (style (cdr (assq :style cont)))
1114           (shr-stylesheet shr-stylesheet)
1115           overlays)
1116       (when style
1117         (setq style (and (string-match "color" style)
1118                          (shr-parse-style style))))
1119       (when bgcolor
1120         (setq style (nconc (list (cons 'background-color bgcolor)) style)))
1121       (when fgcolor
1122         (setq style (nconc (list (cons 'color fgcolor)) style)))
1123       (when style
1124         (setq shr-stylesheet (append style shr-stylesheet)))
1125       (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
1126         (if cache
1127             (progn
1128               (insert (car cache))
1129               (let ((end (length (car cache))))
1130                 (dolist (overlay (cadr cache))
1131                   (let ((new-overlay
1132                          (make-overlay (1+ (- end (nth 0 overlay)))
1133                                        (1+ (- end (nth 1 overlay)))))
1134                         (properties (nth 2 overlay)))
1135                     (while properties
1136                       (overlay-put new-overlay
1137                                    (pop properties) (pop properties)))))))
1138           (let ((shr-width width)
1139                 (shr-indentation 0))
1140             (shr-descend (cons 'td cont)))
1141           (delete-region
1142            (point)
1143            (+ (point)
1144               (skip-chars-backward " \t\n")))
1145           (push (list (cons width cont) (buffer-string)
1146                       (shr-overlays-in-region (point-min) (point-max)))
1147                 shr-content-cache)))
1148       (goto-char (point-min))
1149       (let ((max 0))
1150         (while (not (eobp))
1151           (end-of-line)
1152           (setq max (max max (current-column)))
1153           (forward-line 1))
1154         (when fill
1155           (goto-char (point-min))
1156           ;; If the buffer is totally empty, then put a single blank
1157           ;; line here.
1158           (if (zerop (buffer-size))
1159               (insert (make-string width ? ))
1160             ;; Otherwise, fill the buffer.
1161             (while (not (eobp))
1162               (end-of-line)
1163               (when (> (- width (current-column)) 0)
1164                 (insert (make-string (- width (current-column)) ? )))
1165               (forward-line 1))))
1166         (when style
1167           (shr-colorize-region
1168            (point-min) (point-max)
1169            (cdr (assq 'color shr-stylesheet))
1170            (cdr (assq 'background-color shr-stylesheet))))
1171         (if fill
1172             (list max
1173                   (count-lines (point-min) (point-max))
1174                   (split-string (buffer-string) "\n")
1175                   (shr-collect-overlays))
1176           (list max
1177                 (shr-natural-width)))))))
1178
1179 (defun shr-natural-width ()
1180   (goto-char (point-min))
1181   (let ((current 0)
1182         (max 0))
1183     (while (not (eobp))
1184       (end-of-line)
1185       (setq current (+ current (current-column)))
1186       (unless (get-text-property (point) 'shr-break)
1187         (setq max (max max current)
1188               current 0))
1189       (forward-line 1))
1190     max))
1191
1192 (defun shr-collect-overlays ()
1193   (save-excursion
1194     (goto-char (point-min))
1195     (let ((overlays nil))
1196       (while (not (eobp))
1197         (push (shr-overlays-in-region (point) (line-end-position))
1198               overlays)
1199         (forward-line 1))
1200       (nreverse overlays))))
1201
1202 (defun shr-overlays-in-region (start end)
1203   (let (result)
1204     (dolist (overlay (overlays-in start end))
1205       (push (list (if (> start (overlay-start overlay))
1206                       (- end start)
1207                     (- end (overlay-start overlay)))
1208                   (if (< end (overlay-end overlay))
1209                       0
1210                     (- end (overlay-end overlay)))
1211                   (overlay-properties overlay))
1212             result))
1213     (nreverse result)))
1214
1215 (defun shr-pro-rate-columns (columns)
1216   (let ((total-percentage 0)
1217         (widths (make-vector (length columns) 0)))
1218     (dotimes (i (length columns))
1219       (setq total-percentage (+ total-percentage (aref columns i))))
1220     (setq total-percentage (/ 1.0 total-percentage))
1221     (dotimes (i (length columns))
1222       (aset widths i (max (truncate (* (aref columns i)
1223                                        total-percentage
1224                                        (- shr-width (1+ (length columns)))))
1225                           10)))
1226     widths))
1227
1228 ;; Return a summary of the number and shape of the TDs in the table.
1229 (defun shr-column-specs (cont)
1230   (let ((columns (make-vector (shr-max-columns cont) 1)))
1231     (dolist (row cont)
1232       (when (eq (car row) 'tr)
1233         (let ((i 0))
1234           (dolist (column (cdr row))
1235             (when (memq (car column) '(td th))
1236               (let ((width (cdr (assq :width (cdr column)))))
1237                 (when (and width
1238                            (string-match "\\([0-9]+\\)%" width))
1239                   (aset columns i
1240                         (/ (string-to-number (match-string 1 width))
1241                            100.0))))
1242               (setq i (1+ i)))))))
1243     columns))
1244
1245 (defun shr-count (cont elem)
1246   (let ((i 0))
1247     (dolist (sub cont)
1248       (when (eq (car sub) elem)
1249         (setq i (1+ i))))
1250     i))
1251
1252 (defun shr-max-columns (cont)
1253   (let ((max 0))
1254     (dolist (row cont)
1255       (when (eq (car row) 'tr)
1256         (setq max (max max (+ (shr-count (cdr row) 'td)
1257                               (shr-count (cdr row) 'th))))))
1258     max))
1259
1260 (provide 'shr)
1261
1262 ;;; shr.el ends here