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