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