22ae79b2b6f295d7273d9c00d09e8345ea7d077d
[elisp/gnus.git-] / lisp / html2text.el
1 ;;; html2text.el --- a simple html to plain text converter
2
3 ;; Copyright (C) 2002 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., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, 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   "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.  Observe that if you the tags in the list are presented
61 *without* any \"<\" or \">\". All occurences of a tag appearing in
62 this list are removed, irrespective of whether it is a closing or
63 opening tag, or if the tag has additional attributes. The actual
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     ("u"          . html2text-clean-underline)
79     ("i"          . html2text-clean-italic)
80     ("blockquote" . html2text-clean-blockquote)
81     ("a"          . html2text-clean-anchor)
82     ("ul"         . html2text-clean-ul)
83     ("ol"         . html2text-clean-ol)
84     ("dl"         . html2text-clean-dl)
85     ("center"     . html2text-clean-center))
86   "An alist of tags and processing functions.
87
88 This is an alist where each dotted pair consists of a tag, and then
89 the name of a function to be called when this tag is found. The
90 function is called with the arguments p1, p2, p3 and p4. These are
91 demontrated below:
92
93 \"<b> This is bold text </b>\"
94  ^   ^                 ^    ^
95  |   |                 |    |
96 p1  p2                p3   p4
97
98 Then the called function will typically format the text somewhat and
99 remove the tags.")
100
101 (defvar html2text-remove-tag-list2  '("li" "dt" "dd" "meta")
102   "Another list of removable tags.
103
104 This is a list of tags which are removed similarly to the list
105 `html2text-remove-tag-list' - but these tags are retained for the
106 formatting, and then moved afterward.")
107
108 ;;
109 ;; </Global variables>
110 ;;
111
112 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
113 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
114
115 ;;
116 ;; <Utility functions>
117 ;;
118
119 (defun html2text-buffer-head ()
120   (if (string= mode-name "Article")
121       (beginning-of-buffer)
122     (beginning-of-buffer)
123     )
124   )
125
126 (defun html2text-replace-string (from-string to-string p1 p2)
127   (goto-char p1)
128   (let ((delta (- (string-width to-string) (string-width from-string)))
129         (change 0))
130     (while (search-forward from-string p2 t)
131       (replace-match to-string)
132       (setq change (+ change delta))
133       )
134     change
135     )
136   )
137
138 ;;
139 ;; </Utility functions>
140 ;;
141
142 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
143 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
144
145 ;;
146 ;; <Functions related to attributes> i.e. <font size=+3>
147 ;;
148
149 (defun html2text-attr-value (attr-list attr)
150   (nth 1 (assoc attr attr-list))
151   )
152
153 (defun html2text-get-attr (p1 p2 tag)
154   (goto-char p1)
155   (re-search-forward " +[^ ]" p2 t)
156   (let* ((attr-string (buffer-substring-no-properties (1- (point)) (1- p2)))
157          (tmp-list (split-string attr-string))
158          (attr-list)
159          (counter 0)
160          (prev (car tmp-list))
161          (this (nth 1 tmp-list))
162          (next (nth 2 tmp-list))
163          (index 1))
164
165     (cond
166      ;; size=3
167      ((string-match "[^ ]=[^ ]" prev)
168       (let ((attr  (nth 0 (split-string prev "=")))
169             (value (nth 1 (split-string prev "="))))
170         (setq attr-list (cons (list attr value) attr-list))
171         )
172       )
173      ;; size= 3
174      ((string-match "[^ ]=\\'" prev)
175       (setq attr-list (cons (list (substring prev 0 -1) this) attr-list))
176       )
177      )
178
179     (while (< index (length tmp-list))
180       (cond
181        ;; size=3
182        ((string-match "[^ ]=[^ ]" this)
183         (let ((attr  (nth 0 (split-string this "=")))
184               (value (nth 1 (split-string this "="))))
185           (setq attr-list (cons (list attr value) attr-list))
186           )
187         )
188        ;; size =3
189        ((string-match "\\`=[^ ]" this)
190         (setq attr-list (cons (list prev (substring this 1)) attr-list)))
191
192        ;; size= 3
193        ((string-match "[^ ]=\\'" this)
194         (setq attr-list (cons (list (substring this 0 -1) next) attr-list))
195         )
196
197        ;; size = 3
198        ((string= "=" this)
199         (setq attr-list (cons (list prev next) attr-list))
200         )
201        )
202       (setq index (1+ index))
203       (setq prev this)
204       (setq this next)
205       (setq next (nth (1+ index) tmp-list))
206       )
207
208     ;;
209     ;; Tags with no accompanying "=" i.e. value=nil
210     ;;
211     (setq prev (car tmp-list))
212     (setq this (nth 1 tmp-list))
213     (setq next (nth 2 tmp-list))
214     (setq index 1)
215
216     (if (not (string-match "=" prev))
217         (progn
218           (if (not (string= (substring this 0 1) "="))
219               (setq attr-list (cons (list prev nil) attr-list))
220             )
221           )
222       )
223
224     (while (< index (1- (length tmp-list)))
225       (if (not (string-match "=" this))
226           (if (not (or (string= (substring next 0 1) "=")
227                        (string= (substring prev -1) "=")))
228               (setq attr-list (cons (list this nil) attr-list))
229             )
230         )
231       (setq index (1+ index))
232       (setq prev this)
233       (setq this next)
234       (setq next (nth (1+ index) tmp-list))
235       )
236
237     (if this
238         (progn
239           (if (not (string-match "=" this))
240               (progn
241                 (if (not (string= (substring prev -1) "="))
242                     (setq attr-list (cons (list this nil) attr-list))
243                   )
244                 )
245             )
246           )
247       )
248     attr-list ;; return - value
249     )
250   )
251
252 ;;
253 ;; </Functions related to attributes>
254 ;;
255
256 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
257 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
258
259 ;;
260 ;; <Functions to be called to format a tag-pair>
261 ;;
262 (defun html2text-clean-list-items (p1 p2 list-type)
263   (goto-char p1)
264   (let ((item-nr 0)
265         (items   0))
266     (while (re-search-forward "<li>" p2 t)
267       (setq items (1+ items)))
268     (goto-char p1)
269     (while (< item-nr items)
270       (setq item-nr (1+ item-nr))
271       (re-search-forward "<li>" (point-max) t)
272       (cond
273        ((string= list-type "ul") (insert " o "))
274        ((string= list-type "ol") (insert (format " %s: " item-nr)))
275        (t (insert " x ")))
276       )
277     )
278   )
279
280 (defun html2text-clean-dtdd (p1 p2)
281   (goto-char p1)
282   (let ((items   0)
283         (item-nr 0))
284     (while (re-search-forward "<dt>" p2 t)
285       (setq items (1+ items)))
286     (goto-char p1)
287     (while (< item-nr items)
288       (setq item-nr (1+ item-nr))
289       (re-search-forward "<dt>\\([ ]*\\)" (point-max) t)
290       (if (match-string 1)
291           (kill-region (point) (- (point) (string-width (match-string 1))))
292         )
293       (let ((def-p1 (point))
294             (def-p2 0))
295         (re-search-forward "\\([ ]*\\)\\(</dt>\\|<dd>\\)" (point-max) t)
296         (if (match-string 1)
297             (progn
298               (let* ((mw1 (string-width (match-string 1)))
299                      (mw2 (string-width (match-string 2)))
300                      (mw  (+ mw1 mw2)))
301                 (goto-char (- (point) mw))
302                 (kill-region (point) (+ (point) mw1))
303                 (setq def-p2 (point))
304                 )
305               )
306           (setq def-p2 (- (point) (string-width (match-string 2)))))
307         (put-text-property def-p1 def-p2 'face 'bold)
308         )
309       )
310     )
311   )
312
313 (defun html2text-delete-tags (p1 p2 p3 p4)
314   (kill-region p1 p2)
315   (kill-region (- p3 (- p2 p1)) (- p4 (- p2 p1)))
316   )
317
318 (defun html2text-delete-single-tag (p1 p2)
319   (kill-region p1 p2)
320   )
321
322 (defun html2text-clean-hr (p1 p2)
323   (html2text-delete-single-tag p1 p2)
324   (goto-char p1)
325   (newline 1)
326   (insert (make-string fill-column ?-))
327   )
328
329 (defun html2text-clean-ul (p1 p2 p3 p4)
330   (html2text-delete-tags p1 p2 p3 p4)
331   (html2text-clean-list-items p1 (- p3 (- p1 p2)) "ul")
332   )
333
334 (defun html2text-clean-ol (p1 p2 p3 p4)
335   (html2text-delete-tags p1 p2 p3 p4)
336   (html2text-clean-list-items p1 (- p3 (- p1 p2)) "ol")
337   )
338
339 (defun html2text-clean-dl (p1 p2 p3 p4)
340   (html2text-delete-tags p1 p2 p3 p4)
341   (html2text-clean-dtdd p1 (- p3 (- p1 p2)))
342   )
343
344 (defun html2text-clean-center (p1 p2 p3 p4)
345   (html2text-delete-tags p1 p2 p3 p4)
346   (center-region p1 (- p3 (- p2 p1)))
347   )
348
349 (defun html2text-clean-bold (p1 p2 p3 p4)
350   (put-text-property p2 p3 'face 'bold)
351   (html2text-delete-tags p1 p2 p3 p4)
352   )
353
354 (defun html2text-clean-title (p1 p2 p3 p4)
355   (put-text-property p2 p3 'face 'bold)
356   (html2text-delete-tags p1 p2 p3 p4)
357   )
358
359 (defun html2text-clean-underline (p1 p2 p3 p4)
360   (put-text-property p2 p3 'face 'underline)
361   (html2text-delete-tags p1 p2 p3 p4)
362   )
363
364 (defun html2text-clean-italic (p1 p2 p3 p4)
365   (put-text-property p2 p3 'face 'italic)
366   (html2text-delete-tags p1 p2 p3 p4)
367   )
368
369 (defun html2text-clean-font (p1 p2 p3 p4)
370   (html2text-delete-tags p1 p2 p3 p4)
371   )
372
373 (defun html2text-clean-blockquote (p1 p2 p3 p4)
374   (html2text-delete-tags p1 p2 p3 p4)
375   )
376
377 (defun html2text-clean-anchor (p1 p2 p3 p4)
378   ;; If someone can explain how to make the URL clickable I will
379   ;; surely improve upon this.
380   (let* ((attr-list (html2text-get-attr p1 p2 "a"))
381          (href (html2text-attr-value attr-list "href")))
382     (kill-region p1 p4)
383     (when href
384       (goto-char p1)
385       (insert (substring href 1 -1 ))
386       (put-text-property p1 (point) 'face 'bold))))
387
388 ;;
389 ;; </Functions to be called to format a tag-pair>
390 ;;
391
392 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
393 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
394
395 ;;
396 ;; <Functions to be called to fix up paragraphs>
397 ;;
398
399 (defun html2text-fix-paragraph (p1 p2)
400   (goto-char p1)
401   (let ((has-br-line)
402         (refill-start)
403         (refill-stop))
404     (if (re-search-forward "<br>$" p2 t)
405         (setq has-br-line t)
406       )
407     (if has-br-line
408         (progn
409           (goto-char p1)
410           (if (re-search-forward ".+[^<][^b][^r][^>]$" p2 t)
411               (progn
412                 (beginning-of-line)
413                 (setq refill-start (point))
414                 (goto-char p2)
415                 (re-search-backward ".+[^<][^b][^r][^>]$" refill-start t)
416                 (next-line 1)
417                 (end-of-line)
418                 ;; refill-stop should ideally be adjusted to
419                 ;; accomodate the "<br>" strings which are removed
420                 ;; between refill-start and refill-stop.  Can simply
421                 ;; be returned from my-replace-string
422                 (setq refill-stop (+ (point)
423                                      (html2text-replace-string
424                                       "<br>" ""
425                                       refill-start (point))))
426                 ;; (message "Point = %s  refill-stop = %s" (point) refill-stop)
427                 ;; (sleep-for 4)
428                 (fill-region refill-start refill-stop)
429                 )
430             )
431           )
432       )
433     )
434   (html2text-replace-string "<br>" "" p1 p2)
435   )
436
437 ;;
438 ;; This one is interactive ...
439 ;;
440 (defun html2text-fix-paragraphs ()
441   "This _tries_ to fix up the paragraphs - this is done in quite a ad-hook
442 fashion, quite close to pure guess-work. It does work in some cases though."
443   (interactive)
444   (html2text-buffer-head)
445   (replace-regexp "^<br>$" "")
446   ;; Removing lonely <br> on a single line, if they are left intact we
447   ;; dont have any paragraphs at all.
448   (html2text-buffer-head)
449   (while (< (point) (point-max))
450     (let ((p1 (point)))
451       (forward-paragraph 1)
452       ;;(message "Kaller fix med p1=%s  p2=%s " p1 (1- (point))) (sleep-for 5)
453       (html2text-fix-paragraph p1 (1- (point)))
454       (goto-char p1)
455       (if (< (point) (point-max))
456           (forward-paragraph 1))
457       )
458     )
459   )
460
461 ;;
462 ;; </Functions to be called to fix up paragraphs>
463 ;;
464
465 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
466 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
467
468 ;;
469 ;; <Interactive functions>
470 ;;
471
472 (defun html2text-remove-tags (tag-list)
473   "Removes the tags listed in the list \"html2text-remove-tag-list\".
474 See the documentation for that variable."
475   (interactive)
476   (dolist (tag tag-list)
477     (html2text-buffer-head)
478     (while (re-search-forward (format "\\(</?%s[^>]*>\\)" tag) (point-max) t)
479       (let ((p1 (point)))
480         (search-backward "<")
481         (kill-region (point) p1)
482         )
483       )
484     )
485   )
486
487 (defun html2text-format-tags ()
488   "See the variable \"html2text-format-tag-list\" for documentation"
489   (interactive)
490   (dolist (tag-and-function html2text-format-tag-list)
491     (let ((tag      (car tag-and-function))
492           (function (cdr tag-and-function)))
493       (html2text-buffer-head)
494       (while (re-search-forward (format "\\(<%s\\( [^>]*\\)?>\\)" tag)
495                                 (point-max) t)
496         (let ((p1)
497               (p2 (point))
498               (p3) (p4)
499               (attr (match-string 1)))
500           (search-backward "<" (point-min) t)
501           (setq p1 (point))
502           (re-search-forward (format "</%s>" tag) (point-max) t)
503           (setq p4 (point))
504           (search-backward "</" (point-min) t)
505           (setq p3 (point))
506           (funcall function p1 p2 p3 p4)
507           (goto-char p1)
508           )
509         )
510       )
511     )
512   )
513
514 (defun html2text-substitute ()
515   "See the variable \"html2text-replace-list\" for documentation"
516   (interactive)
517   (dolist (e html2text-replace-list)
518     (html2text-buffer-head)
519     (let ((old-string (car e))
520           (new-string (cdr e)))
521       (html2text-replace-string old-string new-string (point-min) (point-max))
522       )
523     )
524   )
525
526 (defun html2text-format-single-elements ()
527   ""
528   (interactive)
529   (dolist (tag-and-function html2text-format-single-element-list)
530     (let ((tag      (car tag-and-function))
531           (function (cdr tag-and-function)))
532       (html2text-buffer-head)
533       (while (re-search-forward (format "\\(<%s\\( [^>]*\\)?>\\)" tag)
534                                 (point-max) t)
535         (let ((p1)
536               (p2 (point)))
537           (search-backward "<" (point-min) t)
538           (setq p1 (point))
539           (funcall function p1 p2)
540           )
541         )
542       )
543     )
544   )
545
546 ;;
547 ;; Main function
548 ;;
549
550 ;;;###autoload
551 (defun html2text ()
552   "Convert HTML to plain text in the current buffer."
553   (interactive)
554   (save-excursion
555     (let ((case-fold-search t)
556           (buffer-read-only))
557       (html2text-remove-tags html2text-remove-tag-list)
558       (html2text-format-tags)
559       (html2text-remove-tags html2text-remove-tag-list2)
560       (html2text-substitute)
561       (html2text-format-single-elements)
562       (html2text-fix-paragraphs))))
563
564 ;;
565 ;; </Interactive functions>
566 ;;
567
568 ;;; html2text.el ends here