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