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