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