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