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