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