initial commit
[emacs-init.git] / auto-install / htmlize.el
1 ;;; htmlize.el -- Convert buffer text and decorations to HTML.
2
3 ;; Copyright (C) 1997,1998,1999,2000,2001,2002,2003,2005,2006 Hrvoje Niksic
4
5 ;; Author: Hrvoje Niksic <hniksic@xemacs.org>
6 ;; Modified by: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: hypermedia, extensions
8
9 ;; This program 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 ;; This program 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 this program; 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 ;; This package converts the buffer text and the associated
27 ;; decorations to HTML.  Mail to <hniksic@xemacs.org> to discuss
28 ;; features and additions.  All suggestions are more than welcome.
29
30 ;; To use this, just switch to the buffer you want HTML-ized and type
31 ;; `M-x htmlize-buffer'.  You will be switched to a new buffer that
32 ;; contains the resulting HTML code.  You can edit and inspect this
33 ;; buffer, or you can just save it with C-x C-w.  `M-x htmlize-file'
34 ;; will find a file, fontify it, and save the HTML version in
35 ;; FILE.html, without any additional intervention.  `M-x
36 ;; htmlize-many-files' allows you to htmlize any number of files in
37 ;; the same manner.  `M-x htmlize-many-files-dired' does the same for
38 ;; files marked in a dired buffer.
39
40 ;; htmlize supports three types of HTML output, selected by setting
41 ;; `htmlize-output-type': `css', `inline-css', and `font'.  In `css'
42 ;; mode, htmlize uses cascading style sheets to specify colors; it
43 ;; generates classes that correspond to Emacs faces and uses <span
44 ;; class=FACE>...</span> to color parts of text.  In this mode, the
45 ;; produced HTML is valid under the 4.01 strict DTD, as confirmed by
46 ;; the W3C validator.  `inline-css' is like `css', except the CSS is
47 ;; put directly in the STYLE attribute of the SPAN element, making it
48 ;; possible to paste the generated HTML to other documents.  In `font'
49 ;; mode, htmlize uses <font color="...">...</font> to colorize HTML,
50 ;; which is not standard-compliant, but works better in older
51 ;; browsers.  `css' mode is the default.
52
53 ;; You can also use htmlize from your Emacs Lisp code.  When called
54 ;; non-interactively, `htmlize-buffer' and `htmlize-region' will
55 ;; return the resulting HTML buffer, but will not change current
56 ;; buffer or move the point.
57
58 ;; I tried to make the package elisp-compatible with multiple Emacsen,
59 ;; specifically aiming for XEmacs 19.14+ and GNU Emacs 19.34+.  Please
60 ;; let me know if it doesn't work on some of those, and I'll try to
61 ;; fix it.  I relied heavily on the presence of CL extensions,
62 ;; especially for cross-emacs compatibility; please don't try to
63 ;; remove that particular dependency.  When byte-compiling under GNU
64 ;; Emacs, you're likely to get some warnings; just ignore them.
65
66 ;; The latest version should be available at:
67 ;;
68 ;;        <http://fly.srk.fer.hr/~hniksic/emacs/htmlize.el>
69 ;;
70 ;; You can find a sample of htmlize's output (possibly generated with
71 ;; an older version) at:
72 ;;
73 ;;        <http://fly.srk.fer.hr/~hniksic/emacs/htmlize.el.html>
74
75 ;; Thanks go to the multitudes of people who have sent reports and
76 ;; contributed comments, suggestions, and fixes.  They include Ron
77 ;; Gut, Bob Weiner, Toni Drabik, Peter Breton, Thomas Vogels, Juri
78 ;; Linkov, Maciek Pasternacki, and many others.
79
80 ;; User quotes: "You sir, are a sick, sick, _sick_ person. :)"
81 ;;                  -- Bill Perry, author of Emacs/W3
82
83  
84 ;;; Code:
85
86 (require 'cl)
87 (eval-when-compile
88   (if (string-match "XEmacs" emacs-version)
89       (byte-compiler-options
90         (warnings (- unresolved))))
91   (defvar font-lock-auto-fontify)
92   (defvar font-lock-support-mode)
93   (defvar global-font-lock-mode)
94   (when (and (eq emacs-major-version 19)
95              (not (string-match "XEmacs" emacs-version)))
96     ;; Older versions of GNU Emacs fail to autoload cl-extra even when
97     ;; `cl' is loaded.
98     (load "cl-extra")))
99
100 (defconst htmlize-version "1.34")
101
102 ;; Incantations to make custom stuff work without customize, e.g. on
103 ;; XEmacs 19.14 or GNU Emacs 19.34.
104 (eval-and-compile
105   (condition-case ()
106       (require 'custom)
107     (error nil))
108   (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
109       nil                               ; we've got what we needed
110     ;; No custom or obsolete custom, define surrogates.  Define all
111     ;; three macros, so we don't hose another library that expects
112     ;; e.g. `defface' to work after (fboundp 'defcustom) succeeds.
113     (defmacro defgroup (&rest ignored) nil)
114     (defmacro defcustom (var value doc &rest ignored)
115       `(defvar ,var ,value ,doc))
116     (defmacro defface (face value doc &rest stuff)
117       `(make-face ,face))))
118
119 (defgroup htmlize nil
120   "Convert buffer text and faces to HTML."
121   :group 'hypermedia)
122
123 (defcustom htmlize-head-tags ""
124   "*Additional tags to insert within HEAD of the generated document."
125   :type 'string
126   :group 'htmlize)
127
128 (defcustom htmlize-output-type 'css
129   "*Output type of generated HTML, one of `css', `inline-css', or `font'.
130 When set to `css' (the default), htmlize will generate a style sheet
131 with description of faces, and use it in the HTML document, specifying
132 the faces in the actual text with <span class=\"FACE\">.
133
134 When set to `inline-css', the style will be generated as above, but
135 placed directly in the STYLE attribute of the span ELEMENT: <span
136 style=\"STYLE\">.  This makes it easier to paste the resulting HTML to
137 other documents.
138
139 When set to `font', the properties will be set using layout tags
140 <font>, <b>, <i>, <u>, and <strike>.
141
142 `css' output is normally preferred, but `font' is still useful for
143 supporting old, pre-CSS browsers, and both `inline-css' and `font' for
144 easier embedding of colorized text in foreign HTML documents (no style
145 sheet to carry around)."
146   :type '(choice (const css) (const inline-css) (const font))
147   :group 'htmlize)
148
149 (defcustom htmlize-generate-hyperlinks t
150   "*Non-nil means generate the hyperlinks for URLs and mail addresses.
151 This is on by default; set it to nil if you don't want htmlize to
152 insert hyperlinks in the resulting HTML.  (In which case you can still
153 do your own hyperlinkification from htmlize-after-hook.)"
154   :type 'boolean
155   :group 'htmlize)
156
157 (defcustom htmlize-hyperlink-style "
158       a {
159         color: inherit;
160         background-color: inherit;
161         font: inherit;
162         text-decoration: inherit;
163       }
164       a:hover {
165         text-decoration: underline;
166       }
167 "
168   "*The CSS style used for hyperlinks when in CSS mode."
169   :type 'string
170   :group 'htmlize)
171
172 (defcustom htmlize-replace-form-feeds t
173   "*Non-nil means replace form feeds in source code with HTML separators.
174 Form feeds are the ^L characters at line beginnings that are sometimes
175 used to separate sections of source code.  If this variable is set to
176 `t', form feed characters are replaced with the <hr> separator.  If this
177 is a string, it specifies the replacement to use.  Note that <pre> is
178 temporarily closed before the separator is inserted, so the default
179 replacement is effectively \"</pre><hr /><pre>\".  If you specify
180 another replacement, don't forget to close and reopen the <pre> if you
181 want the output to remain valid HTML.
182
183 If you need more elaborate processing, set this to nil and use
184 htmlize-after-hook."
185   :type 'boolean
186   :group 'htmlize)
187
188 (defcustom htmlize-html-charset nil
189   "*The charset declared by the resulting HTML documents.
190 When non-nil, causes htmlize to insert the following in the HEAD section
191 of the generated HTML:
192
193   <meta http-equiv=\"Content-Type\" content=\"text/html; charset=CHARSET\">
194
195 where CHARSET is the value you've set for htmlize-html-charset.  Valid
196 charsets are defined by MIME and include strings like \"iso-8859-1\",
197 \"iso-8859-15\", \"utf-8\", etc.
198
199 If you are using non-Latin-1 charsets, you might need to set this for
200 your documents to render correctly.  Also, the W3C validator requires
201 submitted HTML documents to declare a charset.  So if you care about
202 validation, you can use this to prevent the validator from bitching.
203
204 Needless to say, if you set this, you should actually make sure that
205 the buffer is in the encoding you're claiming it is in.  (Under Mule
206 that is done by ensuring the correct \"file coding system\" for the
207 buffer.)  If you don't understand what that means, this option is
208 probably not for you."
209   :type '(choice (const :tag "Unset" nil)
210                  string)
211   :group 'htmlize)
212
213 (defcustom htmlize-convert-nonascii-to-entities (featurep 'mule)
214   "*Whether non-ASCII characters should be converted to HTML entities.
215
216 When this is non-nil, characters with codes in the 128-255 range will be
217 considered Latin 1 and rewritten as \"&#CODE;\".  Characters with codes
218 above 255 will be converted to \"&#UCS;\", where UCS denotes the Unicode
219 code point of the character.  If the code point cannot be determined,
220 the character will be copied unchanged, as would be the case if the
221 option were nil.
222
223 When the option is nil, the non-ASCII characters are copied to HTML
224 without modification.  In that case, the web server and/or the browser
225 must be set to understand the encoding that was used when saving the
226 buffer.  (You might also want to specify it by setting
227 `htmlize-html-charset'.)
228
229 Note that in an HTML entity \"&#CODE;\", CODE is always a UCS code point,
230 which has nothing to do with the charset the page is in.  For example,
231 \"&#169;\" *always* refers to the copyright symbol, regardless of charset
232 specified by the META tag or the charset sent by the HTTP server.  In
233 other words, \"&#169;\" is exactly equivalent to \"&copy;\".
234
235 By default, entity conversion is turned on for Mule-enabled Emacsen and
236 turned off otherwise.  This is because Mule knows the charset of
237 non-ASCII characters in the buffer.  A non-Mule Emacs cannot tell
238 whether a character with code 0xA9 represents Latin 1 copyright symbol,
239 Latin 2 \"S with caron\", or something else altogether.  Setting this to
240 t without Mule means asserting that 128-255 characters always mean Latin
241 1.
242
243 For most people htmlize will work fine with this option left at the
244 default setting; don't change it unless you know what you're doing."
245   :type 'sexp
246   :group 'htmlize)
247
248 (defcustom htmlize-ignore-face-size 'absolute
249   "*Whether face size should be ignored when generating HTML.
250 If this is nil, face sizes are used.  If set to t, sizes are ignored
251 If set to `absolute', only absolute size specifications are ignored.
252 Please note that font sizes only work with CSS-based output types."
253   :type '(choice (const :tag "Don't ignore" nil)
254                  (const :tag "Ignore all" t)
255                  (const :tag "Ignore absolute" absolute))
256   :group 'htmlize)
257
258 (defcustom htmlize-css-name-prefix ""
259   "*The prefix used for CSS names.
260 The CSS names that htmlize generates from face names are often too
261 generic for CSS files; for example, `font-lock-type-face' is transformed
262 to `type'.  Use this variable to add a prefix to the generated names.
263 The string \"htmlize-\" is an example of a reasonable prefix."
264   :type 'string
265   :group 'htmlize)
266
267 (defcustom htmlize-use-rgb-txt t
268   "*Whether `rgb.txt' should be used to convert color names to RGB.
269
270 This conversion means determining, for instance, that the color
271 \"IndianRed\" corresponds to the (205, 92, 92) RGB triple.  `rgb.txt'
272 is the X color database that maps hundreds of color names to such RGB
273 triples.  When this variable is non-nil, `htmlize' uses `rgb.txt' to
274 look up color names.
275
276 If this variable is nil, htmlize queries Emacs for RGB components of
277 colors using `color-instance-rgb-components' and `x-color-values'.
278 This can yield incorrect results on non-true-color displays.
279
280 If the `rgb.txt' file is not found (which will be the case if you're
281 running Emacs on non-X11 systems), this option is ignored."
282   :type 'boolean
283   :group 'htmlize)
284
285 (defcustom htmlize-html-major-mode nil
286   "The mode the newly created HTML buffer will be put in.
287 Set this to nil if you prefer the default (fundamental) mode."
288   :type '(radio (const :tag "No mode (fundamental)" nil)
289                  (function-item html-mode)
290                  (function :tag "User-defined major mode"))
291   :group 'htmlize)
292
293 (defvar htmlize-before-hook nil
294   "Hook run before htmlizing a buffer.
295 The hook functions are run in the source buffer (not the resulting HTML
296 buffer).")
297
298 (defvar htmlize-after-hook nil
299   "Hook run after htmlizing a buffer.
300 Unlike `htmlize-before-hook', these functions are run in the generated
301 HTML buffer.  You may use them to modify the outlook of the final HTML
302 output.")
303
304 (defvar htmlize-file-hook nil
305   "Hook run by `htmlize-file' after htmlizing a file, but before saving it.")
306
307 (defvar htmlize-buffer-places)
308  
309 ;;; Some cross-Emacs compatibility.
310
311 ;; I try to conditionalize on features rather than Emacs version, but
312 ;; in some cases checking against the version *is* necessary.
313 (defconst htmlize-running-xemacs (string-match "XEmacs" emacs-version))
314
315 (eval-and-compile
316   ;; save-current-buffer, with-current-buffer, and with-temp-buffer
317   ;; are not available in 19.34 and in older XEmacsen.  Strictly
318   ;; speaking, we should stick to our own namespace and define and use
319   ;; htmlize-save-current-buffer, etc.  But non-standard special forms
320   ;; are a pain because they're not properly fontified or indented and
321   ;; because they look weird and ugly.  So I'll just go ahead and
322   ;; define the real ones if they're not available.  If someone
323   ;; convinces me that this breaks something, I'll switch to the
324   ;; "htmlize-" namespace.
325   (unless (fboundp 'save-current-buffer)
326     (defmacro save-current-buffer (&rest forms)
327       `(let ((__scb_current (current-buffer)))
328          (unwind-protect
329              (progn ,@forms)
330            (set-buffer __scb_current)))))
331   (unless (fboundp 'with-current-buffer)
332     (defmacro with-current-buffer (buffer &rest forms)
333       `(save-current-buffer (set-buffer ,buffer) ,@forms)))
334   (unless (fboundp 'with-temp-buffer)
335     (defmacro with-temp-buffer (&rest forms)
336       (let ((temp-buffer (gensym "tb-")))
337         `(let ((,temp-buffer
338                 (get-buffer-create (generate-new-buffer-name " *temp*"))))
339            (unwind-protect
340                (with-current-buffer ,temp-buffer
341                  ,@forms)
342              (and (buffer-live-p ,temp-buffer)
343                   (kill-buffer ,temp-buffer))))))))
344
345 ;; We need a function that efficiently finds the next change of a
346 ;; property (usually `face'), preferably regardless of whether the
347 ;; change occurred because of a text property or an extent/overlay.
348 ;; As it turns out, it is not easy to do that compatibly.
349 ;;
350 ;; Under XEmacs, `next-single-property-change' does that.  Under GNU
351 ;; Emacs beginning with version 21, `next-single-char-property-change'
352 ;; is available and does the same.  GNU Emacs 20 had
353 ;; `next-char-property-change', which we can use.  GNU Emacs 19 didn't
354 ;; provide any means for simultaneously examining overlays and text
355 ;; properties, so when using Emacs 19.34, we punt and fall back to
356 ;; `next-single-property-change', thus ignoring overlays altogether.
357
358 (cond
359  (htmlize-running-xemacs
360   ;; XEmacs: good.
361   (defun htmlize-next-change (pos prop &optional limit)
362     (next-single-property-change pos prop nil (or limit (point-max)))))
363  ((fboundp 'next-single-char-property-change)
364   ;; GNU Emacs 21: good.
365   (defun htmlize-next-change (pos prop &optional limit)
366     (next-single-char-property-change pos prop nil limit)))
367  ((fboundp 'next-char-property-change)
368   ;; GNU Emacs 20: bad, but fixable.
369   (defun htmlize-next-change (pos prop &optional limit)
370     (let ((done nil)
371           (current-value (get-char-property pos prop))
372           newpos next-value)
373       ;; Loop over positions returned by next-char-property-change
374       ;; until the value of PROP changes or we've hit EOB.
375       (while (not done)
376         (setq newpos (next-char-property-change pos limit)
377               next-value (get-char-property newpos prop))
378         (cond ((eq newpos pos)
379                ;; Possibly at EOB?  Whatever, just don't infloop.
380                (setq done t))
381               ((eq next-value current-value)
382                ;; PROP hasn't changed -- keep looping.
383                )
384               (t
385                (setq done t)))
386         (setq pos newpos))
387       pos)))
388  (t
389   ;; GNU Emacs 19.34: hopeless, cannot properly support overlays.
390   (defun htmlize-next-change (pos prop &optional limit)
391     (unless limit
392       (setq limit (point-max)))
393     (let ((res (next-single-property-change pos prop)))
394       (if (or (null res)
395               (> res limit))
396           limit
397         res)))))
398  
399 ;;; Transformation of buffer text: HTML escapes, untabification, etc.
400
401 (defvar htmlize-basic-character-table
402   ;; Map characters in the 0-127 range to either one-character strings
403   ;; or to numeric entities.
404   (let ((table (make-vector 128 ?\0)))
405     ;; Map characters in the 32-126 range to themselves, others to
406     ;; &#CODE entities;
407     (dotimes (i 128)
408       (setf (aref table i) (if (and (>= i 32) (<= i 126))
409                                (char-to-string i)
410                              (format "&#%d;" i))))
411     ;; Set exceptions manually.
412     (setf
413      ;; Don't escape newline, carriage return, and TAB.
414      (aref table ?\n) "\n"
415      (aref table ?\r) "\r"
416      (aref table ?\t) "\t"
417      ;; Escape &, <, and >.
418      (aref table ?&) "&amp;"
419      (aref table ?<) "&lt;"
420      (aref table ?>) "&gt;"
421      ;; Not escaping '"' buys us a measurable speedup.  It's only
422      ;; necessary to quote it for strings used in attribute values,
423      ;; which htmlize doesn't do.
424      ;(aref table ?\") "&quot;"
425      )
426     table))
427
428 ;; A cache of HTML representation of non-ASCII characters.  Depending
429 ;; on availability of `encode-char' and the setting of
430 ;; `htmlize-convert-nonascii-to-entities', this maps non-ASCII
431 ;; characters to either "&#<code>;" or "<char>" (mapconcat's mapper
432 ;; must always return strings).  It's only filled as characters are
433 ;; encountered, so that in a buffer with e.g. French text, it will
434 ;; only ever contain French accented characters as keys.  It's cleared
435 ;; on each entry to htmlize-buffer-1 to allow modifications of
436 ;; `htmlize-convert-nonascii-to-entities' to take effect.
437 (defvar htmlize-extended-character-cache (make-hash-table :test 'eq))
438
439 (defun htmlize-protect-string (string)
440   "HTML-protect string, escaping HTML metacharacters and I18N chars."
441   ;; Only protecting strings that actually contain unsafe or non-ASCII
442   ;; chars removes a lot of unnecessary funcalls and consing.
443   (if (not (string-match "[^\r\n\t -%'-;=?-~]" string))
444       string
445     (mapconcat (lambda (char)
446                  (cond
447                   ((< char 128)
448                    ;; ASCII: use htmlize-basic-character-table.
449                    (aref htmlize-basic-character-table char))
450                   ((gethash char htmlize-extended-character-cache)
451                    ;; We've already seen this char; return the cached
452                    ;; string.
453                    )
454                   ((not htmlize-convert-nonascii-to-entities)
455                    ;; If conversion to entities is not desired, always
456                    ;; copy the char literally.
457                    (setf (gethash char htmlize-extended-character-cache)
458                          (char-to-string char)))
459                   ((< char 256)
460                    ;; Latin 1: no need to call encode-char.
461                    (setf (gethash char htmlize-extended-character-cache)
462                          (format "&#%d;" char)))
463                   ((and (fboundp 'encode-char)
464                         ;; Must check if encode-char works for CHAR;
465                         ;; it fails for Arabic and possibly elsewhere.
466                         (encode-char char 'ucs))
467                    (setf (gethash char htmlize-extended-character-cache)
468                          (format "&#%d;" (encode-char char 'ucs))))
469                   (t
470                    ;; encode-char doesn't work for this char.  Copy it
471                    ;; unchanged and hope for the best.
472                    (setf (gethash char htmlize-extended-character-cache)
473                          (char-to-string char)))))
474                string "")))
475
476 (defconst htmlize-ellipsis "...")
477 (put-text-property 0 (length htmlize-ellipsis) 'htmlize-ellipsis t htmlize-ellipsis)
478
479 (defun htmlize-buffer-substring-no-invisible (beg end)
480   ;; Like buffer-substring-no-properties, but don't copy invisible
481   ;; parts of the region.  Where buffer-substring-no-properties
482   ;; mandates an ellipsis to be shown, htmlize-ellipsis is inserted.
483   (let ((pos beg)
484         visible-list invisible show next-change)
485     ;; Iterate over the changes in the `invisible' property and filter
486     ;; out the portions where it's non-nil, i.e. where the text is
487     ;; invisible.
488     (while (< pos end)
489       (setq invisible (get-char-property pos 'invisible)
490             next-change (htmlize-next-change pos 'invisible end))
491       (if (not (listp buffer-invisibility-spec))
492           ;; If buffer-invisibility-spec is not a list, then all
493           ;; characters with non-nil `invisible' property are visible.
494           (setq show (not invisible))
495         ;; Otherwise, the value of a non-nil `invisible' property can be:
496         ;; 1. a symbol -- make the text invisible if it matches
497         ;;    buffer-invisibility-spec.
498         ;; 2. a list of symbols -- make the text invisible if
499         ;;    any symbol in the list matches
500         ;;    buffer-invisibility-spec.
501         ;; If the match of buffer-invisibility-spec has a non-nil
502         ;; CDR, replace the invisible text with an ellipsis.
503         (let (match)
504           (if (symbolp invisible)
505               (setq match (member* invisible buffer-invisibility-spec
506                                    :key (lambda (i)
507                                           (if (symbolp i) i (car i)))))
508             (setq match (block nil
509                           (dolist (elem invisible)
510                             (let ((m (member*
511                                       elem buffer-invisibility-spec
512                                       :key (lambda (i)
513                                              (if (symbolp i) i (car i))))))
514                               (when m (return m))))
515                           nil)))
516           (setq show (cond ((null match) t)
517                            ((and (cdr-safe (car match))
518                                  ;; Conflate successive ellipses.
519                                  (not (eq show htmlize-ellipsis)))
520                             htmlize-ellipsis)
521                            (t nil)))))
522       (cond ((eq show t)
523              (push (buffer-substring-no-properties pos next-change) visible-list))
524             ((stringp show)
525              (push show visible-list)))
526       (setq pos next-change))
527     (if (= (length visible-list) 1)
528         ;; If VISIBLE-LIST consists of only one element, return it
529         ;; without concatenation.  This avoids additional consing in
530         ;; regions without any invisible text.
531         (car visible-list)
532       (apply #'concat (nreverse visible-list)))))
533
534 (defun htmlize-trim-ellipsis (text)
535   ;; Remove htmlize-ellipses ("...") from the beginning of TEXT if it
536   ;; starts with it.  It checks for the special property of the
537   ;; ellipsis so it doesn't work on ordinary text that begins with
538   ;; "...".
539   (if (get-text-property 0 'htmlize-ellipsis text)
540       (substring text (length htmlize-ellipsis))
541     text))
542
543 (defconst htmlize-tab-spaces
544   ;; A table of strings with spaces.  (aref htmlize-tab-spaces 5) is
545   ;; like (make-string 5 ?\ ), except it doesn't cons.
546   (let ((v (make-vector 32 nil)))
547     (dotimes (i (length v))
548       (setf (aref v i) (make-string i ?\ )))
549     v))
550
551 (defun htmlize-untabify (text start-column)
552   "Untabify TEXT, assuming it starts at START-COLUMN."
553   (let ((column start-column)
554         (last-match 0)
555         (chunk-start 0)
556         chunks match-pos tab-size)
557     (while (string-match "[\t\n]" text last-match)
558       (setq match-pos (match-beginning 0))
559       (cond ((eq (aref text match-pos) ?\t)
560              ;; Encountered a tab: create a chunk of text followed by
561              ;; the expanded tab.
562              (push (substring text chunk-start match-pos) chunks)
563              ;; Increase COLUMN by the length of the text we've
564              ;; skipped since last tab or newline.  (Encountering
565              ;; newline resets it.)
566              (incf column (- match-pos last-match))
567              ;; Calculate tab size based on tab-width and COLUMN.
568              (setq tab-size (- tab-width (% column tab-width)))
569              ;; Expand the tab.
570              (push (aref htmlize-tab-spaces tab-size) chunks)
571              (incf column tab-size)
572              (setq chunk-start (1+ match-pos)))
573             (t
574              ;; Reset COLUMN at beginning of line.
575              (setq column 0)))
576       (setq last-match (1+ match-pos)))
577     ;; If no chunks have been allocated, it means there have been no
578     ;; tabs to expand.  Return TEXT unmodified.
579     (if (null chunks)
580         text
581       (when (< chunk-start (length text))
582         ;; Push the remaining chunk.
583         (push (substring text chunk-start) chunks))
584       ;; Generate the output from the available chunks.
585       (apply #'concat (nreverse chunks)))))
586
587 (defun htmlize-despam-address (string)
588   "Replace every occurrence of '@' in STRING with &#64;.
589 `htmlize-make-hyperlinks' uses this to spam-protect mailto links
590 without modifying their meaning."
591   ;; Suggested by Ville Skytta.
592   (while (string-match "@" string)
593     (setq string (replace-match "&#64;" nil t string)))
594   string)
595
596 (defun htmlize-make-hyperlinks ()
597   "Make hyperlinks in HTML."
598   ;; Function originally submitted by Ville Skytta.  Rewritten by
599   ;; Hrvoje Niksic, then modified by Ville Skytta and Hrvoje Niksic.
600   (goto-char (point-min))
601   (while (re-search-forward
602           "&lt;\\(\\(mailto:\\)?\\([-=+_.a-zA-Z0-9]+@[-_.a-zA-Z0-9]+\\)\\)&gt;"
603           nil t)
604     (let ((address (match-string 3))
605           (link-text (match-string 1)))
606       (delete-region (match-beginning 0) (match-end 0))
607       (insert "&lt;<a href=\"mailto:"
608               (htmlize-despam-address address)
609               "\">"
610               (htmlize-despam-address link-text)
611               "</a>&gt;")))
612   (goto-char (point-min))
613   (while (re-search-forward "&lt;\\(\\(URL:\\)?\\([a-zA-Z]+://[^;]+\\)\\)&gt;"
614                             nil t)
615     (let ((url (match-string 3))
616           (link-text (match-string 1)))
617       (delete-region (match-beginning 0) (match-end 0))
618       (insert "&lt;<a href=\"" url "\">" link-text "</a>&gt;"))))
619
620 ;; Tests for htmlize-make-hyperlinks:
621
622 ;; <mailto:hniksic@xemacs.org>
623 ;; <http://fly.srk.fer.hr>
624 ;; <URL:http://www.xemacs.org>
625 ;; <http://www.mail-archive.com/bbdb-info@xemacs.org/>
626 ;; <hniksic@xemacs.org>
627 ;; <xalan-dev-sc.10148567319.hacuhiucknfgmpfnjcpg-john=doe.com@xml.apache.org>
628
629 (defun htmlize-defang-local-variables ()
630   ;; Juri Linkov reports that an HTML-ized "Local variables" can lead
631   ;; visiting the HTML to fail with "Local variables list is not
632   ;; properly terminated".  He suggested changing the phrase to
633   ;; syntactically equivalent HTML that Emacs doesn't recognize.
634   (goto-char (point-min))
635   (while (search-forward "Local Variables:" nil t)
636     (replace-match "Local Variables&#58;" nil t)))
637   
638  
639 ;;; Color handling.
640
641 (if (fboundp 'locate-file)
642     (defalias 'htmlize-locate-file 'locate-file)
643   (defun htmlize-locate-file (file path)
644     (dolist (dir path nil)
645       (when (file-exists-p (expand-file-name file dir))
646         (return (expand-file-name file dir))))))
647
648 (defvar htmlize-x-library-search-path
649   '("/usr/X11R6/lib/X11/"
650     "/usr/X11R5/lib/X11/"
651     "/usr/lib/X11R6/X11/"
652     "/usr/lib/X11R5/X11/"
653     "/usr/local/X11R6/lib/X11/"
654     "/usr/local/X11R5/lib/X11/"
655     "/usr/local/lib/X11R6/X11/"
656     "/usr/local/lib/X11R5/X11/"
657     "/usr/X11/lib/X11/"
658     "/usr/lib/X11/"
659     "/usr/local/lib/X11/"
660     "/usr/X386/lib/X11/"
661     "/usr/x386/lib/X11/"
662     "/usr/XFree86/lib/X11/"
663     "/usr/unsupported/lib/X11/"
664     "/usr/athena/lib/X11/"
665     "/usr/local/x11r5/lib/X11/"
666     "/usr/lpp/Xamples/lib/X11/"
667     "/usr/openwin/lib/X11/"
668     "/usr/openwin/share/lib/X11/"))
669
670 (defun htmlize-get-color-rgb-hash (&optional rgb-file)
671   "Return a hash table mapping X color names to RGB values.
672 The keys in the hash table are X11 color names, and the values are the
673 #rrggbb RGB specifications, extracted from `rgb.txt'.
674
675 If RGB-FILE is nil, the function will try hard to find a suitable file
676 in the system directories.
677
678 If no rgb.txt file is found, return nil."
679   (let ((rgb-file (or rgb-file (htmlize-locate-file
680                                 "rgb.txt"
681                                 htmlize-x-library-search-path)))
682         (hash nil))
683     (when rgb-file
684       (with-temp-buffer
685         (insert-file-contents rgb-file)
686         (setq hash (make-hash-table :test 'equal))
687         (while (not (eobp))
688           (cond ((looking-at "^\\s-*\\([!#]\\|$\\)")
689                  ;; Skip comments and empty lines.
690                  )
691                 ((looking-at
692                   "[ \t]*\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\(.*\\)")
693                  (setf (gethash (downcase (match-string 4)) hash)
694                        (format "#%02x%02x%02x"
695                                (string-to-number (match-string 1))
696                                (string-to-number (match-string 2))
697                                (string-to-number (match-string 3)))))
698                 (t
699                  (error
700                   "Unrecognized line in %s: %s"
701                   rgb-file
702                   (buffer-substring (point) (progn (end-of-line) (point))))))
703           (forward-line 1))))
704     hash))
705
706 ;; Compile the RGB map when loaded.  On systems where rgb.txt is
707 ;; missing, the value of the variable will be nil, and rgb.txt will
708 ;; not be used.
709 (defvar htmlize-color-rgb-hash (htmlize-get-color-rgb-hash))
710  
711 ;;; Face handling.
712
713 (defun htmlize-face-specifies-property (face prop)
714   ;; Return t if face specifies PROP, as opposed to it being inherited
715   ;; from the default face.  The problem with e.g.
716   ;; `face-foreground-instance' is that it returns an instance for
717   ;; EVERY face because every face inherits from the default face.
718   ;; However, we'd like htmlize-face-{fore,back}ground to return nil
719   ;; when called with a face that doesn't specify its own foreground
720   ;; or background.
721   (or (eq face 'default)
722       (assq 'global (specifier-spec-list (face-property face prop)))))
723
724 (defun htmlize-face-color-internal (face fg)
725   ;; Used only under GNU Emacs.  Return the color of FACE, but don't
726   ;; return "unspecified-fg" or "unspecified-bg".  If the face is
727   ;; `default' and the color is unspecified, look up the color in
728   ;; frame parameters.
729   (let* ((function (if fg #'face-foreground #'face-background))
730          color)
731     (if (>= emacs-major-version 22)
732         ;; For GNU Emacs 22+ set INHERIT to get the inherited values.
733         (setq color (funcall function face nil t))
734       (setq color (funcall function face))
735       ;; For GNU Emacs 21 (which has `face-attribute'): if the color
736       ;; is nil, recursively check for the face's parent.
737       (when (and (null color)
738                  (fboundp 'face-attribute)
739                  (face-attribute face :inherit)
740                  (not (eq (face-attribute face :inherit) 'unspecified)))
741         (setq color (htmlize-face-color-internal
742                      (face-attribute face :inherit) fg))))
743     (when (and (eq face 'default) (null color))
744       (setq color (cdr (assq (if fg 'foreground-color 'background-color)
745                              (frame-parameters)))))
746     (when (or (eq color 'unspecified)
747               (equal color "unspecified-fg")
748               (equal color "unspecified-bg"))
749       (setq color nil))
750     (when (and (eq face 'default)
751                (null color))
752       ;; Assuming black on white doesn't seem right, but I can't think
753       ;; of anything better to do.
754       (setq color (if fg "black" "white")))
755     color))
756
757 (defun htmlize-face-foreground (face)
758   ;; Return the name of the foreground color of FACE.  If FACE does
759   ;; not specify a foreground color, return nil.
760   (cond (htmlize-running-xemacs
761          ;; XEmacs.
762          (and (htmlize-face-specifies-property face 'foreground)
763               (color-instance-name (face-foreground-instance face))))
764         (t
765          ;; GNU Emacs.
766          (htmlize-face-color-internal face t))))
767
768 (defun htmlize-face-background (face)
769   ;; Return the name of the background color of FACE.  If FACE does
770   ;; not specify a background color, return nil.
771   (cond (htmlize-running-xemacs
772          ;; XEmacs.
773          (and (htmlize-face-specifies-property face 'background)
774               (color-instance-name (face-background-instance face))))
775         (t
776          ;; GNU Emacs.
777          (htmlize-face-color-internal face nil))))
778
779 ;; Convert COLOR to the #RRGGBB string.  If COLOR is already in that
780 ;; format, it's left unchanged.
781
782 (defun htmlize-color-to-rgb (color)
783   (let ((rgb-string nil))
784     (cond ((null color)
785            ;; Ignore nil COLOR because it means that the face is not
786            ;; specifying any color.  Hence (htmlize-color-to-rgb nil)
787            ;; returns nil.
788            )
789           ((string-match "\\`#" color)
790            ;; The color is already in #rrggbb format.
791            (setq rgb-string color))
792           ((and htmlize-use-rgb-txt
793                 htmlize-color-rgb-hash)
794            ;; Use of rgb.txt is requested, and it's available on the
795            ;; system.  Use it.
796            (setq rgb-string (gethash (downcase color) htmlize-color-rgb-hash)))
797           (t
798            ;; We're getting the RGB components from Emacs.
799            (let ((rgb
800                   ;; Here I cannot conditionalize on (fboundp ...) 
801                   ;; because ps-print under some versions of GNU Emacs
802                   ;; defines its own dummy version of
803                   ;; `color-instance-rgb-components'.
804                   (if htmlize-running-xemacs
805                       (mapcar (lambda (arg)
806                                 (/ arg 256))
807                               (color-instance-rgb-components
808                                (make-color-instance color)))
809                     (mapcar (lambda (arg)
810                               (/ arg 256))
811                             (x-color-values color)))))
812              (when rgb
813                (setq rgb-string (apply #'format "#%02x%02x%02x" rgb))))))
814     ;; If RGB-STRING is still nil, it means the color cannot be found,
815     ;; for whatever reason.  In that case just punt and return COLOR.
816     ;; Most browsers support a decent set of color names anyway.
817     (or rgb-string color)))
818
819 ;; We store the face properties we care about into an
820 ;; `htmlize-fstruct' type.  That way we only have to analyze face
821 ;; properties, which can be time consuming, once per each face.  The
822 ;; mapping between Emacs faces and htmlize-fstructs is established by
823 ;; htmlize-make-face-map.  The name "fstruct" refers to variables of
824 ;; type `htmlize-fstruct', while the term "face" is reserved for Emacs
825 ;; faces.
826
827 (defstruct htmlize-fstruct
828   foreground                            ; foreground color, #rrggbb
829   background                            ; background color, #rrggbb
830   size                                  ; size
831   boldp                                 ; whether face is bold
832   italicp                               ; whether face is italic
833   underlinep                            ; whether face is underlined
834   overlinep                             ; whether face is overlined
835   strikep                               ; whether face is struck through
836   css-name                              ; CSS name of face
837   )
838
839 (defun htmlize-face-emacs21-attr (fstruct attr value)
840   ;; For ATTR and VALUE, set the equivalent value in FSTRUCT.
841   (case attr
842     (:foreground
843      (setf (htmlize-fstruct-foreground fstruct) (htmlize-color-to-rgb value)))
844     (:background
845      (setf (htmlize-fstruct-background fstruct) (htmlize-color-to-rgb value)))
846     (:height
847      (setf (htmlize-fstruct-size fstruct) value))
848     (:weight
849      (when (string-match (symbol-name value) "bold")
850        (setf (htmlize-fstruct-boldp fstruct) t)))
851     (:slant
852      (setf (htmlize-fstruct-italicp fstruct) (or (eq value 'italic)
853                                                  (eq value 'oblique))))
854     (:bold
855      (setf (htmlize-fstruct-boldp fstruct) value))
856     (:italic
857      (setf (htmlize-fstruct-italicp fstruct) value))
858     (:underline
859      (setf (htmlize-fstruct-underlinep fstruct) value))
860     (:overline
861      (setf (htmlize-fstruct-overlinep fstruct) value))
862     (:strike-through
863      (setf (htmlize-fstruct-strikep fstruct) value))))
864
865 (defun htmlize-face-size (face)
866   ;; The size (height) of FACE, taking inheritance into account.
867   ;; Only works in Emacs 21 and later.
868   (let ((size-list
869          (loop
870           for f = face then (face-attribute f :inherit)
871           until (or (not f) (eq f 'unspecified))
872           for h = (face-attribute f :height)
873           collect (if (eq h 'unspecified) nil h))))
874     (reduce 'htmlize-merge-size (cons nil size-list))))
875
876 (defun htmlize-face-to-fstruct (face)
877   "Convert Emacs face FACE to fstruct."
878   (let ((fstruct (make-htmlize-fstruct
879                   :foreground (htmlize-color-to-rgb
880                                (htmlize-face-foreground face))
881                   :background (htmlize-color-to-rgb
882                                (htmlize-face-background face)))))
883     (cond (htmlize-running-xemacs
884            ;; XEmacs doesn't provide a way to detect whether a face is
885            ;; bold or italic, so we need to examine the font instance.
886            ;; #### This probably doesn't work under MS Windows and/or
887            ;; GTK devices.  I'll need help with those.
888            (let* ((font-instance (face-font-instance face))
889                   (props (font-instance-properties font-instance)))
890              (when (equalp (cdr (assq 'WEIGHT_NAME props)) "bold")
891                (setf (htmlize-fstruct-boldp fstruct) t))
892              (when (or (equalp (cdr (assq 'SLANT props)) "i")
893                        (equalp (cdr (assq 'SLANT props)) "o"))
894                (setf (htmlize-fstruct-italicp fstruct) t))
895              (setf (htmlize-fstruct-strikep fstruct)
896                    (face-strikethru-p face))
897              (setf (htmlize-fstruct-underlinep fstruct)
898                    (face-underline-p face))))
899           ((fboundp 'face-attribute)
900            ;; GNU Emacs 21 and further.
901            (dolist (attr '(:weight :slant :underline :overline :strike-through))
902              (let ((value (if (>= emacs-major-version 22)
903                               ;; Use the INHERIT arg in GNU Emacs 22.
904                               (face-attribute face attr nil t)
905                             ;; Otherwise, fake it.
906                             (let ((face face))
907                               (while (and (eq (face-attribute face attr)
908                                               'unspecified)
909                                           (not (eq (face-attribute face :inherit)
910                                                    'unspecified)))
911                                 (setq face (face-attribute face :inherit)))
912                               (face-attribute face attr)))))
913                (when (and value (not (eq value 'unspecified)))
914                  (htmlize-face-emacs21-attr fstruct attr value))))
915            (let ((size (htmlize-face-size face)))
916              (unless (eql size 1.0)     ; ignore non-spec
917                (setf (htmlize-fstruct-size fstruct) size))))
918           (t
919            ;; Older GNU Emacs.  Some of these functions are only
920            ;; available under Emacs 20+, hence the guards.
921            (when (fboundp 'face-bold-p)
922              (setf (htmlize-fstruct-boldp fstruct) (face-bold-p face)))
923            (when (fboundp 'face-italic-p)
924              (setf (htmlize-fstruct-italicp fstruct) (face-italic-p face)))
925            (setf (htmlize-fstruct-underlinep fstruct)
926                  (face-underline-p face))))
927     ;; Generate the css-name property.  Emacs places no restrictions
928     ;; on the names of symbols that represent faces -- any characters
929     ;; may be in the name, even ^@.  We try hard to beat the face name
930     ;; into shape, both esthetically and according to CSS1 specs.
931     (setf (htmlize-fstruct-css-name fstruct)
932           (let ((name (downcase (symbol-name face))))
933             (when (string-match "\\`font-lock-" name)
934               ;; Change font-lock-FOO-face to FOO.
935               (setq name (replace-match "" t t name)))
936             (when (string-match "-face\\'" name)
937               ;; Drop the redundant "-face" suffix.
938               (setq name (replace-match "" t t name)))
939             (while (string-match "[^-a-zA-Z0-9]" name)
940               ;; Drop the non-alphanumerics.
941               (setq name (replace-match "X" t t name)))
942             (when (string-match "\\`[-0-9]" name)
943               ;; CSS identifiers may not start with a digit.
944               (setq name (concat "X" name)))
945             ;; After these transformations, the face could come
946             ;; out empty.
947             (when (equal name "")
948               (setq name "face"))
949             ;; Apply the prefix.
950             (setq name (concat htmlize-css-name-prefix name))
951             name))
952     fstruct))
953
954 (defmacro htmlize-copy-attr-if-set (attr-list dest source)
955   ;; Expand the code of the type
956   ;; (and (htmlize-fstruct-ATTR source)
957   ;;      (setf (htmlize-fstruct-ATTR dest) (htmlize-fstruct-ATTR source)))
958   ;; for the given list of boolean attributes.
959   (cons 'progn
960         (loop for attr in attr-list
961               for attr-sym = (intern (format "htmlize-fstruct-%s" attr))
962               collect `(and (,attr-sym ,source)
963                             (setf (,attr-sym ,dest) (,attr-sym ,source))))))
964
965 (defun htmlize-merge-size (merged next)
966   ;; Calculate the size of the merge of MERGED and NEXT.
967   (cond ((null merged)     next)
968         ((integerp next)   next)
969         ((null next)       merged)
970         ((floatp merged)   (* merged next))
971         ((integerp merged) (round (* merged next)))))
972
973 (defun htmlize-merge-two-faces (merged next)
974   (htmlize-copy-attr-if-set
975    (foreground background boldp italicp underlinep overlinep strikep)
976    merged next)
977   (setf (htmlize-fstruct-size merged)
978         (htmlize-merge-size (htmlize-fstruct-size merged)
979                             (htmlize-fstruct-size next)))
980   merged)
981
982 (defun htmlize-merge-faces (fstruct-list)
983   (cond ((null fstruct-list)
984          ;; Nothing to do, return a dummy face.
985          (make-htmlize-fstruct))
986         ((null (cdr fstruct-list))
987          ;; Optimize for the common case of a single face, simply
988          ;; return it.
989          (car fstruct-list))
990         (t
991          (reduce #'htmlize-merge-two-faces
992                  (cons (make-htmlize-fstruct) fstruct-list)))))
993
994 ;; GNU Emacs 20+ supports attribute lists in `face' properties.  For
995 ;; example, you can use `(:foreground "red" :weight bold)' as an
996 ;; overlay's "face", or you can even use a list of such lists, etc.
997 ;; We call those "attrlists".
998 ;;
999 ;; htmlize supports attrlist by converting them to fstructs, the same
1000 ;; as with regular faces.
1001
1002 (defun htmlize-attrlist-to-fstruct (attrlist)
1003   ;; Like htmlize-face-to-fstruct, but accepts an ATTRLIST as input.
1004   (let ((fstruct (make-htmlize-fstruct)))
1005     (cond ((eq (car attrlist) 'foreground-color)
1006            ;; ATTRLIST is (foreground-color . COLOR)
1007            (setf (htmlize-fstruct-foreground fstruct)
1008                  (htmlize-color-to-rgb (cdr attrlist))))
1009           ((eq (car attrlist) 'background-color)
1010            ;; ATTRLIST is (background-color . COLOR)
1011            (setf (htmlize-fstruct-background fstruct)
1012                  (htmlize-color-to-rgb (cdr attrlist))))
1013           (t
1014            ;; ATTRLIST is a plist.
1015            (while attrlist
1016              (let ((attr (pop attrlist))
1017                    (value (pop attrlist)))
1018                (when (and value (not (eq value 'unspecified)))
1019                  (htmlize-face-emacs21-attr fstruct attr value))))))
1020     (setf (htmlize-fstruct-css-name fstruct) "ATTRLIST")
1021     fstruct))
1022
1023 (defun htmlize-face-list-p (face-prop)
1024   "Return non-nil if FACE-PROP is a list of faces, nil otherwise."
1025   ;; If not for attrlists, this would return (listp face-prop).  This
1026   ;; way we have to be more careful because attrlist is also a list!
1027   (cond
1028    ((eq face-prop nil)
1029     ;; FACE-PROP being nil means empty list (no face), so return t.
1030     t)
1031    ((symbolp face-prop)
1032     ;; A symbol other than nil means that it's only one face, so return
1033     ;; nil.
1034     nil)
1035    ((not (consp face-prop))
1036     ;; Huh?  Not a symbol or cons -- treat it as a single element.
1037     nil)
1038    (t
1039     ;; We know that FACE-PROP is a cons: check whether it looks like an
1040     ;; ATTRLIST.
1041     (let* ((car (car face-prop))
1042            (attrlist-p (and (symbolp car)
1043                             (or (eq car 'foreground-color)
1044                                 (eq car 'background-color)
1045                                 (eq (aref (symbol-name car) 0) ?:)))))
1046       ;; If FACE-PROP is not an ATTRLIST, it means it's a list of
1047       ;; faces.
1048       (not attrlist-p)))))
1049
1050 (defun htmlize-make-face-map (faces)
1051   ;; Return a hash table mapping Emacs faces to htmlize's fstructs.
1052   ;; The keys are either face symbols or attrlists, so the test
1053   ;; function must be `equal'.
1054   (let ((face-map (make-hash-table :test 'equal))
1055         css-names)
1056     (dolist (face faces)
1057       (unless (gethash face face-map)
1058         ;; Haven't seen FACE yet; convert it to an fstruct and cache
1059         ;; it.
1060         (let ((fstruct (if (symbolp face)
1061                            (htmlize-face-to-fstruct face)
1062                          (htmlize-attrlist-to-fstruct face))))
1063           (setf (gethash face face-map) fstruct)
1064           (let* ((css-name (htmlize-fstruct-css-name fstruct))
1065                  (new-name css-name)
1066                  (i 0))
1067             ;; Uniquify the face's css-name by using NAME-1, NAME-2,
1068             ;; etc.
1069             (while (member new-name css-names)
1070               (setq new-name (format "%s-%s" css-name (incf i))))
1071             (unless (equal new-name css-name)
1072               (setf (htmlize-fstruct-css-name fstruct) new-name))
1073             (push new-name css-names)))))
1074     face-map))
1075
1076 (defun htmlize-unstringify-face (face)
1077   "If FACE is a string, return it interned, otherwise return it unchanged."
1078   (if (stringp face)
1079       (intern face)
1080     face))
1081
1082 (defun htmlize-faces-in-buffer ()
1083   "Return a list of faces used in the current buffer.
1084 Under XEmacs, this returns the set of faces specified by the extents
1085 with the `face' property.  (This covers text properties as well.)  Under
1086 GNU Emacs, it returns the set of faces specified by the `face' text
1087 property and by buffer overlays that specify `face'."
1088   (let (faces)
1089     ;; Testing for (fboundp 'map-extents) doesn't work because W3
1090     ;; defines `map-extents' under FSF.
1091     (if htmlize-running-xemacs
1092         (let (face-prop)
1093           (map-extents (lambda (extent ignored)
1094                          (setq face-prop (extent-face extent)
1095                                ;; FACE-PROP can be a face or a list of
1096                                ;; faces.
1097                                faces (if (listp face-prop)
1098                                          (union face-prop faces)
1099                                        (adjoin face-prop faces)))
1100                          nil)
1101                        nil
1102                        ;; Specify endpoints explicitly to respect
1103                        ;; narrowing.
1104                        (point-min) (point-max) nil nil 'face))
1105       ;; FSF Emacs code.
1106       ;; Faces used by text properties.
1107       (let ((pos (point-min)) face-prop next)
1108         (while (< pos (point-max))
1109           (setq face-prop (get-text-property pos 'face)
1110                 next (or (next-single-property-change pos 'face) (point-max)))
1111           ;; FACE-PROP can be a face/attrlist or a list thereof.
1112           (setq faces (if (htmlize-face-list-p face-prop)
1113                           (nunion (mapcar #'htmlize-unstringify-face face-prop)
1114                                   faces :test 'equal)
1115                         (adjoin (htmlize-unstringify-face face-prop)
1116                                 faces :test 'equal)))
1117           (setq pos next)))
1118       ;; Faces used by overlays.
1119       (dolist (overlay (overlays-in (point-min) (point-max)))
1120         (let ((face-prop (overlay-get overlay 'face)))
1121           ;; FACE-PROP can be a face/attrlist or a list thereof.
1122           (setq faces (if (htmlize-face-list-p face-prop)
1123                           (nunion (mapcar #'htmlize-unstringify-face face-prop)
1124                                   faces :test 'equal)
1125                         (adjoin (htmlize-unstringify-face face-prop)
1126                                 faces :test 'equal))))))
1127     faces))
1128
1129 ;; htmlize-faces-at-point returns the faces in use at point.  The
1130 ;; faces are sorted by increasing priority, i.e. the last face takes
1131 ;; precedence.
1132 ;;
1133 ;; Under XEmacs, this returns all the faces in all the extents at
1134 ;; point.  Under GNU Emacs, this returns all the faces in the `face'
1135 ;; property and all the faces in the overlays at point.
1136
1137 (cond (htmlize-running-xemacs
1138        (defun htmlize-faces-at-point ()
1139          (let (extent extent-list face-list face-prop)
1140            (while (setq extent (extent-at (point) nil 'face extent))
1141              (push extent extent-list))
1142            ;; extent-list is in reverse display order, meaning that
1143            ;; smallest ones come last.  That is the order we want,
1144            ;; except it can be overridden by the `priority' property.
1145            (setq extent-list (stable-sort extent-list #'<
1146                                           :key #'extent-priority))
1147            (dolist (extent extent-list)
1148              (setq face-prop (extent-face extent))
1149              ;; extent's face-list is in reverse order from what we
1150              ;; want, but the `nreverse' below will take care of it.
1151              (setq face-list (if (listp face-prop)
1152                                  (append face-prop face-list)
1153                                (cons face-prop face-list))))
1154            (nreverse face-list))))
1155       (t
1156        (defun htmlize-faces-at-point ()
1157          (let (all-faces)
1158            ;; Faces from text properties.
1159            (let ((face-prop (get-text-property (point) 'face)))
1160              (setq all-faces (if (htmlize-face-list-p face-prop)
1161                                  (nreverse (mapcar #'htmlize-unstringify-face
1162                                                    face-prop))
1163                                (list (htmlize-unstringify-face face-prop)))))
1164            ;; Faces from overlays.
1165            (let ((overlays
1166                   ;; Collect overlays at point that specify `face'.
1167                   (delete-if-not (lambda (o)
1168                                    (overlay-get o 'face))
1169                                  (overlays-at (point))))
1170                  list face-prop)
1171              ;; Sort the overlays so the smaller (more specific) ones
1172              ;; come later.  The number of overlays at each one
1173              ;; position should be very small, so the sort shouldn't
1174              ;; slow things down.
1175              (setq overlays (sort* overlays
1176                                    ;; Sort by ascending...
1177                                    #'<
1178                                    ;; ...overlay size.
1179                                    :key (lambda (o)
1180                                           (- (overlay-end o)
1181                                              (overlay-start o)))))
1182              ;; Overlay priorities, if present, override the above
1183              ;; established order.  Larger overlay priority takes
1184              ;; precedence and therefore comes later in the list.
1185              (setq overlays (stable-sort
1186                              overlays
1187                              ;; Reorder (stably) by acending...
1188                              #'<
1189                              ;; ...overlay priority.
1190                              :key (lambda (o)
1191                                     (or (overlay-get o 'priority) 0))))
1192              (dolist (overlay overlays)
1193                (setq face-prop (overlay-get overlay 'face))
1194                (setq list (if (htmlize-face-list-p face-prop)
1195                               (nconc (nreverse (mapcar
1196                                                 #'htmlize-unstringify-face
1197                                                 face-prop))
1198                                      list)
1199                             (cons (htmlize-unstringify-face face-prop) list))))
1200              ;; Under "Merging Faces" the manual explicitly states
1201              ;; that faces specified by overlays take precedence over
1202              ;; faces specified by text properties.
1203              (setq all-faces (nconc all-faces list)))
1204            all-faces))))
1205  
1206 ;; htmlize supports generating HTML in two several fundamentally
1207 ;; different ways, one with the use of CSS and nested <span> tags, and
1208 ;; the other with the use of the old <font> tags.  Rather than adding
1209 ;; a bunch of ifs to many places, we take a semi-OO approach.
1210 ;; `htmlize-buffer-1' calls a number of "methods", which indirect to
1211 ;; the functions that depend on `htmlize-output-type'.  The currently
1212 ;; used methods are `doctype', `insert-head', `body-tag', and
1213 ;; `insert-text'.  Not all output types define all methods.
1214 ;;
1215 ;; Methods are called either with (htmlize-method METHOD ARGS...) 
1216 ;; special form, or by accessing the function with
1217 ;; (htmlize-method-function 'METHOD) and calling (funcall FUNCTION).
1218 ;; The latter form is useful in tight loops because `htmlize-method'
1219 ;; conses.
1220 ;;
1221 ;; Currently defined output types are `css' and `font'.
1222
1223 (defmacro htmlize-method (method &rest args)
1224   ;; Expand to (htmlize-TYPE-METHOD ...ARGS...).  TYPE is the value of
1225   ;; `htmlize-output-type' at run time.
1226   `(funcall (htmlize-method-function ',method) ,@args))
1227
1228 (defun htmlize-method-function (method)
1229   ;; Return METHOD's function definition for the current output type.
1230   ;; The returned object can be safely funcalled.
1231   (let ((sym (intern (format "htmlize-%s-%s" htmlize-output-type method))))
1232     (indirect-function (if (fboundp sym)
1233                            sym
1234                          (let ((default (intern (concat "htmlize-default-"
1235                                                         (symbol-name method)))))
1236                            (if (fboundp default)
1237                                default
1238                              'ignore))))))
1239
1240 (defvar htmlize-memoization-table (make-hash-table :test 'equal))
1241
1242 (defmacro htmlize-memoize (key generator)
1243   "Return the value of GENERATOR, memoized as KEY.
1244 That means that GENERATOR will be evaluated and returned the first time
1245 it's called with the same value of KEY.  All other times, the cached
1246 \(memoized) value will be returned."
1247   (let ((value (gensym)))
1248     `(let ((,value (gethash ,key htmlize-memoization-table)))
1249        (unless ,value
1250          (setq ,value ,generator)
1251          (setf (gethash ,key htmlize-memoization-table) ,value))
1252        ,value)))
1253  
1254 ;;; Default methods.
1255
1256 (defun htmlize-default-doctype ()
1257   nil                                   ; no doc-string
1258   ;; According to DTDs published by the W3C, it is illegal to embed
1259   ;; <font> in <pre>.  This makes sense in general, but is bad for
1260   ;; htmlize's intended usage of <font> to specify the document color.
1261
1262   ;; To make generated HTML legal, htmlize's `font' mode used to
1263   ;; specify the SGML declaration of "HTML Pro" DTD here.  HTML Pro
1264   ;; aka Silmaril DTD was a project whose goal was to produce a GPL'ed
1265   ;; DTD that would encompass all the incompatible HTML extensions
1266   ;; procured by Netscape, MSIE, and other players in the field.
1267   ;; Apparently the project got abandoned, the last available version
1268   ;; being "Draft 0 Revision 11" from January 1997, as documented at
1269   ;; <http://imbolc.ucc.ie/~pflynn/articles/htmlpro.html>.
1270
1271   ;; Since by now HTML Pro is remembered by none but the most die-hard
1272   ;; early-web-days nostalgics and used by not even them, there is no
1273   ;; use in specifying it.  So we return the standard HTML 4.0
1274   ;; declaration, which makes generated HTML technically illegal.  If
1275   ;; you have a problem with that, use the `css' engine designed to
1276   ;; create fully conforming HTML.
1277
1278   "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\">"
1279
1280   ;; Now-abandoned HTML Pro declaration.
1281   ;"<!DOCTYPE HTML PUBLIC \"+//Silmaril//DTD HTML Pro v0r11 19970101//EN\">"
1282   )
1283
1284 (defun htmlize-default-body-tag (face-map)
1285   nil                                   ; no doc-string
1286   "<body>")
1287  
1288 ;;; CSS based output support.
1289
1290 ;; Internal function; not a method.
1291 (defun htmlize-css-specs (fstruct)
1292   (let (result)
1293     (when (htmlize-fstruct-foreground fstruct)
1294       (push (format "color: %s;" (htmlize-fstruct-foreground fstruct))
1295             result))
1296     (when (htmlize-fstruct-background fstruct)
1297       (push (format "background-color: %s;"
1298                     (htmlize-fstruct-background fstruct))
1299             result))
1300     (let ((size (htmlize-fstruct-size fstruct)))
1301       (when (and size (not (eq htmlize-ignore-face-size t)))
1302         (cond ((floatp size)
1303                (push (format "font-size: %d%%;" (* 100 size)) result))
1304               ((not (eq htmlize-ignore-face-size 'absolute))
1305                (push (format "font-size: %spt;" (/ size 10.0)) result)))))
1306     (when (htmlize-fstruct-boldp fstruct)
1307       (push "font-weight: bold;" result))
1308     (when (htmlize-fstruct-italicp fstruct)
1309       (push "font-style: italic;" result))
1310     (when (htmlize-fstruct-underlinep fstruct)
1311       (push "text-decoration: underline;" result))
1312     (when (htmlize-fstruct-overlinep fstruct)
1313       (push "text-decoration: overline;" result))
1314     (when (htmlize-fstruct-strikep fstruct)
1315       (push "text-decoration: line-through;" result))
1316     (nreverse result)))
1317
1318 (defun htmlize-css-insert-head (buffer-faces face-map)
1319   (insert "    <style type=\"text/css\">\n    <!--\n")
1320   (insert "      body {\n        "
1321           (mapconcat #'identity
1322                      (htmlize-css-specs (gethash 'default face-map))
1323                      "\n        ")
1324           "\n      }\n")
1325   (dolist (face (sort* (copy-list buffer-faces) #'string-lessp
1326                        :key (lambda (f)
1327                               (htmlize-fstruct-css-name (gethash f face-map)))))
1328     (let* ((fstruct (gethash face face-map))
1329            (cleaned-up-face-name
1330             (let ((s
1331                    ;; Use `prin1-to-string' rather than `symbol-name'
1332                    ;; to get the face name because the "face" can also
1333                    ;; be an attrlist, which is not a symbol.
1334                    (prin1-to-string face)))
1335               ;; If the name contains `--' or `*/', remove them.
1336               (while (string-match "--" s)
1337                 (setq s (replace-match "-" t t s)))
1338               (while (string-match "\\*/" s)
1339                 (setq s (replace-match "XX" t t s)))
1340               s))
1341            (specs (htmlize-css-specs fstruct)))
1342       (insert "      ." (htmlize-fstruct-css-name fstruct))
1343       (if (null specs)
1344           (insert " {")
1345         (insert " {\n        /* " cleaned-up-face-name " */\n        "
1346                 (mapconcat #'identity specs "\n        ")))
1347       (insert "\n      }\n")))
1348   (insert htmlize-hyperlink-style
1349           "    -->\n    </style>\n"))
1350
1351 (defun htmlize-css-insert-text (text fstruct-list buffer)
1352   ;; Insert TEXT colored with FACES into BUFFER.  In CSS mode, this is
1353   ;; easy: just nest the text in one <span class=...> tag for each
1354   ;; face in FSTRUCT-LIST.
1355   (dolist (fstruct fstruct-list)
1356     (princ "<span class=\"" buffer)
1357     (princ (htmlize-fstruct-css-name fstruct) buffer)
1358     (princ "\">" buffer))
1359   (princ text buffer)
1360   (dolist (fstruct fstruct-list)
1361     (ignore fstruct)                    ; shut up the byte-compiler
1362     (princ "</span>" buffer)))
1363  
1364 ;; `inline-css' output support.
1365
1366 (defun htmlize-inline-css-body-tag (face-map)
1367   (format "<body style=\"%s\">"
1368           (mapconcat #'identity (htmlize-css-specs (gethash 'default face-map))
1369                      " ")))
1370
1371 (defun htmlize-inline-css-insert-text (text fstruct-list buffer)
1372   (let* ((merged (htmlize-merge-faces fstruct-list))
1373          (style (htmlize-memoize
1374                  merged
1375                  (let ((specs (htmlize-css-specs merged)))
1376                    (and specs
1377                         (mapconcat #'identity (htmlize-css-specs merged) " "))))))
1378     (when style
1379       (princ "<span style=\"" buffer)
1380       (princ style buffer)
1381       (princ "\">" buffer))
1382     (princ text buffer)
1383     (when style
1384       (princ "</span>" buffer))))
1385  
1386 ;;; `font' tag based output support.
1387
1388 (defun htmlize-font-body-tag (face-map)
1389   (let ((fstruct (gethash 'default face-map)))
1390     (format "<body text=\"%s\" bgcolor=\"%s\">"
1391             (htmlize-fstruct-foreground fstruct)
1392             (htmlize-fstruct-background fstruct))))
1393        
1394 (defun htmlize-font-insert-text (text fstruct-list buffer)
1395   ;; In `font' mode, we use the traditional HTML means of altering
1396   ;; presentation: <font> tag for colors, <b> for bold, <u> for
1397   ;; underline, and <strike> for strike-through.
1398   (let* ((merged (htmlize-merge-faces fstruct-list))
1399          (markup (htmlize-memoize
1400                   merged
1401                   (cons (concat
1402                          (and (htmlize-fstruct-foreground merged)
1403                               (format "<font color=\"%s\">" (htmlize-fstruct-foreground merged)))
1404                          (and (htmlize-fstruct-boldp merged)      "<b>")
1405                          (and (htmlize-fstruct-italicp merged)    "<i>")
1406                          (and (htmlize-fstruct-underlinep merged) "<u>")
1407                          (and (htmlize-fstruct-strikep merged)    "<strike>"))
1408                         (concat
1409                          (and (htmlize-fstruct-strikep merged)    "</strike>")
1410                          (and (htmlize-fstruct-underlinep merged) "</u>")
1411                          (and (htmlize-fstruct-italicp merged)    "</i>")
1412                          (and (htmlize-fstruct-boldp merged)      "</b>")
1413                          (and (htmlize-fstruct-foreground merged) "</font>"))))))
1414     (princ (car markup) buffer)
1415     (princ text buffer)
1416     (princ (cdr markup) buffer)))
1417  
1418 (defun htmlize-buffer-1 ()
1419   ;; Internal function; don't call it from outside this file.  Htmlize
1420   ;; current buffer, writing the resulting HTML to a new buffer, and
1421   ;; return it.  Unlike htmlize-buffer, this doesn't change current
1422   ;; buffer or use switch-to-buffer.
1423   (save-excursion
1424     ;; Protect against the hook changing the current buffer.
1425     (save-excursion
1426       (run-hooks 'htmlize-before-hook))
1427     ;; Convince font-lock support modes to fontify the entire buffer
1428     ;; in advance.
1429     (htmlize-ensure-fontified)
1430     (clrhash htmlize-extended-character-cache)
1431     (clrhash htmlize-memoization-table)
1432     (let* ((buffer-faces (htmlize-faces-in-buffer))
1433            (face-map (htmlize-make-face-map (adjoin 'default buffer-faces)))
1434            ;; Generate the new buffer.  It's important that it inherits
1435            ;; default-directory from the current buffer.
1436            (htmlbuf (generate-new-buffer (if (buffer-file-name)
1437                                              (htmlize-make-file-name
1438                                               (file-name-nondirectory
1439                                                (buffer-file-name)))
1440                                            "*html*")))
1441            ;; Having a dummy value in the plist allows writing simply
1442            ;; (plist-put places foo bar).
1443            (places '(nil nil))
1444            (title (if (buffer-file-name)
1445                       (file-name-nondirectory (buffer-file-name))
1446                     (buffer-name))))
1447       ;; Initialize HTMLBUF and insert the HTML prolog.
1448       (with-current-buffer htmlbuf
1449         (buffer-disable-undo)
1450         (insert (htmlize-method doctype) ?\n
1451                 (format "<!-- Created by htmlize-%s in %s mode. -->\n"
1452                         htmlize-version htmlize-output-type)
1453                 "<html>\n  ")
1454         (plist-put places 'head-start (point-marker))
1455         (insert "<head>\n"
1456                 "    <title>" (htmlize-protect-string title) "</title>\n"
1457                 (if htmlize-html-charset
1458                     (format (concat "    <meta http-equiv=\"Content-Type\" "
1459                                     "content=\"text/html; charset=%s\">\n")
1460                             htmlize-html-charset)
1461                   "")
1462                 htmlize-head-tags)
1463         (htmlize-method insert-head buffer-faces face-map)
1464         (insert "  </head>")
1465         (plist-put places 'head-end (point-marker))
1466         (insert "\n  ")
1467         (plist-put places 'body-start (point-marker))
1468         (insert (htmlize-method body-tag face-map)
1469                 "\n    ")
1470         (plist-put places 'content-start (point-marker))
1471         (insert "<pre>\n"))
1472       (let ((insert-text-method
1473              ;; Get the inserter method, so we can funcall it inside
1474              ;; the loop.  Not calling `htmlize-method' in the loop
1475              ;; body yields a measurable speed increase.
1476              (htmlize-method-function 'insert-text))
1477             ;; Declare variables used in loop body outside the loop
1478             ;; because it's faster to establish `let' bindings only
1479             ;; once.
1480             next-change text face-list fstruct-list trailing-ellipsis)
1481         ;; This loop traverses and reads the source buffer, appending
1482         ;; the resulting HTML to HTMLBUF with `princ'.  This method is
1483         ;; fast because: 1) it doesn't require examining the text
1484         ;; properties char by char (htmlize-next-change is used to
1485         ;; move between runs with the same face), and 2) it doesn't
1486         ;; require buffer switches, which are slow in Emacs.
1487         (goto-char (point-min))
1488         (while (not (eobp))
1489           (setq next-change (htmlize-next-change (point) 'face))
1490           ;; Get faces in use between (point) and NEXT-CHANGE, and
1491           ;; convert them to fstructs.
1492           (setq face-list (htmlize-faces-at-point)
1493                 fstruct-list (delq nil (mapcar (lambda (f)
1494                                                  (gethash f face-map))
1495                                                face-list)))
1496           ;; Extract buffer text, sans the invisible parts.  Then
1497           ;; untabify it and escape the HTML metacharacters.
1498           (setq text (htmlize-buffer-substring-no-invisible
1499                       (point) next-change))
1500           (when trailing-ellipsis
1501             (setq text (htmlize-trim-ellipsis text)))
1502           ;; If TEXT ends up empty, don't change trailing-ellipsis.
1503           (when (> (length text) 0)
1504             (setq trailing-ellipsis
1505                   (get-text-property (1- (length text))
1506                                      'htmlize-ellipsis text)))
1507           (setq text (htmlize-untabify text (current-column)))
1508           (setq text (htmlize-protect-string text))
1509           ;; Don't bother writing anything if there's no text (this
1510           ;; happens in invisible regions).
1511           (when (> (length text) 0)
1512             ;; Insert the text, along with the necessary markup to
1513             ;; represent faces in FSTRUCT-LIST.
1514             (funcall insert-text-method text fstruct-list htmlbuf))
1515           (goto-char next-change)))
1516
1517       ;; Insert the epilog and post-process the buffer.
1518       (with-current-buffer htmlbuf
1519         (insert "</pre>")
1520         (plist-put places 'content-end (point-marker))
1521         (insert "\n  </body>")
1522         (plist-put places 'body-end (point-marker))
1523         (insert "\n</html>\n")
1524         (when htmlize-generate-hyperlinks
1525           (htmlize-make-hyperlinks))
1526         (htmlize-defang-local-variables)
1527         (when htmlize-replace-form-feeds
1528           ;; Change each "\n^L" to "<hr />".
1529           (goto-char (point-min))
1530           (let ((source
1531                  ;; ^L has already been escaped, so search for that.
1532                  (htmlize-protect-string "\n\^L"))
1533                 (replacement
1534                  (if (stringp htmlize-replace-form-feeds)
1535                      htmlize-replace-form-feeds
1536                    "</pre><hr /><pre>")))
1537             (while (search-forward source nil t)
1538               (replace-match replacement t t))))
1539         (goto-char (point-min))
1540         (when htmlize-html-major-mode
1541           ;; What sucks about this is that the minor modes, most notably
1542           ;; font-lock-mode, won't be initialized.  Oh well.
1543           (funcall htmlize-html-major-mode))
1544         (set (make-local-variable 'htmlize-buffer-places) places)
1545         (run-hooks 'htmlize-after-hook)
1546         (buffer-enable-undo))
1547       htmlbuf)))
1548
1549 ;; Utility functions.
1550
1551 (defmacro htmlize-with-fontify-message (&rest body)
1552   ;; When forcing fontification of large buffers in
1553   ;; htmlize-ensure-fontified, inform the user that he is waiting for
1554   ;; font-lock, not for htmlize to finish.
1555   `(progn
1556      (if (> (buffer-size) 65536)
1557          (message "Forcing fontification of %s..."
1558                   (buffer-name (current-buffer))))
1559      ,@body
1560      (if (> (buffer-size) 65536)
1561          (message "Forcing fontification of %s...done"
1562                   (buffer-name (current-buffer))))))
1563
1564 (defun htmlize-ensure-fontified ()
1565   ;; If font-lock is being used, ensure that the "support" modes
1566   ;; actually fontify the buffer.  If font-lock is not in use, we
1567   ;; don't care because, except in htmlize-file, we don't force
1568   ;; font-lock on the user.
1569   (when (and (boundp 'font-lock-mode)
1570              font-lock-mode)
1571     ;; In part taken from ps-print-ensure-fontified in GNU Emacs 21.
1572     (cond
1573      ((and (boundp 'jit-lock-mode)
1574            (symbol-value 'jit-lock-mode))
1575       (htmlize-with-fontify-message
1576        (jit-lock-fontify-now (point-min) (point-max))))
1577      ((and (boundp 'lazy-lock-mode)
1578            (symbol-value 'lazy-lock-mode))
1579       (htmlize-with-fontify-message
1580        (lazy-lock-fontify-region (point-min) (point-max))))
1581      ((and (boundp 'lazy-shot-mode)
1582            (symbol-value 'lazy-shot-mode))
1583       (htmlize-with-fontify-message
1584        ;; lazy-shot is amazing in that it must *refontify* the region,
1585        ;; even if the whole buffer has already been fontified.  <sigh>
1586        (lazy-shot-fontify-region (point-min) (point-max))))
1587      ;; There's also fast-lock, but we don't need to handle specially,
1588      ;; I think.  fast-lock doesn't really defer fontification, it
1589      ;; just saves it to an external cache so it's not done twice.
1590      )))
1591
1592  
1593 ;;;###autoload
1594 (defun htmlize-buffer (&optional buffer)
1595   "Convert BUFFER to HTML, preserving colors and decorations.
1596
1597 The generated HTML is available in a new buffer, which is returned.
1598 When invoked interactively, the new buffer is selected in the current
1599 window.  The title of the generated document will be set to the buffer's
1600 file name or, if that's not available, to the buffer's name.
1601
1602 Note that htmlize doesn't fontify your buffers, it only uses the
1603 decorations that are already present.  If you don't set up font-lock or
1604 something else to fontify your buffers, the resulting HTML will be
1605 plain.  Likewise, if you don't like the choice of colors, fix the mode
1606 that created them, or simply alter the faces it uses."
1607   (interactive)
1608   (let ((htmlbuf (with-current-buffer (or buffer (current-buffer))
1609                    (htmlize-buffer-1))))
1610     (when (interactive-p)
1611       (switch-to-buffer htmlbuf))
1612     htmlbuf))
1613
1614 ;;;###autoload
1615 (defun htmlize-region (beg end)
1616   "Convert the region to HTML, preserving colors and decorations.
1617 See `htmlize-buffer' for details."
1618   (interactive "r")
1619   ;; Don't let zmacs region highlighting end up in HTML.
1620   (when (fboundp 'zmacs-deactivate-region)
1621     (zmacs-deactivate-region))
1622   (let ((htmlbuf (save-restriction
1623                    (narrow-to-region beg end)
1624                    (htmlize-buffer-1))))
1625     (when (interactive-p)
1626       (switch-to-buffer htmlbuf))
1627     htmlbuf))
1628
1629 (defun htmlize-region-for-paste (beg end)
1630   "Htmlize the region and return just the HTML as a string.
1631 This forces the `inline-css' style and only returns the HTML body,
1632 but without the BODY tag.  This should make it useful for inserting
1633 the text to another HTML buffer."
1634   (let* ((htmlize-output-type 'inline-css)
1635          (htmlbuf (htmlize-region beg end)))
1636     (unwind-protect
1637         (with-current-buffer htmlbuf
1638           (buffer-substring (plist-get htmlize-buffer-places 'content-start)
1639                             (plist-get htmlize-buffer-places 'content-end)))
1640       (kill-buffer htmlbuf))))
1641
1642 (defun htmlize-make-file-name (file)
1643   "Make an HTML file name from FILE.
1644
1645 In its default implementation, this simply appends `.html' to FILE.
1646 This function is called by htmlize to create the buffer file name, and
1647 by `htmlize-file' to create the target file name.
1648
1649 More elaborate transformations are conceivable, such as changing FILE's
1650 extension to `.html' (\"file.c\" -> \"file.html\").  If you want them,
1651 overload this function to do it and htmlize will comply."
1652   (concat file ".html"))
1653
1654 ;; Older implementation of htmlize-make-file-name that changes FILE's
1655 ;; extension to ".html".
1656 ;(defun htmlize-make-file-name (file)
1657 ;  (let ((extension (file-name-extension file))
1658 ;       (sans-extension (file-name-sans-extension file)))
1659 ;    (if (or (equal extension "html")
1660 ;           (equal extension "htm")
1661 ;           (equal sans-extension ""))
1662 ;       (concat file ".html")
1663 ;      (concat sans-extension ".html"))))
1664
1665 ;;;###autoload
1666 (defun htmlize-file (file &optional target)
1667   "Load FILE, fontify it, convert it to HTML, and save the result.
1668
1669 Contents of FILE are inserted into a temporary buffer, whose major mode
1670 is set with `normal-mode' as appropriate for the file type.  The buffer
1671 is subsequently fontified with `font-lock' and converted to HTML.  Note
1672 that, unlike `htmlize-buffer', this function explicitly turns on
1673 font-lock.  If a form of highlighting other than font-lock is desired,
1674 please use `htmlize-buffer' directly on buffers so highlighted.
1675
1676 Buffers currently visiting FILE are unaffected by this function.  The
1677 function does not change current buffer or move the point.
1678
1679 If TARGET is specified and names a directory, the resulting file will be
1680 saved there instead of to FILE's directory.  If TARGET is specified and
1681 does not name a directory, it will be used as output file name."
1682   (interactive (list (read-file-name
1683                       "HTML-ize file: "
1684                       nil nil nil (and (buffer-file-name)
1685                                        (file-name-nondirectory
1686                                         (buffer-file-name))))))
1687   (let ((output-file (if (and target (not (file-directory-p target)))
1688                          target
1689                        (expand-file-name
1690                         (htmlize-make-file-name (file-name-nondirectory file))
1691                         (or target (file-name-directory file)))))
1692         ;; Try to prevent `find-file-noselect' from triggering
1693         ;; font-lock because we'll fontify explicitly below.
1694         (font-lock-mode nil)
1695         (font-lock-auto-fontify nil)
1696         (global-font-lock-mode nil)
1697         ;; Ignore the size limit for the purposes of htmlization.
1698         (font-lock-maximum-size nil)
1699         ;; Disable font-lock support modes.  This will only work in
1700         ;; more recent Emacs versions, so htmlize-buffer-1 still needs
1701         ;; to call htmlize-ensure-fontified.
1702         (font-lock-support-mode nil))
1703     (with-temp-buffer
1704       ;; Insert FILE into the temporary buffer.
1705       (insert-file-contents file)
1706       ;; Set the file name so normal-mode and htmlize-buffer-1 pick it
1707       ;; up.  Restore it afterwards so with-temp-buffer's kill-buffer
1708       ;; doesn't complain about killing a modified buffer.
1709       (let ((buffer-file-name file))
1710         ;; Set the major mode for the sake of font-lock.
1711         (normal-mode)
1712         (font-lock-mode 1)
1713         (unless font-lock-mode
1714           ;; In GNU Emacs (font-lock-mode 1) doesn't force font-lock,
1715           ;; contrary to the documentation.  This seems to work.
1716           (font-lock-fontify-buffer))
1717         ;; htmlize the buffer and save the HTML.
1718         (with-current-buffer (htmlize-buffer-1)
1719           (unwind-protect
1720               (progn
1721                 (run-hooks 'htmlize-file-hook)
1722                 (write-region (point-min) (point-max) output-file))
1723             (kill-buffer (current-buffer)))))))
1724   ;; I haven't decided on a useful return value yet, so just return
1725   ;; nil.
1726   nil)
1727
1728 ;;;###autoload
1729 (defun htmlize-many-files (files &optional target-directory)
1730   "Convert FILES to HTML and save the corresponding HTML versions.
1731
1732 FILES should be a list of file names to convert.  This function calls
1733 `htmlize-file' on each file; see that function for details.  When
1734 invoked interactively, you are prompted for a list of files to convert,
1735 terminated with RET.
1736
1737 If TARGET-DIRECTORY is specified, the HTML files will be saved to that
1738 directory.  Normally, each HTML file is saved to the directory of the
1739 corresponding source file."
1740   (interactive
1741    (list
1742     (let (list file)
1743       ;; Use empty string as DEFAULT because setting DEFAULT to nil
1744       ;; defaults to the directory name, which is not what we want.
1745       (while (not (equal (setq file (read-file-name
1746                                      "HTML-ize file (RET to finish): "
1747                                      (and list (file-name-directory
1748                                                 (car list)))
1749                                      "" t))
1750                          ""))
1751         (push file list))
1752       (nreverse list))))
1753   ;; Verify that TARGET-DIRECTORY is indeed a directory.  If it's a
1754   ;; file, htmlize-file will use it as target, and that doesn't make
1755   ;; sense.
1756   (and target-directory
1757        (not (file-directory-p target-directory))
1758        (error "target-directory must name a directory: %s" target-directory))
1759   (dolist (file files)
1760     (htmlize-file file target-directory)))
1761
1762 ;;;###autoload
1763 (defun htmlize-many-files-dired (arg &optional target-directory)
1764   "HTMLize dired-marked files."
1765   (interactive "P")
1766   (htmlize-many-files (dired-get-marked-files nil arg) target-directory))
1767
1768 (provide 'htmlize)
1769
1770 ;;; htmlize.el ends here