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