d871af73ef49c00f6c9d7a77d4a6fed65dc99edc
[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     ;; Skip past all white space at the start and ends.
652     (goto-char start)
653     (skip-chars-forward " \t\n")
654     (beginning-of-line)
655     (setq start (point))
656     (goto-char end)
657     (skip-chars-backward " \t\n")
658     (forward-line 1)
659     (setq end (point))
660     (narrow-to-region start end)
661     (let ((width (shr-natural-width))
662           column)
663       (goto-char (point-min))
664       (while (not (eobp))
665         (end-of-line)
666         (when (and (< (setq current-column (current-column)) width)
667                    (< (setq current-column (shr-previous-newline-padding-width
668                                             current-column))
669                       width))
670           (let ((overlay (make-overlay (point) (1+ (point)))))
671             (overlay-put overlay 'before-string
672                          (concat
673                           (mapconcat
674                            (lambda (overlay)
675                              (let ((string (getf (overlay-properties overlay) 'before-string)))
676                                (if (not string)
677                                    ""
678                                  (overlay-put overlay 'before-string "")
679                                  string)))
680                            (overlays-at (point))
681                            "")
682                           (propertize (make-string (- width current-column) ? )
683                                       'face (list :background color))))))
684         (forward-line 1)))))
685
686 (defun shr-previous-newline-padding-width (width)
687   (let ((overlays (overlays-at (point)))
688         (previous-width 0))
689     (if (null overlays)
690         width
691       (dolist (overlay overlays)
692         (setq previous-width
693               (+ previous-width
694                  (length (getf (overlay-properties overlay) 'before-string)))))
695       (+ width previous-width))))
696
697 (defun shr-put-color-1 (start end type color)
698   (let* ((old-props (get-text-property start 'face))
699          (do-put (not (memq type old-props)))
700          change)
701     (while (< start end)
702       (setq change (next-single-property-change start 'face nil end))
703       (when do-put
704         (put-text-property start change 'face
705                            (nconc (list type color) old-props)))
706       (setq old-props (get-text-property change 'face))
707       (setq do-put (not (memq type old-props)))
708       (setq start change))
709     (when (and do-put
710                (> end start))
711       (put-text-property start end 'face
712                          (nconc (list type color old-props))))))
713
714 ;;; Tag-specific rendering rules.
715
716 (defun shr-tag-body (cont)
717   (let* ((start (point))
718          (fgcolor (cdr (assq :fgcolor cont)))
719          (bgcolor (cdr (assq :bgcolor cont)))
720          (shr-stylesheet (list (cons 'color fgcolor)
721                                (cons 'background-color bgcolor))))
722     (shr-generic cont)
723     (shr-colorize-region start (point) fgcolor bgcolor)))
724
725 (defun shr-tag-style (cont)
726   )
727
728 (defun shr-tag-script (cont)
729   )
730
731 (defun shr-tag-label (cont)
732   (shr-generic cont)
733   (shr-ensure-paragraph))
734
735 (defun shr-tag-p (cont)
736   (shr-ensure-paragraph)
737   (shr-indent)
738   (shr-generic cont)
739   (shr-ensure-paragraph))
740
741 (defun shr-tag-div (cont)
742   (shr-ensure-newline)
743   (shr-indent)
744   (shr-generic cont)
745   (shr-ensure-newline))
746
747 (defun shr-tag-b (cont)
748   (shr-fontize-cont cont 'bold))
749
750 (defun shr-tag-i (cont)
751   (shr-fontize-cont cont 'italic))
752
753 (defun shr-tag-em (cont)
754   (shr-fontize-cont cont 'bold))
755
756 (defun shr-tag-strong (cont)
757   (shr-fontize-cont cont 'bold))
758
759 (defun shr-tag-u (cont)
760   (shr-fontize-cont cont 'underline))
761
762 (defun shr-tag-s (cont)
763   (shr-fontize-cont cont 'strike-through))
764
765 (defun shr-parse-style (style)
766   (when style
767     (save-match-data
768       (when (string-match "\n" style)
769         (setq style (replace-match " " t t style))))
770     (let ((plist nil))
771       (dolist (elem (split-string style ";"))
772         (when elem
773           (setq elem (split-string elem ":"))
774           (when (and (car elem)
775                      (cadr elem))
776             (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
777                   (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
778               (when (string-match " *!important\\'" value)
779                 (setq value (substring value 0 (match-beginning 0))))
780               (push (cons (intern name obarray)
781                           value)
782                     plist)))))
783       plist)))
784
785 (defun shr-tag-a (cont)
786   (let ((url (cdr (assq :href cont)))
787         (title (cdr (assq :title cont)))
788         (start (point))
789         shr-start)
790     (shr-generic cont)
791     (shr-urlify (or shr-start start) url title)))
792
793 (defun shr-tag-object (cont)
794   (let ((start (point))
795         url)
796     (dolist (elem cont)
797       (when (eq (car elem) 'embed)
798         (setq url (or url (cdr (assq :src (cdr elem))))))
799       (when (and (eq (car elem) 'param)
800                  (equal (cdr (assq :name (cdr elem))) "movie"))
801         (setq url (or url (cdr (assq :value (cdr elem)))))))
802     (when url
803       (shr-insert " [multimedia] ")
804       (shr-urlify start url))
805     (shr-generic cont)))
806
807 (defun shr-tag-video (cont)
808   (let ((image (cdr (assq :poster cont)))
809         (url (cdr (assq :src cont)))
810         (start (point)))
811     (shr-tag-img nil image)
812     (shr-urlify start url)))
813
814 (defun shr-tag-img (cont &optional url)
815   (when (or url
816             (and cont
817                  (cdr (assq :src cont))))
818     (when (and (> (current-column) 0)
819                (not (eq shr-state 'image)))
820       (insert "\n"))
821     (let ((alt (cdr (assq :alt cont)))
822           (url (or url (cdr (assq :src cont)))))
823       (let ((start (point-marker)))
824         (when (zerop (length alt))
825           (setq alt "*"))
826         (cond
827          ((or (member (cdr (assq :height cont)) '("0" "1"))
828               (member (cdr (assq :width cont)) '("0" "1")))
829           ;; Ignore zero-sized or single-pixel images.
830           )
831          ((and (not shr-inhibit-images)
832                (string-match "\\`cid:" url))
833           (let ((url (substring url (match-end 0)))
834                 image)
835             (if (or (not shr-content-function)
836                     (not (setq image (funcall shr-content-function url))))
837                 (insert alt)
838               (shr-put-image image alt))))
839          ((or shr-inhibit-images
840               (and shr-blocked-images
841                    (string-match shr-blocked-images url)))
842           (setq shr-start (point))
843           (let ((shr-state 'space))
844             (if (> (string-width alt) 8)
845                 (shr-insert (truncate-string-to-width alt 8))
846               (shr-insert alt))))
847          ((url-is-cached (shr-encode-url url))
848           (shr-put-image (shr-get-image-data url) alt))
849          (t
850           (insert alt)
851           (ignore-errors
852             (url-retrieve (shr-encode-url url) 'shr-image-fetched
853                           (list (current-buffer) start (point-marker))
854                           t))))
855         (put-text-property start (point) 'keymap shr-map)
856         (put-text-property start (point) 'shr-alt alt)
857         (put-text-property start (point) 'image-url url)
858         (put-text-property start (point) 'image-displayer
859                            (shr-image-displayer shr-content-function))
860         (put-text-property start (point) 'help-echo alt)
861         (setq shr-state 'image)))))
862
863 (defun shr-tag-pre (cont)
864   (let ((shr-folding-mode 'none))
865     (shr-ensure-newline)
866     (shr-indent)
867     (shr-generic cont)
868     (shr-ensure-newline)))
869
870 (defun shr-tag-blockquote (cont)
871   (shr-ensure-paragraph)
872   (shr-indent)
873   (let ((shr-indentation (+ shr-indentation 4)))
874     (shr-generic cont))
875   (shr-ensure-paragraph))
876
877 (defun shr-tag-ul (cont)
878   (shr-ensure-paragraph)
879   (let ((shr-list-mode 'ul))
880     (shr-generic cont))
881   (shr-ensure-paragraph))
882
883 (defun shr-tag-ol (cont)
884   (shr-ensure-paragraph)
885   (let ((shr-list-mode 1))
886     (shr-generic cont))
887   (shr-ensure-paragraph))
888
889 (defun shr-tag-li (cont)
890   (shr-ensure-paragraph)
891   (shr-indent)
892   (let* ((bullet
893           (if (numberp shr-list-mode)
894               (prog1
895                   (format "%d " shr-list-mode)
896                 (setq shr-list-mode (1+ shr-list-mode)))
897             "* "))
898          (shr-indentation (+ shr-indentation (length bullet))))
899     (insert bullet)
900     (shr-generic cont)))
901
902 (defun shr-tag-br (cont)
903   (unless (bobp)
904     (insert "\n")
905     (shr-indent))
906   (shr-generic cont))
907
908 (defun shr-tag-h1 (cont)
909   (shr-heading cont 'shr-tag-h1))
910
911 (defun shr-tag-h2 (cont)
912   (shr-heading cont 'shr-tag-h2))
913
914 (defun shr-tag-h3 (cont)
915   (shr-heading cont 'shr-tag-h3))
916
917 (defun shr-tag-h4 (cont)
918   (shr-heading cont 'shr-tag-h4))
919
920 (defun shr-tag-h5 (cont)
921   (shr-heading cont 'shr-tag-h5))
922
923 (defun shr-tag-h6 (cont)
924   (shr-heading cont 'shr-tag-h6))
925
926 (defun shr-tag-hr (cont)
927   (shr-ensure-newline)
928   (insert (make-string shr-width shr-hr-line) "\n"))
929
930 (defun shr-tag-title (cont)
931   (shr-heading cont 'bold 'underline))
932
933 (defun shr-tag-font (cont)
934   (let* ((start (point))
935          (color (cdr (assq :color cont)))
936          (shr-stylesheet (nconc (list (cons 'color color))
937                                 shr-stylesheet)))
938     (shr-generic cont)
939     (when color
940       (shr-colorize-region start (point) color
941                            (cdr (assq 'background-color shr-stylesheet))))))
942
943 ;;; Table rendering algorithm.
944
945 ;; Table rendering is the only complicated thing here.  We do this by
946 ;; first counting how many TDs there are in each TR, and registering
947 ;; how wide they think they should be ("width=45%", etc).  Then we
948 ;; render each TD separately (this is done in temporary buffers, so
949 ;; that we can use all the rendering machinery as if we were in the
950 ;; main buffer).  Now we know how much space each TD really takes, so
951 ;; we then render everything again with the new widths, and finally
952 ;; insert all these boxes into the main buffer.
953 (defun shr-tag-table-1 (cont)
954   (setq cont (or (cdr (assq 'tbody cont))
955                  cont))
956   (let* ((shr-inhibit-images t)
957          (shr-table-depth (1+ shr-table-depth))
958          (shr-kinsoku-shorten t)
959          ;; Find all suggested widths.
960          (columns (shr-column-specs cont))
961          ;; Compute how many characters wide each TD should be.
962          (suggested-widths (shr-pro-rate-columns columns))
963          ;; Do a "test rendering" to see how big each TD is (this can
964          ;; be smaller (if there's little text) or bigger (if there's
965          ;; unbreakable text).
966          (sketch (shr-make-table cont suggested-widths))
967          (sketch-widths (shr-table-widths sketch suggested-widths)))
968     ;; This probably won't work very well.
969     (when (> (+ (loop for width across sketch-widths
970                       summing (1+ width))
971                 shr-indentation 1)
972              (frame-width))
973       (setq truncate-lines t))
974     ;; Then render the table again with these new "hard" widths.
975     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
976   ;; Finally, insert all the images after the table.  The Emacs buffer
977   ;; model isn't strong enough to allow us to put the images actually
978   ;; into the tables.
979   (when (zerop shr-table-depth)
980     (dolist (elem (shr-find-elements cont 'img))
981       (shr-tag-img (cdr elem)))))
982
983 (defun shr-tag-table (cont)
984   (shr-ensure-paragraph)
985   (let* ((caption (cdr (assq 'caption cont)))
986          (header (cdr (assq 'thead cont)))
987          (body (or (cdr (assq 'tbody cont)) cont))
988          (footer (cdr (assq 'tfoot cont)))
989          (bgcolor (cdr (assq :bgcolor cont)))
990          (start (point))
991          (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
992                                 shr-stylesheet))
993          (nheader (if header (shr-max-columns header)))
994          (nbody (if body (shr-max-columns body)))
995          (nfooter (if footer (shr-max-columns footer))))
996     (shr-tag-table-1
997      (nconc
998       (if caption `((tr (td ,@caption))))
999       (if header
1000           (if footer
1001               ;; hader + body + footer
1002               (if (= nheader nbody)
1003                   (if (= nbody nfooter)
1004                       `((tr (td (table (tbody ,@header ,@body ,@footer)))))
1005                     (nconc `((tr (td (table (tbody ,@header ,@body)))))
1006                            (if (= nfooter 1)
1007                                footer
1008                              `((tr (td (table (tbody ,@footer))))))))
1009                 (nconc `((tr (td (table (tbody ,@header)))))
1010                        (if (= nbody nfooter)
1011                            `((tr (td (table (tbody ,@body ,@footer)))))
1012                          (nconc `((tr (td (table (tbody ,@body)))))
1013                                 (if (= nfooter 1)
1014                                     footer
1015                                   `((tr (td (table (tbody ,@footer))))))))))
1016             ;; header + body
1017             (if (= nheader nbody)
1018                 `((tr (td (table (tbody ,@header ,@body)))))
1019               (if (= nheader 1)
1020                   `(,@header (tr (td (table (tbody ,@body)))))
1021                 `((tr (td (table (tbody ,@header))))
1022                   (tr (td (table (tbody ,@body))))))))
1023         (if footer
1024             ;; body + footer
1025             (if (= nbody nfooter)
1026                 `((tr (td (table (tbody ,@body ,@footer)))))
1027               (nconc `((tr (td (table (tbody ,@body)))))
1028                      (if (= nfooter 1)
1029                          footer
1030                        `((tr (td (table (tbody ,@footer))))))))
1031           (if caption
1032               `((tr (td (table (tbody ,@body)))))
1033             body)))))
1034     (when bgcolor
1035       (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
1036                            bgcolor))))
1037
1038 (defun shr-find-elements (cont type)
1039   (let (result)
1040     (dolist (elem cont)
1041       (cond ((eq (car elem) type)
1042              (push elem result))
1043             ((consp (cdr elem))
1044              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
1045     (nreverse result)))
1046
1047 (defun shr-insert-table (table widths)
1048   (shr-insert-table-ruler widths)
1049   (dolist (row table)
1050     (let ((start (point))
1051           (height (let ((max 0))
1052                     (dolist (column row)
1053                       (setq max (max max (cadr column))))
1054                     max)))
1055       (dotimes (i height)
1056         (shr-indent)
1057         (insert shr-table-vertical-line "\n"))
1058       (dolist (column row)
1059         (goto-char start)
1060         (let ((lines (nth 2 column))
1061               (overlay-lines (nth 3 column))
1062               overlay overlay-line)
1063           (dolist (line lines)
1064             (setq overlay-line (pop overlay-lines))
1065             (end-of-line)
1066             (insert line shr-table-vertical-line)
1067             (dolist (overlay overlay-line)
1068               (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
1069                                      (- (point) (nth 1 overlay) 1)))
1070                     (properties (nth 2 overlay)))
1071                 (while properties
1072                   (overlay-put o (pop properties) (pop properties)))))
1073             (forward-line 1))
1074           ;; Add blank lines at padding at the bottom of the TD,
1075           ;; possibly.
1076           (dotimes (i (- height (length lines)))
1077             (end-of-line)
1078             (insert (make-string (string-width (car lines)) ? )
1079                     shr-table-vertical-line)
1080             (forward-line 1)))))
1081     (shr-insert-table-ruler widths)))
1082
1083 (defun shr-insert-table-ruler (widths)
1084   (when (and (bolp)
1085              (> shr-indentation 0))
1086     (shr-indent))
1087   (insert shr-table-corner)
1088   (dotimes (i (length widths))
1089     (insert (make-string (aref widths i) shr-table-horizontal-line)
1090             shr-table-corner))
1091   (insert "\n"))
1092
1093 (defun shr-table-widths (table suggested-widths)
1094   (let* ((length (length suggested-widths))
1095          (widths (make-vector length 0))
1096          (natural-widths (make-vector length 0)))
1097     (dolist (row table)
1098       (let ((i 0))
1099         (dolist (column row)
1100           (aset widths i (max (aref widths i)
1101                               (car column)))
1102           (aset natural-widths i (max (aref natural-widths i)
1103                                       (cadr column)))
1104           (setq i (1+ i)))))
1105     (let ((extra (- (apply '+ (append suggested-widths nil))
1106                     (apply '+ (append widths nil))))
1107           (expanded-columns 0))
1108       (when (> extra 0)
1109         (dotimes (i length)
1110           ;; If the natural width is wider than the rendered width, we
1111           ;; want to allow the column to expand.
1112           (when (> (aref natural-widths i) (aref widths i))
1113             (setq expanded-columns (1+ expanded-columns))))
1114         (dotimes (i length)
1115           (when (> (aref natural-widths i) (aref widths i))
1116             (aset widths i (min
1117                             (1+ (aref natural-widths i))
1118                             (+ (/ extra expanded-columns)
1119                                (aref widths i))))))))
1120     widths))
1121
1122 (defun shr-make-table (cont widths &optional fill)
1123   (let ((trs nil))
1124     (dolist (row cont)
1125       (when (eq (car row) 'tr)
1126         (let ((tds nil)
1127               (columns (cdr row))
1128               (i 0)
1129               column)
1130           (while (< i (length widths))
1131             (setq column (pop columns))
1132             (when (or (memq (car column) '(td th))
1133                       (null column))
1134               (push (shr-render-td (cdr column) (aref widths i) fill)
1135                     tds)
1136               (setq i (1+ i))))
1137           (push (nreverse tds) trs))))
1138     (nreverse trs)))
1139
1140 (defun shr-render-td (cont width fill)
1141   (with-temp-buffer
1142     (let ((bgcolor (cdr (assq :bgcolor cont)))
1143           (fgcolor (cdr (assq :fgcolor cont)))
1144           (style (cdr (assq :style cont)))
1145           (shr-stylesheet shr-stylesheet)
1146           overlays)
1147       (when style
1148         (setq style (and (string-match "color" style)
1149                          (shr-parse-style style))))
1150       (when bgcolor
1151         (setq style (nconc (list (cons 'background-color bgcolor)) style)))
1152       (when fgcolor
1153         (setq style (nconc (list (cons 'color fgcolor)) style)))
1154       (when style
1155         (setq shr-stylesheet (append style shr-stylesheet)))
1156       (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
1157         (if cache
1158             (progn
1159               (insert (car cache))
1160               (let ((end (length (car cache))))
1161                 (dolist (overlay (cadr cache))
1162                   (let ((new-overlay
1163                          (make-overlay (1+ (- end (nth 0 overlay)))
1164                                        (1+ (- end (nth 1 overlay)))))
1165                         (properties (nth 2 overlay)))
1166                     (while properties
1167                       (overlay-put new-overlay
1168                                    (pop properties) (pop properties)))))))
1169           (let ((shr-width width)
1170                 (shr-indentation 0))
1171             (shr-descend (cons 'td cont)))
1172           (delete-region
1173            (point)
1174            (+ (point)
1175               (skip-chars-backward " \t\n")))
1176           (push (list (cons width cont) (buffer-string)
1177                       (shr-overlays-in-region (point-min) (point-max)))
1178                 shr-content-cache)))
1179       (goto-char (point-min))
1180       (let ((max 0))
1181         (while (not (eobp))
1182           (end-of-line)
1183           (setq max (max max (current-column)))
1184           (forward-line 1))
1185         (when fill
1186           (goto-char (point-min))
1187           ;; If the buffer is totally empty, then put a single blank
1188           ;; line here.
1189           (if (zerop (buffer-size))
1190               (insert (make-string width ? ))
1191             ;; Otherwise, fill the buffer.
1192             (while (not (eobp))
1193               (end-of-line)
1194               (when (> (- width (current-column)) 0)
1195                 (insert (make-string (- width (current-column)) ? )))
1196               (forward-line 1))))
1197         (when style
1198           (shr-colorize-region
1199            (point-min) (point-max)
1200            (cdr (assq 'color shr-stylesheet))
1201            (cdr (assq 'background-color shr-stylesheet))))
1202         (if fill
1203             (list max
1204                   (count-lines (point-min) (point-max))
1205                   (split-string (buffer-string) "\n")
1206                   (shr-collect-overlays))
1207           (list max
1208                 (shr-natural-width)))))))
1209
1210 (defun shr-natural-width ()
1211   (goto-char (point-min))
1212   (let ((current 0)
1213         (max 0))
1214     (while (not (eobp))
1215       (end-of-line)
1216       (setq current (+ current (current-column)))
1217       (unless (get-text-property (point) 'shr-break)
1218         (setq max (max max current)
1219               current 0))
1220       (forward-line 1))
1221     max))
1222
1223 (defun shr-collect-overlays ()
1224   (save-excursion
1225     (goto-char (point-min))
1226     (let ((overlays nil))
1227       (while (not (eobp))
1228         (push (shr-overlays-in-region (point) (line-end-position))
1229               overlays)
1230         (forward-line 1))
1231       (nreverse overlays))))
1232
1233 (defun shr-overlays-in-region (start end)
1234   (let (result)
1235     (dolist (overlay (overlays-in start end))
1236       (push (list (if (> start (overlay-start overlay))
1237                       (- end start)
1238                     (- end (overlay-start overlay)))
1239                   (if (< end (overlay-end overlay))
1240                       0
1241                     (- end (overlay-end overlay)))
1242                   (overlay-properties overlay))
1243             result))
1244     (nreverse result)))
1245
1246 (defun shr-pro-rate-columns (columns)
1247   (let ((total-percentage 0)
1248         (widths (make-vector (length columns) 0)))
1249     (dotimes (i (length columns))
1250       (setq total-percentage (+ total-percentage (aref columns i))))
1251     (setq total-percentage (/ 1.0 total-percentage))
1252     (dotimes (i (length columns))
1253       (aset widths i (max (truncate (* (aref columns i)
1254                                        total-percentage
1255                                        (- shr-width (1+ (length columns)))))
1256                           10)))
1257     widths))
1258
1259 ;; Return a summary of the number and shape of the TDs in the table.
1260 (defun shr-column-specs (cont)
1261   (let ((columns (make-vector (shr-max-columns cont) 1)))
1262     (dolist (row cont)
1263       (when (eq (car row) 'tr)
1264         (let ((i 0))
1265           (dolist (column (cdr row))
1266             (when (memq (car column) '(td th))
1267               (let ((width (cdr (assq :width (cdr column)))))
1268                 (when (and width
1269                            (string-match "\\([0-9]+\\)%" width))
1270                   (aset columns i
1271                         (/ (string-to-number (match-string 1 width))
1272                            100.0))))
1273               (setq i (1+ i)))))))
1274     columns))
1275
1276 (defun shr-count (cont elem)
1277   (let ((i 0))
1278     (dolist (sub cont)
1279       (when (eq (car sub) elem)
1280         (setq i (1+ i))))
1281     i))
1282
1283 (defun shr-max-columns (cont)
1284   (let ((max 0))
1285     (dolist (row cont)
1286       (when (eq (car row) 'tr)
1287         (setq max (max max (+ (shr-count (cdr row) 'td)
1288                               (shr-count (cdr row) 'th))))))
1289     max))
1290
1291 (provide 'shr)
1292
1293 ;;; shr.el ends here