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