Revision: miles@gnu.org--gnu-2004/gnus--devo--0--patch-160
[gnus] / lisp / html2text.el
1 ;;; html2text.el --- a simple html to plain text converter
2 ;; Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc.
3
4 ;; Author: Joakim Hove <hove@phys.ntnu.no>
5
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
22
23 ;;; Commentary:
24
25 ;; These functions provide a simple way to wash/clean html infected
26 ;; mails.  Definitely do not work in all cases, but some improvement
27 ;; in readability is generally obtained.  Formatting is only done in
28 ;; the buffer, so the next time you enter the article it will be
29 ;; "re-htmlized".
30 ;;
31 ;; The main function is `html2text'.
32
33 ;;; Code:
34
35 ;;
36 ;; <Global variables>
37 ;;
38
39 (eval-when-compile
40   (require 'cl))
41
42 (defvar html2text-format-single-element-list '(("hr" . html2text-clean-hr)))
43
44 (defvar html2text-replace-list
45   '(("&nbsp;" . " ") ("&gt;" . ">") ("&lt;" . "<") ("&quot;" . "\"")
46     ("&amp;" . "&") ("&apos;" . "'"))
47   "The map of entity to text.
48
49 This is an alist were each element is a dotted pair consisting of an
50 old string, and a replacement string.  This replacement is done by the
51 function `html2text-substitute' which basically performs a
52 `replace-string' operation for every element in the list.  This is
53 completely verbatim - without any use of REGEXP.")
54
55 (defvar html2text-remove-tag-list
56   '("html" "body" "p" "img" "dir" "head" "div" "br" "font" "title" "meta")
57   "A list of removable tags.
58
59 This is a list of tags which should be removed, without any
60 formatting.  Note that tags in the list are presented *without*
61 any \"<\" or \">\".  All occurences of a tag appearing in this
62 list are removed, irrespective of whether it is a closing or
63 opening tag, or if the tag has additional attributes.  The
64 deletion is done by the function `html2text-remove-tags'.
65
66 For instance the text:
67
68 \"Here comes something <font size\"+3\" face=\"Helvetica\"> big </font>.\"
69
70 will be reduced to:
71
72 \"Here comes something big.\"
73
74 If this list contains the element \"font\".")
75
76 (defvar html2text-format-tag-list
77   '(("b"          . html2text-clean-bold)
78     ("strong"     . html2text-clean-bold)
79     ("u"          . html2text-clean-underline)
80     ("i"          . html2text-clean-italic)
81     ("em"         . html2text-clean-italic)
82     ("blockquote" . html2text-clean-blockquote)
83     ("a"          . html2text-clean-anchor)
84     ("ul"         . html2text-clean-ul)
85     ("ol"         . html2text-clean-ol)
86     ("dl"         . html2text-clean-dl)
87     ("center"     . html2text-clean-center))
88   "An alist of tags and processing functions.
89
90 This is an alist where each dotted pair consists of a tag, and then
91 the name of a function to be called when this tag is found.  The
92 function is called with the arguments p1, p2, p3 and p4. These are
93 demontrated below:
94
95 \"<b> This is bold text </b>\"
96  ^   ^                 ^    ^
97  |   |                 |    |
98 p1  p2                p3   p4
99
100 Then the called function will typically format the text somewhat and
101 remove the tags.")
102
103 (defvar html2text-remove-tag-list2  '("li" "dt" "dd" "meta")
104   "Another list of removable tags.
105
106 This is a list of tags which are removed similarly to the list
107 `html2text-remove-tag-list' - but these tags are retained for the
108 formatting, and then moved afterward.")
109
110 ;;
111 ;; </Global variables>
112 ;;
113
114 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
115 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
116
117 ;;
118 ;; <Utility functions>
119 ;;
120
121
122 (defun html2text-replace-string (from-string to-string min max)
123   "Replace FROM-STRING with TO-STRING in region from MIN to MAX."
124   (goto-char min)
125   (let ((delta (- (string-width to-string) (string-width from-string)))
126         (change 0))
127     (while (search-forward from-string max t)
128       (replace-match to-string)
129       (setq change (+ change delta)))
130     change))
131
132 ;;
133 ;; </Utility functions>
134 ;;
135
136 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
137 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
138
139 ;;
140 ;; <Functions related to attributes> i.e. <font size=+3>
141 ;;
142
143 (defun html2text-attr-value (list attribute)
144   "Get value of ATTRIBUTE from LIST."
145   (nth 1 (assoc attribute list)))
146
147 (defun html2text-get-attr (p1 p2 tag)
148   (goto-char p1)
149   (re-search-forward " +[^ ]" p2 t)
150   (let* ((attr-string (buffer-substring-no-properties (1- (point)) (1- p2)))
151          (tmp-list (split-string attr-string))
152          (attr-list)
153          (counter 0)
154          (prev (car tmp-list))
155          (this (nth 1 tmp-list))
156          (next (nth 2 tmp-list))
157          (index 1))
158
159     (cond
160      ;; size=3
161      ((string-match "[^ ]=[^ ]" prev)
162       (let ((attr  (nth 0 (split-string prev "=")))
163             (value (nth 1 (split-string prev "="))))
164         (setq attr-list (cons (list attr value) attr-list))))
165      ;; size= 3
166      ((string-match "[^ ]=\\'" prev)
167       (setq attr-list (cons (list (substring prev 0 -1) this) attr-list))))
168
169     (while (< index (length tmp-list))
170       (cond
171        ;; size=3
172        ((string-match "[^ ]=[^ ]" this)
173         (let ((attr  (nth 0 (split-string this "=")))
174               (value (nth 1 (split-string this "="))))
175           (setq attr-list (cons (list attr value) attr-list))))
176        ;; size =3
177        ((string-match "\\`=[^ ]" this)
178         (setq attr-list (cons (list prev (substring this 1)) attr-list)))
179        ;; size= 3
180        ((string-match "[^ ]=\\'" this)
181         (setq attr-list (cons (list (substring this 0 -1) next) attr-list)))
182        ;; size = 3
183        ((string= "=" this)
184         (setq attr-list (cons (list prev next) attr-list))))
185       (setq index (1+ index))
186       (setq prev this)
187       (setq this next)
188       (setq next (nth (1+ index) tmp-list)))
189     ;;
190     ;; Tags with no accompanying "=" i.e. value=nil
191     ;;
192     (setq prev (car tmp-list))
193     (setq this (nth 1 tmp-list))
194     (setq next (nth 2 tmp-list))
195     (setq index 1)
196
197     (when (and (not (string-match "=" prev))
198                (not (string= (substring this 0 1) "=")))
199       (setq attr-list (cons (list prev nil) attr-list)))
200     (while (< index (1- (length tmp-list)))
201       (when (and (not (string-match "=" this))
202                  (not (or (string= (substring next 0 1) "=")
203                           (string= (substring prev -1) "="))))
204         (setq attr-list (cons (list this nil) attr-list)))
205       (setq index (1+ index))
206       (setq prev this)
207       (setq this next)
208       (setq next (nth (1+ index) tmp-list)))
209
210     (when (and this
211                (not (string-match "=" this))
212                (not (string= (substring prev -1) "=")))
213       (setq attr-list (cons (list this nil) attr-list)))
214     ;; return - value
215     attr-list))
216
217 (defun html2text-get-attr (p1 p2)
218   (save-restriction
219     (narrow-to-region p1 p2)
220     (let (result)
221       (goto-char (point-min))
222       (while (not (eobp))
223         (when (re-search-forward "[^= ]+" nil t)
224           (push
225            (list
226             (match-string 0)
227             (when (looking-at " *= *")
228               (goto-char (match-end 0))
229               (buffer-substring 
230                (point)
231                (goto-char (or (ignore-errors (scan-sexps (point) 1))
232                               (point-max))))))
233            result)))
234       result)))
235 ;;
236 ;; </Functions related to attributes>
237 ;;
238
239 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
240 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
241
242 ;;
243 ;; <Functions to be called to format a tag-pair>
244 ;;
245 (defun html2text-clean-list-items (p1 p2 list-type)
246   (goto-char p1)
247   (let ((item-nr 0)
248         (items   0))
249     (while (search-forward "<li>" p2 t)
250       (setq items (1+ items)))
251     (goto-char p1)
252     (while (< item-nr items)
253       (setq item-nr (1+ item-nr))
254       (search-forward "<li>" (point-max) t)
255       (cond
256        ((string= list-type "ul") (insert " o "))
257        ((string= list-type "ol") (insert (format " %s: " item-nr)))
258        (t (insert " x "))))))
259
260 (defun html2text-clean-dtdd (p1 p2)
261   (goto-char p1)
262   (let ((items   0)
263         (item-nr 0))
264     (while (search-forward "<dt>" p2 t)
265       (setq items (1+ items)))
266     (goto-char p1)
267     (while (< item-nr items)
268       (setq item-nr (1+ item-nr))
269       (re-search-forward "<dt>\\([ ]*\\)" (point-max) t)
270       (when (match-string 1)
271         (delete-region (point) (- (point) (string-width (match-string 1)))))
272       (let ((def-p1 (point))
273             (def-p2 0))
274         (re-search-forward "\\([ ]*\\)\\(</dt>\\|<dd>\\)" (point-max) t)
275         (if (match-string 1)
276             (progn
277               (let* ((mw1 (string-width (match-string 1)))
278                      (mw2 (string-width (match-string 2)))
279                      (mw  (+ mw1 mw2)))
280                 (goto-char (- (point) mw))
281                 (delete-region (point) (+ (point) mw1))
282                 (setq def-p2 (point))))
283           (setq def-p2 (- (point) (string-width (match-string 2)))))
284         (put-text-property def-p1 def-p2 'face 'bold)))))
285
286 (defun html2text-delete-tags (p1 p2 p3 p4)
287   (delete-region p1 p2)
288   (delete-region (- p3 (- p2 p1)) (- p4 (- p2 p1))))
289
290 (defun html2text-delete-single-tag (p1 p2)
291   (delete-region p1 p2))
292
293 (defun html2text-clean-hr (p1 p2)
294   (html2text-delete-single-tag p1 p2)
295   (goto-char p1)
296   (newline 1)
297   (insert (make-string fill-column ?-)))
298
299 (defun html2text-clean-ul (p1 p2 p3 p4)
300   (html2text-delete-tags p1 p2 p3 p4)
301   (html2text-clean-list-items p1 (- p3 (- p1 p2)) "ul"))
302
303 (defun html2text-clean-ol (p1 p2 p3 p4)
304   (html2text-delete-tags p1 p2 p3 p4)
305   (html2text-clean-list-items p1 (- p3 (- p1 p2)) "ol"))
306
307 (defun html2text-clean-dl (p1 p2 p3 p4)
308   (html2text-delete-tags p1 p2 p3 p4)
309   (html2text-clean-dtdd p1 (- p3 (- p1 p2))))
310
311 (defun html2text-clean-center (p1 p2 p3 p4)
312   (html2text-delete-tags p1 p2 p3 p4)
313   (center-region p1 (- p3 (- p2 p1))))
314
315 (defun html2text-clean-bold (p1 p2 p3 p4)
316   (put-text-property p2 p3 'face 'bold)
317   (html2text-delete-tags p1 p2 p3 p4))
318
319 (defun html2text-clean-title (p1 p2 p3 p4)
320   (put-text-property p2 p3 'face 'bold)
321   (html2text-delete-tags p1 p2 p3 p4))
322
323 (defun html2text-clean-underline (p1 p2 p3 p4)
324   (put-text-property p2 p3 'face 'underline)
325   (html2text-delete-tags p1 p2 p3 p4))
326
327 (defun html2text-clean-italic (p1 p2 p3 p4)
328   (put-text-property p2 p3 'face 'italic)
329   (html2text-delete-tags p1 p2 p3 p4))
330
331 (defun html2text-clean-font (p1 p2 p3 p4)
332   (html2text-delete-tags p1 p2 p3 p4))
333
334 (defun html2text-clean-blockquote (p1 p2 p3 p4)
335   (html2text-delete-tags p1 p2 p3 p4))
336
337 (defun html2text-clean-anchor (p1 p2 p3 p4)
338   ;; If someone can explain how to make the URL clickable I will surely
339   ;; improve upon this.
340   ;; Maybe `goto-addr.el' can be used here.
341   (let* ((attr-list (html2text-get-attr p1 p2 "a"))
342          (href (html2text-attr-value attr-list "href")))
343     (delete-region p1 p4)
344     (when href
345       (goto-char p1)
346       (insert (substring href 1 -1 ))
347       (put-text-property p1 (point) 'face 'bold))))
348
349 ;;
350 ;; </Functions to be called to format a tag-pair>
351 ;;
352
353 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
354 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
355
356 ;;
357 ;; <Functions to be called to fix up paragraphs>
358 ;;
359
360 (defun html2text-fix-paragraph (p1 p2)
361   (goto-char p1)
362   (let ((refill-start)
363         (refill-stop))
364     (when (re-search-forward "<br>$" p2 t)
365       (goto-char p1)
366       (when (re-search-forward ".+[^<][^b][^r][^>]$" p2 t)
367         (beginning-of-line)
368         (setq refill-start (point))
369         (goto-char p2)
370         (re-search-backward ".+[^<][^b][^r][^>]$" refill-start t)
371         (next-line 1)
372         (end-of-line)
373         ;; refill-stop should ideally be adjusted to
374         ;; accomodate the "<br>" strings which are removed
375         ;; between refill-start and refill-stop.  Can simply
376         ;; be returned from my-replace-string
377         (setq refill-stop (+ (point)
378                              (html2text-replace-string
379                               "<br>" ""
380                               refill-start (point))))
381         ;; (message "Point = %s  refill-stop = %s" (point) refill-stop)
382         ;; (sleep-for 4)
383         (fill-region refill-start refill-stop))))
384   (html2text-replace-string "<br>" "" p1 p2))
385
386 ;;
387 ;; This one is interactive ...
388 ;;
389 (defun html2text-fix-paragraphs ()
390   "This _tries_ to fix up the paragraphs - this is done in quite a ad-hook
391 fashion, quite close to pure guess-work. It does work in some cases though."
392   (interactive)
393   (goto-char (point-min))
394   (replace-regexp "^<br>$" "")
395   ;; Removing lonely <br> on a single line, if they are left intact we
396   ;; dont have any paragraphs at all.
397   (goto-char (point-min))
398   (while (not (eobp))
399     (let ((p1 (point)))
400       (forward-paragraph 1)
401       ;;(message "Kaller fix med p1=%s  p2=%s " p1 (1- (point))) (sleep-for 5)
402       (html2text-fix-paragraph p1 (1- (point)))
403       (goto-char p1)
404       (when (not (eobp))
405         (forward-paragraph 1)))))
406
407 ;;
408 ;; </Functions to be called to fix up paragraphs>
409 ;;
410
411 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
412 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
413
414 ;;
415 ;; <Interactive functions>
416 ;;
417
418 (defun html2text-remove-tags (tag-list)
419   "Removes the tags listed in the list `html2text-remove-tag-list'.
420 See the documentation for that variable."
421   (interactive)
422   (dolist (tag tag-list)
423     (goto-char (point-min))
424     (while (re-search-forward (format "\\(</?%s[^>]*>\\)" tag) (point-max) t)
425       (delete-region (match-beginning 0) (match-end 0)))))
426
427 (defun html2text-format-tags ()
428   "See the variable `html2text-format-tag-list' for documentation."
429   (interactive)
430   (dolist (tag-and-function html2text-format-tag-list)
431     (let ((tag      (car tag-and-function))
432           (function (cdr tag-and-function)))
433       (goto-char (point-min))
434       (while (re-search-forward (format "\\(<%s\\( [^>]*\\)?>\\)" tag)
435                                 (point-max) t)
436         (let ((p1)
437               (p2 (point))
438               (p3) (p4)
439               (attr (match-string 0)))
440           (search-backward "<" (point-min) t)
441           (setq p1 (point))
442           (search-forward (format "</%s>" tag) (point-max) t)
443           (setq p4 (point))
444           (search-backward "</" (point-min) t)
445           (setq p3 (point))
446           (funcall function p1 p2 p3 p4)
447           (goto-char p1))))))
448
449 (defun html2text-substitute ()
450   "See the variable `html2text-replace-list' for documentation."
451   (interactive)
452   (dolist (e html2text-replace-list)
453     (goto-char (point-min))
454     (let ((old-string (car e))
455           (new-string (cdr e)))
456       (html2text-replace-string old-string new-string (point-min) (point-max)))))
457
458 (defun html2text-format-single-elements ()
459   (interactive)
460   (dolist (tag-and-function html2text-format-single-element-list)
461     (let ((tag      (car tag-and-function))
462           (function (cdr tag-and-function)))
463       (goto-char (point-min))
464       (while (re-search-forward (format "\\(<%s\\( [^>]*\\)?>\\)" tag)
465                                 (point-max) t)
466         (let ((p1)
467               (p2 (point)))
468           (search-backward "<" (point-min) t)
469           (setq p1 (point))
470           (funcall function p1 p2))))))
471
472 ;;
473 ;; Main function
474 ;;
475
476 ;;;###autoload
477 (defun html2text ()
478   "Convert HTML to plain text in the current buffer."
479   (interactive)
480   (save-excursion
481     (let ((case-fold-search t)
482           (buffer-read-only))
483       (html2text-remove-tags html2text-remove-tag-list)
484       (html2text-format-tags)
485       (html2text-remove-tags html2text-remove-tag-list2)
486       (html2text-substitute)
487       (html2text-format-single-elements)
488       (html2text-fix-paragraphs))))
489
490 ;;
491 ;; </Interactive functions>
492 ;;
493 (provide 'html2text)
494 ;;; arch-tag: e9e57b79-35d4-4de1-a647-e7e01fe56d1e
495 ;;; html2text.el ends here