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