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