org.el (org-read-date-minibuffer-local-map): Check if we are at the beginning of...
[org-mode.git] / contrib / lisp / htmlize.el
blobc03d6059f27819b4835735097edacaada88a1739
1 ;;; htmlize.el --- Convert buffer text and decorations to HTML.
3 ;; Copyright (C) 1997-2013 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 (format "<img src=\"data:image/%s;base64,%s\"%s />"
605 (or (plist-get imgprops :type) "")
606 (base64-encode-string (plist-get imgprops :data))
607 alt-attr)))))
609 (defconst htmlize-ellipsis "...")
610 (put-text-property 0 (length htmlize-ellipsis) 'htmlize-ellipsis t htmlize-ellipsis)
612 (defun htmlize-match-inv-spec (inv)
613 (member* inv buffer-invisibility-spec
614 :key (lambda (i)
615 (if (symbolp i) i (car i)))))
617 (defun htmlize-decode-invisibility-spec (invisible)
618 ;; Return t, nil, or `ellipsis', depending on how invisible text should be inserted.
620 (if (not (listp buffer-invisibility-spec))
621 ;; If buffer-invisibility-spec is not a list, then all
622 ;; characters with non-nil `invisible' property are visible.
623 (not invisible)
625 ;; Otherwise, the value of a non-nil `invisible' property can be:
626 ;; 1. a symbol -- make the text invisible if it matches
627 ;; buffer-invisibility-spec.
628 ;; 2. a list of symbols -- make the text invisible if
629 ;; any symbol in the list matches
630 ;; buffer-invisibility-spec.
631 ;; If the match of buffer-invisibility-spec has a non-nil
632 ;; CDR, replace the invisible text with an ellipsis.
633 (let ((match (if (symbolp invisible)
634 (htmlize-match-inv-spec invisible)
635 (some #'htmlize-match-inv-spec invisible))))
636 (cond ((null match) t)
637 ((cdr-safe (car match)) 'ellipsis)
638 (t nil)))))
640 (defun htmlize-add-before-after-strings (beg end text)
641 ;; Find overlays specifying before-string and after-string in [beg,
642 ;; pos). If any are found, splice them into TEXT and return the new
643 ;; text.
644 (let (additions)
645 (dolist (overlay (overlays-in beg end))
646 (let ((before (overlay-get overlay 'before-string))
647 (after (overlay-get overlay 'after-string)))
648 (when after
649 (push (cons (- (overlay-end overlay) beg)
650 after)
651 additions))
652 (when before
653 (push (cons (- (overlay-start overlay) beg)
654 before)
655 additions))))
656 (if additions
657 (let ((textlist nil)
658 (strpos 0))
659 (dolist (add (stable-sort additions #'< :key #'car))
660 (let ((addpos (car add))
661 (addtext (cdr add)))
662 (push (substring text strpos addpos) textlist)
663 (push addtext textlist)
664 (setq strpos addpos)))
665 (push (substring text strpos) textlist)
666 (apply #'concat (nreverse textlist)))
667 text)))
669 (defun htmlize-copy-prop (prop beg end string)
670 ;; Copy the specified property from the specified region of the
671 ;; buffer to the target string. We cannot rely on Emacs to copy the
672 ;; property because we want to handle properties coming from both
673 ;; text properties and overlays.
674 (let ((pos beg))
675 (while (< pos end)
676 (let ((value (get-char-property pos prop))
677 (next-change (htmlize-next-change pos prop end)))
678 (when value
679 (put-text-property (- pos beg) (- next-change beg)
680 prop value string))
681 (setq pos next-change)))))
683 (defun htmlize-get-text-with-display (beg end)
684 ;; Like buffer-substring-no-properties, except it copies the
685 ;; `display' property from the buffer, if found.
686 (let ((text (buffer-substring-no-properties beg end)))
687 (htmlize-copy-prop 'display beg end text)
688 (htmlize-copy-prop 'htmlize-link beg end text)
689 (unless htmlize-running-xemacs
690 (setq text (htmlize-add-before-after-strings beg end text)))
691 text))
693 (defun htmlize-buffer-substring-no-invisible (beg end)
694 ;; Like buffer-substring-no-properties, but don't copy invisible
695 ;; parts of the region. Where buffer-substring-no-properties
696 ;; mandates an ellipsis to be shown, htmlize-ellipsis is inserted.
697 (let ((pos beg)
698 visible-list invisible show last-show next-change)
699 ;; Iterate over the changes in the `invisible' property and filter
700 ;; out the portions where it's non-nil, i.e. where the text is
701 ;; invisible.
702 (while (< pos end)
703 (setq invisible (get-char-property pos 'invisible)
704 next-change (htmlize-next-change pos 'invisible end)
705 show (htmlize-decode-invisibility-spec invisible))
706 (cond ((eq show t)
707 (push (htmlize-get-text-with-display pos next-change)
708 visible-list))
709 ((and (eq show 'ellipsis)
710 (not (eq last-show 'ellipsis))
711 ;; Conflate successive ellipses.
712 (push htmlize-ellipsis visible-list))))
713 (setq pos next-change last-show show))
714 (htmlize-concat (nreverse visible-list))))
716 (defun htmlize-trim-ellipsis (text)
717 ;; Remove htmlize-ellipses ("...") from the beginning of TEXT if it
718 ;; starts with it. It checks for the special property of the
719 ;; ellipsis so it doesn't work on ordinary text that begins with
720 ;; "...".
721 (if (get-text-property 0 'htmlize-ellipsis text)
722 (substring text (length htmlize-ellipsis))
723 text))
725 (defconst htmlize-tab-spaces
726 ;; A table of strings with spaces. (aref htmlize-tab-spaces 5) is
727 ;; like (make-string 5 ?\ ), except it doesn't cons.
728 (let ((v (make-vector 32 nil)))
729 (dotimes (i (length v))
730 (setf (aref v i) (make-string i ?\ )))
733 (defun htmlize-untabify (text start-column)
734 "Untabify TEXT, assuming it starts at START-COLUMN."
735 (let ((column start-column)
736 (last-match 0)
737 (chunk-start 0)
738 chunks match-pos tab-size)
739 (while (string-match "[\t\n]" text last-match)
740 (setq match-pos (match-beginning 0))
741 (cond ((eq (aref text match-pos) ?\t)
742 ;; Encountered a tab: create a chunk of text followed by
743 ;; the expanded tab.
744 (push (substring text chunk-start match-pos) chunks)
745 ;; Increase COLUMN by the length of the text we've
746 ;; skipped since last tab or newline. (Encountering
747 ;; newline resets it.)
748 (incf column (- match-pos last-match))
749 ;; Calculate tab size based on tab-width and COLUMN.
750 (setq tab-size (- tab-width (% column tab-width)))
751 ;; Expand the tab, carefully recreating the `display'
752 ;; property if one was on the TAB.
753 (let ((display (get-text-property match-pos 'display text))
754 (expanded-tab (aref htmlize-tab-spaces tab-size)))
755 (when display
756 (put-text-property 0 tab-size 'display display expanded-tab))
757 (push expanded-tab chunks))
758 (incf column tab-size)
759 (setq chunk-start (1+ match-pos)))
761 ;; Reset COLUMN at beginning of line.
762 (setq column 0)))
763 (setq last-match (1+ match-pos)))
764 ;; If no chunks have been allocated, it means there have been no
765 ;; tabs to expand. Return TEXT unmodified.
766 (if (null chunks)
767 text
768 (when (< chunk-start (length text))
769 ;; Push the remaining chunk.
770 (push (substring text chunk-start) chunks))
771 ;; Generate the output from the available chunks.
772 (htmlize-concat (nreverse chunks)))))
774 (defun htmlize-extract-text (beg end trailing-ellipsis)
775 ;; Extract buffer text, sans the invisible parts. Then
776 ;; untabify it and escape the HTML metacharacters.
777 (let ((text (htmlize-buffer-substring-no-invisible beg end)))
778 (when trailing-ellipsis
779 (setq text (htmlize-trim-ellipsis text)))
780 ;; If TEXT ends up empty, don't change trailing-ellipsis.
781 (when (> (length text) 0)
782 (setq trailing-ellipsis
783 (get-text-property (1- (length text))
784 'htmlize-ellipsis text)))
785 (setq text (htmlize-untabify text (current-column)))
786 (setq text (htmlize-string-to-html text))
787 (values text trailing-ellipsis)))
789 (defun htmlize-despam-address (string)
790 "Replace every occurrence of '@' in STRING with %40.
791 This is used to protect mailto links without modifying their meaning."
792 ;; Suggested by Ville Skytta.
793 (while (string-match "@" string)
794 (setq string (replace-match "%40" nil t string)))
795 string)
797 (defun htmlize-make-tmp-overlay (beg end props)
798 (let ((overlay (htmlize-make-overlay beg end)))
799 (htmlize-overlay-put overlay 'htmlize-tmp-overlay t)
800 (while props
801 (htmlize-overlay-put overlay (pop props) (pop props)))
802 overlay))
804 (defun htmlize-delete-tmp-overlays ()
805 (dolist (overlay (htmlize-overlays-in (point-min) (point-max)))
806 (when (htmlize-overlay-get overlay 'htmlize-tmp-overlay)
807 (htmlize-delete-overlay overlay))))
809 (defun htmlize-make-link-overlay (beg end uri)
810 (htmlize-make-tmp-overlay beg end `(htmlize-link (:uri ,uri))))
812 (defun htmlize-create-auto-links ()
813 "Add `htmlize-link' property to all mailto links in the buffer."
814 (save-excursion
815 (goto-char (point-min))
816 (while (re-search-forward
817 "<\\(\\(mailto:\\)?\\([-=+_.a-zA-Z0-9]+@[-_.a-zA-Z0-9]+\\)\\)>"
818 nil t)
819 (let* ((address (match-string 3))
820 (beg (match-beginning 0)) (end (match-end 0))
821 (uri (concat "mailto:" (htmlize-despam-address address))))
822 (htmlize-make-link-overlay beg end uri)))
823 (goto-char (point-min))
824 (while (re-search-forward "<\\(\\(URL:\\)?\\([a-zA-Z]+://[^;>]+\\)\\)>"
825 nil t)
826 (htmlize-make-link-overlay
827 (match-beginning 0) (match-end 0) (match-string 3)))))
829 ;; Tests for htmlize-create-auto-links:
831 ;; <mailto:hniksic@xemacs.org>
832 ;; <http://fly.srk.fer.hr>
833 ;; <URL:http://www.xemacs.org>
834 ;; <http://www.mail-archive.com/bbdb-info@xemacs.org/>
835 ;; <hniksic@xemacs.org>
836 ;; <xalan-dev-sc.10148567319.hacuhiucknfgmpfnjcpg-john=doe.com@xml.apache.org>
838 (defun htmlize-shadow-form-feeds ()
839 (let ((s "\n<hr />"))
840 (put-text-property 0 (length s) 'htmlize-literal t s)
841 (let ((disp `(display ,s)))
842 (while (re-search-forward "\n\^L" nil t)
843 (htmlize-make-tmp-overlay (match-beginning 0) (match-end 0) disp)))))
845 (defun htmlize-defang-local-variables ()
846 ;; Juri Linkov reports that an HTML-ized "Local variables" can lead
847 ;; visiting the HTML to fail with "Local variables list is not
848 ;; properly terminated". He suggested changing the phrase to
849 ;; syntactically equivalent HTML that Emacs doesn't recognize.
850 (goto-char (point-min))
851 (while (search-forward "Local Variables:" nil t)
852 (replace-match "Local Variables&#58;" nil t)))
855 ;;; Color handling.
857 (defvar htmlize-x-library-search-path
858 `(,data-directory
859 "/etc/X11/rgb.txt"
860 "/usr/share/X11/rgb.txt"
861 ;; the remainder of this list really belongs in a museum
862 "/usr/X11R6/lib/X11/"
863 "/usr/X11R5/lib/X11/"
864 "/usr/lib/X11R6/X11/"
865 "/usr/lib/X11R5/X11/"
866 "/usr/local/X11R6/lib/X11/"
867 "/usr/local/X11R5/lib/X11/"
868 "/usr/local/lib/X11R6/X11/"
869 "/usr/local/lib/X11R5/X11/"
870 "/usr/X11/lib/X11/"
871 "/usr/lib/X11/"
872 "/usr/local/lib/X11/"
873 "/usr/X386/lib/X11/"
874 "/usr/x386/lib/X11/"
875 "/usr/XFree86/lib/X11/"
876 "/usr/unsupported/lib/X11/"
877 "/usr/athena/lib/X11/"
878 "/usr/local/x11r5/lib/X11/"
879 "/usr/lpp/Xamples/lib/X11/"
880 "/usr/openwin/lib/X11/"
881 "/usr/openwin/share/lib/X11/"))
883 (defun htmlize-get-color-rgb-hash (&optional rgb-file)
884 "Return a hash table mapping X color names to RGB values.
885 The keys in the hash table are X11 color names, and the values are the
886 #rrggbb RGB specifications, extracted from `rgb.txt'.
888 If RGB-FILE is nil, the function will try hard to find a suitable file
889 in the system directories.
891 If no rgb.txt file is found, return nil."
892 (let ((rgb-file (or rgb-file (locate-file
893 "rgb.txt"
894 htmlize-x-library-search-path)))
895 (hash nil))
896 (when rgb-file
897 (with-temp-buffer
898 (insert-file-contents rgb-file)
899 (setq hash (make-hash-table :test 'equal))
900 (while (not (eobp))
901 (cond ((looking-at "^\\s-*\\([!#]\\|$\\)")
902 ;; Skip comments and empty lines.
904 ((looking-at
905 "[ \t]*\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\(.*\\)")
906 (setf (gethash (downcase (match-string 4)) hash)
907 (format "#%02x%02x%02x"
908 (string-to-number (match-string 1))
909 (string-to-number (match-string 2))
910 (string-to-number (match-string 3)))))
912 (error
913 "Unrecognized line in %s: %s"
914 rgb-file
915 (buffer-substring (point) (progn (end-of-line) (point))))))
916 (forward-line 1))))
917 hash))
919 ;; Compile the RGB map when loaded. On systems where rgb.txt is
920 ;; missing, the value of the variable will be nil, and rgb.txt will
921 ;; not be used.
922 (defvar htmlize-color-rgb-hash (htmlize-get-color-rgb-hash))
924 ;;; Face handling.
926 (defun htmlize-face-specifies-property (face prop)
927 ;; Return t if face specifies PROP, as opposed to it being inherited
928 ;; from the default face. The problem with e.g.
929 ;; `face-foreground-instance' is that it returns an instance for
930 ;; EVERY face because every face inherits from the default face.
931 ;; However, we'd like htmlize-face-{fore,back}ground to return nil
932 ;; when called with a face that doesn't specify its own foreground
933 ;; or background.
934 (or (eq face 'default)
935 (assq 'global (specifier-spec-list (face-property face prop)))))
937 (defun htmlize-face-color-internal (face fg)
938 ;; Used only under GNU Emacs. Return the color of FACE, but don't
939 ;; return "unspecified-fg" or "unspecified-bg". If the face is
940 ;; `default' and the color is unspecified, look up the color in
941 ;; frame parameters.
942 (let* ((function (if fg #'face-foreground #'face-background))
943 color)
944 (if (>= emacs-major-version 22)
945 ;; For GNU Emacs 22+ set INHERIT to get the inherited values.
946 (setq color (funcall function face nil t))
947 (setq color (funcall function face))
948 ;; For GNU Emacs 21 (which has `face-attribute'): if the color
949 ;; is nil, recursively check for the face's parent.
950 (when (and (null color)
951 (fboundp 'face-attribute)
952 (face-attribute face :inherit)
953 (not (eq (face-attribute face :inherit) 'unspecified)))
954 (setq color (htmlize-face-color-internal
955 (face-attribute face :inherit) fg))))
956 (when (and (eq face 'default) (null color))
957 (setq color (cdr (assq (if fg 'foreground-color 'background-color)
958 (frame-parameters)))))
959 (when (or (eq color 'unspecified)
960 (equal color "unspecified-fg")
961 (equal color "unspecified-bg"))
962 (setq color nil))
963 (when (and (eq face 'default)
964 (null color))
965 ;; Assuming black on white doesn't seem right, but I can't think
966 ;; of anything better to do.
967 (setq color (if fg "black" "white")))
968 color))
970 (defun htmlize-face-foreground (face)
971 ;; Return the name of the foreground color of FACE. If FACE does
972 ;; not specify a foreground color, return nil.
973 (cond (htmlize-running-xemacs
974 ;; XEmacs.
975 (and (htmlize-face-specifies-property face 'foreground)
976 (color-instance-name (face-foreground-instance face))))
978 ;; GNU Emacs.
979 (htmlize-face-color-internal face t))))
981 (defun htmlize-face-background (face)
982 ;; Return the name of the background color of FACE. If FACE does
983 ;; not specify a background color, return nil.
984 (cond (htmlize-running-xemacs
985 ;; XEmacs.
986 (and (htmlize-face-specifies-property face 'background)
987 (color-instance-name (face-background-instance face))))
989 ;; GNU Emacs.
990 (htmlize-face-color-internal face nil))))
992 ;; Convert COLOR to the #RRGGBB string. If COLOR is already in that
993 ;; format, it's left unchanged.
995 (defun htmlize-color-to-rgb (color)
996 (let ((rgb-string nil))
997 (cond ((null color)
998 ;; Ignore nil COLOR because it means that the face is not
999 ;; specifying any color. Hence (htmlize-color-to-rgb nil)
1000 ;; returns nil.
1002 ((string-match "\\`#" color)
1003 ;; The color is already in #rrggbb format.
1004 (setq rgb-string color))
1005 ((and htmlize-use-rgb-txt
1006 htmlize-color-rgb-hash)
1007 ;; Use of rgb.txt is requested, and it's available on the
1008 ;; system. Use it.
1009 (setq rgb-string (gethash (downcase color) htmlize-color-rgb-hash)))
1011 ;; We're getting the RGB components from Emacs.
1012 (let ((rgb
1013 (if (fboundp 'color-instance-rgb-components)
1014 (mapcar (lambda (arg)
1015 (/ arg 256))
1016 (color-instance-rgb-components
1017 (make-color-instance color)))
1018 (mapcar (lambda (arg)
1019 (/ arg 256))
1020 (color-values color)))))
1021 (when rgb
1022 (setq rgb-string (apply #'format "#%02x%02x%02x" rgb))))))
1023 ;; If RGB-STRING is still nil, it means the color cannot be found,
1024 ;; for whatever reason. In that case just punt and return COLOR.
1025 ;; Most browsers support a decent set of color names anyway.
1026 (or rgb-string color)))
1028 ;; We store the face properties we care about into an
1029 ;; `htmlize-fstruct' type. That way we only have to analyze face
1030 ;; properties, which can be time consuming, once per each face. The
1031 ;; mapping between Emacs faces and htmlize-fstructs is established by
1032 ;; htmlize-make-face-map. The name "fstruct" refers to variables of
1033 ;; type `htmlize-fstruct', while the term "face" is reserved for Emacs
1034 ;; faces.
1036 (defstruct htmlize-fstruct
1037 foreground ; foreground color, #rrggbb
1038 background ; background color, #rrggbb
1039 size ; size
1040 boldp ; whether face is bold
1041 italicp ; whether face is italic
1042 underlinep ; whether face is underlined
1043 overlinep ; whether face is overlined
1044 strikep ; whether face is struck through
1045 css-name ; CSS name of face
1048 (defun htmlize-face-emacs21-attr (fstruct attr value)
1049 ;; For ATTR and VALUE, set the equivalent value in FSTRUCT.
1050 (case attr
1051 (:foreground
1052 (setf (htmlize-fstruct-foreground fstruct) (htmlize-color-to-rgb value)))
1053 (:background
1054 (setf (htmlize-fstruct-background fstruct) (htmlize-color-to-rgb value)))
1055 (:height
1056 (setf (htmlize-fstruct-size fstruct) value))
1057 (:weight
1058 (when (string-match (symbol-name value) "bold")
1059 (setf (htmlize-fstruct-boldp fstruct) t)))
1060 (:slant
1061 (setf (htmlize-fstruct-italicp fstruct) (or (eq value 'italic)
1062 (eq value 'oblique))))
1063 (:bold
1064 (setf (htmlize-fstruct-boldp fstruct) value))
1065 (:italic
1066 (setf (htmlize-fstruct-italicp fstruct) value))
1067 (:underline
1068 (setf (htmlize-fstruct-underlinep fstruct) value))
1069 (:overline
1070 (setf (htmlize-fstruct-overlinep fstruct) value))
1071 (:strike-through
1072 (setf (htmlize-fstruct-strikep fstruct) value))))
1074 (defun htmlize-face-size (face)
1075 ;; The size (height) of FACE, taking inheritance into account.
1076 ;; Only works in Emacs 21 and later.
1077 (let ((size-list
1078 (loop
1079 for f = face then (face-attribute f :inherit)
1080 until (or (not f) (eq f 'unspecified))
1081 for h = (face-attribute f :height)
1082 collect (if (eq h 'unspecified) nil h))))
1083 (reduce 'htmlize-merge-size (cons nil size-list))))
1085 (defun htmlize-face-css-name (face)
1086 ;; Generate the css-name property for the given face. Emacs places
1087 ;; no restrictions on the names of symbols that represent faces --
1088 ;; any characters may be in the name, even control chars. We try
1089 ;; hard to beat the face name into shape, both esthetically and
1090 ;; according to CSS1 specs.
1091 (let ((name (downcase (symbol-name face))))
1092 (when (string-match "\\`font-lock-" name)
1093 ;; font-lock-FOO-face -> FOO.
1094 (setq name (replace-match "" t t name)))
1095 (when (string-match "-face\\'" name)
1096 ;; Drop the redundant "-face" suffix.
1097 (setq name (replace-match "" t t name)))
1098 (while (string-match "[^-a-zA-Z0-9]" name)
1099 ;; Drop the non-alphanumerics.
1100 (setq name (replace-match "X" t t name)))
1101 (when (string-match "\\`[-0-9]" name)
1102 ;; CSS identifiers may not start with a digit.
1103 (setq name (concat "X" name)))
1104 ;; After these transformations, the face could come out empty.
1105 (when (equal name "")
1106 (setq name "face"))
1107 ;; Apply the prefix.
1108 (concat htmlize-css-name-prefix name)))
1110 (defun htmlize-face-to-fstruct (face)
1111 "Convert Emacs face FACE to fstruct."
1112 (let ((fstruct (make-htmlize-fstruct
1113 :foreground (htmlize-color-to-rgb
1114 (htmlize-face-foreground face))
1115 :background (htmlize-color-to-rgb
1116 (htmlize-face-background face)))))
1117 (if htmlize-running-xemacs
1118 ;; XEmacs doesn't provide a way to detect whether a face is
1119 ;; bold or italic, so we need to examine the font instance.
1120 (let* ((font-instance (face-font-instance face))
1121 (props (font-instance-properties font-instance)))
1122 (when (equalp (cdr (assq 'WEIGHT_NAME props)) "bold")
1123 (setf (htmlize-fstruct-boldp fstruct) t))
1124 (when (or (equalp (cdr (assq 'SLANT props)) "i")
1125 (equalp (cdr (assq 'SLANT props)) "o"))
1126 (setf (htmlize-fstruct-italicp fstruct) t))
1127 (setf (htmlize-fstruct-strikep fstruct)
1128 (face-strikethru-p face))
1129 (setf (htmlize-fstruct-underlinep fstruct)
1130 (face-underline-p face)))
1131 ;; GNU Emacs
1132 (dolist (attr '(:weight :slant :underline :overline :strike-through))
1133 (let ((value (if (>= emacs-major-version 22)
1134 ;; Use the INHERIT arg in GNU Emacs 22.
1135 (face-attribute face attr nil t)
1136 ;; Otherwise, fake it.
1137 (let ((face face))
1138 (while (and (eq (face-attribute face attr)
1139 'unspecified)
1140 (not (eq (face-attribute face :inherit)
1141 'unspecified)))
1142 (setq face (face-attribute face :inherit)))
1143 (face-attribute face attr)))))
1144 (when (and value (not (eq value 'unspecified)))
1145 (htmlize-face-emacs21-attr fstruct attr value))))
1146 (let ((size (htmlize-face-size face)))
1147 (unless (eql size 1.0) ; ignore non-spec
1148 (setf (htmlize-fstruct-size fstruct) size))))
1149 (setf (htmlize-fstruct-css-name fstruct) (htmlize-face-css-name face))
1150 fstruct))
1152 (defmacro htmlize-copy-attr-if-set (attr-list dest source)
1153 ;; Generate code with the following pattern:
1154 ;; (progn
1155 ;; (when (htmlize-fstruct-ATTR source)
1156 ;; (setf (htmlize-fstruct-ATTR dest) (htmlize-fstruct-ATTR source)))
1157 ;; ...)
1158 ;; for the given list of boolean attributes.
1159 (cons 'progn
1160 (loop for attr in attr-list
1161 for attr-sym = (intern (format "htmlize-fstruct-%s" attr))
1162 collect `(when (,attr-sym ,source)
1163 (setf (,attr-sym ,dest) (,attr-sym ,source))))))
1165 (defun htmlize-merge-size (merged next)
1166 ;; Calculate the size of the merge of MERGED and NEXT.
1167 (cond ((null merged) next)
1168 ((integerp next) next)
1169 ((null next) merged)
1170 ((floatp merged) (* merged next))
1171 ((integerp merged) (round (* merged next)))))
1173 (defun htmlize-merge-two-faces (merged next)
1174 (htmlize-copy-attr-if-set
1175 (foreground background boldp italicp underlinep overlinep strikep)
1176 merged next)
1177 (setf (htmlize-fstruct-size merged)
1178 (htmlize-merge-size (htmlize-fstruct-size merged)
1179 (htmlize-fstruct-size next)))
1180 merged)
1182 (defun htmlize-merge-faces (fstruct-list)
1183 (cond ((null fstruct-list)
1184 ;; Nothing to do, return a dummy face.
1185 (make-htmlize-fstruct))
1186 ((null (cdr fstruct-list))
1187 ;; Optimize for the common case of a single face, simply
1188 ;; return it.
1189 (car fstruct-list))
1191 (reduce #'htmlize-merge-two-faces
1192 (cons (make-htmlize-fstruct) fstruct-list)))))
1194 ;; GNU Emacs 20+ supports attribute lists in `face' properties. For
1195 ;; example, you can use `(:foreground "red" :weight bold)' as an
1196 ;; overlay's "face", or you can even use a list of such lists, etc.
1197 ;; We call those "attrlists".
1199 ;; htmlize supports attrlist by converting them to fstructs, the same
1200 ;; as with regular faces.
1202 (defun htmlize-attrlist-to-fstruct (attrlist)
1203 ;; Like htmlize-face-to-fstruct, but accepts an ATTRLIST as input.
1204 (let ((fstruct (make-htmlize-fstruct)))
1205 (cond ((eq (car attrlist) 'foreground-color)
1206 ;; ATTRLIST is (foreground-color . COLOR)
1207 (setf (htmlize-fstruct-foreground fstruct)
1208 (htmlize-color-to-rgb (cdr attrlist))))
1209 ((eq (car attrlist) 'background-color)
1210 ;; ATTRLIST is (background-color . COLOR)
1211 (setf (htmlize-fstruct-background fstruct)
1212 (htmlize-color-to-rgb (cdr attrlist))))
1214 ;; ATTRLIST is a plist.
1215 (while attrlist
1216 (let ((attr (pop attrlist))
1217 (value (pop attrlist)))
1218 (when (and value (not (eq value 'unspecified)))
1219 (htmlize-face-emacs21-attr fstruct attr value))))))
1220 (setf (htmlize-fstruct-css-name fstruct) "ATTRLIST")
1221 fstruct))
1223 (defun htmlize-decode-face-prop (prop)
1224 "Turn face property PROP into a list of face-like objects."
1225 ;; PROP can be a symbol naming a face, a string naming such a
1226 ;; symbol, a cons (foreground-color . COLOR) or (background-color
1227 ;; COLOR), a property list (:attr1 val1 :attr2 val2 ...), or a list
1228 ;; of any of those.
1230 ;; (htmlize-decode-face-prop 'face) -> (face)
1231 ;; (htmlize-decode-face-prop '(face1 face2)) -> (face1 face2)
1232 ;; (htmlize-decode-face-prop '(:attr "val")) -> ((:attr "val"))
1233 ;; (htmlize-decode-face-prop '((:attr "val") face (foreground-color "red")))
1234 ;; -> ((:attr "val") face (foreground-color "red"))
1236 ;; Unrecognized atoms or non-face symbols/strings are silently
1237 ;; stripped away.
1238 (cond ((null prop)
1239 nil)
1240 ((symbolp prop)
1241 (and (facep prop)
1242 (list prop)))
1243 ((stringp prop)
1244 (and (facep (intern-soft prop))
1245 (list prop)))
1246 ((atom prop)
1247 nil)
1248 ((and (symbolp (car prop))
1249 (eq ?: (aref (symbol-name (car prop)) 0)))
1250 (list prop))
1251 ((or (eq (car prop) 'foreground-color)
1252 (eq (car prop) 'background-color))
1253 (list prop))
1255 (apply #'nconc (mapcar #'htmlize-decode-face-prop prop)))))
1257 (defun htmlize-make-face-map (faces)
1258 ;; Return a hash table mapping Emacs faces to htmlize's fstructs.
1259 ;; The keys are either face symbols or attrlists, so the test
1260 ;; function must be `equal'.
1261 (let ((face-map (make-hash-table :test 'equal))
1262 css-names)
1263 (dolist (face faces)
1264 (unless (gethash face face-map)
1265 ;; Haven't seen FACE yet; convert it to an fstruct and cache
1266 ;; it.
1267 (let ((fstruct (if (symbolp face)
1268 (htmlize-face-to-fstruct face)
1269 (htmlize-attrlist-to-fstruct face))))
1270 (setf (gethash face face-map) fstruct)
1271 (let* ((css-name (htmlize-fstruct-css-name fstruct))
1272 (new-name css-name)
1273 (i 0))
1274 ;; Uniquify the face's css-name by using NAME-1, NAME-2,
1275 ;; etc.
1276 (while (member new-name css-names)
1277 (setq new-name (format "%s-%s" css-name (incf i))))
1278 (unless (equal new-name css-name)
1279 (setf (htmlize-fstruct-css-name fstruct) new-name))
1280 (push new-name css-names)))))
1281 face-map))
1283 (defun htmlize-unstringify-face (face)
1284 "If FACE is a string, return it interned, otherwise return it unchanged."
1285 (if (stringp face)
1286 (intern face)
1287 face))
1289 (defun htmlize-faces-in-buffer ()
1290 "Return a list of faces used in the current buffer.
1291 Under XEmacs, this returns the set of faces specified by the extents
1292 with the `face' property. (This covers text properties as well.) Under
1293 GNU Emacs, it returns the set of faces specified by the `face' text
1294 property and by buffer overlays that specify `face'."
1295 (let (faces)
1296 ;; Testing for (fboundp 'map-extents) doesn't work because W3
1297 ;; defines `map-extents' under FSF.
1298 (if htmlize-running-xemacs
1299 (let (face-prop)
1300 (map-extents (lambda (extent ignored)
1301 (setq face-prop (extent-face extent)
1302 ;; FACE-PROP can be a face or a list of
1303 ;; faces.
1304 faces (if (listp face-prop)
1305 (union face-prop faces)
1306 (adjoin face-prop faces)))
1307 nil)
1309 ;; Specify endpoints explicitly to respect
1310 ;; narrowing.
1311 (point-min) (point-max) nil nil 'face))
1312 ;; FSF Emacs code.
1313 ;; Faces used by text properties.
1314 (let ((pos (point-min)) face-prop next)
1315 (while (< pos (point-max))
1316 (setq face-prop (get-text-property pos 'face)
1317 next (or (next-single-property-change pos 'face) (point-max)))
1318 (setq faces (nunion (htmlize-decode-face-prop face-prop)
1319 faces :test 'equal))
1320 (setq pos next)))
1321 ;; Faces used by overlays.
1322 (dolist (overlay (overlays-in (point-min) (point-max)))
1323 (let ((face-prop (overlay-get overlay 'face)))
1324 (setq faces (nunion (htmlize-decode-face-prop face-prop)
1325 faces :test 'equal)))))
1326 faces))
1328 ;; htmlize-faces-at-point returns the faces in use at point. The
1329 ;; faces are sorted by increasing priority, i.e. the last face takes
1330 ;; precedence.
1332 ;; Under XEmacs, this returns all the faces in all the extents at
1333 ;; point. Under GNU Emacs, this returns all the faces in the `face'
1334 ;; property and all the faces in the overlays at point.
1336 (cond (htmlize-running-xemacs
1337 (defun htmlize-faces-at-point ()
1338 (let (extent extent-list face-list face-prop)
1339 (while (setq extent (extent-at (point) nil 'face extent))
1340 (push extent extent-list))
1341 ;; extent-list is in reverse display order, meaning that
1342 ;; smallest ones come last. That is the order we want,
1343 ;; except it can be overridden by the `priority' property.
1344 (setq extent-list (stable-sort extent-list #'<
1345 :key #'extent-priority))
1346 (dolist (extent extent-list)
1347 (setq face-prop (extent-face extent))
1348 ;; extent's face-list is in reverse order from what we
1349 ;; want, but the `nreverse' below will take care of it.
1350 (setq face-list (if (listp face-prop)
1351 (append face-prop face-list)
1352 (cons face-prop face-list))))
1353 (nreverse face-list))))
1355 (defun htmlize-faces-at-point ()
1356 (let (all-faces)
1357 ;; Faces from text properties.
1358 (let ((face-prop (get-text-property (point) 'face)))
1359 (setq all-faces (htmlize-decode-face-prop face-prop)))
1360 ;; Faces from overlays.
1361 (let ((overlays
1362 ;; Collect overlays at point that specify `face'.
1363 (delete-if-not (lambda (o)
1364 (overlay-get o 'face))
1365 (overlays-at (point))))
1366 list face-prop)
1367 ;; Sort the overlays so the smaller (more specific) ones
1368 ;; come later. The number of overlays at each one
1369 ;; position should be very small, so the sort shouldn't
1370 ;; slow things down.
1371 (setq overlays (sort* overlays
1372 ;; Sort by ascending...
1374 ;; ...overlay size.
1375 :key (lambda (o)
1376 (- (overlay-end o)
1377 (overlay-start o)))))
1378 ;; Overlay priorities, if present, override the above
1379 ;; established order. Larger overlay priority takes
1380 ;; precedence and therefore comes later in the list.
1381 (setq overlays (stable-sort
1382 overlays
1383 ;; Reorder (stably) by acending...
1385 ;; ...overlay priority.
1386 :key (lambda (o)
1387 (or (overlay-get o 'priority) 0))))
1388 (dolist (overlay overlays)
1389 (setq face-prop (overlay-get overlay 'face)
1390 list (nconc (htmlize-decode-face-prop face-prop) list)))
1391 ;; Under "Merging Faces" the manual explicitly states
1392 ;; that faces specified by overlays take precedence over
1393 ;; faces specified by text properties.
1394 (setq all-faces (nconc all-faces list)))
1395 all-faces))))
1397 ;; htmlize supports generating HTML in several flavors, some of which
1398 ;; use CSS, and others the <font> element. We take an OO approach and
1399 ;; define "methods" that indirect to the functions that depend on
1400 ;; `htmlize-output-type'. The currently used methods are `doctype',
1401 ;; `insert-head', `body-tag', and `text-markup'. Not all output types
1402 ;; define all methods.
1404 ;; Methods are called either with (htmlize-method METHOD ARGS...)
1405 ;; special form, or by accessing the function with
1406 ;; (htmlize-method-function 'METHOD) and calling (funcall FUNCTION).
1407 ;; The latter form is useful in tight loops because `htmlize-method'
1408 ;; conses.
1410 (defmacro htmlize-method (method &rest args)
1411 ;; Expand to (htmlize-TYPE-METHOD ...ARGS...). TYPE is the value of
1412 ;; `htmlize-output-type' at run time.
1413 `(funcall (htmlize-method-function ',method) ,@args))
1415 (defun htmlize-method-function (method)
1416 ;; Return METHOD's function definition for the current output type.
1417 ;; The returned object can be safely funcalled.
1418 (let ((sym (intern (format "htmlize-%s-%s" htmlize-output-type method))))
1419 (indirect-function (if (fboundp sym)
1421 (let ((default (intern (concat "htmlize-default-"
1422 (symbol-name method)))))
1423 (if (fboundp default)
1424 default
1425 'ignore))))))
1427 (defvar htmlize-memoization-table (make-hash-table :test 'equal))
1429 (defmacro htmlize-memoize (key generator)
1430 "Return the value of GENERATOR, memoized as KEY.
1431 That means that GENERATOR will be evaluated and returned the first time
1432 it's called with the same value of KEY. All other times, the cached
1433 \(memoized) value will be returned."
1434 (let ((value (gensym)))
1435 `(let ((,value (gethash ,key htmlize-memoization-table)))
1436 (unless ,value
1437 (setq ,value ,generator)
1438 (setf (gethash ,key htmlize-memoization-table) ,value))
1439 ,value)))
1441 ;;; Default methods.
1443 (defun htmlize-default-doctype ()
1444 nil ; no doc-string
1445 ;; Note that the `font' output is technically invalid under this DTD
1446 ;; because the DTD doesn't allow embedding <font> in <pre>.
1447 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\">"
1450 (defun htmlize-default-body-tag (face-map)
1451 nil ; no doc-string
1452 face-map ; shut up the byte-compiler
1453 "<body>")
1455 ;;; CSS based output support.
1457 ;; Internal function; not a method.
1458 (defun htmlize-css-specs (fstruct)
1459 (let (result)
1460 (when (htmlize-fstruct-foreground fstruct)
1461 (push (format "color: %s;" (htmlize-fstruct-foreground fstruct))
1462 result))
1463 (when (htmlize-fstruct-background fstruct)
1464 (push (format "background-color: %s;"
1465 (htmlize-fstruct-background fstruct))
1466 result))
1467 (let ((size (htmlize-fstruct-size fstruct)))
1468 (when (and size (not (eq htmlize-ignore-face-size t)))
1469 (cond ((floatp size)
1470 (push (format "font-size: %d%%;" (* 100 size)) result))
1471 ((not (eq htmlize-ignore-face-size 'absolute))
1472 (push (format "font-size: %spt;" (/ size 10.0)) result)))))
1473 (when (htmlize-fstruct-boldp fstruct)
1474 (push "font-weight: bold;" result))
1475 (when (htmlize-fstruct-italicp fstruct)
1476 (push "font-style: italic;" result))
1477 (when (htmlize-fstruct-underlinep fstruct)
1478 (push "text-decoration: underline;" result))
1479 (when (htmlize-fstruct-overlinep fstruct)
1480 (push "text-decoration: overline;" result))
1481 (when (htmlize-fstruct-strikep fstruct)
1482 (push "text-decoration: line-through;" result))
1483 (nreverse result)))
1485 (defun htmlize-css-insert-head (buffer-faces face-map)
1486 (insert " <style type=\"text/css\">\n <!--\n")
1487 (insert " body {\n "
1488 (mapconcat #'identity
1489 (htmlize-css-specs (gethash 'default face-map))
1490 "\n ")
1491 "\n }\n")
1492 (dolist (face (sort* (copy-list buffer-faces) #'string-lessp
1493 :key (lambda (f)
1494 (htmlize-fstruct-css-name (gethash f face-map)))))
1495 (let* ((fstruct (gethash face face-map))
1496 (cleaned-up-face-name
1497 (let ((s
1498 ;; Use `prin1-to-string' rather than `symbol-name'
1499 ;; to get the face name because the "face" can also
1500 ;; be an attrlist, which is not a symbol.
1501 (prin1-to-string face)))
1502 ;; If the name contains `--' or `*/', remove them.
1503 (while (string-match "--" s)
1504 (setq s (replace-match "-" t t s)))
1505 (while (string-match "\\*/" s)
1506 (setq s (replace-match "XX" t t s)))
1508 (specs (htmlize-css-specs fstruct)))
1509 (insert " ." (htmlize-fstruct-css-name fstruct))
1510 (if (null specs)
1511 (insert " {")
1512 (insert " {\n /* " cleaned-up-face-name " */\n "
1513 (mapconcat #'identity specs "\n ")))
1514 (insert "\n }\n")))
1515 (insert htmlize-hyperlink-style
1516 " -->\n </style>\n"))
1518 (defun htmlize-css-text-markup (fstruct-list buffer)
1519 ;; Open the markup needed to insert text colored with FACES into
1520 ;; BUFFER. Return the function that closes the markup.
1522 ;; In CSS mode, this is easy: just nest the text in one <span
1523 ;; class=...> tag for each face in FSTRUCT-LIST.
1524 (dolist (fstruct fstruct-list)
1525 (princ "<span class=\"" buffer)
1526 (princ (htmlize-fstruct-css-name fstruct) buffer)
1527 (princ "\">" buffer))
1528 (htmlize-lexlet ((fstruct-list fstruct-list) (buffer buffer))
1529 (lambda ()
1530 (dolist (fstruct fstruct-list)
1531 (ignore fstruct) ; shut up the byte-compiler
1532 (princ "</span>" buffer)))))
1534 ;; `inline-css' output support.
1536 (defun htmlize-inline-css-body-tag (face-map)
1537 (format "<body style=\"%s\">"
1538 (mapconcat #'identity (htmlize-css-specs (gethash 'default face-map))
1539 " ")))
1541 (defun htmlize-inline-css-text-markup (fstruct-list buffer)
1542 (let* ((merged (htmlize-merge-faces fstruct-list))
1543 (style (htmlize-memoize
1544 merged
1545 (let ((specs (htmlize-css-specs merged)))
1546 (and specs
1547 (mapconcat #'identity (htmlize-css-specs merged) " "))))))
1548 (when style
1549 (princ "<span style=\"" buffer)
1550 (princ style buffer)
1551 (princ "\">" buffer))
1552 (htmlize-lexlet ((style style) (buffer buffer))
1553 (lambda ()
1554 (when style
1555 (princ "</span>" buffer))))))
1557 ;;; `font' tag based output support.
1559 (defun htmlize-font-body-tag (face-map)
1560 (let ((fstruct (gethash 'default face-map)))
1561 (format "<body text=\"%s\" bgcolor=\"%s\">"
1562 (htmlize-fstruct-foreground fstruct)
1563 (htmlize-fstruct-background fstruct))))
1565 (defun htmlize-font-text-markup (fstruct-list buffer)
1566 ;; In `font' mode, we use the traditional HTML means of altering
1567 ;; presentation: <font> tag for colors, <b> for bold, <u> for
1568 ;; underline, and <strike> for strike-through.
1569 (let* ((merged (htmlize-merge-faces fstruct-list))
1570 (markup (htmlize-memoize
1571 merged
1572 (cons (concat
1573 (and (htmlize-fstruct-foreground merged)
1574 (format "<font color=\"%s\">" (htmlize-fstruct-foreground merged)))
1575 (and (htmlize-fstruct-boldp merged) "<b>")
1576 (and (htmlize-fstruct-italicp merged) "<i>")
1577 (and (htmlize-fstruct-underlinep merged) "<u>")
1578 (and (htmlize-fstruct-strikep merged) "<strike>"))
1579 (concat
1580 (and (htmlize-fstruct-strikep merged) "</strike>")
1581 (and (htmlize-fstruct-underlinep merged) "</u>")
1582 (and (htmlize-fstruct-italicp merged) "</i>")
1583 (and (htmlize-fstruct-boldp merged) "</b>")
1584 (and (htmlize-fstruct-foreground merged) "</font>"))))))
1585 (princ (car markup) buffer)
1586 (htmlize-lexlet ((markup markup) (buffer buffer))
1587 (lambda ()
1588 (princ (cdr markup) buffer)))))
1590 (defun htmlize-buffer-1 ()
1591 ;; Internal function; don't call it from outside this file. Htmlize
1592 ;; current buffer, writing the resulting HTML to a new buffer, and
1593 ;; return it. Unlike htmlize-buffer, this doesn't change current
1594 ;; buffer or use switch-to-buffer.
1595 (save-excursion
1596 ;; Protect against the hook changing the current buffer.
1597 (save-excursion
1598 (run-hooks 'htmlize-before-hook))
1599 ;; Convince font-lock support modes to fontify the entire buffer
1600 ;; in advance.
1601 (htmlize-ensure-fontified)
1602 (clrhash htmlize-extended-character-cache)
1603 (clrhash htmlize-memoization-table)
1604 ;; It's important that the new buffer inherits default-directory
1605 ;; from the current buffer.
1606 (let ((htmlbuf (generate-new-buffer (if (buffer-file-name)
1607 (htmlize-make-file-name
1608 (file-name-nondirectory
1609 (buffer-file-name)))
1610 "*html*")))
1611 (completed nil))
1612 (unwind-protect
1613 (let* ((buffer-faces (htmlize-faces-in-buffer))
1614 (face-map (htmlize-make-face-map (adjoin 'default buffer-faces)))
1615 (places (gensym))
1616 (title (if (buffer-file-name)
1617 (file-name-nondirectory (buffer-file-name))
1618 (buffer-name))))
1619 (when htmlize-generate-hyperlinks
1620 (htmlize-create-auto-links))
1621 (when htmlize-replace-form-feeds
1622 (htmlize-shadow-form-feeds))
1624 ;; Initialize HTMLBUF and insert the HTML prolog.
1625 (with-current-buffer htmlbuf
1626 (buffer-disable-undo)
1627 (insert (htmlize-method doctype) ?\n
1628 (format "<!-- Created by htmlize-%s in %s mode. -->\n"
1629 htmlize-version htmlize-output-type)
1630 "<html>\n ")
1631 (put places 'head-start (point-marker))
1632 (insert "<head>\n"
1633 " <title>" (htmlize-protect-string title) "</title>\n"
1634 (if htmlize-html-charset
1635 (format (concat " <meta http-equiv=\"Content-Type\" "
1636 "content=\"text/html; charset=%s\">\n")
1637 htmlize-html-charset)
1639 htmlize-head-tags)
1640 (htmlize-method insert-head buffer-faces face-map)
1641 (insert " </head>")
1642 (put places 'head-end (point-marker))
1643 (insert "\n ")
1644 (put places 'body-start (point-marker))
1645 (insert (htmlize-method body-tag face-map)
1646 "\n ")
1647 (put places 'content-start (point-marker))
1648 (insert "<pre>\n"))
1649 (let ((text-markup
1650 ;; Get the inserter method, so we can funcall it inside
1651 ;; the loop. Not calling `htmlize-method' in the loop
1652 ;; body yields a measurable speed increase.
1653 (htmlize-method-function 'text-markup))
1654 ;; Declare variables used in loop body outside the loop
1655 ;; because it's faster to establish `let' bindings only
1656 ;; once.
1657 next-change text face-list trailing-ellipsis
1658 fstruct-list last-fstruct-list
1659 (close-markup (lambda ())))
1660 ;; This loop traverses and reads the source buffer, appending
1661 ;; the resulting HTML to HTMLBUF. This method is fast
1662 ;; because: 1) it doesn't require examining the text
1663 ;; properties char by char (htmlize-next-face-change is used
1664 ;; to move between runs with the same face), and 2) it doesn't
1665 ;; require frequent buffer switches, which are slow because
1666 ;; they rebind all buffer-local vars.
1667 (goto-char (point-min))
1668 (while (not (eobp))
1669 (setq next-change (htmlize-next-face-change (point)))
1670 ;; Get faces in use between (point) and NEXT-CHANGE, and
1671 ;; convert them to fstructs.
1672 (setq face-list (htmlize-faces-at-point)
1673 fstruct-list (delq nil (mapcar (lambda (f)
1674 (gethash f face-map))
1675 face-list)))
1676 (multiple-value-setq (text trailing-ellipsis)
1677 (htmlize-extract-text (point) next-change trailing-ellipsis))
1678 ;; Don't bother writing anything if there's no text (this
1679 ;; happens in invisible regions).
1680 (when (> (length text) 0)
1681 ;; Open the new markup if necessary and insert the text.
1682 (when (not (equalp fstruct-list last-fstruct-list))
1683 (funcall close-markup)
1684 (setq last-fstruct-list fstruct-list
1685 close-markup (funcall text-markup fstruct-list htmlbuf)))
1686 (princ text htmlbuf))
1687 (goto-char next-change))
1689 ;; We've gone through the buffer; close the markup from
1690 ;; the last run, if any.
1691 (funcall close-markup))
1693 ;; Insert the epilog and post-process the buffer.
1694 (with-current-buffer htmlbuf
1695 (insert "</pre>")
1696 (put places 'content-end (point-marker))
1697 (insert "\n </body>")
1698 (put places 'body-end (point-marker))
1699 (insert "\n</html>\n")
1700 (htmlize-defang-local-variables)
1701 (goto-char (point-min))
1702 (when htmlize-html-major-mode
1703 ;; What sucks about this is that the minor modes, most notably
1704 ;; font-lock-mode, won't be initialized. Oh well.
1705 (funcall htmlize-html-major-mode))
1706 (set (make-local-variable 'htmlize-buffer-places)
1707 (symbol-plist places))
1708 (run-hooks 'htmlize-after-hook)
1709 (buffer-enable-undo))
1710 (setq completed t)
1711 htmlbuf)
1713 (when (not completed)
1714 (kill-buffer htmlbuf))
1715 (htmlize-delete-tmp-overlays)))))
1717 ;; Utility functions.
1719 (defmacro htmlize-with-fontify-message (&rest body)
1720 ;; When forcing fontification of large buffers in
1721 ;; htmlize-ensure-fontified, inform the user that he is waiting for
1722 ;; font-lock, not for htmlize to finish.
1723 `(progn
1724 (if (> (buffer-size) 65536)
1725 (message "Forcing fontification of %s..."
1726 (buffer-name (current-buffer))))
1727 ,@body
1728 (if (> (buffer-size) 65536)
1729 (message "Forcing fontification of %s...done"
1730 (buffer-name (current-buffer))))))
1732 (defun htmlize-ensure-fontified ()
1733 ;; If font-lock is being used, ensure that the "support" modes
1734 ;; actually fontify the buffer. If font-lock is not in use, we
1735 ;; don't care because, except in htmlize-file, we don't force
1736 ;; font-lock on the user.
1737 (when (and (boundp 'font-lock-mode)
1738 font-lock-mode)
1739 ;; In part taken from ps-print-ensure-fontified in GNU Emacs 21.
1740 (cond
1741 ((and (boundp 'jit-lock-mode)
1742 (symbol-value 'jit-lock-mode))
1743 (htmlize-with-fontify-message
1744 (jit-lock-fontify-now (point-min) (point-max))))
1745 ((and (boundp 'lazy-lock-mode)
1746 (symbol-value 'lazy-lock-mode))
1747 (htmlize-with-fontify-message
1748 (lazy-lock-fontify-region (point-min) (point-max))))
1749 ((and (boundp 'lazy-shot-mode)
1750 (symbol-value 'lazy-shot-mode))
1751 (htmlize-with-fontify-message
1752 ;; lazy-shot is amazing in that it must *refontify* the region,
1753 ;; even if the whole buffer has already been fontified. <sigh>
1754 (lazy-shot-fontify-region (point-min) (point-max))))
1755 ;; There's also fast-lock, but we don't need to handle specially,
1756 ;; I think. fast-lock doesn't really defer fontification, it
1757 ;; just saves it to an external cache so it's not done twice.
1761 ;;;###autoload
1762 (defun htmlize-buffer (&optional buffer)
1763 "Convert BUFFER to HTML, preserving colors and decorations.
1765 The generated HTML is available in a new buffer, which is returned.
1766 When invoked interactively, the new buffer is selected in the current
1767 window. The title of the generated document will be set to the buffer's
1768 file name or, if that's not available, to the buffer's name.
1770 Note that htmlize doesn't fontify your buffers, it only uses the
1771 decorations that are already present. If you don't set up font-lock or
1772 something else to fontify your buffers, the resulting HTML will be
1773 plain. Likewise, if you don't like the choice of colors, fix the mode
1774 that created them, or simply alter the faces it uses."
1775 (interactive)
1776 (let ((htmlbuf (with-current-buffer (or buffer (current-buffer))
1777 (htmlize-buffer-1))))
1778 (when (interactive-p)
1779 (switch-to-buffer htmlbuf))
1780 htmlbuf))
1782 ;;;###autoload
1783 (defun htmlize-region (beg end)
1784 "Convert the region to HTML, preserving colors and decorations.
1785 See `htmlize-buffer' for details."
1786 (interactive "r")
1787 ;; Don't let zmacs region highlighting end up in HTML.
1788 (when (fboundp 'zmacs-deactivate-region)
1789 (zmacs-deactivate-region))
1790 (let ((htmlbuf (save-restriction
1791 (narrow-to-region beg end)
1792 (htmlize-buffer-1))))
1793 (when (interactive-p)
1794 (switch-to-buffer htmlbuf))
1795 htmlbuf))
1797 (defun htmlize-region-for-paste (beg end)
1798 "Htmlize the region and return just the HTML as a string.
1799 This forces the `inline-css' style and only returns the HTML body,
1800 but without the BODY tag. This should make it useful for inserting
1801 the text to another HTML buffer."
1802 (let* ((htmlize-output-type 'inline-css)
1803 (htmlbuf (htmlize-region beg end)))
1804 (unwind-protect
1805 (with-current-buffer htmlbuf
1806 (buffer-substring (plist-get htmlize-buffer-places 'content-start)
1807 (plist-get htmlize-buffer-places 'content-end)))
1808 (kill-buffer htmlbuf))))
1810 (defun htmlize-make-file-name (file)
1811 "Make an HTML file name from FILE.
1813 In its default implementation, this simply appends `.html' to FILE.
1814 This function is called by htmlize to create the buffer file name, and
1815 by `htmlize-file' to create the target file name.
1817 More elaborate transformations are conceivable, such as changing FILE's
1818 extension to `.html' (\"file.c\" -> \"file.html\"). If you want them,
1819 overload this function to do it and htmlize will comply."
1820 (concat file ".html"))
1822 ;; Older implementation of htmlize-make-file-name that changes FILE's
1823 ;; extension to ".html".
1824 ;(defun htmlize-make-file-name (file)
1825 ; (let ((extension (file-name-extension file))
1826 ; (sans-extension (file-name-sans-extension file)))
1827 ; (if (or (equal extension "html")
1828 ; (equal extension "htm")
1829 ; (equal sans-extension ""))
1830 ; (concat file ".html")
1831 ; (concat sans-extension ".html"))))
1833 ;;;###autoload
1834 (defun htmlize-file (file &optional target)
1835 "Load FILE, fontify it, convert it to HTML, and save the result.
1837 Contents of FILE are inserted into a temporary buffer, whose major mode
1838 is set with `normal-mode' as appropriate for the file type. The buffer
1839 is subsequently fontified with `font-lock' and converted to HTML. Note
1840 that, unlike `htmlize-buffer', this function explicitly turns on
1841 font-lock. If a form of highlighting other than font-lock is desired,
1842 please use `htmlize-buffer' directly on buffers so highlighted.
1844 Buffers currently visiting FILE are unaffected by this function. The
1845 function does not change current buffer or move the point.
1847 If TARGET is specified and names a directory, the resulting file will be
1848 saved there instead of to FILE's directory. If TARGET is specified and
1849 does not name a directory, it will be used as output file name."
1850 (interactive (list (read-file-name
1851 "HTML-ize file: "
1852 nil nil nil (and (buffer-file-name)
1853 (file-name-nondirectory
1854 (buffer-file-name))))))
1855 (let ((output-file (if (and target (not (file-directory-p target)))
1856 target
1857 (expand-file-name
1858 (htmlize-make-file-name (file-name-nondirectory file))
1859 (or target (file-name-directory file)))))
1860 ;; Try to prevent `find-file-noselect' from triggering
1861 ;; font-lock because we'll fontify explicitly below.
1862 (font-lock-mode nil)
1863 (font-lock-auto-fontify nil)
1864 (global-font-lock-mode nil)
1865 ;; Ignore the size limit for the purposes of htmlization.
1866 (font-lock-maximum-size nil)
1867 ;; Disable font-lock support modes. This will only work in
1868 ;; more recent Emacs versions, so htmlize-buffer-1 still needs
1869 ;; to call htmlize-ensure-fontified.
1870 (font-lock-support-mode nil))
1871 (with-temp-buffer
1872 ;; Insert FILE into the temporary buffer.
1873 (insert-file-contents file)
1874 ;; Set the file name so normal-mode and htmlize-buffer-1 pick it
1875 ;; up. Restore it afterwards so with-temp-buffer's kill-buffer
1876 ;; doesn't complain about killing a modified buffer.
1877 (let ((buffer-file-name file))
1878 ;; Set the major mode for the sake of font-lock.
1879 (normal-mode)
1880 (font-lock-mode 1)
1881 (unless font-lock-mode
1882 ;; In GNU Emacs (font-lock-mode 1) doesn't force font-lock,
1883 ;; contrary to the documentation. This seems to work.
1884 (font-lock-fontify-buffer))
1885 ;; htmlize the buffer and save the HTML.
1886 (with-current-buffer (htmlize-buffer-1)
1887 (unwind-protect
1888 (progn
1889 (run-hooks 'htmlize-file-hook)
1890 (write-region (point-min) (point-max) output-file))
1891 (kill-buffer (current-buffer)))))))
1892 ;; I haven't decided on a useful return value yet, so just return
1893 ;; nil.
1894 nil)
1896 ;;;###autoload
1897 (defun htmlize-many-files (files &optional target-directory)
1898 "Convert FILES to HTML and save the corresponding HTML versions.
1900 FILES should be a list of file names to convert. This function calls
1901 `htmlize-file' on each file; see that function for details. When
1902 invoked interactively, you are prompted for a list of files to convert,
1903 terminated with RET.
1905 If TARGET-DIRECTORY is specified, the HTML files will be saved to that
1906 directory. Normally, each HTML file is saved to the directory of the
1907 corresponding source file."
1908 (interactive
1909 (list
1910 (let (list file)
1911 ;; Use empty string as DEFAULT because setting DEFAULT to nil
1912 ;; defaults to the directory name, which is not what we want.
1913 (while (not (equal (setq file (read-file-name
1914 "HTML-ize file (RET to finish): "
1915 (and list (file-name-directory
1916 (car list)))
1917 "" t))
1918 ""))
1919 (push file list))
1920 (nreverse list))))
1921 ;; Verify that TARGET-DIRECTORY is indeed a directory. If it's a
1922 ;; file, htmlize-file will use it as target, and that doesn't make
1923 ;; sense.
1924 (and target-directory
1925 (not (file-directory-p target-directory))
1926 (error "target-directory must name a directory: %s" target-directory))
1927 (dolist (file files)
1928 (htmlize-file file target-directory)))
1930 ;;;###autoload
1931 (defun htmlize-many-files-dired (arg &optional target-directory)
1932 "HTMLize dired-marked files."
1933 (interactive "P")
1934 (htmlize-many-files (dired-get-marked-files nil arg) target-directory))
1936 (provide 'htmlize)
1938 ;; Local Variables:
1939 ;; byte-compile-warnings: (not cl-functions lexical unresolved obsolete)
1940 ;; lexical-binding: t
1941 ;; End:
1943 ;;; htmlize.el ends here