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