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