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