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