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