]> code.delx.au - gnu-emacs/blob - lisp/gnus/shr.el
Merge from mainline.
[gnu-emacs] / lisp / gnus / shr.el
1 ;;; shr.el --- Simple HTML Renderer
2
3 ;; Copyright (C) 2010-2011 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 (require 'browse-url)
35
36 (defgroup shr nil
37 "Simple HTML Renderer"
38 :group 'mail)
39
40 (defcustom shr-max-image-proportion 0.9
41 "How big pictures displayed are in relation to the window they're in.
42 A value of 0.7 means that they are allowed to take up 70% of the
43 width and height of the window. If they are larger than this,
44 and Emacs supports it, then the images will be rescaled down to
45 fit these criteria."
46 :version "24.1"
47 :group 'shr
48 :type 'float)
49
50 (defcustom shr-blocked-images nil
51 "Images that have URLs matching this regexp will be blocked."
52 :version "24.1"
53 :group 'shr
54 :type 'regexp)
55
56 (defcustom shr-table-horizontal-line ?
57 "Character used to draw horizontal table lines."
58 :group 'shr
59 :type 'character)
60
61 (defcustom shr-table-vertical-line ?
62 "Character used to draw vertical table lines."
63 :group 'shr
64 :type 'character)
65
66 (defcustom shr-table-corner ?
67 "Character used to draw table corners."
68 :group 'shr
69 :type 'character)
70
71 (defcustom shr-hr-line ?-
72 "Character used to draw hr lines."
73 :group 'shr
74 :type 'character)
75
76 (defcustom shr-width fill-column
77 "Frame width to use for rendering.
78 May either be an integer specifying a fixed width in characters,
79 or nil, meaning that the full width of the window should be
80 used."
81 :type '(choice (integer :tag "Fixed width in characters")
82 (const :tag "Use the width of the window" nil))
83 :group 'shr)
84
85 (defvar shr-content-function nil
86 "If bound, this should be a function that will return the content.
87 This is used for cid: URLs, and the function is called with the
88 cid: URL as the argument.")
89
90 ;;; Internal variables.
91
92 (defvar shr-folding-mode nil)
93 (defvar shr-state nil)
94 (defvar shr-start nil)
95 (defvar shr-indentation 0)
96 (defvar shr-inhibit-images nil)
97 (defvar shr-list-mode nil)
98 (defvar shr-content-cache nil)
99 (defvar shr-kinsoku-shorten nil)
100 (defvar shr-table-depth 0)
101 (defvar shr-stylesheet nil)
102
103 (defvar shr-map
104 (let ((map (make-sparse-keymap)))
105 (define-key map "a" 'shr-show-alt-text)
106 (define-key map "i" 'shr-browse-image)
107 (define-key map "I" 'shr-insert-image)
108 (define-key map "u" 'shr-copy-url)
109 (define-key map "v" 'shr-browse-url)
110 (define-key map "o" 'shr-save-contents)
111 (define-key map "\r" 'shr-browse-url)
112 map))
113
114 ;; Public functions and commands.
115
116 (defun shr-visit-file (file)
117 (interactive "fHTML file name: ")
118 (pop-to-buffer "*html*")
119 (erase-buffer)
120 (shr-insert-document
121 (with-temp-buffer
122 (insert-file-contents file)
123 (libxml-parse-html-region (point-min) (point-max)))))
124
125 ;;;###autoload
126 (defun shr-insert-document (dom)
127 (setq shr-content-cache nil)
128 (let ((shr-state nil)
129 (shr-start nil)
130 (shr-width (or shr-width (window-width))))
131 (shr-descend (shr-transform-dom dom))))
132
133 (defun shr-copy-url ()
134 "Copy the URL under point to the kill ring.
135 If called twice, then try to fetch the URL and see whether it
136 redirects somewhere else."
137 (interactive)
138 (let ((url (get-text-property (point) 'shr-url)))
139 (cond
140 ((not url)
141 (message "No URL under point"))
142 ;; Resolve redirected URLs.
143 ((equal url (car kill-ring))
144 (url-retrieve
145 url
146 (lambda (a)
147 (when (and (consp a)
148 (eq (car a) :redirect))
149 (with-temp-buffer
150 (insert (cadr a))
151 (goto-char (point-min))
152 ;; Remove common tracking junk from the URL.
153 (when (re-search-forward ".utm_.*" nil t)
154 (replace-match "" t t))
155 (message "Copied %s" (buffer-string))
156 (copy-region-as-kill (point-min) (point-max)))))))
157 ;; Copy the URL to the kill ring.
158 (t
159 (with-temp-buffer
160 (insert url)
161 (copy-region-as-kill (point-min) (point-max))
162 (message "Copied %s" url))))))
163
164 (defun shr-show-alt-text ()
165 "Show the ALT text of the image under point."
166 (interactive)
167 (let ((text (get-text-property (point) 'shr-alt)))
168 (if (not text)
169 (message "No image under point")
170 (message "%s" text))))
171
172 (defun shr-browse-image ()
173 "Browse the image under point."
174 (interactive)
175 (let ((url (get-text-property (point) 'image-url)))
176 (if (not url)
177 (message "No image under point")
178 (message "Browsing %s..." url)
179 (browse-url url))))
180
181 (defun shr-insert-image ()
182 "Insert the image under point into the buffer."
183 (interactive)
184 (let ((url (get-text-property (point) 'image-url)))
185 (if (not url)
186 (message "No image under point")
187 (message "Inserting %s..." url)
188 (url-retrieve url 'shr-image-fetched
189 (list (current-buffer) (1- (point)) (point-marker))
190 t))))
191
192 ;;; Utility functions.
193
194 (defun shr-transform-dom (dom)
195 (let ((result (list (pop dom))))
196 (dolist (arg (pop dom))
197 (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
198 (cdr arg))
199 result))
200 (dolist (sub dom)
201 (if (stringp sub)
202 (push (cons 'text sub) result)
203 (push (shr-transform-dom sub) result)))
204 (nreverse result)))
205
206 (defun shr-descend (dom)
207 (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray))
208 (style (cdr (assq :style (cdr dom))))
209 (shr-stylesheet shr-stylesheet)
210 (start (point)))
211 (when style
212 (if (string-match "color" style)
213 (setq shr-stylesheet (nconc (shr-parse-style style)
214 shr-stylesheet))
215 (setq style nil)))
216 (if (fboundp function)
217 (funcall function (cdr dom))
218 (shr-generic (cdr dom)))
219 ;; If style is set, then this node has set the color.
220 (when style
221 (shr-colorize-region start (point)
222 (cdr (assq 'color shr-stylesheet))
223 (cdr (assq 'background-color shr-stylesheet))))))
224
225 (defun shr-generic (cont)
226 (dolist (sub cont)
227 (cond
228 ((eq (car sub) 'text)
229 (shr-insert (cdr sub)))
230 ((listp (cdr sub))
231 (shr-descend sub)))))
232
233 (defmacro shr-char-breakable-p (char)
234 "Return non-nil if a line can be broken before and after CHAR."
235 `(aref fill-find-break-point-function-table ,char))
236 (defmacro shr-char-nospace-p (char)
237 "Return non-nil if no space is required before and after CHAR."
238 `(aref fill-nospace-between-words-table ,char))
239
240 ;; KINSOKU is a Japanese word meaning a rule that should not be violated.
241 ;; In Emacs, it is a term used for characters, e.g. punctuation marks,
242 ;; parentheses, and so on, that should not be placed in the beginning
243 ;; of a line or the end of a line.
244 (defmacro shr-char-kinsoku-bol-p (char)
245 "Return non-nil if a line ought not to begin with CHAR."
246 `(aref (char-category-set ,char) ?>))
247 (defmacro shr-char-kinsoku-eol-p (char)
248 "Return non-nil if a line ought not to end with CHAR."
249 `(aref (char-category-set ,char) ?<))
250 (unless (shr-char-kinsoku-bol-p (make-char 'japanese-jisx0208 33 35))
251 (load "kinsoku" nil t))
252
253 (defun shr-insert (text)
254 (when (and (eq shr-state 'image)
255 (not (string-match "\\`[ \t\n]+\\'" text)))
256 (insert "\n")
257 (setq shr-state nil))
258 (cond
259 ((eq shr-folding-mode 'none)
260 (insert text))
261 (t
262 (when (and (string-match "\\`[ \t\n]" text)
263 (not (bolp))
264 (not (eq (char-after (1- (point))) ? )))
265 (insert " "))
266 (dolist (elem (split-string text))
267 (when (and (bolp)
268 (> shr-indentation 0))
269 (shr-indent))
270 ;; No space is needed behind a wide character categorized as
271 ;; kinsoku-bol, between characters both categorized as nospace,
272 ;; or at the beginning of a line.
273 (let (prev)
274 (when (and (> (current-column) shr-indentation)
275 (eq (preceding-char) ? )
276 (or (= (line-beginning-position) (1- (point)))
277 (and (shr-char-breakable-p
278 (setq prev (char-after (- (point) 2))))
279 (shr-char-kinsoku-bol-p prev))
280 (and (shr-char-nospace-p prev)
281 (shr-char-nospace-p (aref elem 0)))))
282 (delete-char -1)))
283 ;; The shr-start is a special variable that is used to pass
284 ;; upwards the first point in the buffer where the text really
285 ;; starts.
286 (unless shr-start
287 (setq shr-start (point)))
288 (insert elem)
289 (let (found)
290 (while (and (> (current-column) shr-width)
291 (progn
292 (setq found (shr-find-fill-point))
293 (not (eolp))))
294 (when (eq (preceding-char) ? )
295 (delete-char -1))
296 (insert "\n")
297 (unless found
298 (put-text-property (1- (point)) (point) 'shr-break t)
299 ;; No space is needed at the beginning of a line.
300 (when (eq (following-char) ? )
301 (delete-char 1)))
302 (when (> shr-indentation 0)
303 (shr-indent))
304 (end-of-line))
305 (insert " ")))
306 (unless (string-match "[ \t\n]\\'" text)
307 (delete-char -1)))))
308
309 (defun shr-find-fill-point ()
310 (when (> (move-to-column shr-width) shr-width)
311 (backward-char 1))
312 (let ((bp (point))
313 failed)
314 (while (not (or (setq failed (= (current-column) shr-indentation))
315 (eq (preceding-char) ? )
316 (eq (following-char) ? )
317 (shr-char-breakable-p (preceding-char))
318 (shr-char-breakable-p (following-char))
319 (if (eq (preceding-char) ?')
320 (not (memq (char-after (- (point) 2))
321 (list nil ?\n ? )))
322 (and (shr-char-kinsoku-bol-p (preceding-char))
323 (shr-char-breakable-p (following-char))
324 (not (shr-char-kinsoku-bol-p (following-char)))))
325 (shr-char-kinsoku-eol-p (following-char))))
326 (backward-char 1))
327 (if (and (not (or failed (eolp)))
328 (eq (preceding-char) ?'))
329 (while (not (or (setq failed (eolp))
330 (eq (following-char) ? )
331 (shr-char-breakable-p (following-char))
332 (shr-char-kinsoku-eol-p (following-char))))
333 (forward-char 1)))
334 (if failed
335 ;; There's no breakable point, so we give it up.
336 (let (found)
337 (goto-char bp)
338 (unless shr-kinsoku-shorten
339 (while (and (setq found (re-search-forward
340 "\\(\\c>\\)\\| \\|\\c<\\|\\c|"
341 (line-end-position) 'move))
342 (eq (preceding-char) ?')))
343 (if (and found (not (match-beginning 1)))
344 (goto-char (match-beginning 0)))))
345 (or
346 (eolp)
347 ;; Don't put kinsoku-bol characters at the beginning of a line,
348 ;; or kinsoku-eol characters at the end of a line.
349 (cond
350 (shr-kinsoku-shorten
351 (while (and (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
352 (shr-char-kinsoku-eol-p (preceding-char)))
353 (backward-char 1))
354 (when (setq failed (= (current-column) shr-indentation))
355 ;; There's no breakable point that doesn't violate kinsoku,
356 ;; so we look for the second best position.
357 (while (and (progn
358 (forward-char 1)
359 (<= (current-column) shr-width))
360 (progn
361 (setq bp (point))
362 (shr-char-kinsoku-eol-p (following-char)))))
363 (goto-char bp)))
364 ((shr-char-kinsoku-eol-p (preceding-char))
365 (if (shr-char-kinsoku-eol-p (following-char))
366 ;; There are consecutive kinsoku-eol characters.
367 (setq failed t)
368 (let ((count 4))
369 (while
370 (progn
371 (backward-char 1)
372 (and (> (setq count (1- count)) 0)
373 (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
374 (or (shr-char-kinsoku-eol-p (preceding-char))
375 (shr-char-kinsoku-bol-p (following-char)))))))
376 (if (setq failed (= (current-column) shr-indentation))
377 ;; There's no breakable point that doesn't violate kinsoku,
378 ;; so we go to the second best position.
379 (if (looking-at "\\(\\c<+\\)\\c<")
380 (goto-char (match-end 1))
381 (forward-char 1)))))
382 (t
383 (if (shr-char-kinsoku-bol-p (preceding-char))
384 ;; There are consecutive kinsoku-bol characters.
385 (setq failed t)
386 (let ((count 4))
387 (while (and (>= (setq count (1- count)) 0)
388 (shr-char-kinsoku-bol-p (following-char))
389 (shr-char-breakable-p (following-char)))
390 (forward-char 1))))))
391 (when (eq (following-char) ? )
392 (forward-char 1))))
393 (not failed)))
394
395 (defun shr-ensure-newline ()
396 (unless (zerop (current-column))
397 (insert "\n")))
398
399 (defun shr-ensure-paragraph ()
400 (unless (bobp)
401 (if (<= (current-column) shr-indentation)
402 (unless (save-excursion
403 (forward-line -1)
404 (looking-at " *$"))
405 (insert "\n"))
406 (if (save-excursion
407 (beginning-of-line)
408 (looking-at " *$"))
409 (insert "\n")
410 (insert "\n\n")))))
411
412 (defun shr-indent ()
413 (when (> shr-indentation 0)
414 (insert (make-string shr-indentation ? ))))
415
416 (defun shr-fontize-cont (cont &rest types)
417 (let (shr-start)
418 (shr-generic cont)
419 (dolist (type types)
420 (shr-add-font (or shr-start (point)) (point) type))))
421
422 ;; Add an overlay in the region, but avoid putting the font properties
423 ;; on blank text at the start of the line, and the newline at the end,
424 ;; to avoid ugliness.
425 (defun shr-add-font (start end type)
426 (save-excursion
427 (goto-char start)
428 (while (< (point) end)
429 (when (bolp)
430 (skip-chars-forward " "))
431 (let ((overlay (make-overlay (point) (min (line-end-position) end))))
432 (overlay-put overlay 'face type))
433 (if (< (line-end-position) end)
434 (forward-line 1)
435 (goto-char end)))))
436
437 (defun shr-browse-url ()
438 "Browse the URL under point."
439 (interactive)
440 (let ((url (get-text-property (point) 'shr-url)))
441 (cond
442 ((not url)
443 (message "No link under point"))
444 ((string-match "^mailto:" url)
445 (browse-url-mailto url))
446 (t
447 (browse-url url)))))
448
449 (defun shr-save-contents (directory)
450 "Save the contents from URL in a file."
451 (interactive "DSave contents of URL to directory: ")
452 (let ((url (get-text-property (point) 'shr-url)))
453 (if (not url)
454 (message "No link under point")
455 (url-retrieve (shr-encode-url url)
456 'shr-store-contents (list url directory)))))
457
458 (defun shr-store-contents (status url directory)
459 (unless (plist-get status :error)
460 (when (or (search-forward "\n\n" nil t)
461 (search-forward "\r\n\r\n" nil t))
462 (write-region (point) (point-max)
463 (expand-file-name (file-name-nondirectory url)
464 directory)))))
465
466 (defun shr-image-fetched (status buffer start end)
467 (when (and (buffer-name buffer)
468 (not (plist-get status :error)))
469 (url-store-in-cache (current-buffer))
470 (when (or (search-forward "\n\n" nil t)
471 (search-forward "\r\n\r\n" nil t))
472 (let ((data (buffer-substring (point) (point-max))))
473 (with-current-buffer buffer
474 (save-excursion
475 (let ((alt (buffer-substring start end))
476 (inhibit-read-only t))
477 (delete-region start end)
478 (goto-char start)
479 (shr-put-image data alt)))))))
480 (kill-buffer (current-buffer)))
481
482 (defun shr-put-image (data alt)
483 (if (display-graphic-p)
484 (let ((image (ignore-errors
485 (shr-rescale-image data))))
486 (when image
487 ;; When inserting big-ish pictures, put them at the
488 ;; beginning of the line.
489 (when (and (> (current-column) 0)
490 (> (car (image-size image t)) 400))
491 (insert "\n"))
492 (insert-image image (or alt "*"))))
493 (insert alt)))
494
495 (defun shr-rescale-image (data)
496 (if (or (not (fboundp 'imagemagick-types))
497 (not (get-buffer-window (current-buffer))))
498 (create-image data nil t)
499 (let* ((image (create-image data nil t))
500 (size (image-size image t))
501 (width (car size))
502 (height (cdr size))
503 (edges (window-inside-pixel-edges
504 (get-buffer-window (current-buffer))))
505 (window-width (truncate (* shr-max-image-proportion
506 (- (nth 2 edges) (nth 0 edges)))))
507 (window-height (truncate (* shr-max-image-proportion
508 (- (nth 3 edges) (nth 1 edges)))))
509 scaled-image)
510 (when (> height window-height)
511 (setq image (or (create-image data 'imagemagick t
512 :height window-height)
513 image))
514 (setq size (image-size image t)))
515 (when (> (car size) window-width)
516 (setq image (or
517 (create-image data 'imagemagick t
518 :width window-width)
519 image)))
520 (when (and (fboundp 'create-animated-image)
521 (eq (image-type data nil t) 'gif))
522 (setq image (create-animated-image data 'gif t)))
523 image)))
524
525 ;; url-cache-extract autoloads url-cache.
526 (declare-function url-cache-create-filename "url-cache" (url))
527 (autoload 'mm-disable-multibyte "mm-util")
528 (autoload 'browse-url-mailto "browse-url")
529
530 (defun shr-get-image-data (url)
531 "Get image data for URL.
532 Return a string with image data."
533 (with-temp-buffer
534 (mm-disable-multibyte)
535 (when (ignore-errors
536 (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
537 t)
538 (when (or (search-forward "\n\n" nil t)
539 (search-forward "\r\n\r\n" nil t))
540 (buffer-substring (point) (point-max))))))
541
542 (defun shr-image-displayer (content-function)
543 "Return a function to display an image.
544 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
545 is an argument. The function to be returned takes three arguments URL,
546 START, and END. Note that START and END should be merkers."
547 `(lambda (url start end)
548 (when url
549 (if (string-match "\\`cid:" url)
550 ,(when content-function
551 `(let ((image (funcall ,content-function
552 (substring url (match-end 0)))))
553 (when image
554 (goto-char start)
555 (shr-put-image image
556 (buffer-substring-no-properties start end))
557 (delete-region (point) end))))
558 (url-retrieve url 'shr-image-fetched
559 (list (current-buffer) start end)
560 t)))))
561
562 (defun shr-heading (cont &rest types)
563 (shr-ensure-paragraph)
564 (apply #'shr-fontize-cont cont types)
565 (shr-ensure-paragraph))
566
567 (autoload 'widget-convert-button "wid-edit")
568
569 (defun shr-urlify (start url &optional title)
570 (widget-convert-button
571 'url-link start (point)
572 :help-echo (if title (format "%s (%s)" url title) url)
573 :keymap shr-map
574 url)
575 (put-text-property start (point) 'shr-url url))
576
577 (defun shr-encode-url (url)
578 "Encode URL."
579 (browse-url-url-encode-chars url "[)$ ]"))
580
581 (autoload 'shr-color-visible "shr-color")
582 (autoload 'shr-color->hexadecimal "shr-color")
583
584 (defun shr-color-check (fg bg)
585 "Check that FG is visible on BG.
586 Returns (fg bg) with corrected values.
587 Returns nil if the colors that would be used are the default
588 ones, in case fg and bg are nil."
589 (when (or fg bg)
590 (let ((fixed (cond ((null fg) 'fg)
591 ((null bg) 'bg))))
592 ;; Convert colors to hexadecimal, or set them to default.
593 (let ((fg (or (shr-color->hexadecimal fg)
594 (frame-parameter nil 'foreground-color)))
595 (bg (or (shr-color->hexadecimal bg)
596 (frame-parameter nil 'background-color))))
597 (cond ((eq fixed 'bg)
598 ;; Only return the new fg
599 (list nil (cadr (shr-color-visible bg fg t))))
600 ((eq fixed 'fg)
601 ;; Invert args and results and return only the new bg
602 (list (cadr (shr-color-visible fg bg t)) nil))
603 (t
604 (shr-color-visible bg fg)))))))
605
606 (defun shr-colorize-region (start end fg &optional bg)
607 (when (or fg bg)
608 (let ((new-colors (shr-color-check fg bg)))
609 (when new-colors
610 (when fg
611 (shr-put-color start end :foreground (cadr new-colors)))
612 (when bg
613 (shr-put-color start end :background (car new-colors))))
614 new-colors)))
615
616 ;; Put a color in the region, but avoid putting colors on on blank
617 ;; text at the start of the line, and the newline at the end, to avoid
618 ;; ugliness. Also, don't overwrite any existing color information,
619 ;; since this can be called recursively, and we want the "inner" color
620 ;; to win.
621 (defun shr-put-color (start end type color)
622 (save-excursion
623 (goto-char start)
624 (while (< (point) end)
625 (when (and (bolp)
626 (not (eq type :background)))
627 (skip-chars-forward " "))
628 (when (> (line-end-position) (point))
629 (shr-put-color-1 (point) (min (line-end-position) end) type color))
630 (if (< (line-end-position) end)
631 (forward-line 1)
632 (goto-char end)))
633 (when (and (eq type :background)
634 (= shr-table-depth 0))
635 (shr-expand-newlines start end color))))
636
637 (defun shr-expand-newlines (start end color)
638 (save-restriction
639 ;; Skip past all white space at the start and ends.
640 (goto-char start)
641 (skip-chars-forward " \t\n")
642 (beginning-of-line)
643 (setq start (point))
644 (goto-char end)
645 (skip-chars-backward " \t\n")
646 (forward-line 1)
647 (setq end (point))
648 (narrow-to-region start end)
649 (let ((width (shr-natural-width))
650 column)
651 (goto-char (point-min))
652 (while (not (eobp))
653 (end-of-line)
654 (when (and (< (setq column (current-column)) width)
655 (< (setq column (shr-previous-newline-padding-width column))
656 width))
657 (let ((overlay (make-overlay (point) (1+ (point)))))
658 (overlay-put overlay 'before-string
659 (concat
660 (mapconcat
661 (lambda (overlay)
662 (let ((string (plist-get
663 (overlay-properties overlay)
664 'before-string)))
665 (if (not string)
666 ""
667 (overlay-put overlay 'before-string "")
668 string)))
669 (overlays-at (point))
670 "")
671 (propertize (make-string (- width column) ? )
672 'face (list :background color))))))
673 (forward-line 1)))))
674
675 (defun shr-previous-newline-padding-width (width)
676 (let ((overlays (overlays-at (point)))
677 (previous-width 0))
678 (if (null overlays)
679 width
680 (dolist (overlay overlays)
681 (setq previous-width
682 (+ previous-width
683 (length (plist-get (overlay-properties overlay)
684 'before-string)))))
685 (+ width previous-width))))
686
687 (defun shr-put-color-1 (start end type color)
688 (let* ((old-props (get-text-property start 'face))
689 (do-put (not (memq type old-props)))
690 change)
691 (while (< start end)
692 (setq change (next-single-property-change start 'face nil end))
693 (when do-put
694 (put-text-property start change 'face
695 (nconc (list type color) old-props)))
696 (setq old-props (get-text-property change 'face))
697 (setq do-put (not (memq type old-props)))
698 (setq start change))
699 (when (and do-put
700 (> end start))
701 (put-text-property start end 'face
702 (nconc (list type color old-props))))))
703
704 ;;; Tag-specific rendering rules.
705
706 (defun shr-tag-body (cont)
707 (let* ((start (point))
708 (fgcolor (cdr (or (assq :fgcolor cont)
709 (assq :text cont))))
710 (bgcolor (cdr (assq :bgcolor cont)))
711 (shr-stylesheet (list (cons 'color fgcolor)
712 (cons 'background-color bgcolor))))
713 (shr-generic cont)
714 (shr-colorize-region start (point) fgcolor bgcolor)))
715
716 (defun shr-tag-style (cont)
717 )
718
719 (defun shr-tag-script (cont)
720 )
721
722 (defun shr-tag-label (cont)
723 (shr-generic cont)
724 (shr-ensure-paragraph))
725
726 (defun shr-tag-p (cont)
727 (shr-ensure-paragraph)
728 (shr-indent)
729 (shr-generic cont)
730 (shr-ensure-paragraph))
731
732 (defun shr-tag-div (cont)
733 (shr-ensure-newline)
734 (shr-indent)
735 (shr-generic cont)
736 (shr-ensure-newline))
737
738 (defun shr-tag-b (cont)
739 (shr-fontize-cont cont 'bold))
740
741 (defun shr-tag-i (cont)
742 (shr-fontize-cont cont 'italic))
743
744 (defun shr-tag-em (cont)
745 (shr-fontize-cont cont 'bold))
746
747 (defun shr-tag-strong (cont)
748 (shr-fontize-cont cont 'bold))
749
750 (defun shr-tag-u (cont)
751 (shr-fontize-cont cont 'underline))
752
753 (defun shr-tag-s (cont)
754 (shr-fontize-cont cont 'strike-through))
755
756 (defun shr-parse-style (style)
757 (when style
758 (save-match-data
759 (when (string-match "\n" style)
760 (setq style (replace-match " " t t style))))
761 (let ((plist nil))
762 (dolist (elem (split-string style ";"))
763 (when elem
764 (setq elem (split-string elem ":"))
765 (when (and (car elem)
766 (cadr elem))
767 (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
768 (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
769 (when (string-match " *!important\\'" value)
770 (setq value (substring value 0 (match-beginning 0))))
771 (push (cons (intern name obarray)
772 value)
773 plist)))))
774 plist)))
775
776 (defun shr-tag-a (cont)
777 (let ((url (cdr (assq :href cont)))
778 (title (cdr (assq :title cont)))
779 (start (point))
780 shr-start)
781 (shr-generic cont)
782 (shr-urlify (or shr-start start) url title)))
783
784 (defun shr-tag-object (cont)
785 (let ((start (point))
786 url)
787 (dolist (elem cont)
788 (when (eq (car elem) 'embed)
789 (setq url (or url (cdr (assq :src (cdr elem))))))
790 (when (and (eq (car elem) 'param)
791 (equal (cdr (assq :name (cdr elem))) "movie"))
792 (setq url (or url (cdr (assq :value (cdr elem)))))))
793 (when url
794 (shr-insert " [multimedia] ")
795 (shr-urlify start url))
796 (shr-generic cont)))
797
798 (defun shr-tag-video (cont)
799 (let ((image (cdr (assq :poster cont)))
800 (url (cdr (assq :src cont)))
801 (start (point)))
802 (shr-tag-img nil image)
803 (shr-urlify start url)))
804
805 (defun shr-tag-img (cont &optional url)
806 (when (or url
807 (and cont
808 (cdr (assq :src cont))))
809 (when (and (> (current-column) 0)
810 (not (eq shr-state 'image)))
811 (insert "\n"))
812 (let ((alt (cdr (assq :alt cont)))
813 (url (or url (cdr (assq :src cont)))))
814 (let ((start (point-marker)))
815 (when (zerop (length alt))
816 (setq alt "*"))
817 (cond
818 ((or (member (cdr (assq :height cont)) '("0" "1"))
819 (member (cdr (assq :width cont)) '("0" "1")))
820 ;; Ignore zero-sized or single-pixel images.
821 )
822 ((and (not shr-inhibit-images)
823 (string-match "\\`cid:" url))
824 (let ((url (substring url (match-end 0)))
825 image)
826 (if (or (not shr-content-function)
827 (not (setq image (funcall shr-content-function url))))
828 (insert alt)
829 (shr-put-image image alt))))
830 ((or shr-inhibit-images
831 (and shr-blocked-images
832 (string-match shr-blocked-images url)))
833 (setq shr-start (point))
834 (let ((shr-state 'space))
835 (if (> (string-width alt) 8)
836 (shr-insert (truncate-string-to-width alt 8))
837 (shr-insert alt))))
838 ((url-is-cached (shr-encode-url url))
839 (shr-put-image (shr-get-image-data url) alt))
840 (t
841 (insert alt)
842 (ignore-errors
843 (url-retrieve (shr-encode-url url) 'shr-image-fetched
844 (list (current-buffer) start (point-marker))
845 t))))
846 (put-text-property start (point) 'keymap shr-map)
847 (put-text-property start (point) 'shr-alt alt)
848 (put-text-property start (point) 'image-url url)
849 (put-text-property start (point) 'image-displayer
850 (shr-image-displayer shr-content-function))
851 (put-text-property start (point) 'help-echo alt)
852 (setq shr-state 'image)))))
853
854 (defun shr-tag-pre (cont)
855 (let ((shr-folding-mode 'none))
856 (shr-ensure-newline)
857 (shr-indent)
858 (shr-generic cont)
859 (shr-ensure-newline)))
860
861 (defun shr-tag-blockquote (cont)
862 (shr-ensure-paragraph)
863 (shr-indent)
864 (let ((shr-indentation (+ shr-indentation 4)))
865 (shr-generic cont))
866 (shr-ensure-paragraph))
867
868 (defun shr-tag-ul (cont)
869 (shr-ensure-paragraph)
870 (let ((shr-list-mode 'ul))
871 (shr-generic cont))
872 (shr-ensure-paragraph))
873
874 (defun shr-tag-ol (cont)
875 (shr-ensure-paragraph)
876 (let ((shr-list-mode 1))
877 (shr-generic cont))
878 (shr-ensure-paragraph))
879
880 (defun shr-tag-li (cont)
881 (shr-ensure-paragraph)
882 (shr-indent)
883 (let* ((bullet
884 (if (numberp shr-list-mode)
885 (prog1
886 (format "%d " shr-list-mode)
887 (setq shr-list-mode (1+ shr-list-mode)))
888 "* "))
889 (shr-indentation (+ shr-indentation (length bullet))))
890 (insert bullet)
891 (shr-generic cont)))
892
893 (defun shr-tag-br (cont)
894 (unless (bobp)
895 (insert "\n")
896 (shr-indent))
897 (shr-generic cont))
898
899 (defun shr-tag-h1 (cont)
900 (shr-heading cont 'bold 'underline))
901
902 (defun shr-tag-h2 (cont)
903 (shr-heading cont 'bold))
904
905 (defun shr-tag-h3 (cont)
906 (shr-heading cont 'italic))
907
908 (defun shr-tag-h4 (cont)
909 (shr-heading cont))
910
911 (defun shr-tag-h5 (cont)
912 (shr-heading cont))
913
914 (defun shr-tag-h6 (cont)
915 (shr-heading cont))
916
917 (defun shr-tag-hr (cont)
918 (shr-ensure-newline)
919 (insert (make-string shr-width shr-hr-line) "\n"))
920
921 (defun shr-tag-title (cont)
922 (shr-heading cont 'bold 'underline))
923
924 (defun shr-tag-font (cont)
925 (let* ((start (point))
926 (color (cdr (assq :color cont)))
927 (shr-stylesheet (nconc (list (cons 'color color))
928 shr-stylesheet)))
929 (shr-generic cont)
930 (when color
931 (shr-colorize-region start (point) color
932 (cdr (assq 'background-color shr-stylesheet))))))
933
934 ;;; Table rendering algorithm.
935
936 ;; Table rendering is the only complicated thing here. We do this by
937 ;; first counting how many TDs there are in each TR, and registering
938 ;; how wide they think they should be ("width=45%", etc). Then we
939 ;; render each TD separately (this is done in temporary buffers, so
940 ;; that we can use all the rendering machinery as if we were in the
941 ;; main buffer). Now we know how much space each TD really takes, so
942 ;; we then render everything again with the new widths, and finally
943 ;; insert all these boxes into the main buffer.
944 (defun shr-tag-table-1 (cont)
945 (setq cont (or (cdr (assq 'tbody cont))
946 cont))
947 (let* ((shr-inhibit-images t)
948 (shr-table-depth (1+ shr-table-depth))
949 (shr-kinsoku-shorten t)
950 ;; Find all suggested widths.
951 (columns (shr-column-specs cont))
952 ;; Compute how many characters wide each TD should be.
953 (suggested-widths (shr-pro-rate-columns columns))
954 ;; Do a "test rendering" to see how big each TD is (this can
955 ;; be smaller (if there's little text) or bigger (if there's
956 ;; unbreakable text).
957 (sketch (shr-make-table cont suggested-widths))
958 (sketch-widths (shr-table-widths sketch suggested-widths)))
959 ;; This probably won't work very well.
960 (when (> (+ (loop for width across sketch-widths
961 summing (1+ width))
962 shr-indentation 1)
963 (frame-width))
964 (setq truncate-lines t))
965 ;; Then render the table again with these new "hard" widths.
966 (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
967 ;; Finally, insert all the images after the table. The Emacs buffer
968 ;; model isn't strong enough to allow us to put the images actually
969 ;; into the tables.
970 (when (zerop shr-table-depth)
971 (dolist (elem (shr-find-elements cont 'img))
972 (shr-tag-img (cdr elem)))))
973
974 (defun shr-tag-table (cont)
975 (shr-ensure-paragraph)
976 (let* ((caption (cdr (assq 'caption cont)))
977 (header (cdr (assq 'thead cont)))
978 (body (or (cdr (assq 'tbody cont)) cont))
979 (footer (cdr (assq 'tfoot cont)))
980 (bgcolor (cdr (assq :bgcolor cont)))
981 (start (point))
982 (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
983 shr-stylesheet))
984 (nheader (if header (shr-max-columns header)))
985 (nbody (if body (shr-max-columns body)))
986 (nfooter (if footer (shr-max-columns footer))))
987 (shr-tag-table-1
988 (nconc
989 (if caption `((tr (td ,@caption))))
990 (if header
991 (if footer
992 ;; hader + body + footer
993 (if (= nheader nbody)
994 (if (= nbody nfooter)
995 `((tr (td (table (tbody ,@header ,@body ,@footer)))))
996 (nconc `((tr (td (table (tbody ,@header ,@body)))))
997 (if (= nfooter 1)
998 footer
999 `((tr (td (table (tbody ,@footer))))))))
1000 (nconc `((tr (td (table (tbody ,@header)))))
1001 (if (= nbody nfooter)
1002 `((tr (td (table (tbody ,@body ,@footer)))))
1003 (nconc `((tr (td (table (tbody ,@body)))))
1004 (if (= nfooter 1)
1005 footer
1006 `((tr (td (table (tbody ,@footer))))))))))
1007 ;; header + body
1008 (if (= nheader nbody)
1009 `((tr (td (table (tbody ,@header ,@body)))))
1010 (if (= nheader 1)
1011 `(,@header (tr (td (table (tbody ,@body)))))
1012 `((tr (td (table (tbody ,@header))))
1013 (tr (td (table (tbody ,@body))))))))
1014 (if footer
1015 ;; body + footer
1016 (if (= nbody nfooter)
1017 `((tr (td (table (tbody ,@body ,@footer)))))
1018 (nconc `((tr (td (table (tbody ,@body)))))
1019 (if (= nfooter 1)
1020 footer
1021 `((tr (td (table (tbody ,@footer))))))))
1022 (if caption
1023 `((tr (td (table (tbody ,@body)))))
1024 body)))))
1025 (when bgcolor
1026 (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
1027 bgcolor))))
1028
1029 (defun shr-find-elements (cont type)
1030 (let (result)
1031 (dolist (elem cont)
1032 (cond ((eq (car elem) type)
1033 (push elem result))
1034 ((consp (cdr elem))
1035 (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
1036 (nreverse result)))
1037
1038 (defun shr-insert-table (table widths)
1039 (shr-insert-table-ruler widths)
1040 (dolist (row table)
1041 (let ((start (point))
1042 (height (let ((max 0))
1043 (dolist (column row)
1044 (setq max (max max (cadr column))))
1045 max)))
1046 (dotimes (i height)
1047 (shr-indent)
1048 (insert shr-table-vertical-line "\n"))
1049 (dolist (column row)
1050 (goto-char start)
1051 (let ((lines (nth 2 column))
1052 (overlay-lines (nth 3 column))
1053 overlay overlay-line)
1054 (dolist (line lines)
1055 (setq overlay-line (pop overlay-lines))
1056 (end-of-line)
1057 (insert line shr-table-vertical-line)
1058 (dolist (overlay overlay-line)
1059 (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
1060 (- (point) (nth 1 overlay) 1)))
1061 (properties (nth 2 overlay)))
1062 (while properties
1063 (overlay-put o (pop properties) (pop properties)))))
1064 (forward-line 1))
1065 ;; Add blank lines at padding at the bottom of the TD,
1066 ;; possibly.
1067 (dotimes (i (- height (length lines)))
1068 (end-of-line)
1069 (let ((start (point)))
1070 (insert (make-string (string-width (car lines)) ? )
1071 shr-table-vertical-line)
1072 (when (nth 4 column)
1073 (shr-put-color start (1- (point)) :background (nth 4 column))))
1074 (forward-line 1)))))
1075 (shr-insert-table-ruler widths)))
1076
1077 (defun shr-insert-table-ruler (widths)
1078 (when (and (bolp)
1079 (> shr-indentation 0))
1080 (shr-indent))
1081 (insert shr-table-corner)
1082 (dotimes (i (length widths))
1083 (insert (make-string (aref widths i) shr-table-horizontal-line)
1084 shr-table-corner))
1085 (insert "\n"))
1086
1087 (defun shr-table-widths (table suggested-widths)
1088 (let* ((length (length suggested-widths))
1089 (widths (make-vector length 0))
1090 (natural-widths (make-vector length 0)))
1091 (dolist (row table)
1092 (let ((i 0))
1093 (dolist (column row)
1094 (aset widths i (max (aref widths i)
1095 (car column)))
1096 (aset natural-widths i (max (aref natural-widths i)
1097 (cadr column)))
1098 (setq i (1+ i)))))
1099 (let ((extra (- (apply '+ (append suggested-widths nil))
1100 (apply '+ (append widths nil))))
1101 (expanded-columns 0))
1102 (when (> extra 0)
1103 (dotimes (i length)
1104 ;; If the natural width is wider than the rendered width, we
1105 ;; want to allow the column to expand.
1106 (when (> (aref natural-widths i) (aref widths i))
1107 (setq expanded-columns (1+ expanded-columns))))
1108 (dotimes (i length)
1109 (when (> (aref natural-widths i) (aref widths i))
1110 (aset widths i (min
1111 (1+ (aref natural-widths i))
1112 (+ (/ extra expanded-columns)
1113 (aref widths i))))))))
1114 widths))
1115
1116 (defun shr-make-table (cont widths &optional fill)
1117 (let ((trs nil))
1118 (dolist (row cont)
1119 (when (eq (car row) 'tr)
1120 (let ((tds nil)
1121 (columns (cdr row))
1122 (i 0)
1123 column)
1124 (while (< i (length widths))
1125 (setq column (pop columns))
1126 (when (or (memq (car column) '(td th))
1127 (null column))
1128 (push (shr-render-td (cdr column) (aref widths i) fill)
1129 tds)
1130 (setq i (1+ i))))
1131 (push (nreverse tds) trs))))
1132 (nreverse trs)))
1133
1134 (defun shr-render-td (cont width fill)
1135 (with-temp-buffer
1136 (let ((bgcolor (cdr (assq :bgcolor cont)))
1137 (fgcolor (cdr (assq :fgcolor cont)))
1138 (style (cdr (assq :style cont)))
1139 (shr-stylesheet shr-stylesheet)
1140 overlays actual-colors)
1141 (when style
1142 (setq style (and (string-match "color" style)
1143 (shr-parse-style style))))
1144 (when bgcolor
1145 (setq style (nconc (list (cons 'background-color bgcolor)) style)))
1146 (when fgcolor
1147 (setq style (nconc (list (cons 'color fgcolor)) style)))
1148 (when style
1149 (setq shr-stylesheet (append style shr-stylesheet)))
1150 (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
1151 (if cache
1152 (progn
1153 (insert (car cache))
1154 (let ((end (length (car cache))))
1155 (dolist (overlay (cadr cache))
1156 (let ((new-overlay
1157 (make-overlay (1+ (- end (nth 0 overlay)))
1158 (1+ (- end (nth 1 overlay)))))
1159 (properties (nth 2 overlay)))
1160 (while properties
1161 (overlay-put new-overlay
1162 (pop properties) (pop properties)))))))
1163 (let ((shr-width width)
1164 (shr-indentation 0))
1165 (shr-descend (cons 'td cont)))
1166 (delete-region
1167 (point)
1168 (+ (point)
1169 (skip-chars-backward " \t\n")))
1170 (push (list (cons width cont) (buffer-string)
1171 (shr-overlays-in-region (point-min) (point-max)))
1172 shr-content-cache)))
1173 (goto-char (point-min))
1174 (let ((max 0))
1175 (while (not (eobp))
1176 (end-of-line)
1177 (setq max (max max (current-column)))
1178 (forward-line 1))
1179 (when fill
1180 (goto-char (point-min))
1181 ;; If the buffer is totally empty, then put a single blank
1182 ;; line here.
1183 (if (zerop (buffer-size))
1184 (insert (make-string width ? ))
1185 ;; Otherwise, fill the buffer.
1186 (while (not (eobp))
1187 (end-of-line)
1188 (when (> (- width (current-column)) 0)
1189 (insert (make-string (- width (current-column)) ? )))
1190 (forward-line 1)))
1191 (when style
1192 (setq actual-colors
1193 (shr-colorize-region
1194 (point-min) (point-max)
1195 (cdr (assq 'color shr-stylesheet))
1196 (cdr (assq 'background-color shr-stylesheet))))))
1197 (if fill
1198 (list max
1199 (count-lines (point-min) (point-max))
1200 (split-string (buffer-string) "\n")
1201 (shr-collect-overlays)
1202 (car actual-colors))
1203 (list max
1204 (shr-natural-width)))))))
1205
1206 (defun shr-natural-width ()
1207 (goto-char (point-min))
1208 (let ((current 0)
1209 (max 0))
1210 (while (not (eobp))
1211 (end-of-line)
1212 (setq current (+ current (current-column)))
1213 (unless (get-text-property (point) 'shr-break)
1214 (setq max (max max current)
1215 current 0))
1216 (forward-line 1))
1217 max))
1218
1219 (defun shr-collect-overlays ()
1220 (save-excursion
1221 (goto-char (point-min))
1222 (let ((overlays nil))
1223 (while (not (eobp))
1224 (push (shr-overlays-in-region (point) (line-end-position))
1225 overlays)
1226 (forward-line 1))
1227 (nreverse overlays))))
1228
1229 (defun shr-overlays-in-region (start end)
1230 (let (result)
1231 (dolist (overlay (overlays-in start end))
1232 (push (list (if (> start (overlay-start overlay))
1233 (- end start)
1234 (- end (overlay-start overlay)))
1235 (if (< end (overlay-end overlay))
1236 0
1237 (- end (overlay-end overlay)))
1238 (overlay-properties overlay))
1239 result))
1240 (nreverse result)))
1241
1242 (defun shr-pro-rate-columns (columns)
1243 (let ((total-percentage 0)
1244 (widths (make-vector (length columns) 0)))
1245 (dotimes (i (length columns))
1246 (setq total-percentage (+ total-percentage (aref columns i))))
1247 (setq total-percentage (/ 1.0 total-percentage))
1248 (dotimes (i (length columns))
1249 (aset widths i (max (truncate (* (aref columns i)
1250 total-percentage
1251 (- shr-width (1+ (length columns)))))
1252 10)))
1253 widths))
1254
1255 ;; Return a summary of the number and shape of the TDs in the table.
1256 (defun shr-column-specs (cont)
1257 (let ((columns (make-vector (shr-max-columns cont) 1)))
1258 (dolist (row cont)
1259 (when (eq (car row) 'tr)
1260 (let ((i 0))
1261 (dolist (column (cdr row))
1262 (when (memq (car column) '(td th))
1263 (let ((width (cdr (assq :width (cdr column)))))
1264 (when (and width
1265 (string-match "\\([0-9]+\\)%" width))
1266 (aset columns i
1267 (/ (string-to-number (match-string 1 width))
1268 100.0))))
1269 (setq i (1+ i)))))))
1270 columns))
1271
1272 (defun shr-count (cont elem)
1273 (let ((i 0))
1274 (dolist (sub cont)
1275 (when (eq (car sub) elem)
1276 (setq i (1+ i))))
1277 i))
1278
1279 (defun shr-max-columns (cont)
1280 (let ((max 0))
1281 (dolist (row cont)
1282 (when (eq (car row) 'tr)
1283 (setq max (max max (+ (shr-count (cdr row) 'td)
1284 (shr-count (cdr row) 'th))))))
1285 max))
1286
1287 (provide 'shr)
1288
1289 ;;; shr.el ends here