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