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