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