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