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