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