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