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