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