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