shr.el (shr-insert): Revert last change.
[emacs.git] / lisp / gnus / shr.el
blob69973fbfb5028b90c476eafe165e66d9f80415ba
1 ;;; shr.el --- Simple HTML Renderer
3 ;; Copyright (C) 2010 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 (require 'browse-url)
35 (unless (aref (char-category-set (make-char 'japanese-jisx0208 33 35)) ?>)
36 (load "kinsoku" nil t))
38 (defgroup shr nil
39 "Simple HTML Renderer"
40 :group 'mail)
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 'regexp)
58 (defcustom shr-table-horizontal-line ?-
59 "Character used to draw horizontal table lines."
60 :group 'shr
61 :type 'character)
63 (defcustom shr-table-vertical-line ?|
64 "Character used to draw vertical table lines."
65 :group 'shr
66 :type 'character)
68 (defcustom shr-table-corner ?+
69 "Character used to draw table corners."
70 :group 'shr
71 :type 'character)
73 (defcustom shr-hr-line ?-
74 "Character used to draw hr lines."
75 :group 'shr
76 :type 'character)
78 (defcustom shr-width fill-column
79 "Frame width to use for rendering."
80 :type 'integer
81 :group 'shr)
83 (defvar shr-content-function nil
84 "If bound, this should be a function that will return the content.
85 This is used for cid: URLs, and the function is called with the
86 cid: URL as the argument.")
88 ;;; Internal variables.
90 (defvar shr-folding-mode nil)
91 (defvar shr-state nil)
92 (defvar shr-start nil)
93 (defvar shr-indentation 0)
94 (defvar shr-inhibit-images nil)
95 (defvar shr-list-mode nil)
96 (defvar shr-content-cache nil)
97 (defvar shr-kinsoku-shorten nil)
98 (defvar shr-table-depth 0)
100 (defvar shr-map
101 (let ((map (make-sparse-keymap)))
102 (define-key map "a" 'shr-show-alt-text)
103 (define-key map "i" 'shr-browse-image)
104 (define-key map "I" 'shr-insert-image)
105 (define-key map "u" 'shr-copy-url)
106 (define-key map "v" 'shr-browse-url)
107 (define-key map "o" 'shr-save-contents)
108 (define-key map "\r" 'shr-browse-url)
109 map))
111 ;; Public functions and commands.
113 ;;;###autoload
114 (defun shr-insert-document (dom)
115 (setq shr-content-cache nil)
116 (let ((shr-state nil)
117 (shr-start nil))
118 (shr-descend (shr-transform-dom dom))))
120 (defun shr-copy-url ()
121 "Copy the URL under point to the kill ring.
122 If called twice, then try to fetch the URL and see whether it
123 redirects somewhere else."
124 (interactive)
125 (let ((url (get-text-property (point) 'shr-url)))
126 (cond
127 ((not url)
128 (message "No URL under point"))
129 ;; Resolve redirected URLs.
130 ((equal url (car kill-ring))
131 (url-retrieve
133 (lambda (a)
134 (when (and (consp a)
135 (eq (car a) :redirect))
136 (with-temp-buffer
137 (insert (cadr a))
138 (goto-char (point-min))
139 ;; Remove common tracking junk from the URL.
140 (when (re-search-forward ".utm_.*" nil t)
141 (replace-match "" t t))
142 (message "Copied %s" (buffer-string))
143 (copy-region-as-kill (point-min) (point-max)))))))
144 ;; Copy the URL to the kill ring.
146 (with-temp-buffer
147 (insert url)
148 (copy-region-as-kill (point-min) (point-max))
149 (message "Copied %s" url))))))
151 (defun shr-show-alt-text ()
152 "Show the ALT text of the image under point."
153 (interactive)
154 (let ((text (get-text-property (point) 'shr-alt)))
155 (if (not text)
156 (message "No image under point")
157 (message "%s" text))))
159 (defun shr-browse-image ()
160 "Browse the image under point."
161 (interactive)
162 (let ((url (get-text-property (point) 'image-url)))
163 (if (not url)
164 (message "No image under point")
165 (message "Browsing %s..." url)
166 (browse-url url))))
168 (defun shr-insert-image ()
169 "Insert the image under point into the buffer."
170 (interactive)
171 (let ((url (get-text-property (point) 'image-url)))
172 (if (not url)
173 (message "No image under point")
174 (message "Inserting %s..." url)
175 (url-retrieve url 'shr-image-fetched
176 (list (current-buffer) (1- (point)) (point-marker))
177 t))))
179 ;;; Utility functions.
181 (defun shr-transform-dom (dom)
182 (let ((result (list (pop dom))))
183 (dolist (arg (pop dom))
184 (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
185 (cdr arg))
186 result))
187 (dolist (sub dom)
188 (if (stringp sub)
189 (push (cons 'text sub) result)
190 (push (shr-transform-dom sub) result)))
191 (nreverse result)))
193 (defun shr-descend (dom)
194 (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray))
195 (style (cdr (assq :style (cdr dom))))
196 (start (point)))
197 (when (and style
198 (string-match "color" style))
199 (setq style (shr-parse-style style)))
200 (if (fboundp function)
201 (funcall function (cdr dom))
202 (shr-generic (cdr dom)))
203 (when (consp style)
204 (shr-insert-background-overlay (cdr (assq 'background-color style))
205 start)
206 (shr-insert-foreground-overlay (cdr (assq 'color style))
207 start (point)))))
209 (defun shr-generic (cont)
210 (dolist (sub cont)
211 (cond
212 ((eq (car sub) 'text)
213 (shr-insert (cdr sub)))
214 ((listp (cdr sub))
215 (shr-descend sub)))))
217 (defun shr-insert (text)
218 (when (and (eq shr-state 'image)
219 (not (string-match "\\`[ \t\n]+\\'" text)))
220 (insert "\n")
221 (setq shr-state nil))
222 (cond
223 ((eq shr-folding-mode 'none)
224 (insert text))
226 (when (and (string-match "\\`[ \t\n]" text)
227 (not (bolp))
228 (not (eq (char-after (1- (point))) ? )))
229 (insert " "))
230 (dolist (elem (split-string text))
231 (when (and (bolp)
232 (> shr-indentation 0))
233 (shr-indent))
234 ;; The shr-start is a special variable that is used to pass
235 ;; upwards the first point in the buffer where the text really
236 ;; starts.
237 (unless shr-start
238 (setq shr-start (point)))
239 ;; No space is needed behind a wide character categorized as
240 ;; kinsoku-bol, between characters both categorized as nospace,
241 ;; or at the beginning of a line.
242 (let (prev)
243 (when (and (eq (preceding-char) ? )
244 (or (= (line-beginning-position) (1- (point)))
245 (and (aref fill-find-break-point-function-table
246 (setq prev (char-after (- (point) 2))))
247 (aref (char-category-set prev) ?>))
248 (and (aref fill-nospace-between-words-table prev)
249 (aref fill-nospace-between-words-table
250 (aref elem 0)))))
251 (delete-char -1)))
252 (insert elem)
253 (let (found)
254 (while (and (> (current-column) shr-width)
255 (progn
256 (setq found (shr-find-fill-point))
257 (not (eolp))))
258 (when (eq (preceding-char) ? )
259 (delete-char -1))
260 (insert "\n")
261 (unless found
262 (put-text-property (1- (point)) (point) 'shr-break t)
263 ;; No space is needed at the beginning of a line.
264 (when (eq (following-char) ? )
265 (delete-char 1)))
266 (when (> shr-indentation 0)
267 (shr-indent))
268 (end-of-line))
269 (insert " ")))
270 (unless (string-match "[ \t\n]\\'" text)
271 (delete-char -1)))))
273 (defun shr-find-fill-point ()
274 (when (> (move-to-column shr-width) shr-width)
275 (backward-char 1))
276 (let (failed)
277 (while (not
278 (or (setq failed (= (current-column) shr-indentation))
279 (eq (preceding-char) ? )
280 (eq (following-char) ? )
281 (aref fill-find-break-point-function-table (preceding-char))
282 (aref (char-category-set (preceding-char)) ?>)))
283 (backward-char 1))
284 (if failed
285 ;; There's no breakable point, so we give it up.
286 (progn
287 (end-of-line)
288 (while (aref fill-find-break-point-function-table (preceding-char))
289 (backward-char 1))
290 nil)
292 (eolp)
293 (progn
294 ;; Don't put kinsoku-bol characters at the beginning of a line,
295 ;; or kinsoku-eol characters at the end of a line.
296 (cond
297 (shr-kinsoku-shorten
298 (while (and
299 (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
300 (not (or (aref (char-category-set (preceding-char)) ?>)
301 (aref (char-category-set (following-char)) ?<)))
302 (or (aref (char-category-set (preceding-char)) ?<)
303 (aref (char-category-set (following-char)) ?>)))
304 (backward-char 1)))
305 ((aref (char-category-set (preceding-char)) ?<)
306 (let ((count 3))
307 (while (progn
308 (backward-char 1)
309 (and
310 (> (setq count (1- count)) 0)
311 (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
312 (or (aref (char-category-set (preceding-char)) ?<)
313 (aref (char-category-set (following-char)) ?>))))))
314 (if (and (setq failed (= (current-column) shr-indentation))
315 (re-search-forward "\\c|" (line-end-position) 'move))
316 ;; There's no breakable point that doesn't violate kinsoku,
317 ;; so we look for the second best position.
318 (let (bp)
319 (while (and (<= (current-column) shr-width)
320 (progn
321 (setq bp (point))
322 (not (eolp)))
323 (aref fill-find-break-point-function-table
324 (following-char)))
325 (forward-char 1))
326 (goto-char (or bp (line-end-position))))))
328 (let ((count 4))
329 (while (and (>= (setq count (1- count)) 0)
330 (aref (char-category-set (following-char)) ?>)
331 (aref fill-find-break-point-function-table
332 (following-char)))
333 (forward-char 1)))))
334 (when (eq (following-char) ? )
335 (forward-char 1))
336 (not failed))))))
338 (defun shr-ensure-newline ()
339 (unless (zerop (current-column))
340 (insert "\n")))
342 (defun shr-ensure-paragraph ()
343 (unless (bobp)
344 (if (<= (current-column) shr-indentation)
345 (unless (save-excursion
346 (forward-line -1)
347 (looking-at " *$"))
348 (insert "\n"))
349 (if (save-excursion
350 (beginning-of-line)
351 (looking-at " *$"))
352 (insert "\n")
353 (insert "\n\n")))))
355 (defun shr-indent ()
356 (when (> shr-indentation 0)
357 (insert (make-string shr-indentation ? ))))
359 (defun shr-fontize-cont (cont &rest types)
360 (let (shr-start)
361 (shr-generic cont)
362 (dolist (type types)
363 (shr-add-font (or shr-start (point)) (point) type))))
365 ;; Add an overlay in the region, but avoid putting the font properties
366 ;; on blank text at the start of the line, and the newline at the end,
367 ;; to avoid ugliness.
368 (defun shr-add-font (start end type)
369 (save-excursion
370 (goto-char start)
371 (while (< (point) end)
372 (when (bolp)
373 (skip-chars-forward " "))
374 (let ((overlay (make-overlay (point) (min (line-end-position) end))))
375 (overlay-put overlay 'face type))
376 (if (< (line-end-position) end)
377 (forward-line 1)
378 (goto-char end)))))
380 (defun shr-browse-url ()
381 "Browse the URL under point."
382 (interactive)
383 (let ((url (get-text-property (point) 'shr-url)))
384 (cond
385 ((not url)
386 (message "No link under point"))
387 ((string-match "^mailto:" url)
388 (browse-url-mailto url))
390 (browse-url url)))))
392 (defun shr-save-contents (directory)
393 "Save the contents from URL in a file."
394 (interactive "DSave contents of URL to directory: ")
395 (let ((url (get-text-property (point) 'shr-url)))
396 (if (not url)
397 (message "No link under point")
398 (url-retrieve (shr-encode-url url)
399 'shr-store-contents (list url directory)))))
401 (defun shr-store-contents (status url directory)
402 (unless (plist-get status :error)
403 (when (or (search-forward "\n\n" nil t)
404 (search-forward "\r\n\r\n" nil t))
405 (write-region (point) (point-max)
406 (expand-file-name (file-name-nondirectory url)
407 directory)))))
409 (defun shr-image-fetched (status buffer start end)
410 (when (and (buffer-name buffer)
411 (not (plist-get status :error)))
412 (url-store-in-cache (current-buffer))
413 (when (or (search-forward "\n\n" nil t)
414 (search-forward "\r\n\r\n" nil t))
415 (let ((data (buffer-substring (point) (point-max))))
416 (with-current-buffer buffer
417 (let ((alt (buffer-substring start end))
418 (inhibit-read-only t))
419 (delete-region start end)
420 (goto-char start)
421 (shr-put-image data alt))))))
422 (kill-buffer (current-buffer)))
424 (defun shr-put-image (data alt)
425 (if (display-graphic-p)
426 (let ((image (ignore-errors
427 (shr-rescale-image data))))
428 (when image
429 ;; When inserting big-ish pictures, put them at the
430 ;; beginning of the line.
431 (when (and (> (current-column) 0)
432 (> (car (image-size image t)) 400))
433 (insert "\n"))
434 (insert-image image (or alt "*"))))
435 (insert alt)))
437 (defun shr-rescale-image (data)
438 (if (or (not (fboundp 'imagemagick-types))
439 (not (get-buffer-window (current-buffer))))
440 (create-image data nil t)
441 (let* ((image (create-image data nil t))
442 (size (image-size image t))
443 (width (car size))
444 (height (cdr size))
445 (edges (window-inside-pixel-edges
446 (get-buffer-window (current-buffer))))
447 (window-width (truncate (* shr-max-image-proportion
448 (- (nth 2 edges) (nth 0 edges)))))
449 (window-height (truncate (* shr-max-image-proportion
450 (- (nth 3 edges) (nth 1 edges)))))
451 scaled-image)
452 (when (> height window-height)
453 (setq image (or (create-image data 'imagemagick t
454 :height window-height)
455 image))
456 (setq size (image-size image t)))
457 (when (> (car size) window-width)
458 (setq image (or
459 (create-image data 'imagemagick t
460 :width window-width)
461 image)))
462 image)))
464 ;; url-cache-extract autoloads url-cache.
465 (declare-function url-cache-create-filename "url-cache" (url))
466 (autoload 'mm-disable-multibyte "mm-util")
467 (autoload 'browse-url-mailto "browse-url")
469 (defun shr-get-image-data (url)
470 "Get image data for URL.
471 Return a string with image data."
472 (with-temp-buffer
473 (mm-disable-multibyte)
474 (when (ignore-errors
475 (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
477 (when (or (search-forward "\n\n" nil t)
478 (search-forward "\r\n\r\n" nil t))
479 (buffer-substring (point) (point-max))))))
481 (defun shr-image-displayer (content-function)
482 "Return a function to display an image.
483 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
484 is an argument. The function to be returned takes three arguments URL,
485 START, and END."
486 `(lambda (url start end)
487 (when url
488 (if (string-match "\\`cid:" url)
489 ,(when content-function
490 `(let ((image (funcall ,content-function
491 (substring url (match-end 0)))))
492 (when image
493 (goto-char start)
494 (shr-put-image image
495 (prog1
496 (buffer-substring-no-properties start end)
497 (delete-region start end))))))
498 (url-retrieve url 'shr-image-fetched
499 (list (current-buffer) start end)
500 t)))))
502 (defun shr-heading (cont &rest types)
503 (shr-ensure-paragraph)
504 (apply #'shr-fontize-cont cont types)
505 (shr-ensure-paragraph))
507 (autoload 'widget-convert-button "wid-edit")
509 (defun shr-urlify (start url)
510 (widget-convert-button
511 'url-link start (point)
512 :help-echo url
513 :keymap shr-map
514 url)
515 (put-text-property start (point) 'shr-url url))
517 (defun shr-encode-url (url)
518 "Encode URL."
519 (browse-url-url-encode-chars url "[)$ ]"))
521 (autoload 'shr-color-visible "shr-color")
522 (autoload 'shr-color->hexadecimal "shr-color")
524 (defun shr-color-check (fg bg)
525 "Check that FG is visible on BG.
526 Returns (fg bg) with corrected values.
527 Returns nil if the colors that would be used are the default
528 ones, in case fg and bg are nil."
529 (when (or fg bg)
530 (let ((fixed (cond ((null fg) 'fg)
531 ((null bg) 'bg))))
532 ;; Convert colors to hexadecimal, or set them to default.
533 (let ((fg (or (shr-color->hexadecimal fg)
534 (frame-parameter nil 'foreground-color)))
535 (bg (or (shr-color->hexadecimal bg)
536 (frame-parameter nil 'background-color))))
537 (cond ((eq fixed 'bg)
538 ;; Only return the new fg
539 (list nil (cadr (shr-color-visible bg fg t))))
540 ((eq fixed 'fg)
541 ;; Invert args and results and return only the new bg
542 (list (cadr (shr-color-visible fg bg t)) nil))
544 (shr-color-visible bg fg)))))))
546 (defun shr-get-background (pos)
547 "Return background color at POS."
548 (dolist (overlay (overlays-in pos (1+ pos)))
549 (let ((background (plist-get (overlay-get overlay 'face)
550 :background)))
551 (when background
552 (return background)))))
554 (defun shr-insert-foreground-overlay (fg start end)
555 (when fg
556 (let ((bg (shr-get-background start)))
557 (let ((new-colors (shr-color-check fg bg)))
558 (when new-colors
559 (overlay-put (make-overlay start end) 'face
560 (list :foreground (cadr new-colors))))))))
562 (defun shr-insert-background-overlay (bg start)
563 "Insert an overlay with background color BG at START.
564 The overlay has rear-advance set to t, so it will be used when
565 text will be inserted at start."
566 (when bg
567 (let ((new-colors (shr-color-check nil bg)))
568 (when new-colors
569 (overlay-put (make-overlay start start nil nil t) 'face
570 (list :background (car new-colors)))))))
572 ;;; Tag-specific rendering rules.
574 (defun shr-tag-body (cont)
575 (let ((start (point))
576 (fgcolor (cdr (assq :fgcolor cont)))
577 (bgcolor (cdr (assq :bgcolor cont))))
578 (shr-insert-background-overlay bgcolor start)
579 (shr-generic cont)
580 (shr-insert-foreground-overlay fgcolor start (point))))
582 (defun shr-tag-p (cont)
583 (shr-ensure-paragraph)
584 (shr-indent)
585 (shr-generic cont)
586 (shr-ensure-paragraph))
588 (defun shr-tag-div (cont)
589 (shr-ensure-newline)
590 (shr-indent)
591 (shr-generic cont)
592 (shr-ensure-newline))
594 (defun shr-tag-b (cont)
595 (shr-fontize-cont cont 'bold))
597 (defun shr-tag-i (cont)
598 (shr-fontize-cont cont 'italic))
600 (defun shr-tag-em (cont)
601 (shr-fontize-cont cont 'bold))
603 (defun shr-tag-strong (cont)
604 (shr-fontize-cont cont 'bold))
606 (defun shr-tag-u (cont)
607 (shr-fontize-cont cont 'underline))
609 (defun shr-tag-s (cont)
610 (shr-fontize-cont cont 'strike-through))
612 (defun shr-parse-style (style)
613 (when style
614 (save-match-data
615 (when (string-match "\n" style)
616 (setq style (replace-match " " t t style))))
617 (let ((plist nil))
618 (dolist (elem (split-string style ";"))
619 (when elem
620 (setq elem (split-string elem ":"))
621 (when (and (car elem)
622 (cadr elem))
623 (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
624 (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
625 (when (string-match " *!important\\'" value)
626 (setq value (substring value 0 (match-beginning 0))))
627 (push (cons (intern name obarray)
628 value)
629 plist)))))
630 plist)))
632 (defun shr-tag-a (cont)
633 (let ((url (cdr (assq :href cont)))
634 (start (point))
635 shr-start)
636 (shr-generic cont)
637 (shr-urlify (or shr-start start) url)))
639 (defun shr-tag-object (cont)
640 (let ((start (point))
641 url)
642 (dolist (elem cont)
643 (when (eq (car elem) 'embed)
644 (setq url (or url (cdr (assq :src (cdr elem))))))
645 (when (and (eq (car elem) 'param)
646 (equal (cdr (assq :name (cdr elem))) "movie"))
647 (setq url (or url (cdr (assq :value (cdr elem)))))))
648 (when url
649 (shr-insert " [multimedia] ")
650 (shr-urlify start url))
651 (shr-generic cont)))
653 (defun shr-tag-video (cont)
654 (let ((image (cdr (assq :poster cont)))
655 (url (cdr (assq :src cont)))
656 (start (point)))
657 (shr-tag-img nil image)
658 (shr-urlify start url)))
660 (defun shr-tag-img (cont &optional url)
661 (when (or url
662 (and cont
663 (cdr (assq :src cont))))
664 (when (and (> (current-column) 0)
665 (not (eq shr-state 'image)))
666 (insert "\n"))
667 (let ((alt (cdr (assq :alt cont)))
668 (url (or url (cdr (assq :src cont)))))
669 (let ((start (point-marker)))
670 (when (zerop (length alt))
671 (setq alt "*"))
672 (cond
673 ((or (member (cdr (assq :height cont)) '("0" "1"))
674 (member (cdr (assq :width cont)) '("0" "1")))
675 ;; Ignore zero-sized or single-pixel images.
677 ((and (not shr-inhibit-images)
678 (string-match "\\`cid:" url))
679 (let ((url (substring url (match-end 0)))
680 image)
681 (if (or (not shr-content-function)
682 (not (setq image (funcall shr-content-function url))))
683 (insert alt)
684 (shr-put-image image alt))))
685 ((or shr-inhibit-images
686 (and shr-blocked-images
687 (string-match shr-blocked-images url)))
688 (setq shr-start (point))
689 (let ((shr-state 'space))
690 (if (> (string-width alt) 8)
691 (shr-insert (truncate-string-to-width alt 8))
692 (shr-insert alt))))
693 ((url-is-cached (shr-encode-url url))
694 (shr-put-image (shr-get-image-data url) alt))
696 (insert alt)
697 (ignore-errors
698 (url-retrieve (shr-encode-url url) 'shr-image-fetched
699 (list (current-buffer) start (point-marker))
700 t))))
701 (put-text-property start (point) 'keymap shr-map)
702 (put-text-property start (point) 'shr-alt alt)
703 (put-text-property start (point) 'image-url url)
704 (put-text-property start (point) 'image-displayer
705 (shr-image-displayer shr-content-function))
706 (put-text-property start (point) 'help-echo alt)
707 (setq shr-state 'image)))))
709 (defun shr-tag-pre (cont)
710 (let ((shr-folding-mode 'none))
711 (shr-ensure-newline)
712 (shr-indent)
713 (shr-generic cont)
714 (shr-ensure-newline)))
716 (defun shr-tag-blockquote (cont)
717 (shr-ensure-paragraph)
718 (shr-indent)
719 (let ((shr-indentation (+ shr-indentation 4)))
720 (shr-generic cont))
721 (shr-ensure-paragraph))
723 (defun shr-tag-ul (cont)
724 (shr-ensure-paragraph)
725 (let ((shr-list-mode 'ul))
726 (shr-generic cont))
727 (shr-ensure-paragraph))
729 (defun shr-tag-ol (cont)
730 (shr-ensure-paragraph)
731 (let ((shr-list-mode 1))
732 (shr-generic cont))
733 (shr-ensure-paragraph))
735 (defun shr-tag-li (cont)
736 (shr-ensure-paragraph)
737 (shr-indent)
738 (let* ((bullet
739 (if (numberp shr-list-mode)
740 (prog1
741 (format "%d " shr-list-mode)
742 (setq shr-list-mode (1+ shr-list-mode)))
743 "* "))
744 (shr-indentation (+ shr-indentation (length bullet))))
745 (insert bullet)
746 (shr-generic cont)))
748 (defun shr-tag-br (cont)
749 (unless (bobp)
750 (insert "\n")
751 (shr-indent))
752 (shr-generic cont))
754 (defun shr-tag-h1 (cont)
755 (shr-heading cont 'bold 'underline))
757 (defun shr-tag-h2 (cont)
758 (shr-heading cont 'bold))
760 (defun shr-tag-h3 (cont)
761 (shr-heading cont 'italic))
763 (defun shr-tag-h4 (cont)
764 (shr-heading cont))
766 (defun shr-tag-h5 (cont)
767 (shr-heading cont))
769 (defun shr-tag-h6 (cont)
770 (shr-heading cont))
772 (defun shr-tag-hr (cont)
773 (shr-ensure-newline)
774 (insert (make-string shr-width shr-hr-line) "\n"))
776 (defun shr-tag-title (cont)
777 (shr-heading cont 'bold 'underline))
779 (defun shr-tag-font (cont)
780 (let ((start (point))
781 (color (cdr (assq :color cont))))
782 (shr-generic cont)
783 (shr-insert-foreground-overlay color start (point))))
785 ;;; Table rendering algorithm.
787 ;; Table rendering is the only complicated thing here. We do this by
788 ;; first counting how many TDs there are in each TR, and registering
789 ;; how wide they think they should be ("width=45%", etc). Then we
790 ;; render each TD separately (this is done in temporary buffers, so
791 ;; that we can use all the rendering machinery as if we were in the
792 ;; main buffer). Now we know how much space each TD really takes, so
793 ;; we then render everything again with the new widths, and finally
794 ;; insert all these boxes into the main buffer.
795 (defun shr-tag-table-1 (cont)
796 (setq cont (or (cdr (assq 'tbody cont))
797 cont))
798 (let* ((shr-inhibit-images t)
799 (shr-table-depth (1+ shr-table-depth))
800 (shr-kinsoku-shorten t)
801 ;; Find all suggested widths.
802 (columns (shr-column-specs cont))
803 ;; Compute how many characters wide each TD should be.
804 (suggested-widths (shr-pro-rate-columns columns))
805 ;; Do a "test rendering" to see how big each TD is (this can
806 ;; be smaller (if there's little text) or bigger (if there's
807 ;; unbreakable text).
808 (sketch (shr-make-table cont suggested-widths))
809 (sketch-widths (shr-table-widths sketch suggested-widths)))
810 ;; This probably won't work very well.
811 (when (> (+ (loop for width across sketch-widths
812 summing (1+ width))
813 shr-indentation 1)
814 (frame-width))
815 (setq truncate-lines t))
816 ;; Then render the table again with these new "hard" widths.
817 (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
818 ;; Finally, insert all the images after the table. The Emacs buffer
819 ;; model isn't strong enough to allow us to put the images actually
820 ;; into the tables.
821 (when (zerop shr-table-depth)
822 (dolist (elem (shr-find-elements cont 'img))
823 (shr-tag-img (cdr elem)))))
825 (defun shr-tag-table (cont)
826 (shr-ensure-paragraph)
827 (let* ((caption (cdr (assq 'caption cont)))
828 (header (cdr (assq 'thead cont)))
829 (body (or (cdr (assq 'tbody cont)) cont))
830 (footer (cdr (assq 'tfoot cont)))
831 (bgcolor (cdr (assq :bgcolor cont)))
832 (nheader (if header (shr-max-columns header)))
833 (nbody (if body (shr-max-columns body)))
834 (nfooter (if footer (shr-max-columns footer))))
835 (shr-insert-background-overlay bgcolor (point))
836 (shr-tag-table-1
837 (nconc
838 (if caption `((tr (td ,@caption))))
839 (if header
840 (if footer
841 ;; hader + body + footer
842 (if (= nheader nbody)
843 (if (= nbody nfooter)
844 `((tr (td (table (tbody ,@header ,@body ,@footer)))))
845 (nconc `((tr (td (table (tbody ,@header ,@body)))))
846 (if (= nfooter 1)
847 footer
848 `((tr (td (table (tbody ,@footer))))))))
849 (nconc `((tr (td (table (tbody ,@header)))))
850 (if (= nbody nfooter)
851 `((tr (td (table (tbody ,@body ,@footer)))))
852 (nconc `((tr (td (table (tbody ,@body)))))
853 (if (= nfooter 1)
854 footer
855 `((tr (td (table (tbody ,@footer))))))))))
856 ;; header + body
857 (if (= nheader nbody)
858 `((tr (td (table (tbody ,@header ,@body)))))
859 (if (= nheader 1)
860 `(,@header (tr (td (table (tbody ,@body)))))
861 `((tr (td (table (tbody ,@header))))
862 (tr (td (table (tbody ,@body))))))))
863 (if footer
864 ;; body + footer
865 (if (= nbody nfooter)
866 `((tr (td (table (tbody ,@body ,@footer)))))
867 (nconc `((tr (td (table (tbody ,@body)))))
868 (if (= nfooter 1)
869 footer
870 `((tr (td (table (tbody ,@footer))))))))
871 (if caption
872 `((tr (td (table (tbody ,@body)))))
873 body)))))))
875 (defun shr-find-elements (cont type)
876 (let (result)
877 (dolist (elem cont)
878 (cond ((eq (car elem) type)
879 (push elem result))
880 ((consp (cdr elem))
881 (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
882 (nreverse result)))
884 (defun shr-insert-table (table widths)
885 (shr-insert-table-ruler widths)
886 (dolist (row table)
887 (let ((start (point))
888 (height (let ((max 0))
889 (dolist (column row)
890 (setq max (max max (cadr column))))
891 max)))
892 (dotimes (i height)
893 (shr-indent)
894 (insert shr-table-vertical-line "\n"))
895 (dolist (column row)
896 (goto-char start)
897 (let ((lines (nth 2 column))
898 (overlay-lines (nth 3 column))
899 overlay overlay-line)
900 (dolist (line lines)
901 (setq overlay-line (pop overlay-lines))
902 (end-of-line)
903 (insert line shr-table-vertical-line)
904 (dolist (overlay overlay-line)
905 (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
906 (- (point) (nth 1 overlay) 1)))
907 (properties (nth 2 overlay)))
908 (while properties
909 (overlay-put o (pop properties) (pop properties)))))
910 (forward-line 1))
911 ;; Add blank lines at padding at the bottom of the TD,
912 ;; possibly.
913 (dotimes (i (- height (length lines)))
914 (end-of-line)
915 (insert (make-string (string-width (car lines)) ? )
916 shr-table-vertical-line)
917 (forward-line 1)))))
918 (shr-insert-table-ruler widths)))
920 (defun shr-insert-table-ruler (widths)
921 (when (and (bolp)
922 (> shr-indentation 0))
923 (shr-indent))
924 (insert shr-table-corner)
925 (dotimes (i (length widths))
926 (insert (make-string (aref widths i) shr-table-horizontal-line)
927 shr-table-corner))
928 (insert "\n"))
930 (defun shr-table-widths (table suggested-widths)
931 (let* ((length (length suggested-widths))
932 (widths (make-vector length 0))
933 (natural-widths (make-vector length 0)))
934 (dolist (row table)
935 (let ((i 0))
936 (dolist (column row)
937 (aset widths i (max (aref widths i)
938 (car column)))
939 (aset natural-widths i (max (aref natural-widths i)
940 (cadr column)))
941 (setq i (1+ i)))))
942 (let ((extra (- (apply '+ (append suggested-widths nil))
943 (apply '+ (append widths nil))))
944 (expanded-columns 0))
945 (when (> extra 0)
946 (dotimes (i length)
947 ;; If the natural width is wider than the rendered width, we
948 ;; want to allow the column to expand.
949 (when (> (aref natural-widths i) (aref widths i))
950 (setq expanded-columns (1+ expanded-columns))))
951 (dotimes (i length)
952 (when (> (aref natural-widths i) (aref widths i))
953 (aset widths i (min
954 (1+ (aref natural-widths i))
955 (+ (/ extra expanded-columns)
956 (aref widths i))))))))
957 widths))
959 (defun shr-make-table (cont widths &optional fill)
960 (let ((trs nil))
961 (dolist (row cont)
962 (when (eq (car row) 'tr)
963 (let ((tds nil)
964 (columns (cdr row))
965 (i 0)
966 column)
967 (while (< i (length widths))
968 (setq column (pop columns))
969 (when (or (memq (car column) '(td th))
970 (null column))
971 (push (shr-render-td (cdr column) (aref widths i) fill)
972 tds)
973 (setq i (1+ i))))
974 (push (nreverse tds) trs))))
975 (nreverse trs)))
977 (defun shr-render-td (cont width fill)
978 (let ((background (shr-get-background (point))))
979 (with-temp-buffer
980 (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
981 (if cache
982 (insert cache)
983 (shr-insert-background-overlay (or (cdr (assq :bgcolor cont))
984 background)
985 (point))
986 (let ((shr-width width)
987 (shr-indentation 0))
988 (shr-generic cont))
989 (delete-region
990 (point)
991 (+ (point)
992 (skip-chars-backward " \t\n")))
993 (push (cons (cons width cont) (buffer-string))
994 shr-content-cache)))
995 (goto-char (point-min))
996 (let ((max 0))
997 (while (not (eobp))
998 (end-of-line)
999 (setq max (max max (current-column)))
1000 (forward-line 1))
1001 (when fill
1002 (goto-char (point-min))
1003 ;; If the buffer is totally empty, then put a single blank
1004 ;; line here.
1005 (if (zerop (buffer-size))
1006 (insert (make-string width ? ))
1007 ;; Otherwise, fill the buffer.
1008 (while (not (eobp))
1009 (end-of-line)
1010 (when (> (- width (current-column)) 0)
1011 (insert (make-string (- width (current-column)) ? )))
1012 (forward-line 1))))
1013 (if fill
1014 (list max
1015 (count-lines (point-min) (point-max))
1016 (split-string (buffer-string) "\n")
1017 (shr-collect-overlays))
1018 (list max
1019 (shr-natural-width)))))))
1021 (defun shr-natural-width ()
1022 (goto-char (point-min))
1023 (let ((current 0)
1024 (max 0))
1025 (while (not (eobp))
1026 (end-of-line)
1027 (setq current (+ current (current-column)))
1028 (unless (get-text-property (point) 'shr-break)
1029 (setq max (max max current)
1030 current 0))
1031 (forward-line 1))
1032 max))
1034 (defun shr-collect-overlays ()
1035 (save-excursion
1036 (goto-char (point-min))
1037 (let ((overlays nil))
1038 (while (not (eobp))
1039 (push (shr-overlays-in-region (point) (line-end-position))
1040 overlays)
1041 (forward-line 1))
1042 (nreverse overlays))))
1044 (defun shr-overlays-in-region (start end)
1045 (let (result)
1046 (dolist (overlay (overlays-in start end))
1047 (push (list (if (> start (overlay-start overlay))
1048 (- end start)
1049 (- end (overlay-start overlay)))
1050 (if (< end (overlay-end overlay))
1052 (- end (overlay-end overlay)))
1053 (overlay-properties overlay))
1054 result))
1055 (nreverse result)))
1057 (defun shr-pro-rate-columns (columns)
1058 (let ((total-percentage 0)
1059 (widths (make-vector (length columns) 0)))
1060 (dotimes (i (length columns))
1061 (setq total-percentage (+ total-percentage (aref columns i))))
1062 (setq total-percentage (/ 1.0 total-percentage))
1063 (dotimes (i (length columns))
1064 (aset widths i (max (truncate (* (aref columns i)
1065 total-percentage
1066 (- shr-width (1+ (length columns)))))
1067 10)))
1068 widths))
1070 ;; Return a summary of the number and shape of the TDs in the table.
1071 (defun shr-column-specs (cont)
1072 (let ((columns (make-vector (shr-max-columns cont) 1)))
1073 (dolist (row cont)
1074 (when (eq (car row) 'tr)
1075 (let ((i 0))
1076 (dolist (column (cdr row))
1077 (when (memq (car column) '(td th))
1078 (let ((width (cdr (assq :width (cdr column)))))
1079 (when (and width
1080 (string-match "\\([0-9]+\\)%" width))
1081 (aset columns i
1082 (/ (string-to-number (match-string 1 width))
1083 100.0))))
1084 (setq i (1+ i)))))))
1085 columns))
1087 (defun shr-count (cont elem)
1088 (let ((i 0))
1089 (dolist (sub cont)
1090 (when (eq (car sub) elem)
1091 (setq i (1+ i))))
1094 (defun shr-max-columns (cont)
1095 (let ((max 0))
1096 (dolist (row cont)
1097 (when (eq (car row) 'tr)
1098 (setq max (max max (+ (shr-count (cdr row) 'td)
1099 (shr-count (cdr row) 'th))))))
1100 max))
1102 (provide 'shr)
1104 ;;; shr.el ends here