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