ed30f5f86020cc0d06fce26ac3b4983214d7bf6b
[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
471 (defun shr-put-image (data alt)
472   (if (display-graphic-p)
473       (let ((image (ignore-errors
474                      (shr-rescale-image data))))
475         (when image
476           ;; When inserting big-ish pictures, put them at the
477           ;; beginning of the line.
478           (when (and (> (current-column) 0)
479                      (> (car (image-size image t)) 400))
480             (insert "\n"))
481           (insert-image image (or alt "*"))))
482     (insert alt)))
483
484 (defun shr-rescale-image (data)
485   (if (or (not (fboundp 'imagemagick-types))
486           (not (get-buffer-window (current-buffer))))
487       (create-image data nil t)
488     (let* ((image (create-image data nil t))
489            (size (image-size image t))
490            (width (car size))
491            (height (cdr size))
492            (edges (window-inside-pixel-edges
493                    (get-buffer-window (current-buffer))))
494            (window-width (truncate (* shr-max-image-proportion
495                                       (- (nth 2 edges) (nth 0 edges)))))
496            (window-height (truncate (* shr-max-image-proportion
497                                        (- (nth 3 edges) (nth 1 edges)))))
498            scaled-image)
499       (when (> height window-height)
500         (setq image (or (create-image data 'imagemagick t
501                                       :height window-height)
502                         image))
503         (setq size (image-size image t)))
504       (when (> (car size) window-width)
505         (setq image (or
506                      (create-image data 'imagemagick t
507                                    :width window-width)
508                      image)))
509       (when (and (fboundp 'create-animated-image)
510                  (eq (image-type data nil t) 'gif))
511         (setq image (create-animated-image data 'gif t)))
512       image)))
513
514 ;; url-cache-extract autoloads url-cache.
515 (declare-function url-cache-create-filename "url-cache" (url))
516 (autoload 'mm-disable-multibyte "mm-util")
517 (autoload 'browse-url-mailto "browse-url")
518
519 (defun shr-get-image-data (url)
520   "Get image data for URL.
521 Return a string with image data."
522   (with-temp-buffer
523     (mm-disable-multibyte)
524     (when (ignore-errors
525             (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
526             t)
527       (when (or (search-forward "\n\n" nil t)
528                 (search-forward "\r\n\r\n" nil t))
529         (buffer-substring (point) (point-max))))))
530
531 (defun shr-image-displayer (content-function)
532   "Return a function to display an image.
533 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
534 is an argument.  The function to be returned takes three arguments URL,
535 START, and END.  Note that START and END should be merkers."
536   `(lambda (url start end)
537      (when url
538        (if (string-match "\\`cid:" url)
539            ,(when content-function
540               `(let ((image (funcall ,content-function
541                                      (substring url (match-end 0)))))
542                  (when image
543                    (goto-char start)
544                    (shr-put-image image
545                                   (buffer-substring-no-properties start end))
546                    (delete-region (point) end))))
547          (url-retrieve url 'shr-image-fetched
548                        (list (current-buffer) start end)
549                        t)))))
550
551 (defun shr-heading (cont &rest types)
552   (shr-ensure-paragraph)
553   (apply #'shr-fontize-cont cont types)
554   (shr-ensure-paragraph))
555
556 (autoload 'widget-convert-button "wid-edit")
557
558 (defun shr-urlify (start url &optional title)
559   (widget-convert-button
560    'url-link start (point)
561    :help-echo (if title (format "%s (%s)" url title) url)
562    :keymap shr-map
563    url)
564   (put-text-property start (point) 'shr-url url))
565
566 (defun shr-encode-url (url)
567   "Encode URL."
568   (browse-url-url-encode-chars url "[)$ ]"))
569
570 (autoload 'shr-color-visible "shr-color")
571 (autoload 'shr-color->hexadecimal "shr-color")
572
573 (defun shr-color-check (fg bg)
574   "Check that FG is visible on BG.
575 Returns (fg bg) with corrected values.
576 Returns nil if the colors that would be used are the default
577 ones, in case fg and bg are nil."
578   (when (or fg bg)
579     (let ((fixed (cond ((null fg) 'fg)
580                        ((null bg) 'bg))))
581       ;; Convert colors to hexadecimal, or set them to default.
582       (let ((fg (or (shr-color->hexadecimal fg)
583                     (frame-parameter nil 'foreground-color)))
584             (bg (or (shr-color->hexadecimal bg)
585                     (frame-parameter nil 'background-color))))
586         (cond ((eq fixed 'bg)
587                ;; Only return the new fg
588                (list nil (cadr (shr-color-visible bg fg t))))
589               ((eq fixed 'fg)
590                ;; Invert args and results and return only the new bg
591                (list (cadr (shr-color-visible fg bg t)) nil))
592               (t
593                (shr-color-visible bg fg)))))))
594
595 (defun shr-colorize-region (start end fg &optional bg)
596   (when (or fg bg)
597     (let ((new-colors (shr-color-check fg bg)))
598       (when new-colors
599         (when fg
600           (shr-put-color start end :foreground (cadr new-colors)))
601         (when bg
602           (shr-put-color start end :background (car new-colors)))))))
603
604 ;; Put a color in the region, but avoid putting colors on on blank
605 ;; text at the start of the line, and the newline at the end, to avoid
606 ;; ugliness.  Also, don't overwrite any existing color information,
607 ;; since this can be called recursively, and we want the "inner" color
608 ;; to win.
609 (defun shr-put-color (start end type color)
610   (save-excursion
611     (goto-char start)
612     (while (< (point) end)
613       (when (bolp)
614         (skip-chars-forward " "))
615       (when (> (line-end-position) (point))
616         (shr-put-color-1 (point) (min (line-end-position) end) type color))
617       (if (< (line-end-position) end)
618           (forward-line 1)
619         (goto-char end)))))
620
621 (defun shr-put-color-1 (start end type color)
622   (let* ((old-props (get-text-property start 'face))
623          (do-put (not (memq type old-props)))
624          change)
625     (while (< start end)
626       (setq change (next-single-property-change start 'face nil end))
627       (when do-put
628         (put-text-property start change 'face
629                            (nconc (list type color) old-props)))
630       (setq old-props (get-text-property change 'face))
631       (setq do-put (not (memq type old-props)))
632       (setq start change))
633     (when (and do-put
634                (> end start))
635       (put-text-property start end 'face
636                          (nconc (list type color old-props))))))
637
638 ;;; Tag-specific rendering rules.
639
640 (defun shr-tag-body (cont)
641   (let* ((start (point))
642          (fgcolor (cdr (assq :fgcolor cont)))
643          (bgcolor (cdr (assq :bgcolor cont)))
644          (shr-stylesheet (list (cons 'color fgcolor)
645                                (cons 'background-color bgcolor))))
646     (shr-generic cont)
647     (shr-colorize-region start (point) fgcolor bgcolor)))
648
649 (defun shr-tag-style (cont)
650   )
651
652 (defun shr-tag-script (cont)
653   )
654
655 (defun shr-tag-label (cont)
656   (shr-generic cont)
657   (shr-ensure-paragraph))
658
659 (defun shr-tag-p (cont)
660   (shr-ensure-paragraph)
661   (shr-indent)
662   (shr-generic cont)
663   (shr-ensure-paragraph))
664
665 (defun shr-tag-div (cont)
666   (shr-ensure-newline)
667   (shr-indent)
668   (shr-generic cont)
669   (shr-ensure-newline))
670
671 (defun shr-tag-b (cont)
672   (shr-fontize-cont cont 'bold))
673
674 (defun shr-tag-i (cont)
675   (shr-fontize-cont cont 'italic))
676
677 (defun shr-tag-em (cont)
678   (shr-fontize-cont cont 'bold))
679
680 (defun shr-tag-strong (cont)
681   (shr-fontize-cont cont 'bold))
682
683 (defun shr-tag-u (cont)
684   (shr-fontize-cont cont 'underline))
685
686 (defun shr-tag-s (cont)
687   (shr-fontize-cont cont 'strike-through))
688
689 (defun shr-parse-style (style)
690   (when style
691     (save-match-data
692       (when (string-match "\n" style)
693         (setq style (replace-match " " t t style))))
694     (let ((plist nil))
695       (dolist (elem (split-string style ";"))
696         (when elem
697           (setq elem (split-string elem ":"))
698           (when (and (car elem)
699                      (cadr elem))
700             (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
701                   (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
702               (when (string-match " *!important\\'" value)
703                 (setq value (substring value 0 (match-beginning 0))))
704               (push (cons (intern name obarray)
705                           value)
706                     plist)))))
707       plist)))
708
709 (defun shr-tag-a (cont)
710   (let ((url (cdr (assq :href cont)))
711         (title (cdr (assq :title cont)))
712         (start (point))
713         shr-start)
714     (shr-generic cont)
715     (shr-urlify (or shr-start start) url title)))
716
717 (defun shr-tag-object (cont)
718   (let ((start (point))
719         url)
720     (dolist (elem cont)
721       (when (eq (car elem) 'embed)
722         (setq url (or url (cdr (assq :src (cdr elem))))))
723       (when (and (eq (car elem) 'param)
724                  (equal (cdr (assq :name (cdr elem))) "movie"))
725         (setq url (or url (cdr (assq :value (cdr elem)))))))
726     (when url
727       (shr-insert " [multimedia] ")
728       (shr-urlify start url))
729     (shr-generic cont)))
730
731 (defun shr-tag-video (cont)
732   (let ((image (cdr (assq :poster cont)))
733         (url (cdr (assq :src cont)))
734         (start (point)))
735     (shr-tag-img nil image)
736     (shr-urlify start url)))
737
738 (defun shr-tag-img (cont &optional url)
739   (when (or url
740             (and cont
741                  (cdr (assq :src cont))))
742     (when (and (> (current-column) 0)
743                (not (eq shr-state 'image)))
744       (insert "\n"))
745     (let ((alt (cdr (assq :alt cont)))
746           (url (or url (cdr (assq :src cont)))))
747       (let ((start (point-marker)))
748         (when (zerop (length alt))
749           (setq alt "*"))
750         (cond
751          ((or (member (cdr (assq :height cont)) '("0" "1"))
752               (member (cdr (assq :width cont)) '("0" "1")))
753           ;; Ignore zero-sized or single-pixel images.
754           )
755          ((and (not shr-inhibit-images)
756                (string-match "\\`cid:" url))
757           (let ((url (substring url (match-end 0)))
758                 image)
759             (if (or (not shr-content-function)
760                     (not (setq image (funcall shr-content-function url))))
761                 (insert alt)
762               (shr-put-image image alt))))
763          ((or shr-inhibit-images
764               (and shr-blocked-images
765                    (string-match shr-blocked-images url)))
766           (setq shr-start (point))
767           (let ((shr-state 'space))
768             (if (> (string-width alt) 8)
769                 (shr-insert (truncate-string-to-width alt 8))
770               (shr-insert alt))))
771          ((url-is-cached (shr-encode-url url))
772           (shr-put-image (shr-get-image-data url) alt))
773          (t
774           (insert alt)
775           (ignore-errors
776             (url-retrieve (shr-encode-url url) 'shr-image-fetched
777                           (list (current-buffer) start (point-marker))
778                           t))))
779         (put-text-property start (point) 'keymap shr-map)
780         (put-text-property start (point) 'shr-alt alt)
781         (put-text-property start (point) 'image-url url)
782         (put-text-property start (point) 'image-displayer
783                            (shr-image-displayer shr-content-function))
784         (put-text-property start (point) 'help-echo alt)
785         (setq shr-state 'image)))))
786
787 (defun shr-tag-pre (cont)
788   (let ((shr-folding-mode 'none))
789     (shr-ensure-newline)
790     (shr-indent)
791     (shr-generic cont)
792     (shr-ensure-newline)))
793
794 (defun shr-tag-blockquote (cont)
795   (shr-ensure-paragraph)
796   (shr-indent)
797   (let ((shr-indentation (+ shr-indentation 4)))
798     (shr-generic cont))
799   (shr-ensure-paragraph))
800
801 (defun shr-tag-ul (cont)
802   (shr-ensure-paragraph)
803   (let ((shr-list-mode 'ul))
804     (shr-generic cont))
805   (shr-ensure-paragraph))
806
807 (defun shr-tag-ol (cont)
808   (shr-ensure-paragraph)
809   (let ((shr-list-mode 1))
810     (shr-generic cont))
811   (shr-ensure-paragraph))
812
813 (defun shr-tag-li (cont)
814   (shr-ensure-paragraph)
815   (shr-indent)
816   (let* ((bullet
817           (if (numberp shr-list-mode)
818               (prog1
819                   (format "%d " shr-list-mode)
820                 (setq shr-list-mode (1+ shr-list-mode)))
821             "* "))
822          (shr-indentation (+ shr-indentation (length bullet))))
823     (insert bullet)
824     (shr-generic cont)))
825
826 (defun shr-tag-br (cont)
827   (unless (bobp)
828     (insert "\n")
829     (shr-indent))
830   (shr-generic cont))
831
832 (defun shr-tag-h1 (cont)
833   (shr-heading cont 'bold 'underline))
834
835 (defun shr-tag-h2 (cont)
836   (shr-heading cont 'bold))
837
838 (defun shr-tag-h3 (cont)
839   (shr-heading cont 'italic))
840
841 (defun shr-tag-h4 (cont)
842   (shr-heading cont))
843
844 (defun shr-tag-h5 (cont)
845   (shr-heading cont))
846
847 (defun shr-tag-h6 (cont)
848   (shr-heading cont))
849
850 (defun shr-tag-hr (cont)
851   (shr-ensure-newline)
852   (insert (make-string shr-width shr-hr-line) "\n"))
853
854 (defun shr-tag-title (cont)
855   (shr-heading cont 'bold 'underline))
856
857 (defun shr-tag-font (cont)
858   (let* ((start (point))
859          (color (cdr (assq :color cont)))
860          (shr-stylesheet (nconc (list (cons 'color color))
861                                 shr-stylesheet)))
862     (shr-generic cont)
863     (when color
864       (shr-colorize-region start (point) color
865                            (cdr (assq 'background-color shr-stylesheet))))))
866
867 ;;; Table rendering algorithm.
868
869 ;; Table rendering is the only complicated thing here.  We do this by
870 ;; first counting how many TDs there are in each TR, and registering
871 ;; how wide they think they should be ("width=45%", etc).  Then we
872 ;; render each TD separately (this is done in temporary buffers, so
873 ;; that we can use all the rendering machinery as if we were in the
874 ;; main buffer).  Now we know how much space each TD really takes, so
875 ;; we then render everything again with the new widths, and finally
876 ;; insert all these boxes into the main buffer.
877 (defun shr-tag-table-1 (cont)
878   (setq cont (or (cdr (assq 'tbody cont))
879                  cont))
880   (let* ((shr-inhibit-images t)
881          (shr-table-depth (1+ shr-table-depth))
882          (shr-kinsoku-shorten t)
883          ;; Find all suggested widths.
884          (columns (shr-column-specs cont))
885          ;; Compute how many characters wide each TD should be.
886          (suggested-widths (shr-pro-rate-columns columns))
887          ;; Do a "test rendering" to see how big each TD is (this can
888          ;; be smaller (if there's little text) or bigger (if there's
889          ;; unbreakable text).
890          (sketch (shr-make-table cont suggested-widths))
891          (sketch-widths (shr-table-widths sketch suggested-widths)))
892     ;; This probably won't work very well.
893     (when (> (+ (loop for width across sketch-widths
894                       summing (1+ width))
895                 shr-indentation 1)
896              (frame-width))
897       (setq truncate-lines t))
898     ;; Then render the table again with these new "hard" widths.
899     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
900   ;; Finally, insert all the images after the table.  The Emacs buffer
901   ;; model isn't strong enough to allow us to put the images actually
902   ;; into the tables.
903   (when (zerop shr-table-depth)
904     (dolist (elem (shr-find-elements cont 'img))
905       (shr-tag-img (cdr elem)))))
906
907 (defun shr-tag-table (cont)
908   (shr-ensure-paragraph)
909   (let* ((caption (cdr (assq 'caption cont)))
910          (header (cdr (assq 'thead cont)))
911          (body (or (cdr (assq 'tbody cont)) cont))
912          (footer (cdr (assq 'tfoot cont)))
913          (bgcolor (cdr (assq :bgcolor cont)))
914          (start (point))
915          (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
916                                 shr-stylesheet))
917          (nheader (if header (shr-max-columns header)))
918          (nbody (if body (shr-max-columns body)))
919          (nfooter (if footer (shr-max-columns footer))))
920     (shr-tag-table-1
921      (nconc
922       (if caption `((tr (td ,@caption))))
923       (if header
924           (if footer
925               ;; hader + body + footer
926               (if (= nheader nbody)
927                   (if (= nbody nfooter)
928                       `((tr (td (table (tbody ,@header ,@body ,@footer)))))
929                     (nconc `((tr (td (table (tbody ,@header ,@body)))))
930                            (if (= nfooter 1)
931                                footer
932                              `((tr (td (table (tbody ,@footer))))))))
933                 (nconc `((tr (td (table (tbody ,@header)))))
934                        (if (= nbody nfooter)
935                            `((tr (td (table (tbody ,@body ,@footer)))))
936                          (nconc `((tr (td (table (tbody ,@body)))))
937                                 (if (= nfooter 1)
938                                     footer
939                                   `((tr (td (table (tbody ,@footer))))))))))
940             ;; header + body
941             (if (= nheader nbody)
942                 `((tr (td (table (tbody ,@header ,@body)))))
943               (if (= nheader 1)
944                   `(,@header (tr (td (table (tbody ,@body)))))
945                 `((tr (td (table (tbody ,@header))))
946                   (tr (td (table (tbody ,@body))))))))
947         (if footer
948             ;; body + footer
949             (if (= nbody nfooter)
950                 `((tr (td (table (tbody ,@body ,@footer)))))
951               (nconc `((tr (td (table (tbody ,@body)))))
952                      (if (= nfooter 1)
953                          footer
954                        `((tr (td (table (tbody ,@footer))))))))
955           (if caption
956               `((tr (td (table (tbody ,@body)))))
957             body)))))
958     (when bgcolor
959       (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
960                            bgcolor))))
961
962 (defun shr-find-elements (cont type)
963   (let (result)
964     (dolist (elem cont)
965       (cond ((eq (car elem) type)
966              (push elem result))
967             ((consp (cdr elem))
968              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
969     (nreverse result)))
970
971 (defun shr-insert-table (table widths)
972   (shr-insert-table-ruler widths)
973   (dolist (row table)
974     (let ((start (point))
975           (height (let ((max 0))
976                     (dolist (column row)
977                       (setq max (max max (cadr column))))
978                     max)))
979       (dotimes (i height)
980         (shr-indent)
981         (insert shr-table-vertical-line "\n"))
982       (dolist (column row)
983         (goto-char start)
984         (let ((lines (nth 2 column))
985               (overlay-lines (nth 3 column))
986               overlay overlay-line)
987           (dolist (line lines)
988             (setq overlay-line (pop overlay-lines))
989             (end-of-line)
990             (insert line shr-table-vertical-line)
991             (dolist (overlay overlay-line)
992               (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
993                                      (- (point) (nth 1 overlay) 1)))
994                     (properties (nth 2 overlay)))
995                 (while properties
996                   (overlay-put o (pop properties) (pop properties)))))
997             (forward-line 1))
998           ;; Add blank lines at padding at the bottom of the TD,
999           ;; possibly.
1000           (dotimes (i (- height (length lines)))
1001             (end-of-line)
1002             (insert (make-string (string-width (car lines)) ? )
1003                     shr-table-vertical-line)
1004             (forward-line 1)))))
1005     (shr-insert-table-ruler widths)))
1006
1007 (defun shr-insert-table-ruler (widths)
1008   (when (and (bolp)
1009              (> shr-indentation 0))
1010     (shr-indent))
1011   (insert shr-table-corner)
1012   (dotimes (i (length widths))
1013     (insert (make-string (aref widths i) shr-table-horizontal-line)
1014             shr-table-corner))
1015   (insert "\n"))
1016
1017 (defun shr-table-widths (table suggested-widths)
1018   (let* ((length (length suggested-widths))
1019          (widths (make-vector length 0))
1020          (natural-widths (make-vector length 0)))
1021     (dolist (row table)
1022       (let ((i 0))
1023         (dolist (column row)
1024           (aset widths i (max (aref widths i)
1025                               (car column)))
1026           (aset natural-widths i (max (aref natural-widths i)
1027                                       (cadr column)))
1028           (setq i (1+ i)))))
1029     (let ((extra (- (apply '+ (append suggested-widths nil))
1030                     (apply '+ (append widths nil))))
1031           (expanded-columns 0))
1032       (when (> extra 0)
1033         (dotimes (i length)
1034           ;; If the natural width is wider than the rendered width, we
1035           ;; want to allow the column to expand.
1036           (when (> (aref natural-widths i) (aref widths i))
1037             (setq expanded-columns (1+ expanded-columns))))
1038         (dotimes (i length)
1039           (when (> (aref natural-widths i) (aref widths i))
1040             (aset widths i (min
1041                             (1+ (aref natural-widths i))
1042                             (+ (/ extra expanded-columns)
1043                                (aref widths i))))))))
1044     widths))
1045
1046 (defun shr-make-table (cont widths &optional fill)
1047   (let ((trs nil))
1048     (dolist (row cont)
1049       (when (eq (car row) 'tr)
1050         (let ((tds nil)
1051               (columns (cdr row))
1052               (i 0)
1053               column)
1054           (while (< i (length widths))
1055             (setq column (pop columns))
1056             (when (or (memq (car column) '(td th))
1057                       (null column))
1058               (push (shr-render-td (cdr column) (aref widths i) fill)
1059                     tds)
1060               (setq i (1+ i))))
1061           (push (nreverse tds) trs))))
1062     (nreverse trs)))
1063
1064 (defun shr-render-td (cont width fill)
1065   (with-temp-buffer
1066     (let ((bgcolor (cdr (assq :bgcolor cont)))
1067           (fgcolor (cdr (assq :fgcolor cont)))
1068           (style (cdr (assq :style cont)))
1069           (shr-stylesheet shr-stylesheet)
1070           overlays)
1071       (when style
1072         (setq style (and (string-match "color" style)
1073                          (shr-parse-style style))))
1074       (when bgcolor
1075         (setq style (nconc (list (cons 'background-color bgcolor)) style)))
1076       (when fgcolor
1077         (setq style (nconc (list (cons 'color fgcolor)) style)))
1078       (when style
1079         (setq shr-stylesheet (append style shr-stylesheet)))
1080       (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
1081         (if cache
1082             (progn
1083               (insert (car cache))
1084               (let ((end (length (car cache))))
1085                 (dolist (overlay (cadr cache))
1086                   (let ((new-overlay
1087                          (make-overlay (1+ (- end (nth 0 overlay)))
1088                                        (1+ (- end (nth 1 overlay)))))
1089                         (properties (nth 2 overlay)))
1090                     (while properties
1091                       (overlay-put new-overlay
1092                                    (pop properties) (pop properties)))))))
1093           (let ((shr-width width)
1094                 (shr-indentation 0))
1095             (shr-descend (cons 'td cont)))
1096           (delete-region
1097            (point)
1098            (+ (point)
1099               (skip-chars-backward " \t\n")))
1100           (push (list (cons width cont) (buffer-string)
1101                       (shr-overlays-in-region (point-min) (point-max)))
1102                 shr-content-cache)))
1103       (goto-char (point-min))
1104       (let ((max 0))
1105         (while (not (eobp))
1106           (end-of-line)
1107           (setq max (max max (current-column)))
1108           (forward-line 1))
1109         (when fill
1110           (goto-char (point-min))
1111           ;; If the buffer is totally empty, then put a single blank
1112           ;; line here.
1113           (if (zerop (buffer-size))
1114               (insert (make-string width ? ))
1115             ;; Otherwise, fill the buffer.
1116             (while (not (eobp))
1117               (end-of-line)
1118               (when (> (- width (current-column)) 0)
1119                 (insert (make-string (- width (current-column)) ? )))
1120               (forward-line 1))))
1121         (when style
1122           (shr-colorize-region
1123            (point-min) (point-max)
1124            (cdr (assq 'color shr-stylesheet))
1125            (cdr (assq 'background-color shr-stylesheet))))
1126         (if fill
1127             (list max
1128                   (count-lines (point-min) (point-max))
1129                   (split-string (buffer-string) "\n")
1130                   (shr-collect-overlays))
1131           (list max
1132                 (shr-natural-width)))))))
1133
1134 (defun shr-natural-width ()
1135   (goto-char (point-min))
1136   (let ((current 0)
1137         (max 0))
1138     (while (not (eobp))
1139       (end-of-line)
1140       (setq current (+ current (current-column)))
1141       (unless (get-text-property (point) 'shr-break)
1142         (setq max (max max current)
1143               current 0))
1144       (forward-line 1))
1145     max))
1146
1147 (defun shr-collect-overlays ()
1148   (save-excursion
1149     (goto-char (point-min))
1150     (let ((overlays nil))
1151       (while (not (eobp))
1152         (push (shr-overlays-in-region (point) (line-end-position))
1153               overlays)
1154         (forward-line 1))
1155       (nreverse overlays))))
1156
1157 (defun shr-overlays-in-region (start end)
1158   (let (result)
1159     (dolist (overlay (overlays-in start end))
1160       (push (list (if (> start (overlay-start overlay))
1161                       (- end start)
1162                     (- end (overlay-start overlay)))
1163                   (if (< end (overlay-end overlay))
1164                       0
1165                     (- end (overlay-end overlay)))
1166                   (overlay-properties overlay))
1167             result))
1168     (nreverse result)))
1169
1170 (defun shr-pro-rate-columns (columns)
1171   (let ((total-percentage 0)
1172         (widths (make-vector (length columns) 0)))
1173     (dotimes (i (length columns))
1174       (setq total-percentage (+ total-percentage (aref columns i))))
1175     (setq total-percentage (/ 1.0 total-percentage))
1176     (dotimes (i (length columns))
1177       (aset widths i (max (truncate (* (aref columns i)
1178                                        total-percentage
1179                                        (- shr-width (1+ (length columns)))))
1180                           10)))
1181     widths))
1182
1183 ;; Return a summary of the number and shape of the TDs in the table.
1184 (defun shr-column-specs (cont)
1185   (let ((columns (make-vector (shr-max-columns cont) 1)))
1186     (dolist (row cont)
1187       (when (eq (car row) 'tr)
1188         (let ((i 0))
1189           (dolist (column (cdr row))
1190             (when (memq (car column) '(td th))
1191               (let ((width (cdr (assq :width (cdr column)))))
1192                 (when (and width
1193                            (string-match "\\([0-9]+\\)%" width))
1194                   (aset columns i
1195                         (/ (string-to-number (match-string 1 width))
1196                            100.0))))
1197               (setq i (1+ i)))))))
1198     columns))
1199
1200 (defun shr-count (cont elem)
1201   (let ((i 0))
1202     (dolist (sub cont)
1203       (when (eq (car sub) elem)
1204         (setq i (1+ i))))
1205     i))
1206
1207 (defun shr-max-columns (cont)
1208   (let ((max 0))
1209     (dolist (row cont)
1210       (when (eq (car row) 'tr)
1211         (setq max (max max (+ (shr-count (cdr row) 'td)
1212                               (shr-count (cdr row) 'th))))))
1213     max))
1214
1215 (provide 'shr)
1216
1217 ;;; shr.el ends here