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