Fix typo
[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 (and style
198                ;; HACK: we only parse if there's color information, since
199                ;; that's the only thing we are rendering.
200                (string-match "color" style))
201       (setq shr-stylesheet (nconc (shr-parse-style style)
202                                   shr-stylesheet)))
203     ;; Render content
204     (if (fboundp function)
205         (funcall function (cdr dom))
206       (shr-generic (cdr dom)))
207     ;; Apply style
208     (shr-colorize-region start (point)
209                          (cdr (assq 'color shr-stylesheet))
210                          (cdr (assq 'background-color shr-stylesheet)))))
211
212 (defun shr-generic (cont)
213   (dolist (sub cont)
214     (cond
215      ((eq (car sub) 'text)
216       (shr-insert (cdr sub)))
217      ((listp (cdr sub))
218       (shr-descend sub)))))
219
220 (defmacro shr-char-breakable-p (char)
221   "Return non-nil if a line can be broken before and after CHAR."
222   `(aref fill-find-break-point-function-table ,char))
223 (defmacro shr-char-nospace-p (char)
224   "Return non-nil if no space is required before and after CHAR."
225   `(aref fill-nospace-between-words-table ,char))
226
227 ;; KINSOKU is a Japanese word meaning a rule that should not be violated.
228 ;; In Emacs, it is a term used for characters, e.g. punctuation marks,
229 ;; parentheses, and so on, that should not be placed in the beginning
230 ;; of a line or the end of a line.
231 (defmacro shr-char-kinsoku-bol-p (char)
232   "Return non-nil if a line ought not to begin with CHAR."
233   `(aref (char-category-set ,char) ?>))
234 (defmacro shr-char-kinsoku-eol-p (char)
235   "Return non-nil if a line ought not to end with CHAR."
236   `(aref (char-category-set ,char) ?<))
237 (unless (shr-char-kinsoku-bol-p (make-char 'japanese-jisx0208 33 35))
238   (load "kinsoku" nil t))
239
240 (defun shr-insert (text)
241   (when (and (eq shr-state 'image)
242              (not (string-match "\\`[ \t\n]+\\'" text)))
243     (insert "\n")
244     (setq shr-state nil))
245   (cond
246    ((eq shr-folding-mode 'none)
247     (insert text))
248    (t
249     (when (and (string-match "\\`[ \t\n]" text)
250                (not (bolp))
251                (not (eq (char-after (1- (point))) ? )))
252       (insert " "))
253     (dolist (elem (split-string text))
254       (when (and (bolp)
255                  (> shr-indentation 0))
256         (shr-indent))
257       ;; The shr-start is a special variable that is used to pass
258       ;; upwards the first point in the buffer where the text really
259       ;; starts.
260       (unless shr-start
261         (setq shr-start (point)))
262       ;; No space is needed behind a wide character categorized as
263       ;; kinsoku-bol, between characters both categorized as nospace,
264       ;; or at the beginning of a line.
265       (let (prev)
266         (when (and (eq (preceding-char) ? )
267                    (or (= (line-beginning-position) (1- (point)))
268                        (and (shr-char-breakable-p
269                              (setq prev (char-after (- (point) 2))))
270                             (shr-char-kinsoku-bol-p prev))
271                        (and (shr-char-nospace-p prev)
272                             (shr-char-nospace-p (aref elem 0)))))
273           (delete-char -1)))
274       (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                       ;; There're some kinsoku CJK chars that aren't breakable.
309                       (and (shr-char-kinsoku-bol-p (preceding-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."
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                                   (prog1
539                                       (buffer-substring-no-properties start end)
540                                     (delete-region start end))))))
541          (url-retrieve url 'shr-image-fetched
542                        (list (current-buffer) start end)
543                        t)))))
544
545 (defun shr-heading (cont &rest types)
546   (shr-ensure-paragraph)
547   (apply #'shr-fontize-cont cont types)
548   (shr-ensure-paragraph))
549
550 (autoload 'widget-convert-button "wid-edit")
551
552 (defun shr-urlify (start url &optional title)
553   (widget-convert-button
554    'url-link start (point)
555    :help-echo (if title (format "%s (%s)" url title) url)
556    :keymap shr-map
557    url)
558   (put-text-property start (point) 'shr-url url))
559
560 (defun shr-encode-url (url)
561   "Encode URL."
562   (browse-url-url-encode-chars url "[)$ ]"))
563
564 (autoload 'shr-color-visible "shr-color")
565 (autoload 'shr-color->hexadecimal "shr-color")
566
567 (defun shr-color-check (fg bg)
568   "Check that FG is visible on BG.
569 Returns (fg bg) with corrected values.
570 Returns nil if the colors that would be used are the default
571 ones, in case fg and bg are nil."
572   (when (or fg bg)
573     (let ((fixed (cond ((null fg) 'fg)
574                        ((null bg) 'bg))))
575       ;; Convert colors to hexadecimal, or set them to default.
576       (let ((fg (or (shr-color->hexadecimal fg)
577                     (frame-parameter nil 'foreground-color)))
578             (bg (or (shr-color->hexadecimal bg)
579                     (frame-parameter nil 'background-color))))
580         (cond ((eq fixed 'bg)
581                ;; Only return the new fg
582                (list nil (cadr (shr-color-visible bg fg t))))
583               ((eq fixed 'fg)
584                ;; Invert args and results and return only the new bg
585                (list (cadr (shr-color-visible fg bg t)) nil))
586               (t
587                (shr-color-visible bg fg)))))))
588
589 (defun shr-colorize-region (start end fg &optional bg)
590   "Colorize region from START to END.
591 Use foreground color FG and background color BG.
592 Apply color check via `shr-color-check'."
593   (when (or fg bg)
594     (let ((new-colors (shr-color-check fg bg)))
595       (when new-colors
596         (shr-put-color start end :foreground (cadr new-colors))
597         (when bg
598           (shr-put-color start end :background (car new-colors)))))))
599
600 ;; Put a color in the region, but avoid putting colors on on blank
601 ;; text at the start of the line, and the newline at the end, to avoid
602 ;; ugliness.  Also, don't overwrite any existing color information,
603 ;; since this can be called recursively, and we want the "inner" color
604 ;; to win.
605 (defun shr-put-color (start end type color)
606   (save-excursion
607     (goto-char start)
608     (while (< (point) end)
609       (when (bolp)
610         (skip-chars-forward " "))
611       (when (> (line-end-position) (point))
612         (shr-put-color-1 (point) (min (line-end-position) end) type color))
613       (if (< (line-end-position) end)
614           (forward-line 1)
615         (goto-char end)))))
616
617 (defun shr-put-color-1 (start end type color)
618   (let* ((old-props (get-text-property start 'face))
619          (do-put (not (memq type old-props)))
620          change)
621     (while (< start end)
622       (setq change (next-single-property-change start 'face nil end))
623       (when do-put
624         (put-text-property start change 'face
625                            (nconc (list type color) old-props)))
626       (setq old-props (get-text-property change 'face))
627       (setq do-put (not (memq type old-props)))
628       (setq start change))
629     (when (and do-put
630                (> end start))
631       (put-text-property start end 'face
632                          (nconc (list type color old-props))))))
633
634 ;;; Tag-specific rendering rules.
635
636 (defun shr-tag-body (cont)
637   (let* ((start (point))
638          (fgcolor (cdr (assq :fgcolor cont)))
639          (bgcolor (cdr (assq :bgcolor cont)))
640          (shr-stylesheet (if fgcolor
641                              (if bgcolor
642                                  `((color . ,fgcolor)
643                                    (background-color . ,bgcolor) ,@shr-stylesheet)
644                                `((color . ,fgcolor) ,@shr-stylesheet))
645                            (if bgcolor
646                                `((background-color . ,bgcolor) ,@shr-stylesheet)
647                              shr-stylesheet))))
648     (shr-generic cont)))
649
650 (defun shr-tag-p (cont)
651   (shr-ensure-paragraph)
652   (shr-indent)
653   (shr-generic cont)
654   (shr-ensure-paragraph))
655
656 (defun shr-tag-div (cont)
657   (shr-ensure-newline)
658   (shr-indent)
659   (shr-generic cont)
660   (shr-ensure-newline))
661
662 (defun shr-tag-b (cont)
663   (shr-fontize-cont cont 'bold))
664
665 (defun shr-tag-i (cont)
666   (shr-fontize-cont cont 'italic))
667
668 (defun shr-tag-em (cont)
669   (shr-fontize-cont cont 'bold))
670
671 (defun shr-tag-strong (cont)
672   (shr-fontize-cont cont 'bold))
673
674 (defun shr-tag-u (cont)
675   (shr-fontize-cont cont 'underline))
676
677 (defun shr-tag-s (cont)
678   (shr-fontize-cont cont 'strike-through))
679
680 (defun shr-parse-style (style)
681   (when style
682     (save-match-data
683       (when (string-match "\n" style)
684         (setq style (replace-match " " t t style))))
685     (let ((plist nil))
686       (dolist (elem (split-string style ";"))
687         (when elem
688           (setq elem (split-string elem ":"))
689           (when (and (car elem)
690                      (cadr elem))
691             (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
692                   (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
693               (when (string-match " *!important\\'" value)
694                 (setq value (substring value 0 (match-beginning 0))))
695               (push (cons (intern name obarray)
696                           value)
697                     plist)))))
698       plist)))
699
700 (defun shr-tag-a (cont)
701   (let ((url (cdr (assq :href cont)))
702         (title (cdr (assq :title cont)))
703         (start (point))
704         shr-start)
705     (shr-generic cont)
706     (shr-urlify (or shr-start start) url title)))
707
708 (defun shr-tag-object (cont)
709   (let ((start (point))
710         url)
711     (dolist (elem cont)
712       (when (eq (car elem) 'embed)
713         (setq url (or url (cdr (assq :src (cdr elem))))))
714       (when (and (eq (car elem) 'param)
715                  (equal (cdr (assq :name (cdr elem))) "movie"))
716         (setq url (or url (cdr (assq :value (cdr elem)))))))
717     (when url
718       (shr-insert " [multimedia] ")
719       (shr-urlify start url))
720     (shr-generic cont)))
721
722 (defun shr-tag-video (cont)
723   (let ((image (cdr (assq :poster cont)))
724         (url (cdr (assq :src cont)))
725         (start (point)))
726     (shr-tag-img nil image)
727     (shr-urlify start url)))
728
729 (defun shr-tag-img (cont &optional url)
730   (when (or url
731             (and cont
732                  (cdr (assq :src cont))))
733     (when (and (> (current-column) 0)
734                (not (eq shr-state 'image)))
735       (insert "\n"))
736     (let ((alt (cdr (assq :alt cont)))
737           (url (or url (cdr (assq :src cont)))))
738       (let ((start (point-marker)))
739         (when (zerop (length alt))
740           (setq alt "*"))
741         (cond
742          ((or (member (cdr (assq :height cont)) '("0" "1"))
743               (member (cdr (assq :width cont)) '("0" "1")))
744           ;; Ignore zero-sized or single-pixel images.
745           )
746          ((and (not shr-inhibit-images)
747                (string-match "\\`cid:" url))
748           (let ((url (substring url (match-end 0)))
749                 image)
750             (if (or (not shr-content-function)
751                     (not (setq image (funcall shr-content-function url))))
752                 (insert alt)
753               (shr-put-image image alt))))
754          ((or shr-inhibit-images
755               (and shr-blocked-images
756                    (string-match shr-blocked-images url)))
757           (setq shr-start (point))
758           (let ((shr-state 'space))
759             (if (> (string-width alt) 8)
760                 (shr-insert (truncate-string-to-width alt 8))
761               (shr-insert alt))))
762          ((url-is-cached (shr-encode-url url))
763           (shr-put-image (shr-get-image-data url) alt))
764          (t
765           (insert alt)
766           (ignore-errors
767             (url-retrieve (shr-encode-url url) 'shr-image-fetched
768                           (list (current-buffer) start (point-marker))
769                           t))))
770         (put-text-property start (point) 'keymap shr-map)
771         (put-text-property start (point) 'shr-alt alt)
772         (put-text-property start (point) 'image-url url)
773         (put-text-property start (point) 'image-displayer
774                            (shr-image-displayer shr-content-function))
775         (put-text-property start (point) 'help-echo alt)
776         (setq shr-state 'image)))))
777
778 (defun shr-tag-pre (cont)
779   (let ((shr-folding-mode 'none))
780     (shr-ensure-newline)
781     (shr-indent)
782     (shr-generic cont)
783     (shr-ensure-newline)))
784
785 (defun shr-tag-blockquote (cont)
786   (shr-ensure-paragraph)
787   (shr-indent)
788   (let ((shr-indentation (+ shr-indentation 4)))
789     (shr-generic cont))
790   (shr-ensure-paragraph))
791
792 (defun shr-tag-ul (cont)
793   (shr-ensure-paragraph)
794   (let ((shr-list-mode 'ul))
795     (shr-generic cont))
796   (shr-ensure-paragraph))
797
798 (defun shr-tag-ol (cont)
799   (shr-ensure-paragraph)
800   (let ((shr-list-mode 1))
801     (shr-generic cont))
802   (shr-ensure-paragraph))
803
804 (defun shr-tag-li (cont)
805   (shr-ensure-paragraph)
806   (shr-indent)
807   (let* ((bullet
808           (if (numberp shr-list-mode)
809               (prog1
810                   (format "%d " shr-list-mode)
811                 (setq shr-list-mode (1+ shr-list-mode)))
812             "* "))
813          (shr-indentation (+ shr-indentation (length bullet))))
814     (insert bullet)
815     (shr-generic cont)))
816
817 (defun shr-tag-br (cont)
818   (unless (bobp)
819     (insert "\n")
820     (shr-indent))
821   (shr-generic cont))
822
823 (defun shr-tag-h1 (cont)
824   (shr-heading cont 'bold 'underline))
825
826 (defun shr-tag-h2 (cont)
827   (shr-heading cont 'bold))
828
829 (defun shr-tag-h3 (cont)
830   (shr-heading cont 'italic))
831
832 (defun shr-tag-h4 (cont)
833   (shr-heading cont))
834
835 (defun shr-tag-h5 (cont)
836   (shr-heading cont))
837
838 (defun shr-tag-h6 (cont)
839   (shr-heading cont))
840
841 (defun shr-tag-hr (cont)
842   (shr-ensure-newline)
843   (insert (make-string shr-width shr-hr-line) "\n"))
844
845 (defun shr-tag-title (cont)
846   (shr-heading cont 'bold 'underline))
847
848 (defun shr-tag-font (cont)
849   (let* ((start (point))
850          (color (cdr (assq :color cont)))
851          (shr-stylesheet (if color
852                              `((color . ,color) ,@shr-stylesheet)
853                            shr-stylesheet)))
854     (shr-generic cont)))
855
856 ;;; Table rendering algorithm.
857
858 ;; Table rendering is the only complicated thing here.  We do this by
859 ;; first counting how many TDs there are in each TR, and registering
860 ;; how wide they think they should be ("width=45%", etc).  Then we
861 ;; render each TD separately (this is done in temporary buffers, so
862 ;; that we can use all the rendering machinery as if we were in the
863 ;; main buffer).  Now we know how much space each TD really takes, so
864 ;; we then render everything again with the new widths, and finally
865 ;; insert all these boxes into the main buffer.
866 (defun shr-tag-table-1 (cont)
867   (setq cont (or (cdr (assq 'tbody cont))
868                  cont))
869   (let* ((shr-inhibit-images t)
870          (shr-table-depth (1+ shr-table-depth))
871          (shr-kinsoku-shorten t)
872          ;; Find all suggested widths.
873          (columns (shr-column-specs cont))
874          ;; Compute how many characters wide each TD should be.
875          (suggested-widths (shr-pro-rate-columns columns))
876          ;; Do a "test rendering" to see how big each TD is (this can
877          ;; be smaller (if there's little text) or bigger (if there's
878          ;; unbreakable text).
879          (sketch (shr-make-table cont suggested-widths))
880          (sketch-widths (shr-table-widths sketch suggested-widths)))
881     ;; This probably won't work very well.
882     (when (> (+ (loop for width across sketch-widths
883                       summing (1+ width))
884                 shr-indentation 1)
885              (frame-width))
886       (setq truncate-lines t))
887     ;; Then render the table again with these new "hard" widths.
888     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
889   ;; Finally, insert all the images after the table.  The Emacs buffer
890   ;; model isn't strong enough to allow us to put the images actually
891   ;; into the tables.
892   (when (zerop shr-table-depth)
893     (dolist (elem (shr-find-elements cont 'img))
894       (shr-tag-img (cdr elem)))))
895
896 (defun shr-tag-table (cont)
897   (shr-ensure-paragraph)
898   (let* ((caption (cdr (assq 'caption cont)))
899          (header (cdr (assq 'thead cont)))
900          (body (or (cdr (assq 'tbody cont)) cont))
901          (footer (cdr (assq 'tfoot cont)))
902          (bgcolor (cdr (assq :bgcolor cont)))
903          (nheader (if header (shr-max-columns header)))
904          (nbody (if body (shr-max-columns body)))
905          (nfooter (if footer (shr-max-columns footer))))
906     (shr-tag-table-1
907      (nconc
908       (if caption `((tr (td ,@caption))))
909       (if header
910           (if footer
911               ;; hader + body + footer
912               (if (= nheader nbody)
913                   (if (= nbody nfooter)
914                       `((tr (td (table (tbody ,@header ,@body ,@footer)))))
915                     (nconc `((tr (td (table (tbody ,@header ,@body)))))
916                            (if (= nfooter 1)
917                                footer
918                              `((tr (td (table (tbody ,@footer))))))))
919                 (nconc `((tr (td (table (tbody ,@header)))))
920                        (if (= nbody nfooter)
921                            `((tr (td (table (tbody ,@body ,@footer)))))
922                          (nconc `((tr (td (table (tbody ,@body)))))
923                                 (if (= nfooter 1)
924                                     footer
925                                   `((tr (td (table (tbody ,@footer))))))))))
926             ;; header + body
927             (if (= nheader nbody)
928                 `((tr (td (table (tbody ,@header ,@body)))))
929               (if (= nheader 1)
930                   `(,@header (tr (td (table (tbody ,@body)))))
931                 `((tr (td (table (tbody ,@header))))
932                   (tr (td (table (tbody ,@body))))))))
933         (if footer
934             ;; body + footer
935             (if (= nbody nfooter)
936                 `((tr (td (table (tbody ,@body ,@footer)))))
937               (nconc `((tr (td (table (tbody ,@body)))))
938                      (if (= nfooter 1)
939                          footer
940                        `((tr (td (table (tbody ,@footer))))))))
941           (if caption
942               `((tr (td (table (tbody ,@body)))))
943             body)))))))
944
945 (defun shr-find-elements (cont type)
946   (let (result)
947     (dolist (elem cont)
948       (cond ((eq (car elem) type)
949              (push elem result))
950             ((consp (cdr elem))
951              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
952     (nreverse result)))
953
954 (defun shr-insert-table (table widths)
955   (shr-insert-table-ruler widths)
956   (dolist (row table)
957     (let ((start (point))
958           (height (let ((max 0))
959                     (dolist (column row)
960                       (setq max (max max (cadr column))))
961                     max)))
962       (dotimes (i height)
963         (shr-indent)
964         (insert shr-table-vertical-line "\n"))
965       (dolist (column row)
966         (goto-char start)
967         (let ((lines (nth 2 column))
968               (overlay-lines (nth 3 column))
969               overlay overlay-line)
970           (dolist (line lines)
971             (setq overlay-line (pop overlay-lines))
972             (end-of-line)
973             (insert line shr-table-vertical-line)
974             (dolist (overlay overlay-line)
975               (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
976                                      (- (point) (nth 1 overlay) 1)))
977                     (properties (nth 2 overlay)))
978                 (while properties
979                   (overlay-put o (pop properties) (pop properties)))))
980             (forward-line 1))
981           ;; Add blank lines at padding at the bottom of the TD,
982           ;; possibly.
983           (dotimes (i (- height (length lines)))
984             (end-of-line)
985             (insert (make-string (string-width (car lines)) ? )
986                     shr-table-vertical-line)
987             (forward-line 1)))))
988     (shr-insert-table-ruler widths)))
989
990 (defun shr-insert-table-ruler (widths)
991   (when (and (bolp)
992              (> shr-indentation 0))
993     (shr-indent))
994   (insert shr-table-corner)
995   (dotimes (i (length widths))
996     (insert (make-string (aref widths i) shr-table-horizontal-line)
997             shr-table-corner))
998   (insert "\n"))
999
1000 (defun shr-table-widths (table suggested-widths)
1001   (let* ((length (length suggested-widths))
1002          (widths (make-vector length 0))
1003          (natural-widths (make-vector length 0)))
1004     (dolist (row table)
1005       (let ((i 0))
1006         (dolist (column row)
1007           (aset widths i (max (aref widths i)
1008                               (car column)))
1009           (aset natural-widths i (max (aref natural-widths i)
1010                                       (cadr column)))
1011           (setq i (1+ i)))))
1012     (let ((extra (- (apply '+ (append suggested-widths nil))
1013                     (apply '+ (append widths nil))))
1014           (expanded-columns 0))
1015       (when (> extra 0)
1016         (dotimes (i length)
1017           ;; If the natural width is wider than the rendered width, we
1018           ;; want to allow the column to expand.
1019           (when (> (aref natural-widths i) (aref widths i))
1020             (setq expanded-columns (1+ expanded-columns))))
1021         (dotimes (i length)
1022           (when (> (aref natural-widths i) (aref widths i))
1023             (aset widths i (min
1024                             (1+ (aref natural-widths i))
1025                             (+ (/ extra expanded-columns)
1026                                (aref widths i))))))))
1027     widths))
1028
1029 (defun shr-make-table (cont widths &optional fill)
1030   (let ((trs nil))
1031     (dolist (row cont)
1032       (when (eq (car row) 'tr)
1033         (let ((tds nil)
1034               (columns (cdr row))
1035               (i 0)
1036               column)
1037           (while (< i (length widths))
1038             (setq column (pop columns))
1039             (when (or (memq (car column) '(td th))
1040                       (null column))
1041               (push (shr-render-td (cdr column) (aref widths i) fill)
1042                     tds)
1043               (setq i (1+ i))))
1044           (push (nreverse tds) trs))))
1045     (nreverse trs)))
1046
1047 (defun shr-render-td (cont width fill)
1048   (with-temp-buffer
1049     (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
1050       (if cache
1051           (insert cache)
1052         (let ((shr-width width)
1053               (shr-indentation 0))
1054           (shr-descend (cons 'td cont)))
1055         (delete-region
1056          (point)
1057          (+ (point)
1058             (skip-chars-backward " \t\n")))
1059         (push (cons (cons width cont) (buffer-string))
1060               shr-content-cache)))
1061     (goto-char (point-min))
1062     (let ((max 0))
1063       (while (not (eobp))
1064         (end-of-line)
1065         (setq max (max max (current-column)))
1066         (forward-line 1))
1067       (when fill
1068         (goto-char (point-min))
1069         ;; If the buffer is totally empty, then put a single blank
1070         ;; line here.
1071         (if (zerop (buffer-size))
1072             (insert (make-string width ? ))
1073           ;; Otherwise, fill the buffer.
1074           (while (not (eobp))
1075             (end-of-line)
1076             (when (> (- width (current-column)) 0)
1077               (insert (make-string (- width (current-column)) ? )))
1078             (forward-line 1))))
1079       (if fill
1080           (list max
1081                 (count-lines (point-min) (point-max))
1082                 (split-string (buffer-string) "\n")
1083                 (shr-collect-overlays))
1084         (list max
1085               (shr-natural-width))))))
1086
1087 (defun shr-natural-width ()
1088   (goto-char (point-min))
1089   (let ((current 0)
1090         (max 0))
1091     (while (not (eobp))
1092       (end-of-line)
1093       (setq current (+ current (current-column)))
1094       (unless (get-text-property (point) 'shr-break)
1095         (setq max (max max current)
1096               current 0))
1097       (forward-line 1))
1098     max))
1099
1100 (defun shr-collect-overlays ()
1101   (save-excursion
1102     (goto-char (point-min))
1103     (let ((overlays nil))
1104       (while (not (eobp))
1105         (push (shr-overlays-in-region (point) (line-end-position))
1106               overlays)
1107         (forward-line 1))
1108       (nreverse overlays))))
1109
1110 (defun shr-overlays-in-region (start end)
1111   (let (result)
1112     (dolist (overlay (overlays-in start end))
1113       (push (list (if (> start (overlay-start overlay))
1114                       (- end start)
1115                     (- end (overlay-start overlay)))
1116                   (if (< end (overlay-end overlay))
1117                       0
1118                     (- end (overlay-end overlay)))
1119                   (overlay-properties overlay))
1120             result))
1121     (nreverse result)))
1122
1123 (defun shr-pro-rate-columns (columns)
1124   (let ((total-percentage 0)
1125         (widths (make-vector (length columns) 0)))
1126     (dotimes (i (length columns))
1127       (setq total-percentage (+ total-percentage (aref columns i))))
1128     (setq total-percentage (/ 1.0 total-percentage))
1129     (dotimes (i (length columns))
1130       (aset widths i (max (truncate (* (aref columns i)
1131                                        total-percentage
1132                                        (- shr-width (1+ (length columns)))))
1133                           10)))
1134     widths))
1135
1136 ;; Return a summary of the number and shape of the TDs in the table.
1137 (defun shr-column-specs (cont)
1138   (let ((columns (make-vector (shr-max-columns cont) 1)))
1139     (dolist (row cont)
1140       (when (eq (car row) 'tr)
1141         (let ((i 0))
1142           (dolist (column (cdr row))
1143             (when (memq (car column) '(td th))
1144               (let ((width (cdr (assq :width (cdr column)))))
1145                 (when (and width
1146                            (string-match "\\([0-9]+\\)%" width))
1147                   (aset columns i
1148                         (/ (string-to-number (match-string 1 width))
1149                            100.0))))
1150               (setq i (1+ i)))))))
1151     columns))
1152
1153 (defun shr-count (cont elem)
1154   (let ((i 0))
1155     (dolist (sub cont)
1156       (when (eq (car sub) elem)
1157         (setq i (1+ i))))
1158     i))
1159
1160 (defun shr-max-columns (cont)
1161   (let ((max 0))
1162     (dolist (row cont)
1163       (when (eq (car row) 'tr)
1164         (setq max (max max (+ (shr-count (cdr row) 'td)
1165                               (shr-count (cdr row) 'th))))))
1166     max))
1167
1168 (provide 'shr)
1169
1170 ;;; shr.el ends here