Update copyright years.
[org-mode.git] / contrib / lisp / htmlize.el
blobd88a753af5ae870fb3375ff15a53ba030460e625
1 ;;; htmlize.el --- Convert buffer text and decorations to HTML.
3 ;; Copyright (C) 1997-2014 Hrvoje Niksic
5 ;; Author: Hrvoje Niksic <hniksic@xemacs.org>
6 ;; Keywords: hypermedia, extensions
7 ;; Version: 1.43
9 ;; This file is not part of GNU Emacs.
11 ;; This program is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
16 ;; This program is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with this program; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
26 ;;; Commentary:
28 ;; This package converts the buffer text and the associated
29 ;; decorations to HTML. Mail to <hniksic@xemacs.org> to discuss
30 ;; features and additions. All suggestions are more than welcome.
32 ;; To use it, just switch to the buffer you want HTML-ized and type
33 ;; `M-x htmlize-buffer'. You will be switched to a new buffer that
34 ;; contains the resulting HTML code. You can edit and inspect this
35 ;; buffer, or you can just save it with C-x C-w. `M-x htmlize-file'
36 ;; will find a file, fontify it, and save the HTML version in
37 ;; FILE.html, without any additional intervention. `M-x
38 ;; htmlize-many-files' allows you to htmlize any number of files in
39 ;; the same manner. `M-x htmlize-many-files-dired' does the same for
40 ;; files marked in a dired buffer.
42 ;; htmlize supports three types of HTML output, selected by setting
43 ;; `htmlize-output-type': `css', `inline-css', and `font'. In `css'
44 ;; mode, htmlize uses cascading style sheets to specify colors; it
45 ;; generates classes that correspond to Emacs faces and uses <span
46 ;; class=FACE>...</span> to color parts of text. In this mode, the
47 ;; produced HTML is valid under the 4.01 strict DTD, as confirmed by
48 ;; the W3C validator. `inline-css' is like `css', except the CSS is
49 ;; put directly in the STYLE attribute of the SPAN element, making it
50 ;; possible to paste the generated HTML into existing HTML documents.
51 ;; In `font' mode, htmlize uses <font color="...">...</font> to
52 ;; colorize HTML, which is not standard-compliant, but works better in
53 ;; older browsers. `css' mode is the default.
55 ;; You can also use htmlize from your Emacs Lisp code. When called
56 ;; non-interactively, `htmlize-buffer' and `htmlize-region' will
57 ;; return the resulting HTML buffer, but will not change current
58 ;; buffer or move the point. htmlize will do its best to work on
59 ;; non-windowing Emacs sessions but the result will be limited to
60 ;; colors supported by the terminal.
62 ;; htmlize aims for compatibility with Emacsen version 21 and later.
63 ;; Please let me know if it doesn't work on the version of XEmacs or
64 ;; GNU Emacs that you are using. The package relies on the presence
65 ;; of CL extensions, especially for cross-emacs compatibility; please
66 ;; don't try to remove that dependency. I see no practical problems
67 ;; with using the full power of the CL extensions, except that one
68 ;; might learn to like them too much.
70 ;; The latest version is available as a git repository at:
72 ;; <http://fly.srk.fer.hr/~hniksic/emacs/htmlize.git>
74 ;; The snapshot of the latest release can be obtained at:
76 ;; <http://fly.srk.fer.hr/~hniksic/emacs/htmlize.el.cgi>
78 ;; You can find a sample of htmlize's output (possibly generated with
79 ;; an older version) at:
81 ;; <http://fly.srk.fer.hr/~hniksic/emacs/htmlize.el.html>
83 ;; Thanks go to the many people who have sent reports and contributed
84 ;; comments, suggestions, and fixes. They include Ron Gut, Bob
85 ;; Weiner, Toni Drabik, Peter Breton, Ville Skytta, Thomas Vogels,
86 ;; Juri Linkov, Maciek Pasternacki, and many others.
88 ;; User quotes: "You sir, are a sick, sick, _sick_ person. :)"
89 ;; -- Bill Perry, author of Emacs/W3
92 ;;; Code:
94 (require 'cl)
95 (eval-when-compile
96 (defvar unresolved)
97 (if (string-match "XEmacs" emacs-version)
98 (byte-compiler-options
99 (warnings (- unresolved))))
100 (defvar font-lock-auto-fontify)
101 (defvar font-lock-support-mode)
102 (defvar global-font-lock-mode))
104 (defconst htmlize-version "1.43")
106 (defgroup htmlize nil
107 "Convert buffer text and faces to HTML."
108 :group 'hypermedia)
110 (defcustom htmlize-head-tags ""
111 "Additional tags to insert within HEAD of the generated document."
112 :type 'string
113 :group 'htmlize)
115 (defcustom htmlize-output-type 'css
116 "Output type of generated HTML, one of `css', `inline-css', or `font'.
117 When set to `css' (the default), htmlize will generate a style sheet
118 with description of faces, and use it in the HTML document, specifying
119 the faces in the actual text with <span class=\"FACE\">.
121 When set to `inline-css', the style will be generated as above, but
122 placed directly in the STYLE attribute of the span ELEMENT: <span
123 style=\"STYLE\">. This makes it easier to paste the resulting HTML to
124 other documents.
126 When set to `font', the properties will be set using layout tags
127 <font>, <b>, <i>, <u>, and <strike>.
129 `css' output is normally preferred, but `font' is still useful for
130 supporting old, pre-CSS browsers, and both `inline-css' and `font' for
131 easier embedding of colorized text in foreign HTML documents (no style
132 sheet to carry around)."
133 :type '(choice (const css) (const inline-css) (const font))
134 :group 'htmlize)
136 (defcustom htmlize-use-images t
137 "Whether htmlize generates `img' for images attached to buffer contents."
138 :type 'boolean
139 :group 'htmlize)
141 (defcustom htmlize-force-inline-images nil
142 "Non-nil means generate all images inline using data URLs.
143 Normally htmlize converts image descriptors with :file properties to
144 relative URIs, and those with :data properties to data URIs. With this
145 flag set, the images specified as a file name are loaded into memory and
146 embedded in the HTML as data URIs."
147 :type 'boolean
148 :group 'htmlize)
150 (defcustom htmlize-max-alt-text 100
151 "Maximum size of text to use as ALT text in images.
153 Normally when htmlize encounters text covered by the `display' property
154 that specifies an image, it generates an `alt' attribute containing the
155 original text. If the text is larger than `htmlize-max-alt-text' characters,
156 this will not be done.")
158 (defcustom htmlize-transform-image 'htmlize-default-transform-image
159 "Function called to modify the image descriptor.
161 The function is called with the image descriptor found in the buffer and
162 the text the image is supposed to replace. It should return a (possibly
163 different) image descriptor property list or a replacement string to use
164 instead of of the original buffer text.
166 Returning nil is the same as returning the original text."
167 :type 'boolean
168 :group 'htmlize)
170 (defcustom htmlize-generate-hyperlinks t
171 "Non-nil means auto-generate the links from URLs and mail addresses in buffer.
173 This is on by default; set it to nil if you don't want htmlize to
174 autogenerate such links. Note that this option only turns off automatic
175 search for contents that looks like URLs and converting them to links.
176 It has no effect on whether htmlize respects the `htmlize-link' property."
177 :type 'boolean
178 :group 'htmlize)
180 (defcustom htmlize-hyperlink-style "
182 color: inherit;
183 background-color: inherit;
184 font: inherit;
185 text-decoration: inherit;
187 a:hover {
188 text-decoration: underline;
191 "The CSS style used for hyperlinks when in CSS mode."
192 :type 'string
193 :group 'htmlize)
195 (defcustom htmlize-replace-form-feeds t
196 "Non-nil means replace form feeds in source code with HTML separators.
197 Form feeds are the ^L characters at line beginnings that are sometimes
198 used to separate sections of source code. If this variable is set to
199 `t', form feed characters are replaced with the <hr> separator. If this
200 is a string, it specifies the replacement to use. Note that <pre> is
201 temporarily closed before the separator is inserted, so the default
202 replacement is effectively \"</pre><hr /><pre>\". If you specify
203 another replacement, don't forget to close and reopen the <pre> if you
204 want the output to remain valid HTML.
206 If you need more elaborate processing, set this to nil and use
207 htmlize-after-hook."
208 :type 'boolean
209 :group 'htmlize)
211 (defcustom htmlize-html-charset nil
212 "The charset declared by the resulting HTML documents.
213 When non-nil, causes htmlize to insert the following in the HEAD section
214 of the generated HTML:
216 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=CHARSET\">
218 where CHARSET is the value you've set for htmlize-html-charset. Valid
219 charsets are defined by MIME and include strings like \"iso-8859-1\",
220 \"iso-8859-15\", \"utf-8\", etc.
222 If you are using non-Latin-1 charsets, you might need to set this for
223 your documents to render correctly. Also, the W3C validator requires
224 submitted HTML documents to declare a charset. So if you care about
225 validation, you can use this to prevent the validator from bitching.
227 Needless to say, if you set this, you should actually make sure that
228 the buffer is in the encoding you're claiming it is in. (This is
229 normally achieved by using the correct file coding system for the
230 buffer.) If you don't understand what that means, you should probably
231 leave this option in its default setting."
232 :type '(choice (const :tag "Unset" nil)
233 string)
234 :group 'htmlize)
236 (defcustom htmlize-convert-nonascii-to-entities t
237 "Whether non-ASCII characters should be converted to HTML entities.
239 When this is non-nil, characters with codes in the 128-255 range will be
240 considered Latin 1 and rewritten as \"&#CODE;\". Characters with codes
241 above 255 will be converted to \"&#UCS;\", where UCS denotes the Unicode
242 code point of the character. If the code point cannot be determined,
243 the character will be copied unchanged, as would be the case if the
244 option were nil.
246 When the option is nil, the non-ASCII characters are copied to HTML
247 without modification. In that case, the web server and/or the browser
248 must be set to understand the encoding that was used when saving the
249 buffer. (You might also want to specify it by setting
250 `htmlize-html-charset'.)
252 Note that in an HTML entity \"&#CODE;\", CODE is always a UCS code point,
253 which has nothing to do with the charset the page is in. For example,
254 \"&#169;\" *always* refers to the copyright symbol, regardless of charset
255 specified by the META tag or the charset sent by the HTTP server. In
256 other words, \"&#169;\" is exactly equivalent to \"&copy;\".
258 For most people htmlize will work fine with this option left at the
259 default setting; don't change it unless you know what you're doing."
260 :type 'sexp
261 :group 'htmlize)
263 (defcustom htmlize-ignore-face-size 'absolute
264 "Whether face size should be ignored when generating HTML.
265 If this is nil, face sizes are used. If set to t, sizes are ignored
266 If set to `absolute', only absolute size specifications are ignored.
267 Please note that font sizes only work with CSS-based output types."
268 :type '(choice (const :tag "Don't ignore" nil)
269 (const :tag "Ignore all" t)
270 (const :tag "Ignore absolute" absolute))
271 :group 'htmlize)
273 (defcustom htmlize-css-name-prefix ""
274 "The prefix used for CSS names.
275 The CSS names that htmlize generates from face names are often too
276 generic for CSS files; for example, `font-lock-type-face' is transformed
277 to `type'. Use this variable to add a prefix to the generated names.
278 The string \"htmlize-\" is an example of a reasonable prefix."
279 :type 'string
280 :group 'htmlize)
282 (defcustom htmlize-use-rgb-txt t
283 "Whether `rgb.txt' should be used to convert color names to RGB.
285 This conversion means determining, for instance, that the color
286 \"IndianRed\" corresponds to the (205, 92, 92) RGB triple. `rgb.txt'
287 is the X color database that maps hundreds of color names to such RGB
288 triples. When this variable is non-nil, `htmlize' uses `rgb.txt' to
289 look up color names.
291 If this variable is nil, htmlize queries Emacs for RGB components of
292 colors using `color-instance-rgb-components' and `color-values'.
293 This can yield incorrect results on non-true-color displays.
295 If the `rgb.txt' file is not found (which will be the case if you're
296 running Emacs on non-X11 systems), this option is ignored."
297 :type 'boolean
298 :group 'htmlize)
300 (defcustom htmlize-html-major-mode nil
301 "The mode the newly created HTML buffer will be put in.
302 Set this to nil if you prefer the default (fundamental) mode."
303 :type '(radio (const :tag "No mode (fundamental)" nil)
304 (function-item html-mode)
305 (function :tag "User-defined major mode"))
306 :group 'htmlize)
308 (defvar htmlize-before-hook nil
309 "Hook run before htmlizing a buffer.
310 The hook functions are run in the source buffer (not the resulting HTML
311 buffer).")
313 (defvar htmlize-after-hook nil
314 "Hook run after htmlizing a buffer.
315 Unlike `htmlize-before-hook', these functions are run in the generated
316 HTML buffer. You may use them to modify the outlook of the final HTML
317 output.")
319 (defvar htmlize-file-hook nil
320 "Hook run by `htmlize-file' after htmlizing a file, but before saving it.")
322 (defvar htmlize-buffer-places)
324 ;;; Some cross-Emacs compatibility.
326 ;; I try to conditionalize on features rather than Emacs version, but
327 ;; in some cases checking against the version *is* necessary.
328 (defconst htmlize-running-xemacs (string-match "XEmacs" emacs-version))
330 ;; We need a function that efficiently finds the next change of a
331 ;; property regardless of whether the change occurred because of a
332 ;; text property or an extent/overlay.
333 (cond
334 (htmlize-running-xemacs
335 (defun htmlize-next-change (pos prop &optional limit)
336 (if prop
337 (next-single-char-property-change pos prop nil (or limit (point-max)))
338 (next-property-change pos nil (or limit (point-max)))))
339 (defun htmlize-next-face-change (pos &optional limit)
340 (htmlize-next-change pos 'face limit)))
341 ((fboundp 'next-single-char-property-change)
342 ;; GNU Emacs 21+
343 (defun htmlize-next-change (pos prop &optional limit)
344 (if prop
345 (next-single-char-property-change pos prop nil limit)
346 (next-char-property-change pos limit)))
347 (defun htmlize-overlay-faces-at (pos)
348 (delq nil (mapcar (lambda (o) (overlay-get o 'face)) (overlays-at pos))))
349 (defun htmlize-next-face-change (pos &optional limit)
350 ;; (htmlize-next-change pos 'face limit) would skip over entire
351 ;; overlays that specify the `face' property, even when they
352 ;; contain smaller text properties that also specify `face'.
353 ;; Emacs display engine merges those faces, and so must we.
354 (or limit
355 (setq limit (point-max)))
356 (let ((next-prop (next-single-property-change pos 'face nil limit))
357 (overlay-faces (htmlize-overlay-faces-at pos)))
358 (while (progn
359 (setq pos (next-overlay-change pos))
360 (and (< pos next-prop)
361 (equal overlay-faces (htmlize-overlay-faces-at pos)))))
362 (setq pos (min pos next-prop))
363 ;; Additionally, we include the entire region that specifies the
364 ;; `display' property.
365 (when (get-char-property pos 'display)
366 (setq pos (next-single-char-property-change pos 'display nil limit)))
367 pos)))
369 (error "htmlize requires next-single-property-change or \
370 next-single-char-property-change")))
372 (defmacro htmlize-lexlet (&rest letforms)
373 (declare (indent 1) (debug let))
374 (if (and (boundp 'lexical-binding)
375 lexical-binding)
376 `(let ,@letforms)
377 ;; cl extensions have a macro implementing lexical let
378 `(lexical-let ,@letforms)))
380 ;; Simple overlay emulation for XEmacs
382 (cond
383 (htmlize-running-xemacs
384 (defalias 'htmlize-make-overlay 'make-extent)
385 (defalias 'htmlize-overlay-put 'set-extent-property)
386 (defalias 'htmlize-overlay-get 'extent-property)
387 (defun htmlize-overlays-in (beg end) (extent-list nil beg end))
388 (defalias 'htmlize-delete-overlay 'detach-extent))
390 (defalias 'htmlize-make-overlay 'make-overlay)
391 (defalias 'htmlize-overlay-put 'overlay-put)
392 (defalias 'htmlize-overlay-get 'overlay-get)
393 (defalias 'htmlize-overlays-in 'overlays-in)
394 (defalias 'htmlize-delete-overlay 'delete-overlay)))
397 ;;; Transformation of buffer text: HTML escapes, untabification, etc.
399 (defvar htmlize-basic-character-table
400 ;; Map characters in the 0-127 range to either one-character strings
401 ;; or to numeric entities.
402 (let ((table (make-vector 128 ?\0)))
403 ;; Map characters in the 32-126 range to themselves, others to
404 ;; &#CODE entities;
405 (dotimes (i 128)
406 (setf (aref table i) (if (and (>= i 32) (<= i 126))
407 (char-to-string i)
408 (format "&#%d;" i))))
409 ;; Set exceptions manually.
410 (setf
411 ;; Don't escape newline, carriage return, and TAB.
412 (aref table ?\n) "\n"
413 (aref table ?\r) "\r"
414 (aref table ?\t) "\t"
415 ;; Escape &, <, and >.
416 (aref table ?&) "&amp;"
417 (aref table ?<) "&lt;"
418 (aref table ?>) "&gt;"
419 ;; Not escaping '"' buys us a measurable speedup. It's only
420 ;; necessary to quote it for strings used in attribute values,
421 ;; which htmlize doesn't typically do.
422 ;(aref table ?\") "&quot;"
424 table))
426 ;; A cache of HTML representation of non-ASCII characters. Depending
427 ;; on the setting of `htmlize-convert-nonascii-to-entities', this maps
428 ;; non-ASCII characters to either "&#<code>;" or "<char>" (mapconcat's
429 ;; mapper must always return strings). It's only filled as characters
430 ;; are encountered, so that in a buffer with e.g. French text, it will
431 ;; only ever contain French accented characters as keys. It's cleared
432 ;; on each entry to htmlize-buffer-1 to allow modifications of
433 ;; `htmlize-convert-nonascii-to-entities' to take effect.
434 (defvar htmlize-extended-character-cache (make-hash-table :test 'eq))
436 (defun htmlize-protect-string (string)
437 "HTML-protect string, escaping HTML metacharacters and I18N chars."
438 ;; Only protecting strings that actually contain unsafe or non-ASCII
439 ;; chars removes a lot of unnecessary funcalls and consing.
440 (if (not (string-match "[^\r\n\t -%'-;=?-~]" string))
441 string
442 (mapconcat (lambda (char)
443 (cond
444 ((< char 128)
445 ;; ASCII: use htmlize-basic-character-table.
446 (aref htmlize-basic-character-table char))
447 ((gethash char htmlize-extended-character-cache)
448 ;; We've already seen this char; return the cached
449 ;; string.
451 ((not htmlize-convert-nonascii-to-entities)
452 ;; If conversion to entities is not desired, always
453 ;; copy the char literally.
454 (setf (gethash char htmlize-extended-character-cache)
455 (char-to-string char)))
456 ((< char 256)
457 ;; Latin 1: no need to call encode-char.
458 (setf (gethash char htmlize-extended-character-cache)
459 (format "&#%d;" char)))
460 ((encode-char char 'ucs)
461 ;; Must check if encode-char works for CHAR;
462 ;; it fails for Arabic and possibly elsewhere.
463 (setf (gethash char htmlize-extended-character-cache)
464 (format "&#%d;" (encode-char char 'ucs))))
466 ;; encode-char doesn't work for this char. Copy it
467 ;; unchanged and hope for the best.
468 (setf (gethash char htmlize-extended-character-cache)
469 (char-to-string char)))))
470 string "")))
472 (defun htmlize-attr-escape (string)
473 ;; Like htmlize-protect-string, but also escapes double-quoted
474 ;; strings to make it usable in attribute values.
475 (setq string (htmlize-protect-string string))
476 (if (not (string-match "\"" string))
477 string
478 (mapconcat (lambda (char)
479 (if (eql char ?\")
480 "&quot;"
481 (char-to-string char)))
482 string "")))
484 (defsubst htmlize-concat (list)
485 (if (and (consp list) (null (cdr list)))
486 ;; Don't create a new string in the common case where the list only
487 ;; consists of one element.
488 (car list)
489 (apply #'concat list)))
491 (defun htmlize-format-link (linkprops text)
492 (let ((uri (if (stringp linkprops)
493 linkprops
494 (plist-get linkprops :uri)))
495 (escaped-text (htmlize-protect-string text)))
496 (if uri
497 (format "<a href=\"%s\">%s</a>" (htmlize-attr-escape uri) escaped-text)
498 escaped-text)))
500 (defun htmlize-escape-or-link (string)
501 ;; Escape STRING and/or add hyperlinks. STRING comes from a
502 ;; `display' property.
503 (let ((pos 0) (end (length string)) outlist)
504 (while (< pos end)
505 (let* ((link (get-char-property pos 'htmlize-link string))
506 (next-link-change (next-single-property-change
507 pos 'htmlize-link string end))
508 (chunk (substring string pos next-link-change)))
509 (push
510 (cond (link
511 (htmlize-format-link link chunk))
512 ((get-char-property 0 'htmlize-literal chunk)
513 chunk)
515 (htmlize-protect-string chunk)))
516 outlist)
517 (setq pos next-link-change)))
518 (htmlize-concat (nreverse outlist))))
520 (defun htmlize-display-prop-to-html (display text)
521 (let (desc)
522 (cond ((stringp display)
523 ;; Emacs ignores recursive display properties.
524 (htmlize-escape-or-link display))
525 ((not (eq (car-safe display) 'image))
526 (htmlize-protect-string text))
527 ((null (setq desc (funcall htmlize-transform-image
528 (cdr display) text)))
529 (htmlize-escape-or-link text))
530 ((stringp desc)
531 (htmlize-escape-or-link desc))
533 (htmlize-generate-image desc text)))))
535 (defun htmlize-string-to-html (string)
536 ;; Convert the string to HTML, including images attached as
537 ;; `display' property and links as `htmlize-link' property. In a
538 ;; string without images or links, this is equivalent to
539 ;; `htmlize-protect-string'.
540 (let ((pos 0) (end (length string)) outlist)
541 (while (< pos end)
542 (let* ((display (get-char-property pos 'display string))
543 (next-display-change (next-single-property-change
544 pos 'display string end))
545 (chunk (substring string pos next-display-change)))
546 (push
547 (if display
548 (htmlize-display-prop-to-html display chunk)
549 (htmlize-escape-or-link chunk))
550 outlist)
551 (setq pos next-display-change)))
552 (htmlize-concat (nreverse outlist))))
554 (defun htmlize-default-transform-image (imgprops _text)
555 "Default transformation of image descriptor to something usable in HTML.
557 If `htmlize-use-images' is nil, the function always returns nil, meaning
558 use original text. Otherwise, it tries to find the image for images that
559 specify a file name. If `htmlize-force-inline-images' is non-nil, it also
560 converts the :file attribute to :data and returns the modified property
561 list."
562 (when htmlize-use-images
563 (when (plist-get imgprops :file)
564 (let ((location (plist-get (cdr (find-image (list imgprops))) :file)))
565 (when location
566 (setq imgprops (plist-put (copy-list imgprops) :file location)))))
567 (if htmlize-force-inline-images
568 (let ((location (plist-get imgprops :file))
569 data)
570 (when location
571 (with-temp-buffer
572 (condition-case nil
573 (progn
574 (insert-file-contents-literally location)
575 (setq data (buffer-string)))
576 (error nil))))
577 ;; if successful, return the new plist, otherwise return
578 ;; nil, which will use the original text
579 (and data
580 (plist-put (plist-put imgprops :file nil)
581 :data data)))
582 imgprops)))
584 (defun htmlize-alt-text (_imgprops origtext)
585 (and (/= (length origtext) 0)
586 (<= (length origtext) htmlize-max-alt-text)
587 (not (string-match "[\0-\x1f]" origtext))
588 origtext))
590 (defun htmlize-generate-image (imgprops origtext)
591 (let* ((alt-text (htmlize-alt-text imgprops origtext))
592 (alt-attr (if alt-text
593 (format " alt=\"%s\"" (htmlize-attr-escape alt-text))
594 "")))
595 (cond ((plist-get imgprops :file)
596 ;; Try to find the image in image-load-path
597 (let* ((found-props (cdr (find-image (list imgprops))))
598 (file (or (plist-get found-props :file)
599 (plist-get imgprops :file))))
600 (format "<img src=\"%s\"%s />"
601 (htmlize-attr-escape (file-relative-name file))
602 alt-attr)))
603 ((plist-get imgprops :data)
604 (if (equalp (plist-get imgprops :type) 'svg)
605 (plist-get imgprops :data)
606 (format "<img src=\"data:image/%s;base64,%s\"%s />"
607 (or (plist-get imgprops :type) "")
608 (base64-encode-string (plist-get imgprops :data))
609 alt-attr))))))
611 (defconst htmlize-ellipsis "...")
612 (put-text-property 0 (length htmlize-ellipsis) 'htmlize-ellipsis t htmlize-ellipsis)
614 (defun htmlize-match-inv-spec (inv)
615 (member* inv buffer-invisibility-spec
616 :key (lambda (i)
617 (if (symbolp i) i (car i)))))
619 (defun htmlize-decode-invisibility-spec (invisible)
620 ;; Return t, nil, or `ellipsis', depending on how invisible text should be inserted.
622 (if (not (listp buffer-invisibility-spec))
623 ;; If buffer-invisibility-spec is not a list, then all
624 ;; characters with non-nil `invisible' property are visible.
625 (not invisible)
627 ;; Otherwise, the value of a non-nil `invisible' property can be:
628 ;; 1. a symbol -- make the text invisible if it matches
629 ;; buffer-invisibility-spec.
630 ;; 2. a list of symbols -- make the text invisible if
631 ;; any symbol in the list matches
632 ;; buffer-invisibility-spec.
633 ;; If the match of buffer-invisibility-spec has a non-nil
634 ;; CDR, replace the invisible text with an ellipsis.
635 (let ((match (if (symbolp invisible)
636 (htmlize-match-inv-spec invisible)
637 (some #'htmlize-match-inv-spec invisible))))
638 (cond ((null match) t)
639 ((cdr-safe (car match)) 'ellipsis)
640 (t nil)))))
642 (defun htmlize-add-before-after-strings (beg end text)
643 ;; Find overlays specifying before-string and after-string in [beg,
644 ;; pos). If any are found, splice them into TEXT and return the new
645 ;; text.
646 (let (additions)
647 (dolist (overlay (overlays-in beg end))
648 (let ((before (overlay-get overlay 'before-string))
649 (after (overlay-get overlay 'after-string)))
650 (when after
651 (push (cons (- (overlay-end overlay) beg)
652 after)
653 additions))
654 (when before
655 (push (cons (- (overlay-start overlay) beg)
656 before)
657 additions))))
658 (if additions
659 (let ((textlist nil)
660 (strpos 0))
661 (dolist (add (stable-sort additions #'< :key #'car))
662 (let ((addpos (car add))
663 (addtext (cdr add)))
664 (push (substring text strpos addpos) textlist)
665 (push addtext textlist)
666 (setq strpos addpos)))
667 (push (substring text strpos) textlist)
668 (apply #'concat (nreverse textlist)))
669 text)))
671 (defun htmlize-copy-prop (prop beg end string)
672 ;; Copy the specified property from the specified region of the
673 ;; buffer to the target string. We cannot rely on Emacs to copy the
674 ;; property because we want to handle properties coming from both
675 ;; text properties and overlays.
676 (let ((pos beg))
677 (while (< pos end)
678 (let ((value (get-char-property pos prop))
679 (next-change (htmlize-next-change pos prop end)))
680 (when value
681 (put-text-property (- pos beg) (- next-change beg)
682 prop value string))
683 (setq pos next-change)))))
685 (defun htmlize-get-text-with-display (beg end)
686 ;; Like buffer-substring-no-properties, except it copies the
687 ;; `display' property from the buffer, if found.
688 (let ((text (buffer-substring-no-properties beg end)))
689 (htmlize-copy-prop 'display beg end text)
690 (htmlize-copy-prop 'htmlize-link beg end text)
691 (unless htmlize-running-xemacs
692 (setq text (htmlize-add-before-after-strings beg end text)))
693 text))
695 (defun htmlize-buffer-substring-no-invisible (beg end)
696 ;; Like buffer-substring-no-properties, but don't copy invisible
697 ;; parts of the region. Where buffer-substring-no-properties
698 ;; mandates an ellipsis to be shown, htmlize-ellipsis is inserted.
699 (let ((pos beg)
700 visible-list invisible show last-show next-change)
701 ;; Iterate over the changes in the `invisible' property and filter
702 ;; out the portions where it's non-nil, i.e. where the text is
703 ;; invisible.
704 (while (< pos end)
705 (setq invisible (get-char-property pos 'invisible)
706 next-change (htmlize-next-change pos 'invisible end)
707 show (htmlize-decode-invisibility-spec invisible))
708 (cond ((eq show t)
709 (push (htmlize-get-text-with-display pos next-change)
710 visible-list))
711 ((and (eq show 'ellipsis)
712 (not (eq last-show 'ellipsis))
713 ;; Conflate successive ellipses.
714 (push htmlize-ellipsis visible-list))))
715 (setq pos next-change last-show show))
716 (htmlize-concat (nreverse visible-list))))
718 (defun htmlize-trim-ellipsis (text)
719 ;; Remove htmlize-ellipses ("...") from the beginning of TEXT if it
720 ;; starts with it. It checks for the special property of the
721 ;; ellipsis so it doesn't work on ordinary text that begins with
722 ;; "...".
723 (if (get-text-property 0 'htmlize-ellipsis text)
724 (substring text (length htmlize-ellipsis))
725 text))
727 (defconst htmlize-tab-spaces
728 ;; A table of strings with spaces. (aref htmlize-tab-spaces 5) is
729 ;; like (make-string 5 ?\ ), except it doesn't cons.
730 (let ((v (make-vector 32 nil)))
731 (dotimes (i (length v))
732 (setf (aref v i) (make-string i ?\ )))
735 (defun htmlize-untabify (text start-column)
736 "Untabify TEXT, assuming it starts at START-COLUMN."
737 (let ((column start-column)
738 (last-match 0)
739 (chunk-start 0)
740 chunks match-pos tab-size)
741 (while (string-match "[\t\n]" text last-match)
742 (setq match-pos (match-beginning 0))
743 (cond ((eq (aref text match-pos) ?\t)
744 ;; Encountered a tab: create a chunk of text followed by
745 ;; the expanded tab.
746 (push (substring text chunk-start match-pos) chunks)
747 ;; Increase COLUMN by the length of the text we've
748 ;; skipped since last tab or newline. (Encountering
749 ;; newline resets it.)
750 (incf column (- match-pos last-match))
751 ;; Calculate tab size based on tab-width and COLUMN.
752 (setq tab-size (- tab-width (% column tab-width)))
753 ;; Expand the tab, carefully recreating the `display'
754 ;; property if one was on the TAB.
755 (let ((display (get-text-property match-pos 'display text))
756 (expanded-tab (aref htmlize-tab-spaces tab-size)))
757 (when display
758 (put-text-property 0 tab-size 'display display expanded-tab))
759 (push expanded-tab chunks))
760 (incf column tab-size)
761 (setq chunk-start (1+ match-pos)))
763 ;; Reset COLUMN at beginning of line.
764 (setq column 0)))
765 (setq last-match (1+ match-pos)))
766 ;; If no chunks have been allocated, it means there have been no
767 ;; tabs to expand. Return TEXT unmodified.
768 (if (null chunks)
769 text
770 (when (< chunk-start (length text))
771 ;; Push the remaining chunk.
772 (push (substring text chunk-start) chunks))
773 ;; Generate the output from the available chunks.
774 (htmlize-concat (nreverse chunks)))))
776 (defun htmlize-extract-text (beg end trailing-ellipsis)
777 ;; Extract buffer text, sans the invisible parts. Then
778 ;; untabify it and escape the HTML metacharacters.
779 (let ((text (htmlize-buffer-substring-no-invisible beg end)))
780 (when trailing-ellipsis
781 (setq text (htmlize-trim-ellipsis text)))
782 ;; If TEXT ends up empty, don't change trailing-ellipsis.
783 (when (> (length text) 0)
784 (setq trailing-ellipsis
785 (get-text-property (1- (length text))
786 'htmlize-ellipsis text)))
787 (setq text (htmlize-untabify text (current-column)))
788 (setq text (htmlize-string-to-html text))
789 (values text trailing-ellipsis)))
791 (defun htmlize-despam-address (string)
792 "Replace every occurrence of '@' in STRING with %40.
793 This is used to protect mailto links without modifying their meaning."
794 ;; Suggested by Ville Skytta.
795 (while (string-match "@" string)
796 (setq string (replace-match "%40" nil t string)))
797 string)
799 (defun htmlize-make-tmp-overlay (beg end props)
800 (let ((overlay (htmlize-make-overlay beg end)))
801 (htmlize-overlay-put overlay 'htmlize-tmp-overlay t)
802 (while props
803 (htmlize-overlay-put overlay (pop props) (pop props)))
804 overlay))
806 (defun htmlize-delete-tmp-overlays ()
807 (dolist (overlay (htmlize-overlays-in (point-min) (point-max)))
808 (when (htmlize-overlay-get overlay 'htmlize-tmp-overlay)
809 (htmlize-delete-overlay overlay))))
811 (defun htmlize-make-link-overlay (beg end uri)
812 (htmlize-make-tmp-overlay beg end `(htmlize-link (:uri ,uri))))
814 (defun htmlize-create-auto-links ()
815 "Add `htmlize-link' property to all mailto links in the buffer."
816 (save-excursion
817 (goto-char (point-min))
818 (while (re-search-forward
819 "<\\(\\(mailto:\\)?\\([-=+_.a-zA-Z0-9]+@[-_.a-zA-Z0-9]+\\)\\)>"
820 nil t)
821 (let* ((address (match-string 3))
822 (beg (match-beginning 0)) (end (match-end 0))
823 (uri (concat "mailto:" (htmlize-despam-address address))))
824 (htmlize-make-link-overlay beg end uri)))
825 (goto-char (point-min))
826 (while (re-search-forward "<\\(\\(URL:\\)?\\([a-zA-Z]+://[^;>]+\\)\\)>"
827 nil t)
828 (htmlize-make-link-overlay
829 (match-beginning 0) (match-end 0) (match-string 3)))))
831 ;; Tests for htmlize-create-auto-links:
833 ;; <mailto:hniksic@xemacs.org>
834 ;; <http://fly.srk.fer.hr>
835 ;; <URL:http://www.xemacs.org>
836 ;; <http://www.mail-archive.com/bbdb-info@xemacs.org/>
837 ;; <hniksic@xemacs.org>
838 ;; <xalan-dev-sc.10148567319.hacuhiucknfgmpfnjcpg-john=doe.com@xml.apache.org>
840 (defun htmlize-shadow-form-feeds ()
841 (let ((s "\n<hr />"))
842 (put-text-property 0 (length s) 'htmlize-literal t s)
843 (let ((disp `(display ,s)))
844 (while (re-search-forward "\n\^L" nil t)
845 (htmlize-make-tmp-overlay (match-beginning 0) (match-end 0) disp)))))
847 (defun htmlize-defang-local-variables ()
848 ;; Juri Linkov reports that an HTML-ized "Local variables" can lead
849 ;; visiting the HTML to fail with "Local variables list is not
850 ;; properly terminated". He suggested changing the phrase to
851 ;; syntactically equivalent HTML that Emacs doesn't recognize.
852 (goto-char (point-min))
853 (while (search-forward "Local Variables:" nil t)
854 (replace-match "Local Variables&#58;" nil t)))
857 ;;; Color handling.
859 (defvar htmlize-x-library-search-path
860 `(,data-directory
861 "/etc/X11/rgb.txt"
862 "/usr/share/X11/rgb.txt"
863 ;; the remainder of this list really belongs in a museum
864 "/usr/X11R6/lib/X11/"
865 "/usr/X11R5/lib/X11/"
866 "/usr/lib/X11R6/X11/"
867 "/usr/lib/X11R5/X11/"
868 "/usr/local/X11R6/lib/X11/"
869 "/usr/local/X11R5/lib/X11/"
870 "/usr/local/lib/X11R6/X11/"
871 "/usr/local/lib/X11R5/X11/"
872 "/usr/X11/lib/X11/"
873 "/usr/lib/X11/"
874 "/usr/local/lib/X11/"
875 "/usr/X386/lib/X11/"
876 "/usr/x386/lib/X11/"
877 "/usr/XFree86/lib/X11/"
878 "/usr/unsupported/lib/X11/"
879 "/usr/athena/lib/X11/"
880 "/usr/local/x11r5/lib/X11/"
881 "/usr/lpp/Xamples/lib/X11/"
882 "/usr/openwin/lib/X11/"
883 "/usr/openwin/share/lib/X11/"))
885 (defun htmlize-get-color-rgb-hash (&optional rgb-file)
886 "Return a hash table mapping X color names to RGB values.
887 The keys in the hash table are X11 color names, and the values are the
888 #rrggbb RGB specifications, extracted from `rgb.txt'.
890 If RGB-FILE is nil, the function will try hard to find a suitable file
891 in the system directories.
893 If no rgb.txt file is found, return nil."
894 (let ((rgb-file (or rgb-file (locate-file
895 "rgb.txt"
896 htmlize-x-library-search-path)))
897 (hash nil))
898 (when rgb-file
899 (with-temp-buffer
900 (insert-file-contents rgb-file)
901 (setq hash (make-hash-table :test 'equal))
902 (while (not (eobp))
903 (cond ((looking-at "^\\s-*\\([!#]\\|$\\)")
904 ;; Skip comments and empty lines.
906 ((looking-at
907 "[ \t]*\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\(.*\\)")
908 (setf (gethash (downcase (match-string 4)) hash)
909 (format "#%02x%02x%02x"
910 (string-to-number (match-string 1))
911 (string-to-number (match-string 2))
912 (string-to-number (match-string 3)))))
914 (error
915 "Unrecognized line in %s: %s"
916 rgb-file
917 (buffer-substring (point) (progn (end-of-line) (point))))))
918 (forward-line 1))))
919 hash))
921 ;; Compile the RGB map when loaded. On systems where rgb.txt is
922 ;; missing, the value of the variable will be nil, and rgb.txt will
923 ;; not be used.
924 (defvar htmlize-color-rgb-hash (htmlize-get-color-rgb-hash))
926 ;;; Face handling.
928 (defun htmlize-face-specifies-property (face prop)
929 ;; Return t if face specifies PROP, as opposed to it being inherited
930 ;; from the default face. The problem with e.g.
931 ;; `face-foreground-instance' is that it returns an instance for
932 ;; EVERY face because every face inherits from the default face.
933 ;; However, we'd like htmlize-face-{fore,back}ground to return nil
934 ;; when called with a face that doesn't specify its own foreground
935 ;; or background.
936 (or (eq face 'default)
937 (assq 'global (specifier-spec-list (face-property face prop)))))
939 (defun htmlize-face-color-internal (face fg)
940 ;; Used only under GNU Emacs. Return the color of FACE, but don't
941 ;; return "unspecified-fg" or "unspecified-bg". If the face is
942 ;; `default' and the color is unspecified, look up the color in
943 ;; frame parameters.
944 (let* ((function (if fg #'face-foreground #'face-background))
945 color)
946 (if (>= emacs-major-version 22)
947 ;; For GNU Emacs 22+ set INHERIT to get the inherited values.
948 (setq color (funcall function face nil t))
949 (setq color (funcall function face))
950 ;; For GNU Emacs 21 (which has `face-attribute'): if the color
951 ;; is nil, recursively check for the face's parent.
952 (when (and (null color)
953 (fboundp 'face-attribute)
954 (face-attribute face :inherit)
955 (not (eq (face-attribute face :inherit) 'unspecified)))
956 (setq color (htmlize-face-color-internal
957 (face-attribute face :inherit) fg))))
958 (when (and (eq face 'default) (null color))
959 (setq color (cdr (assq (if fg 'foreground-color 'background-color)
960 (frame-parameters)))))
961 (when (or (eq color 'unspecified)
962 (equal color "unspecified-fg")
963 (equal color "unspecified-bg"))
964 (setq color nil))
965 (when (and (eq face 'default)
966 (null color))
967 ;; Assuming black on white doesn't seem right, but I can't think
968 ;; of anything better to do.
969 (setq color (if fg "black" "white")))
970 color))
972 (defun htmlize-face-foreground (face)
973 ;; Return the name of the foreground color of FACE. If FACE does
974 ;; not specify a foreground color, return nil.
975 (cond (htmlize-running-xemacs
976 ;; XEmacs.
977 (and (htmlize-face-specifies-property face 'foreground)
978 (color-instance-name (face-foreground-instance face))))
980 ;; GNU Emacs.
981 (htmlize-face-color-internal face t))))
983 (defun htmlize-face-background (face)
984 ;; Return the name of the background color of FACE. If FACE does
985 ;; not specify a background color, return nil.
986 (cond (htmlize-running-xemacs
987 ;; XEmacs.
988 (and (htmlize-face-specifies-property face 'background)
989 (color-instance-name (face-background-instance face))))
991 ;; GNU Emacs.
992 (htmlize-face-color-internal face nil))))
994 ;; Convert COLOR to the #RRGGBB string. If COLOR is already in that
995 ;; format, it's left unchanged.
997 (defun htmlize-color-to-rgb (color)
998 (let ((rgb-string nil))
999 (cond ((null color)
1000 ;; Ignore nil COLOR because it means that the face is not
1001 ;; specifying any color. Hence (htmlize-color-to-rgb nil)
1002 ;; returns nil.
1004 ((string-match "\\`#" color)
1005 ;; The color is already in #rrggbb format.
1006 (setq rgb-string color))
1007 ((and htmlize-use-rgb-txt
1008 htmlize-color-rgb-hash)
1009 ;; Use of rgb.txt is requested, and it's available on the
1010 ;; system. Use it.
1011 (setq rgb-string (gethash (downcase color) htmlize-color-rgb-hash)))
1013 ;; We're getting the RGB components from Emacs.
1014 (let ((rgb
1015 (if (fboundp 'color-instance-rgb-components)
1016 (mapcar (lambda (arg)
1017 (/ arg 256))
1018 (color-instance-rgb-components
1019 (make-color-instance color)))
1020 (mapcar (lambda (arg)
1021 (/ arg 256))
1022 (color-values color)))))
1023 (when rgb
1024 (setq rgb-string (apply #'format "#%02x%02x%02x" rgb))))))
1025 ;; If RGB-STRING is still nil, it means the color cannot be found,
1026 ;; for whatever reason. In that case just punt and return COLOR.
1027 ;; Most browsers support a decent set of color names anyway.
1028 (or rgb-string color)))
1030 ;; We store the face properties we care about into an
1031 ;; `htmlize-fstruct' type. That way we only have to analyze face
1032 ;; properties, which can be time consuming, once per each face. The
1033 ;; mapping between Emacs faces and htmlize-fstructs is established by
1034 ;; htmlize-make-face-map. The name "fstruct" refers to variables of
1035 ;; type `htmlize-fstruct', while the term "face" is reserved for Emacs
1036 ;; faces.
1038 (defstruct htmlize-fstruct
1039 foreground ; foreground color, #rrggbb
1040 background ; background color, #rrggbb
1041 size ; size
1042 boldp ; whether face is bold
1043 italicp ; whether face is italic
1044 underlinep ; whether face is underlined
1045 overlinep ; whether face is overlined
1046 strikep ; whether face is struck through
1047 css-name ; CSS name of face
1050 (defun htmlize-face-emacs21-attr (fstruct attr value)
1051 ;; For ATTR and VALUE, set the equivalent value in FSTRUCT.
1052 (case attr
1053 (:foreground
1054 (setf (htmlize-fstruct-foreground fstruct) (htmlize-color-to-rgb value)))
1055 (:background
1056 (setf (htmlize-fstruct-background fstruct) (htmlize-color-to-rgb value)))
1057 (:height
1058 (setf (htmlize-fstruct-size fstruct) value))
1059 (:weight
1060 (when (string-match (symbol-name value) "bold")
1061 (setf (htmlize-fstruct-boldp fstruct) t)))
1062 (:slant
1063 (setf (htmlize-fstruct-italicp fstruct) (or (eq value 'italic)
1064 (eq value 'oblique))))
1065 (:bold
1066 (setf (htmlize-fstruct-boldp fstruct) value))
1067 (:italic
1068 (setf (htmlize-fstruct-italicp fstruct) value))
1069 (:underline
1070 (setf (htmlize-fstruct-underlinep fstruct) value))
1071 (:overline
1072 (setf (htmlize-fstruct-overlinep fstruct) value))
1073 (:strike-through
1074 (setf (htmlize-fstruct-strikep fstruct) value))))
1076 (defun htmlize-face-size (face)
1077 ;; The size (height) of FACE, taking inheritance into account.
1078 ;; Only works in Emacs 21 and later.
1079 (let ((size-list
1080 (loop
1081 for f = face then (face-attribute f :inherit)
1082 until (or (not f) (eq f 'unspecified))
1083 for h = (face-attribute f :height)
1084 collect (if (eq h 'unspecified) nil h))))
1085 (reduce 'htmlize-merge-size (cons nil size-list))))
1087 (defun htmlize-face-css-name (face)
1088 ;; Generate the css-name property for the given face. Emacs places
1089 ;; no restrictions on the names of symbols that represent faces --
1090 ;; any characters may be in the name, even control chars. We try
1091 ;; hard to beat the face name into shape, both esthetically and
1092 ;; according to CSS1 specs.
1093 (let ((name (downcase (symbol-name face))))
1094 (when (string-match "\\`font-lock-" name)
1095 ;; font-lock-FOO-face -> FOO.
1096 (setq name (replace-match "" t t name)))
1097 (when (string-match "-face\\'" name)
1098 ;; Drop the redundant "-face" suffix.
1099 (setq name (replace-match "" t t name)))
1100 (while (string-match "[^-a-zA-Z0-9]" name)
1101 ;; Drop the non-alphanumerics.
1102 (setq name (replace-match "X" t t name)))
1103 (when (string-match "\\`[-0-9]" name)
1104 ;; CSS identifiers may not start with a digit.
1105 (setq name (concat "X" name)))
1106 ;; After these transformations, the face could come out empty.
1107 (when (equal name "")
1108 (setq name "face"))
1109 ;; Apply the prefix.
1110 (concat htmlize-css-name-prefix name)))
1112 (defun htmlize-face-to-fstruct (face)
1113 "Convert Emacs face FACE to fstruct."
1114 (let ((fstruct (make-htmlize-fstruct
1115 :foreground (htmlize-color-to-rgb
1116 (htmlize-face-foreground face))
1117 :background (htmlize-color-to-rgb
1118 (htmlize-face-background face)))))
1119 (if htmlize-running-xemacs
1120 ;; XEmacs doesn't provide a way to detect whether a face is
1121 ;; bold or italic, so we need to examine the font instance.
1122 (let* ((font-instance (face-font-instance face))
1123 (props (font-instance-properties font-instance)))
1124 (when (equalp (cdr (assq 'WEIGHT_NAME props)) "bold")
1125 (setf (htmlize-fstruct-boldp fstruct) t))
1126 (when (or (equalp (cdr (assq 'SLANT props)) "i")
1127 (equalp (cdr (assq 'SLANT props)) "o"))
1128 (setf (htmlize-fstruct-italicp fstruct) t))
1129 (setf (htmlize-fstruct-strikep fstruct)
1130 (face-strikethru-p face))
1131 (setf (htmlize-fstruct-underlinep fstruct)
1132 (face-underline-p face)))
1133 ;; GNU Emacs
1134 (dolist (attr '(:weight :slant :underline :overline :strike-through))
1135 (let ((value (if (>= emacs-major-version 22)
1136 ;; Use the INHERIT arg in GNU Emacs 22.
1137 (face-attribute face attr nil t)
1138 ;; Otherwise, fake it.
1139 (let ((face face))
1140 (while (and (eq (face-attribute face attr)
1141 'unspecified)
1142 (not (eq (face-attribute face :inherit)
1143 'unspecified)))
1144 (setq face (face-attribute face :inherit)))
1145 (face-attribute face attr)))))
1146 (when (and value (not (eq value 'unspecified)))
1147 (htmlize-face-emacs21-attr fstruct attr value))))
1148 (let ((size (htmlize-face-size face)))
1149 (unless (eql size 1.0) ; ignore non-spec
1150 (setf (htmlize-fstruct-size fstruct) size))))
1151 (setf (htmlize-fstruct-css-name fstruct) (htmlize-face-css-name face))
1152 fstruct))
1154 (defmacro htmlize-copy-attr-if-set (attr-list dest source)
1155 ;; Generate code with the following pattern:
1156 ;; (progn
1157 ;; (when (htmlize-fstruct-ATTR source)
1158 ;; (setf (htmlize-fstruct-ATTR dest) (htmlize-fstruct-ATTR source)))
1159 ;; ...)
1160 ;; for the given list of boolean attributes.
1161 (cons 'progn
1162 (loop for attr in attr-list
1163 for attr-sym = (intern (format "htmlize-fstruct-%s" attr))
1164 collect `(when (,attr-sym ,source)
1165 (setf (,attr-sym ,dest) (,attr-sym ,source))))))
1167 (defun htmlize-merge-size (merged next)
1168 ;; Calculate the size of the merge of MERGED and NEXT.
1169 (cond ((null merged) next)
1170 ((integerp next) next)
1171 ((null next) merged)
1172 ((floatp merged) (* merged next))
1173 ((integerp merged) (round (* merged next)))))
1175 (defun htmlize-merge-two-faces (merged next)
1176 (htmlize-copy-attr-if-set
1177 (foreground background boldp italicp underlinep overlinep strikep)
1178 merged next)
1179 (setf (htmlize-fstruct-size merged)
1180 (htmlize-merge-size (htmlize-fstruct-size merged)
1181 (htmlize-fstruct-size next)))
1182 merged)
1184 (defun htmlize-merge-faces (fstruct-list)
1185 (cond ((null fstruct-list)
1186 ;; Nothing to do, return a dummy face.
1187 (make-htmlize-fstruct))
1188 ((null (cdr fstruct-list))
1189 ;; Optimize for the common case of a single face, simply
1190 ;; return it.
1191 (car fstruct-list))
1193 (reduce #'htmlize-merge-two-faces
1194 (cons (make-htmlize-fstruct) fstruct-list)))))
1196 ;; GNU Emacs 20+ supports attribute lists in `face' properties. For
1197 ;; example, you can use `(:foreground "red" :weight bold)' as an
1198 ;; overlay's "face", or you can even use a list of such lists, etc.
1199 ;; We call those "attrlists".
1201 ;; htmlize supports attrlist by converting them to fstructs, the same
1202 ;; as with regular faces.
1204 (defun htmlize-attrlist-to-fstruct (attrlist)
1205 ;; Like htmlize-face-to-fstruct, but accepts an ATTRLIST as input.
1206 (let ((fstruct (make-htmlize-fstruct)))
1207 (cond ((eq (car attrlist) 'foreground-color)
1208 ;; ATTRLIST is (foreground-color . COLOR)
1209 (setf (htmlize-fstruct-foreground fstruct)
1210 (htmlize-color-to-rgb (cdr attrlist))))
1211 ((eq (car attrlist) 'background-color)
1212 ;; ATTRLIST is (background-color . COLOR)
1213 (setf (htmlize-fstruct-background fstruct)
1214 (htmlize-color-to-rgb (cdr attrlist))))
1216 ;; ATTRLIST is a plist.
1217 (while attrlist
1218 (let ((attr (pop attrlist))
1219 (value (pop attrlist)))
1220 (when (and value (not (eq value 'unspecified)))
1221 (htmlize-face-emacs21-attr fstruct attr value))))))
1222 (setf (htmlize-fstruct-css-name fstruct) "ATTRLIST")
1223 fstruct))
1225 (defun htmlize-decode-face-prop (prop)
1226 "Turn face property PROP into a list of face-like objects."
1227 ;; PROP can be a symbol naming a face, a string naming such a
1228 ;; symbol, a cons (foreground-color . COLOR) or (background-color
1229 ;; COLOR), a property list (:attr1 val1 :attr2 val2 ...), or a list
1230 ;; of any of those.
1232 ;; (htmlize-decode-face-prop 'face) -> (face)
1233 ;; (htmlize-decode-face-prop '(face1 face2)) -> (face1 face2)
1234 ;; (htmlize-decode-face-prop '(:attr "val")) -> ((:attr "val"))
1235 ;; (htmlize-decode-face-prop '((:attr "val") face (foreground-color "red")))
1236 ;; -> ((:attr "val") face (foreground-color "red"))
1238 ;; Unrecognized atoms or non-face symbols/strings are silently
1239 ;; stripped away.
1240 (cond ((null prop)
1241 nil)
1242 ((symbolp prop)
1243 (and (facep prop)
1244 (list prop)))
1245 ((stringp prop)
1246 (and (facep (intern-soft prop))
1247 (list prop)))
1248 ((atom prop)
1249 nil)
1250 ((and (symbolp (car prop))
1251 (eq ?: (aref (symbol-name (car prop)) 0)))
1252 (list prop))
1253 ((or (eq (car prop) 'foreground-color)
1254 (eq (car prop) 'background-color))
1255 (list prop))
1257 (apply #'nconc (mapcar #'htmlize-decode-face-prop prop)))))
1259 (defun htmlize-make-face-map (faces)
1260 ;; Return a hash table mapping Emacs faces to htmlize's fstructs.
1261 ;; The keys are either face symbols or attrlists, so the test
1262 ;; function must be `equal'.
1263 (let ((face-map (make-hash-table :test 'equal))
1264 css-names)
1265 (dolist (face faces)
1266 (unless (gethash face face-map)
1267 ;; Haven't seen FACE yet; convert it to an fstruct and cache
1268 ;; it.
1269 (let ((fstruct (if (symbolp face)
1270 (htmlize-face-to-fstruct face)
1271 (htmlize-attrlist-to-fstruct face))))
1272 (setf (gethash face face-map) fstruct)
1273 (let* ((css-name (htmlize-fstruct-css-name fstruct))
1274 (new-name css-name)
1275 (i 0))
1276 ;; Uniquify the face's css-name by using NAME-1, NAME-2,
1277 ;; etc.
1278 (while (member new-name css-names)
1279 (setq new-name (format "%s-%s" css-name (incf i))))
1280 (unless (equal new-name css-name)
1281 (setf (htmlize-fstruct-css-name fstruct) new-name))
1282 (push new-name css-names)))))
1283 face-map))
1285 (defun htmlize-unstringify-face (face)
1286 "If FACE is a string, return it interned, otherwise return it unchanged."
1287 (if (stringp face)
1288 (intern face)
1289 face))
1291 (defun htmlize-faces-in-buffer ()
1292 "Return a list of faces used in the current buffer.
1293 Under XEmacs, this returns the set of faces specified by the extents
1294 with the `face' property. (This covers text properties as well.) Under
1295 GNU Emacs, it returns the set of faces specified by the `face' text
1296 property and by buffer overlays that specify `face'."
1297 (let (faces)
1298 ;; Testing for (fboundp 'map-extents) doesn't work because W3
1299 ;; defines `map-extents' under FSF.
1300 (if htmlize-running-xemacs
1301 (let (face-prop)
1302 (map-extents (lambda (extent ignored)
1303 (setq face-prop (extent-face extent)
1304 ;; FACE-PROP can be a face or a list of
1305 ;; faces.
1306 faces (if (listp face-prop)
1307 (union face-prop faces)
1308 (adjoin face-prop faces)))
1309 nil)
1311 ;; Specify endpoints explicitly to respect
1312 ;; narrowing.
1313 (point-min) (point-max) nil nil 'face))
1314 ;; FSF Emacs code.
1315 ;; Faces used by text properties.
1316 (let ((pos (point-min)) face-prop next)
1317 (while (< pos (point-max))
1318 (setq face-prop (get-text-property pos 'face)
1319 next (or (next-single-property-change pos 'face) (point-max)))
1320 (setq faces (nunion (htmlize-decode-face-prop face-prop)
1321 faces :test 'equal))
1322 (setq pos next)))
1323 ;; Faces used by overlays.
1324 (dolist (overlay (overlays-in (point-min) (point-max)))
1325 (let ((face-prop (overlay-get overlay 'face)))
1326 (setq faces (nunion (htmlize-decode-face-prop face-prop)
1327 faces :test 'equal)))))
1328 faces))
1330 ;; htmlize-faces-at-point returns the faces in use at point. The
1331 ;; faces are sorted by increasing priority, i.e. the last face takes
1332 ;; precedence.
1334 ;; Under XEmacs, this returns all the faces in all the extents at
1335 ;; point. Under GNU Emacs, this returns all the faces in the `face'
1336 ;; property and all the faces in the overlays at point.
1338 (cond (htmlize-running-xemacs
1339 (defun htmlize-faces-at-point ()
1340 (let (extent extent-list face-list face-prop)
1341 (while (setq extent (extent-at (point) nil 'face extent))
1342 (push extent extent-list))
1343 ;; extent-list is in reverse display order, meaning that
1344 ;; smallest ones come last. That is the order we want,
1345 ;; except it can be overridden by the `priority' property.
1346 (setq extent-list (stable-sort extent-list #'<
1347 :key #'extent-priority))
1348 (dolist (extent extent-list)
1349 (setq face-prop (extent-face extent))
1350 ;; extent's face-list is in reverse order from what we
1351 ;; want, but the `nreverse' below will take care of it.
1352 (setq face-list (if (listp face-prop)
1353 (append face-prop face-list)
1354 (cons face-prop face-list))))
1355 (nreverse face-list))))
1357 (defun htmlize-faces-at-point ()
1358 (let (all-faces)
1359 ;; Faces from text properties.
1360 (let ((face-prop (get-text-property (point) 'face)))
1361 (setq all-faces (htmlize-decode-face-prop face-prop)))
1362 ;; Faces from overlays.
1363 (let ((overlays
1364 ;; Collect overlays at point that specify `face'.
1365 (delete-if-not (lambda (o)
1366 (overlay-get o 'face))
1367 (overlays-at (point))))
1368 list face-prop)
1369 ;; Sort the overlays so the smaller (more specific) ones
1370 ;; come later. The number of overlays at each one
1371 ;; position should be very small, so the sort shouldn't
1372 ;; slow things down.
1373 (setq overlays (sort* overlays
1374 ;; Sort by ascending...
1376 ;; ...overlay size.
1377 :key (lambda (o)
1378 (- (overlay-end o)
1379 (overlay-start o)))))
1380 ;; Overlay priorities, if present, override the above
1381 ;; established order. Larger overlay priority takes
1382 ;; precedence and therefore comes later in the list.
1383 (setq overlays (stable-sort
1384 overlays
1385 ;; Reorder (stably) by acending...
1387 ;; ...overlay priority.
1388 :key (lambda (o)
1389 (or (overlay-get o 'priority) 0))))
1390 (dolist (overlay overlays)
1391 (setq face-prop (overlay-get overlay 'face)
1392 list (nconc (htmlize-decode-face-prop face-prop) list)))
1393 ;; Under "Merging Faces" the manual explicitly states
1394 ;; that faces specified by overlays take precedence over
1395 ;; faces specified by text properties.
1396 (setq all-faces (nconc all-faces list)))
1397 all-faces))))
1399 ;; htmlize supports generating HTML in several flavors, some of which
1400 ;; use CSS, and others the <font> element. We take an OO approach and
1401 ;; define "methods" that indirect to the functions that depend on
1402 ;; `htmlize-output-type'. The currently used methods are `doctype',
1403 ;; `insert-head', `body-tag', and `text-markup'. Not all output types
1404 ;; define all methods.
1406 ;; Methods are called either with (htmlize-method METHOD ARGS...)
1407 ;; special form, or by accessing the function with
1408 ;; (htmlize-method-function 'METHOD) and calling (funcall FUNCTION).
1409 ;; The latter form is useful in tight loops because `htmlize-method'
1410 ;; conses.
1412 (defmacro htmlize-method (method &rest args)
1413 ;; Expand to (htmlize-TYPE-METHOD ...ARGS...). TYPE is the value of
1414 ;; `htmlize-output-type' at run time.
1415 `(funcall (htmlize-method-function ',method) ,@args))
1417 (defun htmlize-method-function (method)
1418 ;; Return METHOD's function definition for the current output type.
1419 ;; The returned object can be safely funcalled.
1420 (let ((sym (intern (format "htmlize-%s-%s" htmlize-output-type method))))
1421 (indirect-function (if (fboundp sym)
1423 (let ((default (intern (concat "htmlize-default-"
1424 (symbol-name method)))))
1425 (if (fboundp default)
1426 default
1427 'ignore))))))
1429 (defvar htmlize-memoization-table (make-hash-table :test 'equal))
1431 (defmacro htmlize-memoize (key generator)
1432 "Return the value of GENERATOR, memoized as KEY.
1433 That means that GENERATOR will be evaluated and returned the first time
1434 it's called with the same value of KEY. All other times, the cached
1435 \(memoized) value will be returned."
1436 (let ((value (gensym)))
1437 `(let ((,value (gethash ,key htmlize-memoization-table)))
1438 (unless ,value
1439 (setq ,value ,generator)
1440 (setf (gethash ,key htmlize-memoization-table) ,value))
1441 ,value)))
1443 ;;; Default methods.
1445 (defun htmlize-default-doctype ()
1446 nil ; no doc-string
1447 ;; Note that the `font' output is technically invalid under this DTD
1448 ;; because the DTD doesn't allow embedding <font> in <pre>.
1449 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\">"
1452 (defun htmlize-default-body-tag (face-map)
1453 nil ; no doc-string
1454 face-map ; shut up the byte-compiler
1455 "<body>")
1457 ;;; CSS based output support.
1459 ;; Internal function; not a method.
1460 (defun htmlize-css-specs (fstruct)
1461 (let (result)
1462 (when (htmlize-fstruct-foreground fstruct)
1463 (push (format "color: %s;" (htmlize-fstruct-foreground fstruct))
1464 result))
1465 (when (htmlize-fstruct-background fstruct)
1466 (push (format "background-color: %s;"
1467 (htmlize-fstruct-background fstruct))
1468 result))
1469 (let ((size (htmlize-fstruct-size fstruct)))
1470 (when (and size (not (eq htmlize-ignore-face-size t)))
1471 (cond ((floatp size)
1472 (push (format "font-size: %d%%;" (* 100 size)) result))
1473 ((not (eq htmlize-ignore-face-size 'absolute))
1474 (push (format "font-size: %spt;" (/ size 10.0)) result)))))
1475 (when (htmlize-fstruct-boldp fstruct)
1476 (push "font-weight: bold;" result))
1477 (when (htmlize-fstruct-italicp fstruct)
1478 (push "font-style: italic;" result))
1479 (when (htmlize-fstruct-underlinep fstruct)
1480 (push "text-decoration: underline;" result))
1481 (when (htmlize-fstruct-overlinep fstruct)
1482 (push "text-decoration: overline;" result))
1483 (when (htmlize-fstruct-strikep fstruct)
1484 (push "text-decoration: line-through;" result))
1485 (nreverse result)))
1487 (defun htmlize-css-insert-head (buffer-faces face-map)
1488 (insert " <style type=\"text/css\">\n <!--\n")
1489 (insert " body {\n "
1490 (mapconcat #'identity
1491 (htmlize-css-specs (gethash 'default face-map))
1492 "\n ")
1493 "\n }\n")
1494 (dolist (face (sort* (copy-list buffer-faces) #'string-lessp
1495 :key (lambda (f)
1496 (htmlize-fstruct-css-name (gethash f face-map)))))
1497 (let* ((fstruct (gethash face face-map))
1498 (cleaned-up-face-name
1499 (let ((s
1500 ;; Use `prin1-to-string' rather than `symbol-name'
1501 ;; to get the face name because the "face" can also
1502 ;; be an attrlist, which is not a symbol.
1503 (prin1-to-string face)))
1504 ;; If the name contains `--' or `*/', remove them.
1505 (while (string-match "--" s)
1506 (setq s (replace-match "-" t t s)))
1507 (while (string-match "\\*/" s)
1508 (setq s (replace-match "XX" t t s)))
1510 (specs (htmlize-css-specs fstruct)))
1511 (insert " ." (htmlize-fstruct-css-name fstruct))
1512 (if (null specs)
1513 (insert " {")
1514 (insert " {\n /* " cleaned-up-face-name " */\n "
1515 (mapconcat #'identity specs "\n ")))
1516 (insert "\n }\n")))
1517 (insert htmlize-hyperlink-style
1518 " -->\n </style>\n"))
1520 (defun htmlize-css-text-markup (fstruct-list buffer)
1521 ;; Open the markup needed to insert text colored with FACES into
1522 ;; BUFFER. Return the function that closes the markup.
1524 ;; In CSS mode, this is easy: just nest the text in one <span
1525 ;; class=...> tag for each face in FSTRUCT-LIST.
1526 (dolist (fstruct fstruct-list)
1527 (princ "<span class=\"" buffer)
1528 (princ (htmlize-fstruct-css-name fstruct) buffer)
1529 (princ "\">" buffer))
1530 (htmlize-lexlet ((fstruct-list fstruct-list) (buffer buffer))
1531 (lambda ()
1532 (dolist (fstruct fstruct-list)
1533 (ignore fstruct) ; shut up the byte-compiler
1534 (princ "</span>" buffer)))))
1536 ;; `inline-css' output support.
1538 (defun htmlize-inline-css-body-tag (face-map)
1539 (format "<body style=\"%s\">"
1540 (mapconcat #'identity (htmlize-css-specs (gethash 'default face-map))
1541 " ")))
1543 (defun htmlize-inline-css-text-markup (fstruct-list buffer)
1544 (let* ((merged (htmlize-merge-faces fstruct-list))
1545 (style (htmlize-memoize
1546 merged
1547 (let ((specs (htmlize-css-specs merged)))
1548 (and specs
1549 (mapconcat #'identity (htmlize-css-specs merged) " "))))))
1550 (when style
1551 (princ "<span style=\"" buffer)
1552 (princ style buffer)
1553 (princ "\">" buffer))
1554 (htmlize-lexlet ((style style) (buffer buffer))
1555 (lambda ()
1556 (when style
1557 (princ "</span>" buffer))))))
1559 ;;; `font' tag based output support.
1561 (defun htmlize-font-body-tag (face-map)
1562 (let ((fstruct (gethash 'default face-map)))
1563 (format "<body text=\"%s\" bgcolor=\"%s\">"
1564 (htmlize-fstruct-foreground fstruct)
1565 (htmlize-fstruct-background fstruct))))
1567 (defun htmlize-font-text-markup (fstruct-list buffer)
1568 ;; In `font' mode, we use the traditional HTML means of altering
1569 ;; presentation: <font> tag for colors, <b> for bold, <u> for
1570 ;; underline, and <strike> for strike-through.
1571 (let* ((merged (htmlize-merge-faces fstruct-list))
1572 (markup (htmlize-memoize
1573 merged
1574 (cons (concat
1575 (and (htmlize-fstruct-foreground merged)
1576 (format "<font color=\"%s\">" (htmlize-fstruct-foreground merged)))
1577 (and (htmlize-fstruct-boldp merged) "<b>")
1578 (and (htmlize-fstruct-italicp merged) "<i>")
1579 (and (htmlize-fstruct-underlinep merged) "<u>")
1580 (and (htmlize-fstruct-strikep merged) "<strike>"))
1581 (concat
1582 (and (htmlize-fstruct-strikep merged) "</strike>")
1583 (and (htmlize-fstruct-underlinep merged) "</u>")
1584 (and (htmlize-fstruct-italicp merged) "</i>")
1585 (and (htmlize-fstruct-boldp merged) "</b>")
1586 (and (htmlize-fstruct-foreground merged) "</font>"))))))
1587 (princ (car markup) buffer)
1588 (htmlize-lexlet ((markup markup) (buffer buffer))
1589 (lambda ()
1590 (princ (cdr markup) buffer)))))
1592 (defun htmlize-buffer-1 ()
1593 ;; Internal function; don't call it from outside this file. Htmlize
1594 ;; current buffer, writing the resulting HTML to a new buffer, and
1595 ;; return it. Unlike htmlize-buffer, this doesn't change current
1596 ;; buffer or use switch-to-buffer.
1597 (save-excursion
1598 ;; Protect against the hook changing the current buffer.
1599 (save-excursion
1600 (run-hooks 'htmlize-before-hook))
1601 ;; Convince font-lock support modes to fontify the entire buffer
1602 ;; in advance.
1603 (htmlize-ensure-fontified)
1604 (clrhash htmlize-extended-character-cache)
1605 (clrhash htmlize-memoization-table)
1606 ;; It's important that the new buffer inherits default-directory
1607 ;; from the current buffer.
1608 (let ((htmlbuf (generate-new-buffer (if (buffer-file-name)
1609 (htmlize-make-file-name
1610 (file-name-nondirectory
1611 (buffer-file-name)))
1612 "*html*")))
1613 (completed nil))
1614 (unwind-protect
1615 (let* ((buffer-faces (htmlize-faces-in-buffer))
1616 (face-map (htmlize-make-face-map (adjoin 'default buffer-faces)))
1617 (places (gensym))
1618 (title (if (buffer-file-name)
1619 (file-name-nondirectory (buffer-file-name))
1620 (buffer-name))))
1621 (when htmlize-generate-hyperlinks
1622 (htmlize-create-auto-links))
1623 (when htmlize-replace-form-feeds
1624 (htmlize-shadow-form-feeds))
1626 ;; Initialize HTMLBUF and insert the HTML prolog.
1627 (with-current-buffer htmlbuf
1628 (buffer-disable-undo)
1629 (insert (htmlize-method doctype) ?\n
1630 (format "<!-- Created by htmlize-%s in %s mode. -->\n"
1631 htmlize-version htmlize-output-type)
1632 "<html>\n ")
1633 (put places 'head-start (point-marker))
1634 (insert "<head>\n"
1635 " <title>" (htmlize-protect-string title) "</title>\n"
1636 (if htmlize-html-charset
1637 (format (concat " <meta http-equiv=\"Content-Type\" "
1638 "content=\"text/html; charset=%s\">\n")
1639 htmlize-html-charset)
1641 htmlize-head-tags)
1642 (htmlize-method insert-head buffer-faces face-map)
1643 (insert " </head>")
1644 (put places 'head-end (point-marker))
1645 (insert "\n ")
1646 (put places 'body-start (point-marker))
1647 (insert (htmlize-method body-tag face-map)
1648 "\n ")
1649 (put places 'content-start (point-marker))
1650 (insert "<pre>\n"))
1651 (let ((text-markup
1652 ;; Get the inserter method, so we can funcall it inside
1653 ;; the loop. Not calling `htmlize-method' in the loop
1654 ;; body yields a measurable speed increase.
1655 (htmlize-method-function 'text-markup))
1656 ;; Declare variables used in loop body outside the loop
1657 ;; because it's faster to establish `let' bindings only
1658 ;; once.
1659 next-change text face-list trailing-ellipsis
1660 fstruct-list last-fstruct-list
1661 (close-markup (lambda ())))
1662 ;; This loop traverses and reads the source buffer, appending
1663 ;; the resulting HTML to HTMLBUF. This method is fast
1664 ;; because: 1) it doesn't require examining the text
1665 ;; properties char by char (htmlize-next-face-change is used
1666 ;; to move between runs with the same face), and 2) it doesn't
1667 ;; require frequent buffer switches, which are slow because
1668 ;; they rebind all buffer-local vars.
1669 (goto-char (point-min))
1670 (while (not (eobp))
1671 (setq next-change (htmlize-next-face-change (point)))
1672 ;; Get faces in use between (point) and NEXT-CHANGE, and
1673 ;; convert them to fstructs.
1674 (setq face-list (htmlize-faces-at-point)
1675 fstruct-list (delq nil (mapcar (lambda (f)
1676 (gethash f face-map))
1677 face-list)))
1678 (multiple-value-setq (text trailing-ellipsis)
1679 (htmlize-extract-text (point) next-change trailing-ellipsis))
1680 ;; Don't bother writing anything if there's no text (this
1681 ;; happens in invisible regions).
1682 (when (> (length text) 0)
1683 ;; Open the new markup if necessary and insert the text.
1684 (when (not (equalp fstruct-list last-fstruct-list))
1685 (funcall close-markup)
1686 (setq last-fstruct-list fstruct-list
1687 close-markup (funcall text-markup fstruct-list htmlbuf)))
1688 (princ text htmlbuf))
1689 (goto-char next-change))
1691 ;; We've gone through the buffer; close the markup from
1692 ;; the last run, if any.
1693 (funcall close-markup))
1695 ;; Insert the epilog and post-process the buffer.
1696 (with-current-buffer htmlbuf
1697 (insert "</pre>")
1698 (put places 'content-end (point-marker))
1699 (insert "\n </body>")
1700 (put places 'body-end (point-marker))
1701 (insert "\n</html>\n")
1702 (htmlize-defang-local-variables)
1703 (goto-char (point-min))
1704 (when htmlize-html-major-mode
1705 ;; What sucks about this is that the minor modes, most notably
1706 ;; font-lock-mode, won't be initialized. Oh well.
1707 (funcall htmlize-html-major-mode))
1708 (set (make-local-variable 'htmlize-buffer-places)
1709 (symbol-plist places))
1710 (run-hooks 'htmlize-after-hook)
1711 (buffer-enable-undo))
1712 (setq completed t)
1713 htmlbuf)
1715 (when (not completed)
1716 (kill-buffer htmlbuf))
1717 (htmlize-delete-tmp-overlays)))))
1719 ;; Utility functions.
1721 (defmacro htmlize-with-fontify-message (&rest body)
1722 ;; When forcing fontification of large buffers in
1723 ;; htmlize-ensure-fontified, inform the user that he is waiting for
1724 ;; font-lock, not for htmlize to finish.
1725 `(progn
1726 (if (> (buffer-size) 65536)
1727 (message "Forcing fontification of %s..."
1728 (buffer-name (current-buffer))))
1729 ,@body
1730 (if (> (buffer-size) 65536)
1731 (message "Forcing fontification of %s...done"
1732 (buffer-name (current-buffer))))))
1734 (defun htmlize-ensure-fontified ()
1735 ;; If font-lock is being used, ensure that the "support" modes
1736 ;; actually fontify the buffer. If font-lock is not in use, we
1737 ;; don't care because, except in htmlize-file, we don't force
1738 ;; font-lock on the user.
1739 (when (and (boundp 'font-lock-mode)
1740 font-lock-mode)
1741 ;; In part taken from ps-print-ensure-fontified in GNU Emacs 21.
1742 (cond
1743 ((and (boundp 'jit-lock-mode)
1744 (symbol-value 'jit-lock-mode))
1745 (htmlize-with-fontify-message
1746 (jit-lock-fontify-now (point-min) (point-max))))
1747 ((and (boundp 'lazy-lock-mode)
1748 (symbol-value 'lazy-lock-mode))
1749 (htmlize-with-fontify-message
1750 (lazy-lock-fontify-region (point-min) (point-max))))
1751 ((and (boundp 'lazy-shot-mode)
1752 (symbol-value 'lazy-shot-mode))
1753 (htmlize-with-fontify-message
1754 ;; lazy-shot is amazing in that it must *refontify* the region,
1755 ;; even if the whole buffer has already been fontified. <sigh>
1756 (lazy-shot-fontify-region (point-min) (point-max))))
1757 ;; There's also fast-lock, but we don't need to handle specially,
1758 ;; I think. fast-lock doesn't really defer fontification, it
1759 ;; just saves it to an external cache so it's not done twice.
1763 ;;;###autoload
1764 (defun htmlize-buffer (&optional buffer)
1765 "Convert BUFFER to HTML, preserving colors and decorations.
1767 The generated HTML is available in a new buffer, which is returned.
1768 When invoked interactively, the new buffer is selected in the current
1769 window. The title of the generated document will be set to the buffer's
1770 file name or, if that's not available, to the buffer's name.
1772 Note that htmlize doesn't fontify your buffers, it only uses the
1773 decorations that are already present. If you don't set up font-lock or
1774 something else to fontify your buffers, the resulting HTML will be
1775 plain. Likewise, if you don't like the choice of colors, fix the mode
1776 that created them, or simply alter the faces it uses."
1777 (interactive)
1778 (let ((htmlbuf (with-current-buffer (or buffer (current-buffer))
1779 (htmlize-buffer-1))))
1780 (when (interactive-p)
1781 (switch-to-buffer htmlbuf))
1782 htmlbuf))
1784 ;;;###autoload
1785 (defun htmlize-region (beg end)
1786 "Convert the region to HTML, preserving colors and decorations.
1787 See `htmlize-buffer' for details."
1788 (interactive "r")
1789 ;; Don't let zmacs region highlighting end up in HTML.
1790 (when (fboundp 'zmacs-deactivate-region)
1791 (zmacs-deactivate-region))
1792 (let ((htmlbuf (save-restriction
1793 (narrow-to-region beg end)
1794 (htmlize-buffer-1))))
1795 (when (interactive-p)
1796 (switch-to-buffer htmlbuf))
1797 htmlbuf))
1799 (defun htmlize-region-for-paste (beg end)
1800 "Htmlize the region and return just the HTML as a string.
1801 This forces the `inline-css' style and only returns the HTML body,
1802 but without the BODY tag. This should make it useful for inserting
1803 the text to another HTML buffer."
1804 (let* ((htmlize-output-type 'inline-css)
1805 (htmlbuf (htmlize-region beg end)))
1806 (unwind-protect
1807 (with-current-buffer htmlbuf
1808 (buffer-substring (plist-get htmlize-buffer-places 'content-start)
1809 (plist-get htmlize-buffer-places 'content-end)))
1810 (kill-buffer htmlbuf))))
1812 (defun htmlize-make-file-name (file)
1813 "Make an HTML file name from FILE.
1815 In its default implementation, this simply appends `.html' to FILE.
1816 This function is called by htmlize to create the buffer file name, and
1817 by `htmlize-file' to create the target file name.
1819 More elaborate transformations are conceivable, such as changing FILE's
1820 extension to `.html' (\"file.c\" -> \"file.html\"). If you want them,
1821 overload this function to do it and htmlize will comply."
1822 (concat file ".html"))
1824 ;; Older implementation of htmlize-make-file-name that changes FILE's
1825 ;; extension to ".html".
1826 ;(defun htmlize-make-file-name (file)
1827 ; (let ((extension (file-name-extension file))
1828 ; (sans-extension (file-name-sans-extension file)))
1829 ; (if (or (equal extension "html")
1830 ; (equal extension "htm")
1831 ; (equal sans-extension ""))
1832 ; (concat file ".html")
1833 ; (concat sans-extension ".html"))))
1835 ;;;###autoload
1836 (defun htmlize-file (file &optional target)
1837 "Load FILE, fontify it, convert it to HTML, and save the result.
1839 Contents of FILE are inserted into a temporary buffer, whose major mode
1840 is set with `normal-mode' as appropriate for the file type. The buffer
1841 is subsequently fontified with `font-lock' and converted to HTML. Note
1842 that, unlike `htmlize-buffer', this function explicitly turns on
1843 font-lock. If a form of highlighting other than font-lock is desired,
1844 please use `htmlize-buffer' directly on buffers so highlighted.
1846 Buffers currently visiting FILE are unaffected by this function. The
1847 function does not change current buffer or move the point.
1849 If TARGET is specified and names a directory, the resulting file will be
1850 saved there instead of to FILE's directory. If TARGET is specified and
1851 does not name a directory, it will be used as output file name."
1852 (interactive (list (read-file-name
1853 "HTML-ize file: "
1854 nil nil nil (and (buffer-file-name)
1855 (file-name-nondirectory
1856 (buffer-file-name))))))
1857 (let ((output-file (if (and target (not (file-directory-p target)))
1858 target
1859 (expand-file-name
1860 (htmlize-make-file-name (file-name-nondirectory file))
1861 (or target (file-name-directory file)))))
1862 ;; Try to prevent `find-file-noselect' from triggering
1863 ;; font-lock because we'll fontify explicitly below.
1864 (font-lock-mode nil)
1865 (font-lock-auto-fontify nil)
1866 (global-font-lock-mode nil)
1867 ;; Ignore the size limit for the purposes of htmlization.
1868 (font-lock-maximum-size nil)
1869 ;; Disable font-lock support modes. This will only work in
1870 ;; more recent Emacs versions, so htmlize-buffer-1 still needs
1871 ;; to call htmlize-ensure-fontified.
1872 (font-lock-support-mode nil))
1873 (with-temp-buffer
1874 ;; Insert FILE into the temporary buffer.
1875 (insert-file-contents file)
1876 ;; Set the file name so normal-mode and htmlize-buffer-1 pick it
1877 ;; up. Restore it afterwards so with-temp-buffer's kill-buffer
1878 ;; doesn't complain about killing a modified buffer.
1879 (let ((buffer-file-name file))
1880 ;; Set the major mode for the sake of font-lock.
1881 (normal-mode)
1882 (font-lock-mode 1)
1883 (unless font-lock-mode
1884 ;; In GNU Emacs (font-lock-mode 1) doesn't force font-lock,
1885 ;; contrary to the documentation. This seems to work.
1886 (font-lock-fontify-buffer))
1887 ;; htmlize the buffer and save the HTML.
1888 (with-current-buffer (htmlize-buffer-1)
1889 (unwind-protect
1890 (progn
1891 (run-hooks 'htmlize-file-hook)
1892 (write-region (point-min) (point-max) output-file))
1893 (kill-buffer (current-buffer)))))))
1894 ;; I haven't decided on a useful return value yet, so just return
1895 ;; nil.
1896 nil)
1898 ;;;###autoload
1899 (defun htmlize-many-files (files &optional target-directory)
1900 "Convert FILES to HTML and save the corresponding HTML versions.
1902 FILES should be a list of file names to convert. This function calls
1903 `htmlize-file' on each file; see that function for details. When
1904 invoked interactively, you are prompted for a list of files to convert,
1905 terminated with RET.
1907 If TARGET-DIRECTORY is specified, the HTML files will be saved to that
1908 directory. Normally, each HTML file is saved to the directory of the
1909 corresponding source file."
1910 (interactive
1911 (list
1912 (let (list file)
1913 ;; Use empty string as DEFAULT because setting DEFAULT to nil
1914 ;; defaults to the directory name, which is not what we want.
1915 (while (not (equal (setq file (read-file-name
1916 "HTML-ize file (RET to finish): "
1917 (and list (file-name-directory
1918 (car list)))
1919 "" t))
1920 ""))
1921 (push file list))
1922 (nreverse list))))
1923 ;; Verify that TARGET-DIRECTORY is indeed a directory. If it's a
1924 ;; file, htmlize-file will use it as target, and that doesn't make
1925 ;; sense.
1926 (and target-directory
1927 (not (file-directory-p target-directory))
1928 (error "target-directory must name a directory: %s" target-directory))
1929 (dolist (file files)
1930 (htmlize-file file target-directory)))
1932 ;;;###autoload
1933 (defun htmlize-many-files-dired (arg &optional target-directory)
1934 "HTMLize dired-marked files."
1935 (interactive "P")
1936 (htmlize-many-files (dired-get-marked-files nil arg) target-directory))
1938 (provide 'htmlize)
1940 ;; Local Variables:
1941 ;; byte-compile-warnings: (not cl-functions lexical unresolved obsolete)
1942 ;; lexical-binding: t
1943 ;; End:
1945 ;;; htmlize.el ends here