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