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