Port recent flexmember changes to NetBSD
[emacs.git] / lisp / htmlfontify.el
blob8cbe3c1dc9e4c2597d7a943bd68074603d54478a
1 ;;; htmlfontify.el --- htmlize a buffer/source tree with optional hyperlinks
3 ;; Copyright (C) 2002-2003, 2009-2016 Free Software Foundation, Inc.
5 ;; Emacs Lisp Archive Entry
6 ;; Package: htmlfontify
7 ;; Filename: htmlfontify.el
8 ;; Version: 0.21
9 ;; Keywords: html, hypermedia, markup, etags
10 ;; Author: Vivek Dasmohapatra <vivek@etla.org>
11 ;; Maintainer: Vivek Dasmohapatra <vivek@etla.org>
12 ;; Created: 2002-01-05
13 ;; Description: htmlize a buffer/source tree with optional hyperlinks
14 ;; URL: http://rtfm.etla.org/emacs/htmlfontify/
15 ;; Compatibility: Emacs23, Emacs22
16 ;; Incompatibility: Emacs19, Emacs20, Emacs21
17 ;; Last Updated: Thu 2009-11-19 01:31:21 +0000
19 ;; This file is part of GNU Emacs.
21 ;; GNU Emacs is free software: you can redistribute it and/or modify
22 ;; it under the terms of the GNU General Public License as published by
23 ;; the Free Software Foundation, either version 3 of the License, or
24 ;; (at your option) any later version.
26 ;; GNU Emacs is distributed in the hope that it will be useful,
27 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
28 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 ;; GNU General Public License for more details.
31 ;; You should have received a copy of the GNU General Public License
32 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
34 ;;; Commentary:
35 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
36 ;; I have made some changes to make it work for Emacs 22. A lot of
37 ;; small bug fixes related to the format of text and overlay
38 ;; properties (which might have changed since the beginning of 2003
39 ;; when this file was originally written).
41 ;; The function `hfy-face-at' currently carries much of the burden of
42 ;; my lacking understanding of the formats mentioned above and should
43 ;; need some knowledgeable help.
45 ;; Another thing that maybe could be fixed is that overlay background
46 ;; colors which are now only seen where there is text (in the XHTML
47 ;; output). A bit of CSS tweaking is necessary there.
49 ;; The face 'default has a value :background "SystemWindow" for the
50 ;; background color. There is no explicit notion that this should be
51 ;; considered transparent, but I have assumed that it could be handled
52 ;; like if it was here. (I am unsure that background and foreground
53 ;; priorities are handled ok, but it looks ok in my tests now.)
55 ;; 2007-12-27 Lennart Borgman
56 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
58 ;; Here's some elisp code to html-pretty-print an Emacs buffer, preserving
59 ;; the Emacs syntax/whatever highlighting. It also knows how to drive etags
60 ;; (exuberant-ctags or Emacs etags) and hyperlink the code according
61 ;; to its (etags') output.
63 ;; NOTE: Currently the hyperlinking code only knows how to drive GNU find
64 ;; and the exuberant and GNU variants of etags : I do not know of any other
65 ;; etags variants, but mechanisms have been provided to allow htmlfontify
66 ;; to be taught how to drive them. As long as your version of find has
67 ;; the -path test and is reasonably sane, you should be fine.
69 ;; A sample of the htmlfontified / hyperlinked output of this module can be
70 ;; found at http://rtfm.etla.org/sql/dbishell/src/ - it's not perfect, but
71 ;; it's a hell of a lot faster and more thorough than I could hope to be
72 ;; doing this by hand.
74 ;; some user / horrified onlooker comments:
75 ;; What? No! There's something deeply wrong here... (R. Shufflebotham)
76 ;; You're a freak. (D. Silverstone)
77 ;; Aren't we giving you enough to do? (J. Busuttil)
78 ;; You're almost as messed up as Lexx is! (N. Graves-Morris)
80 ;;; History:
81 ;; Changes: moved to changelog (CHANGES) file.
83 ;;; Code:
84 (eval-when-compile (require 'cl))
85 (require 'faces)
86 ;; (`facep' `face-attr-construct' `x-color-values' `color-values' `face-name')
87 (require 'custom)
88 ;; (`defgroup' `defcustom')
89 (require 'font-lock)
90 ;; (`font-lock-fontify-region')
91 (require 'cus-edit)
93 (require 'htmlfontify-loaddefs)
95 (defconst htmlfontify-version 0.21)
97 (defconst hfy-meta-tags
98 (format "<meta name=\"generator\" content=\"emacs %s; htmlfontify %0.2f\" />"
99 emacs-version htmlfontify-version)
100 "The generator meta tag for this version of htmlfontify.")
102 (defconst htmlfontify-manual "Htmlfontify Manual"
103 "Copy and convert buffers and files to HTML, adding hyperlinks between files
104 \(driven by etags) if requested.
105 \nInteractive functions:
106 `htmlfontify-buffer'
107 `htmlfontify-run-etags'
108 `htmlfontify-copy-and-link-dir'
109 `htmlfontify-load-rgb-file'
110 `htmlfontify-unload-rgb-file'\n
111 In order to:\n
112 fontify a file you have open: \\[htmlfontify-buffer]
113 prepare the etags map for a directory: \\[htmlfontify-run-etags]
114 copy a directory, fontifying as you go: \\[htmlfontify-copy-and-link-dir]\n
115 The following might be useful when running non-windowed or in batch mode:
116 \(note that they shouldn't be necessary - we have a built in map)\n
117 load an X11 style rgb.txt file: \\[htmlfontify-load-rgb-file]
118 unload the current rgb.txt file: \\[htmlfontify-unload-rgb-file]\n
119 And here's a programmatic example:\n
120 \(defun rtfm-build-page-header (file style)
121 (format \"#define TEMPLATE red+black.html
122 #define DEBUG 1
123 #include <build/menu-dirlist|>\\n
124 html-css-url := /css/red+black.css
125 title := rtfm.etla.org ( %s / src/%s )
126 bodytag :=
127 head <=STYLESHEET;\\n
129 STYLESHEET
130 main-title := rtfm / %s / src/%s\\n
131 main-content <=MAIN_CONTENT;\\n\" rtfm-section file style rtfm-section file))
133 \(defun rtfm-build-page-footer (file) \"\\nMAIN_CONTENT\\n\")
135 \(defun rtfm-build-source-docs (section srcdir destdir)
136 (interactive
137 \"s section[eg- emacs / p4-blame]:\\nD source-dir: \\nD output-dir: \")
138 (require \\='htmlfontify)
139 (hfy-load-tags-cache srcdir)
140 (let ((hfy-page-header \\='rtfm-build-page-header)
141 (hfy-page-footer \\='rtfm-build-page-footer)
142 (rtfm-section section)
143 (hfy-index-file \"index\"))
144 (htmlfontify-run-etags srcdir)
145 (htmlfontify-copy-and-link-dir srcdir destdir \".src\" \".html\")))")
147 (defgroup htmlfontify nil
148 "Convert buffers and files to HTML."
149 :group 'applications
150 :link '(variable-link htmlfontify-manual)
151 :link '(custom-manual "(htmlfontify) Top")
152 :link '(info-link "(htmlfontify) Customization")
153 :prefix "hfy-")
155 (defcustom hfy-page-header 'hfy-default-header
156 "Function called to build the header of the HTML source.
157 This is called with two arguments (the filename relative to the top
158 level source directory being etag'd and fontified), and a string containing
159 the <style>...</style> text to embed in the document.
160 It should return a string that will be used as the header for the
161 htmlfontified version of the source file.\n
162 See also `hfy-page-footer'."
163 :group 'htmlfontify
164 ;; FIXME: Why place such a :tag everywhere? Isn't it imposing your
165 ;; own Custom preference on your users? --Stef
166 :tag "page-header"
167 :type '(function))
169 (defcustom hfy-split-index nil
170 "Whether or not to split the index `hfy-index-file' alphabetically.
171 If non-nil, the index is split on the first letter of each tag.
172 Useful when the index would otherwise be large and take
173 a long time to render or be difficult to navigate."
174 :group 'htmlfontify
175 :tag "split-index"
176 :type '(boolean))
178 (defcustom hfy-page-footer 'hfy-default-footer
179 "As `hfy-page-header', but generates the output footer.
180 It takes only one argument, the filename."
181 :group 'htmlfontify
182 :tag "page-footer"
183 :type '(function))
185 (defcustom hfy-extn ".html"
186 "File extension used for output files."
187 :group 'htmlfontify
188 :tag "extension"
189 :type '(string))
191 (defcustom hfy-src-doc-link-style "text-decoration: underline;"
192 "String to add to the `<style> a' variant of an htmlfontify CSS class."
193 :group 'htmlfontify
194 :tag "src-doc-link-style"
195 :type '(string))
197 (defcustom hfy-src-doc-link-unstyle " text-decoration: none;"
198 "Regex to remove from the `<style> a' variant of an htmlfontify CSS class."
199 :group 'htmlfontify
200 :tag "src-doc-link-unstyle"
201 :type '(string))
203 (defcustom hfy-link-extn nil
204 "File extension used for href links.
205 Useful where the htmlfontify output files are going to be processed
206 again, with a resulting change in file extension. If nil, then any
207 code using this should fall back to `hfy-extn'."
208 :group 'htmlfontify
209 :tag "link-extension"
210 :type '(choice string (const nil)))
212 (defcustom hfy-link-style-fun 'hfy-link-style-string
213 "Function to customize the appearance of hyperlinks.
214 Set this to a function, which will be called with one argument
215 \(a \"{ foo: bar; ...}\" CSS style-string) - it should return a copy of
216 its argument, altered so as to make any changes you want made for text which
217 is a hyperlink, in addition to being in the class to which that style would
218 normally be applied."
219 :group 'htmlfontify
220 :tag "link-style-function"
221 :type '(function))
223 (defcustom hfy-index-file "hfy-index"
224 "Name (sans extension) of the tag definition index file produced during
225 fontification-and-hyperlinking."
226 :group 'htmlfontify
227 :tag "index-file"
228 :type '(string))
230 (defcustom hfy-instance-file "hfy-instance"
231 "Name (sans extension) of the tag usage index file produced during
232 fontification-and-hyperlinking."
233 :group 'htmlfontify
234 :tag "instance-file"
235 :type '(string))
237 (defcustom hfy-html-quote-regex "\\([<\"&>]\\)"
238 "Regex to match (with a single back-reference per match) strings in HTML
239 which should be quoted with `hfy-html-quote' (and `hfy-html-quote-map')
240 to make them safe."
241 :group 'htmlfontify
242 :tag "html-quote-regex"
243 :type '(regexp))
245 (define-obsolete-variable-alias 'hfy-init-kludge-hooks 'hfy-init-kludge-hook
246 "23.2")
247 (defcustom hfy-init-kludge-hook '(hfy-kludge-cperl-mode)
248 "List of functions to call when starting `htmlfontify-buffer' to do any
249 kludging necessary to get highlighting modes to behave as you want, even
250 when not running under a window system."
251 :group 'htmlfontify
252 :tag "init-kludge-hooks"
253 :type '(hook))
255 (define-obsolete-variable-alias 'hfy-post-html-hooks 'hfy-post-html-hook "24.3")
256 (defcustom hfy-post-html-hook nil
257 "List of functions to call after creating and filling the HTML buffer.
258 These functions will be called with the HTML buffer as the current buffer."
259 :group 'htmlfontify
260 :tag "post-html-hooks"
261 :options '(set-auto-mode)
262 :type '(hook))
264 (defcustom hfy-default-face-def nil
265 "Fallback `defface' specification for the face `default', used when
266 `hfy-display-class' has been set (the normal htmlfontify way of extracting
267 potentially non-current face information doesn't necessarily work for
268 `default').\n
269 Example: I customize this to:\n
270 \((t :background \"black\" :foreground \"white\" :family \"misc-fixed\"))"
271 :group 'htmlfontify
272 :tag "default-face-definition"
273 :type '(alist))
275 (defcustom hfy-etag-regex (concat ".*"
276 "\x7f" "\\([^\x01\n]+\\)"
277 "\x01" "\\([0-9]+\\)"
278 "," "\\([0-9]+\\)$"
279 "\\|" ".*\x7f[0-9]+,[0-9]+$")
280 "Regex used to parse an etags entry: must have 3 subexps, corresponding,
281 in order, to:\n
282 1 - The tag
283 2 - The line
284 3 - The char (point) at which the tag occurs."
285 :group 'htmlfontify
286 :tag "etag-regex"
287 :type '(regexp))
289 (defcustom hfy-html-quote-map '(("\"" "&quot;")
290 ("<" "&lt;" )
291 ("&" "&amp;" )
292 (">" "&gt;" ))
293 "Alist of char -> entity mappings used to make the text HTML-safe."
294 :group 'htmlfontify
295 :tag "html-quote-map"
296 :type '(alist :key-type (string)))
297 (defconst hfy-e2x-etags-cmd "for src in `find . -type f`;
299 ETAGS=%s;
300 case ${src} in
301 *.ad[absm]|*.[CFHMSacfhlmpsty]|*.def|*.in[cs]|*.s[as]|*.src|*.cc|\\
302 *.hh|*.[chy]++|*.[ch]pp|*.[chy]xx|*.pdb|*.[ch]s|*.[Cc][Oo][Bb]|\\
303 *.[eh]rl|*.f90|*.for|*.java|*.[cem]l|*.clisp|*.lisp|*.[Ll][Ss][Pp]|\\
304 [Mm]akefile*|*.pas|*.[Pp][LlMm]|*.psw|*.lm|*.pc|*.prolog|*.oak|\\
305 *.p[sy]|*.sch|*.scheme|*.[Ss][Cc][Mm]|*.[Ss][Mm]|*.bib|*.cl[os]|\\
306 *.ltx|*.sty|*.TeX|*.tex|*.texi|*.texinfo|*.txi|*.x[bp]m|*.yy|\\
307 *.[Ss][Qq][Ll])
308 ${ETAGS} -o- ${src};
311 FTYPE=`file ${src}`;
312 case ${FTYPE} in
313 *script*text*)
314 ${ETAGS} -o- ${src};
316 *text*)
317 SHEBANG=`head -n1 ${src} | grep '#!' -c`;
318 if [ ${SHEBANG} -eq 1 ];
319 then
320 ${ETAGS} -o- ${src};
323 esac;
325 esac;
326 done;")
328 (defconst hfy-etags-cmd-alist-default
329 `(("emacs etags" . ,hfy-e2x-etags-cmd)
330 ("exuberant ctags" . "%s -R -f -" )))
332 (defcustom hfy-etags-cmd-alist
333 hfy-etags-cmd-alist-default
334 "Alist of possible shell commands that will generate etags output that
335 `htmlfontify' can use. `%s' will be replaced by `hfy-etags-bin'."
336 :group 'htmlfontify
337 :tag "etags-cmd-alist"
338 :type '(alist :key-type (string) :value-type (string)))
340 (defcustom hfy-etags-bin "etags"
341 "Location of etags binary (we begin by assuming it's in your path).\n
342 Note that if etags is not in your path, you will need to alter the shell
343 commands in `hfy-etags-cmd-alist'."
344 :group 'htmlfontify
345 :tag "etags-bin"
346 :type '(file))
348 (defcustom hfy-shell-file-name "/bin/sh"
349 "Shell (Bourne or compatible) to invoke for complex shell operations."
350 :group 'htmlfontify
351 :tag "shell-file-name"
352 :type '(file))
354 (defcustom hfy-ignored-properties '(read-only
355 intangible
356 modification-hooks
357 insert-in-front-hooks
358 insert-behind-hooks
359 point-entered
360 point-left)
361 "Properties to omit when copying a fontified buffer for HTML transformation."
362 :group 'htmlfontify
363 :tag "ignored-properties"
364 :type '(repeat symbol))
366 (defun hfy-which-etags ()
367 "Return a string indicating which flavor of etags we are using."
368 (let ((v (shell-command-to-string (concat hfy-etags-bin " --version"))))
369 (cond ((string-match "exube" v) "exuberant ctags")
370 ((string-match "GNU E" v) "emacs etags" )) ))
372 (defcustom hfy-etags-cmd
373 ;; We used to wrap this in a `eval-and-compile', but:
374 ;; - it had no effect because this expression was not seen by the
375 ;; byte-compiler (defcustom used to quote this argument).
376 ;; - it signals an error (`hfy-which-etags' is not defined at compile-time).
377 ;; - we want this auto-detection to reflect the system on which Emacs is run
378 ;; rather than the one on which it's compiled.
379 (cdr (assoc (hfy-which-etags) hfy-etags-cmd-alist))
380 "The etags equivalent command to run in a source directory to generate a tags
381 file for the whole source tree from there on down. The command should emit
382 the etags output on stdout.\n
383 Two canned commands are provided - they drive Emacs's etags and
384 exuberant-ctags' etags respectively."
385 :group 'htmlfontify
386 :tag "etags-command"
387 :type (let ((clist (list '(string))))
388 (dolist (C hfy-etags-cmd-alist)
389 (push (list 'const :tag (car C) (cdr C)) clist))
390 (cons 'choice clist)))
392 (defcustom hfy-istext-command "file %s | sed -e 's@^[^:]*:[ \t]*@@'"
393 "Command to run with the name of a file, to see whether it is a text file
394 or not. The command should emit a string containing the word `text' if
395 the file is a text file, and a string not containing `text' otherwise."
396 :group 'htmlfontify
397 :tag "istext-command"
398 :type '(string))
400 (defcustom hfy-find-cmd
401 "find . -type f \\! -name \\*~ \\! -name \\*.flc \\! -path \\*/CVS/\\*"
402 "Find command used to harvest a list of files to attempt to fontify."
403 :group 'htmlfontify
404 :tag "find-command"
405 :type '(string))
407 (defcustom hfy-display-class nil
408 "Display class to use to determine which display class to use when
409 calculating a face's attributes. This is useful when, for example, you
410 are running Emacs on a tty or in batch mode, and want htmlfontify to have
411 access to the face spec you would use if you were connected to an X display.\n
412 Some valid class specification elements are:\n
413 (class color)
414 (class grayscale)
415 (background dark)
416 (background light)
417 (type x-toolkit)
418 (type tty)
419 (type motif)
420 (type lucid)
421 Multiple values for a tag may be combined, to indicate that any one or more
422 of these values in the specification key constitutes a match, eg:\n
423 ((class color grayscale) (type tty)) would match any of:\n
424 ((class color))
425 ((class grayscale))
426 ((class color grayscale))
427 ((class color foo))
428 ((type tty))
429 ((type tty) (class color))\n
430 and so on."
431 :type '(alist :key-type (symbol) :value-type (symbol))
432 :group 'htmlfontify
433 :tag "display-class"
434 :options '((type (choice (const :tag "X11" x-toolkit)
435 (const :tag "Terminal" tty )
436 (const :tag "Lucid Toolkit" lucid )
437 (const :tag "Motif Toolkit" motif )))
439 (class (choice (const :tag "Color" color )
440 (const :tag "Grayscale" grayscale)))
442 (background (choice (const :tag "Dark" dark )
443 (const :tag "Bright" light ))) ))
445 (defcustom hfy-optimizations (list 'keep-overlays)
446 "Optimizations to turn on: So far, the following have been implemented:\n
447 merge-adjacent-tags: If two (or more) span tags are adjacent, identical and
448 separated by nothing more than whitespace, they will
449 be merged into one span.
450 zap-comment-links : Suppress hyperlinking of tags found in comments.
451 zap-string-links : Suppress hyperlinking of tags found in strings.
452 div-wrapper : Add <div class=\"default\"> </div> tags around the
453 output.
454 keep-overlays : More of a bell (or possibly whistle) than an
455 optimization - If on, preserve overlay highlighting
456 (cf ediff or goo-font-lock) as well as basic faces.\n
457 body-text-only : Emit only body-text. In concrete terms,
458 1. Suppress calls to `hfy-page-header'and
459 `hfy-page-footer'
460 2. Pretend that `div-wrapper' option above is
461 turned off
462 3. Don't enclose output in <pre> </pre> tags
463 And the following are planned but not yet available:\n
464 kill-context-leak : Suppress hyperlinking between files highlighted by
465 different modes.\n
466 Note: like compiler optimizations, these optimize the _output_ of the code,
467 not the processing of the source itself, and are therefore likely to slow
468 htmlfontify down, at least a little. Except for skip-refontification,
469 which can never slow you down, but may result in incomplete fontification."
470 :type '(set (const :tag "merge-adjacent-tags" merge-adjacent-tags )
471 (const :tag "zap-comment-links" zap-comment-links )
472 (const :tag "zap-string-links" zap-string-links )
473 (const :tag "skip-refontification" skip-refontification)
474 (const :tag "kill-context-leak" kill-context-leak )
475 (const :tag "div-wrapper" div-wrapper )
476 (const :tag "keep-overlays" keep-overlays )
477 (const :tag "body-text-only" body-text-only ))
478 :group 'htmlfontify
479 :tag "optimizations")
480 (define-obsolete-variable-alias 'hfy-optimisations 'hfy-optimizations "25.1")
482 (defvar hfy-tags-cache nil
483 "Alist of the form:\n
484 \((\"/src/dir/0\" . tag-hash0) (\"/src/dir/1\" tag-hash1) ...)\n
485 Each tag hash entry then contains entries of the form:\n
486 \"tag_string\" => ((\"file/name.ext\" line char) ... )\n
487 ie an alist mapping (relative) file paths to line and character offsets.\n
488 See also `hfy-load-tags-cache'.")
490 (defvar hfy-tags-sortl nil
491 "Alist of the form ((\"/src/dir\" . (tag0 tag1 tag2)) ... )\n
492 where the tags are stored in descending order of length.\n
493 See also `hfy-load-tags-cache'.")
495 (defvar hfy-tags-rmap nil
496 "Alist of the form ((\"/src/dir\" . tag-rmap-hash))\n
497 where tag-rmap-hash has entries of the form:
498 \"tag_string\" => ( \"file/name.ext\" line char )
499 Unlike `hfy-tags-cache' these are the locations of occurrences of
500 tagged items, not the locations of their definitions.")
502 (defvar hfy-style-assoc 'please-ignore-this-line
503 "An assoc representing/describing an Emacs face.
504 Properties may be repeated, in which case later properties should be
505 treated as if they were inherited from a `parent' font.
506 \(For some properties, only the first encountered value is of any importance,
507 for others the values might be cumulative, and for others they might be
508 cumulative in a complex way.)\n
509 Some examples:\n
510 \(hfy-face-to-style \\='default) =>
511 ((\"background\" . \"rgb(0, 0, 0)\")
512 (\"color\" . \"rgb(255, 255, 255)\")
513 (\"font-style\" . \"normal\")
514 (\"font-weight\" . \"500\")
515 (\"font-stretch\" . \"normal\")
516 (\"font-family\" . \"misc-fixed\")
517 (\"font-size\" . \"13pt\")
518 (\"text-decoration\" . \"none\"))\n
519 \(hfy-face-to-style \\='Info-title-3-face) =>
520 ((\"font-weight\" . \"700\")
521 (\"font-family\" . \"helv\")
522 (\"font-size\" . \"120%\")
523 (\"text-decoration\" . \"none\"))\n")
525 (defvar hfy-sheet-assoc 'please-ignore-this-line
526 "An assoc with elements of the form (face-name style-name . style-string):\n
527 '((default \"default\" . \"{background: black; color: white}\")
528 (font-lock-string-face \"string\" . \"{color: rgb(64,224,208)}\"))" )
530 (defvar hfy-facemap-assoc 'please-ignore-this-line
531 "An assoc of (point . FACE-SYMBOL) or (point . DEFFACE-LIST)
532 and (point . \\='end) elements, in descending order of point value
533 \(ie from the file's end to its beginning).\n
534 The map is in reverse order because inserting a <style> tag (or any other
535 string) at `point' invalidates the map for all entries with a greater value of
536 point. By traversing the map from greatest to least point, we still invalidate
537 the map as we go, but only those points we have already dealt with (and
538 therefore no longer care about) will be invalid at any time.\n
539 \\='((64820 . end)
540 (64744 . font-lock-comment-face)
541 (64736 . end)
542 (64722 . font-lock-string-face)
543 (64630 . end)
544 (64623 . font-lock-string-face)
545 (64449 . end)
546 (64446 . font-lock-keyword-face)
547 (64406 . end)
548 (64395 . font-lock-constant-face)
549 (64393 . end)
550 (64386 . font-lock-keyword-face)
551 (64379 . end)
552 ;; big similar section elided. You get the idea.
553 (4285 . font-lock-constant-face)
554 (4285 . end)
555 (4221 . font-lock-comment-face)
556 (4221 . end)
557 (4197 . font-lock-constant-face)
558 (4197 . end)
559 (1 . font-lock-comment-face))")
561 (defvar hfy-tmpfont-stack nil
562 "An alist of derived fonts resulting from overlays.")
564 (defconst hfy-hex-regex "[0-9A-Fa-f]")
566 (defconst hfy-triplet-regex
567 (concat
568 "\\(" hfy-hex-regex hfy-hex-regex "\\)"
569 "\\(" hfy-hex-regex hfy-hex-regex "\\)"
570 "\\(" hfy-hex-regex hfy-hex-regex "\\)"))
572 (defun hfy-interq (set-a set-b)
573 "Return the intersection (using `eq') of two lists SET-A and SET-B."
574 (let ((sa set-a) (interq nil) (elt nil))
575 (while sa
576 (setq elt (car sa)
577 sa (cdr sa))
578 (if (memq elt set-b) (setq interq (cons elt interq))))
579 interq))
581 (defun hfy-colour-vals (colour)
582 "Where COLOUR is a color name or #XXXXXX style triplet, return a
583 list of three (16 bit) rgb values for said color.\n
584 If a window system is unavailable, calls `hfy-fallback-colour-values'."
585 (if (string-match hfy-triplet-regex colour)
586 (mapcar
587 (lambda (x) (* (string-to-number (match-string x colour) 16) 257))
588 '(1 2 3))
589 ;;(message ">> %s" colour)
590 (if window-system
591 (if (fboundp 'color-values)
592 (color-values colour)
593 ;;(message "[%S]" window-system)
594 (x-color-values colour))
595 ;; blarg - tty colors are no good - go fetch some X colors:
596 (hfy-fallback-colour-values colour))))
598 (defvar hfy-cperl-mode-kludged-p nil)
600 (defun hfy-kludge-cperl-mode ()
601 "CPerl mode does its damnedest not to do some of its fontification when not
602 in a windowing system - try to trick it..."
603 (if (not hfy-cperl-mode-kludged-p)
604 (progn (if (not window-system)
605 (let ((window-system 'htmlfontify))
606 (eval-and-compile (require 'cperl-mode))
607 (setq cperl-syntaxify-by-font-lock t)))
608 (setq hfy-cperl-mode-kludged-p t))) )
610 (defun hfy-opt (symbol)
611 "Is option SYMBOL set."
612 (memq symbol hfy-optimizations))
614 (defun hfy-default-header (file style)
615 "Default value for `hfy-page-header'.
616 FILE is the name of the file.
617 STYLE is the inline CSS stylesheet (or tag referring to an external sheet)."
618 ;; (format "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
619 ;; <html>\n <head>\n <title>%s</title>\n %s\n </head>\n <body>\n" file style))
620 (format "<?xml version=\"1.0\" encoding=\"utf-8\"?>
621 <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"
622 \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">
623 <html xmlns=\"http://www.w3.org/1999/xhtml\">
624 <head>
625 <title>%s</title>
627 <script type=\"text/javascript\"><!--
628 // this function is needed to work around
629 // a bug in IE related to element attributes
630 function hasClass(obj)
632 var result = false;
633 if (obj.getAttributeNode(\"class\") != null)
635 result = obj.getAttributeNode(\"class\").value;
637 return result;
640 function stripe(id)
642 // the flag we'll use to keep track of
643 // whether the current row is odd or even
644 var even = false;
646 // if arguments are provided to specify the colors
647 // of the even & odd rows, then use the them;
648 // otherwise use the following defaults:
649 var evenColor = arguments[1] ? arguments[1] : \"#fff\";
650 var oddColor = arguments[2] ? arguments[2] : \"#ddd\";
652 // obtain a reference to the desired table
653 // if no such table exists, abort
654 var table = document.getElementById(id);
655 if (! table) { return; }
657 // by definition, tables can have more than one tbody
658 // element, so we'll have to get the list of child
659 // &lt;tbody&gt;s
660 var tbodies = table.getElementsByTagName(\"tbody\");
662 // and iterate through them...
663 for (var h = 0; h < tbodies.length; h++)
665 // find all the &lt;tr&gt; elements...
666 var trs = tbodies[h].getElementsByTagName(\"tr\");
668 // ... and iterate through them
669 for (var i = 0; i < trs.length; i++)
671 // avoid rows that have a class attribute
672 // or backgroundColor style
673 if (! hasClass(trs[i]) &&
674 ! trs[i].style.backgroundColor)
676 // get all the cells in this row...
677 var tds = trs[i].getElementsByTagName(\"td\");
679 // and iterate through them...
680 for (var j = 0; j < tds.length; j++)
682 var mytd = tds[j];
684 // avoid cells that have a class attribute
685 // or backgroundColor style
686 if (! hasClass(mytd) &&
687 ! mytd.style.backgroundColor)
689 mytd.style.backgroundColor =
690 even ? evenColor : oddColor;
694 // flip from odd to even, or vice-versa
695 even = ! even;
700 function toggle_invis( name )
702 var filter =
703 { acceptNode:
704 function( node )
705 { var classname = node.id;
706 if( classname )
707 { var classbase = classname.substr( 0, name.length );
708 if( classbase == name ) { return NodeFilter.FILTER_ACCEPT; } }
709 return NodeFilter.FILTER_SKIP; } };
710 var walker = document.createTreeWalker( document.body ,
711 NodeFilter.SHOW_ELEMENT ,
712 filter ,
713 false );
714 while( walker.nextNode() )
716 var e = walker.currentNode;
717 if( e.style.display == \"none\" ) { e.style.display = \"inline\"; }
718 else { e.style.display = \"none\"; }
721 --> </script>
722 </head>
723 <body onload=\"stripe('index'); return true;\">\n"
724 (mapconcat 'hfy-html-quote (mapcar 'char-to-string file) "") style))
726 (defun hfy-default-footer (_file)
727 "Default value for `hfy-page-footer'.
728 FILE is the name of the file being rendered, in case it is needed."
729 "\n </body>\n</html>\n")
731 (defun hfy-link-style-string (style-string)
732 "Replace the end of a CSS style declaration STYLE-STRING with the contents
733 of the variable `hfy-src-doc-link-style', removing text matching the regex
734 `hfy-src-doc-link-unstyle' first, if necessary."
735 ;;(message "hfy-colour-vals");;DBUG
736 (if (string-match hfy-src-doc-link-unstyle style-string)
737 (setq style-string (replace-match "" 'fixed-case 'literal style-string)))
738 (if (and (not (string-match hfy-src-doc-link-style style-string))
739 (string-match "} *$" style-string))
740 (concat (replace-match hfy-src-doc-link-style
741 'fixed-case
742 'literal
743 style-string) " }")
744 style-string))
746 ;; utility functions - cast emacs style specification values into their
747 ;; css2 equivalents:
748 (defun hfy-triplet (colour)
749 "Takes a COLOUR name (string) and return a CSS rgb(R, G, B) triplet string.
750 Uses the definition of \"white\" to map the numbers to the 0-255 range, so
751 if you've redefined white, (esp. if you've redefined it to have a triplet
752 member lower than that of the color you are processing) strange things
753 may happen."
754 ;;(message "hfy-colour-vals");;DBUG
755 ;; TODO? Can we do somehow do better than this?
756 (cond
757 ((equal colour "unspecified-fg") (setq colour "black"))
758 ((equal colour "unspecified-bg") (setq colour "white")))
759 (let ((white (mapcar (lambda (I) (float (1+ I))) (hfy-colour-vals "white")))
760 (rgb16 (mapcar (lambda (I) (float (1+ I))) (hfy-colour-vals colour))))
761 (if rgb16
762 ;;(apply 'format "rgb(%d, %d, %d)"
763 ;; Use #rrggbb instead, it is smaller
764 (apply 'format "#%02x%02x%02x"
765 (mapcar (lambda (X)
766 (* (/ (nth X rgb16)
767 (nth X white)) 255))
768 '(0 1 2))))))
770 (defun hfy-family (family) (list (cons "font-family" family)))
771 (defun hfy-bgcol (colour) (list (cons "background" (hfy-triplet colour))))
772 (defun hfy-colour (colour) (list (cons "color" (hfy-triplet colour))))
773 (defun hfy-width (width) (list (cons "font-stretch" (symbol-name width))))
775 (defcustom hfy-font-zoom 1.05
776 "Font scaling from Emacs to HTML."
777 :type 'float
778 :group 'htmlfontify)
780 (defun hfy-size (height)
781 "Derive a CSS font-size specifier from an Emacs font :height attribute HEIGHT.
782 Does not cope with the case where height is a function to be applied to
783 the height of the underlying font."
784 ;; In ttys, the default face has :height == 1.
785 (and (not (display-graphic-p)) (equal 1 height) (setq height 100))
786 (list
787 (cond
788 ;;(t (cons "font-size" ": 1em"))
789 ((floatp height)
790 (cons "font-size" (format "%d%%" (* (* hfy-font-zoom height) 100))))
791 ((integerp height)
792 (cons "font-size" (format "%dpt" (/ (* hfy-font-zoom height) 10 )))) )) )
794 (defun hfy-slant (slant)
795 "Derive a font-style CSS specifier from the Emacs :slant attribute SLANT:
796 CSS does not define the reverse-* styles, so just maps those to the
797 regular specifiers."
798 (list (cons "font-style"
799 (or (cdr (assq slant '((italic . "italic")
800 (reverse-italic . "italic" )
801 (oblique . "oblique")
802 (reverse-oblique . "oblique"))))
803 "normal"))))
805 (defun hfy-weight (weight)
806 "Derive a font-weight CSS specifier from an Emacs weight spec symbol WEIGHT."
807 (list (cons "font-weight" (cdr (assq weight '((ultra-bold . "900")
808 (extra-bold . "800")
809 (bold . "700")
810 (semi-bold . "600")
811 (normal . "500")
812 (semi-light . "400")
813 (light . "300")
814 (extra-light . "200")
815 (ultra-light . "100")))))))
817 (defun hfy-box-to-border-assoc (spec)
818 (if spec
819 (let ((tag (car spec))
820 (val (cadr spec)))
821 (cons (case tag
822 (:color (cons "colour" val))
823 (:width (cons "width" val))
824 (:style (cons "style" val)))
825 (hfy-box-to-border-assoc (cddr spec))))))
827 (defun hfy-box-to-style (spec)
828 (let* ((css (hfy-box-to-border-assoc spec))
829 (col (cdr (assoc "colour" css)))
830 (s (cdr (assoc "style" css))))
831 (list
832 (if col (cons "border-color" (cdr (assoc "colour" css))))
833 (cons "border-width" (format "%dpx" (or (cdr (assoc "width" css)) 1)))
834 (cons "border-style" (case s
835 (released-button "outset")
836 (pressed-button "inset" )
837 (t "solid" ))))))
839 (defun hfy-box (box)
840 "Derive CSS border-* attributes from the Emacs :box attribute BOX."
841 (if box
842 (cond
843 ((integerp box) (list (cons "border-width" (format "%dpx" box))))
844 ((stringp box) (list (cons "border" (format "solid %s 1px" box))))
845 ((listp box) (hfy-box-to-style box) ))) )
847 (defun hfy-decor (tag _val)
848 "Derive CSS text-decoration specifiers from various Emacs font attributes.
849 TAG is an Emacs font attribute key (eg :underline).
850 VAL is ignored."
851 (list
852 ;; FIXME: Why not '("text-decoration" . "underline")? --Stef
853 (case tag
854 (:underline (cons "text-decoration" "underline" ))
855 (:overline (cons "text-decoration" "overline" ))
856 (:strike-through (cons "text-decoration" "line-through")))))
858 (defun hfy-invisible (&optional _val)
859 "This text should be invisible.
860 Do something in CSS to make that happen.
861 VAL is ignored here."
862 '(("display" . "none")))
864 (defun hfy-combined-face-spec (face)
865 "Return a `defface' style alist of possible specifications for FACE.
866 Entries resulting from customization (`custom-set-faces') will take
867 precedence."
868 (append
869 (if (and hfy-display-class hfy-default-face-def (eq face 'default))
870 hfy-default-face-def)
871 (get face 'saved-face)
872 (get face 'face-defface-spec)))
874 (defun hfy-face-attr-for-class (face &optional class)
875 "Return the face attributes for FACE.
876 If CLASS is set, it must be a `defface' alist key [see below],
877 in which case the first face specification returned by `hfy-combined-face-spec'
878 which *doesn't* clash with CLASS is returned.\n
879 \(A specification with a class of t is considered to match any class you
880 specify - this matches Emacs's behavior when deciding on which face attributes
881 to use, to the best of my understanding).\n
882 If CLASS is nil, then you just get whatever `face-attr-construct' returns,
883 ie the current specification in effect for FACE.\n
884 *NOTE*: This function forces any face that is not `default' and which has
885 no :inherit property to inherit from `default' (this is because `default'
886 is magical in that Emacs's fonts behave as if they inherit implicitly from
887 `default', but no such behavior exists in HTML/CSS).\n
888 See also `hfy-display-class' for details of valid values for CLASS."
889 (let ((face-spec
890 (if class
891 (let ((face-props (hfy-combined-face-spec face))
892 (face-specn nil)
893 (face-class nil)
894 (face-attrs nil)
895 (face-score -1)
896 (face-match nil))
897 (while face-props
898 (setq face-specn (car face-props)
899 face-class (car face-specn)
900 face-attrs (cdr face-specn)
901 face-props (cdr face-props))
902 ;; if the current element CEL of CLASS is t we match
903 ;; if the current face-class is t, we match
904 ;; if the cdr of CEL has a non-nil
905 ;; intersection with the cdr of the first member of
906 ;; the current face-class with the same car as CEL, we match
907 ;; if we actually clash, then we can't match
908 (let ((cbuf class)
909 (cel nil)
910 (key nil)
911 (val nil)
912 (x nil)
913 (next nil)
914 (score 0))
915 (while (and cbuf (not next))
916 (setq cel (car cbuf)
917 cbuf (cdr cbuf)
918 key (car cel)
919 val (cdr cel)
920 val (if (listp val) val (list val)))
921 (cond
922 ((or (eq cel t)
923 (memq face-class '(t default))) ;Default match.
924 (setq score 0) (ignore "t match"))
925 ((not (cdr (assq key face-class))) ;Neither good nor bad.
926 nil (ignore "non match, non collision"))
927 ((setq x (hfy-interq val (cdr (assq key face-class))))
928 (setq score (+ score (length x)))
929 (ignore "intersection"))
930 (t ;; nope.
931 (setq next t score -10) (ignore "collision")) ))
932 (if (> score face-score)
933 (progn
934 (setq face-match face-attrs
935 face-score score )
936 (ignore "%d << %S/%S" score face-class class))
937 (ignore "--- %d ---- (insufficient)" score)) ))
938 ;; matched ? last attrs : nil
939 (if face-match
940 (if (listp (car face-match)) (car face-match) face-match)
941 nil))
942 ;; Unfortunately the default face returns a
943 ;; :background. Fortunately we can remove it, but how do we do
944 ;; that in a non-system specific way?
945 (let ((spec (face-attr-construct face))
946 (new-spec nil))
947 (if (not (memq :background spec))
948 spec
949 (while spec
950 (let ((a (nth 0 spec))
951 (b (nth 1 spec)))
952 (unless (and (eq a :background)
953 (stringp b)
954 (string= b "SystemWindow"))
955 (setq new-spec (cons a (cons b new-spec)))))
956 (setq spec (cddr spec)))
957 new-spec)))))
958 (if (or (memq :inherit face-spec) (eq 'default face))
959 face-spec
960 (append face-spec (list :inherit 'default)))))
962 ;; construct an assoc of (css-tag-name . css-tag-value) pairs
963 ;; from a face or assoc of face attributes:
965 ;; Some tests etc:
966 ;; (mumamo-message-with-face "testing face" 'highlight)
967 ;; (mumamo-message-with-face "testing face" '(:foreground "red" :background "yellow"))
968 ;; (hfy-face-to-style-i '(:inherit default foreground-color "red"))
969 ;; default face=(:stipple nil :background "SystemWindow" :foreground
970 ;; "SystemWindowText" :inverse-video nil :box nil :strike-through
971 ;; nil :overline nil :underline nil :slant normal :weight normal
972 ;; :height 98 :width normal :family "outline-courier new")
973 (defun hfy-face-to-style-i (fn)
974 "The guts of `hfy-face-to-style': FN should be a `defface' font spec,
975 as returned by `face-attr-construct' or `hfy-face-attr-for-class'.
976 Note that this function does not get font-sizes right if they are based
977 on inherited modifiers (via the :inherit) attribute, and any other
978 modifiers that are cumulative if they appear multiple times need to be
979 merged by the user - `hfy-flatten-style' should do this."
980 ;;(message "hfy-face-to-style-i");;DBUG
982 ;; fn's value could be something like
983 ;; (:inherit
984 ;; ((foreground-color . "blue"))
985 ;; (foreground-color . "blue")
986 ;; nil)
988 (when fn
989 (let ((key (car fn))
990 (val (cadr fn))
991 (next (cddr fn))
992 (that nil)
993 (this nil)
994 (parent nil))
995 (if (eq key :inherit)
996 (let ((vs (if (listp val) val (list val))))
997 ;; (let ((x '(a b))) (setq x (append '(c d) x)))
998 ;; (let ((x '(a b))) (setq x (append '(c d) x)))
999 (dolist (v vs)
1000 (setq parent
1001 (append
1002 parent
1003 (hfy-face-to-style-i
1004 (hfy-face-attr-for-class v hfy-display-class))))))
1005 (setq this
1006 (if val (case key
1007 (:family (hfy-family val))
1008 (:width (hfy-width val))
1009 (:weight (hfy-weight val))
1010 (:slant (hfy-slant val))
1011 (:foreground (hfy-colour val))
1012 (:background (hfy-bgcol val))
1013 (:box (hfy-box val))
1014 (:height (hfy-size val))
1015 (:underline (hfy-decor key val))
1016 (:overline (hfy-decor key val))
1017 (:strike-through (hfy-decor key val))
1018 (:invisible (hfy-invisible val))
1019 (:bold (hfy-weight 'bold))
1020 (:italic (hfy-slant 'italic))))))
1021 (setq that (hfy-face-to-style-i next))
1022 ;;(lwarn t :warning "%S => %S" fn (nconc this that parent))
1023 (nconc this parent that))) )
1025 (defun hfy-size-to-int (spec)
1026 "Convert SPEC, a CSS font-size specifier, to an Emacs :height attribute value.
1027 Used while merging multiple font-size attributes."
1028 ;;(message "hfy-size-to-int");;DBUG
1029 (list
1030 (if (string-match "\\([0-9]+\\)\\(%\\|pt\\)" spec)
1031 (cond ((string= "%" (match-string 2 spec))
1032 (/ (string-to-number (match-string 1 spec)) 100.0))
1033 ((string= "pt" (match-string 2 spec))
1034 (* (string-to-number (match-string 1 spec)) 10)))
1035 (string-to-number spec))) )
1037 ;; size is different, in that in order to get it right at all,
1038 ;; we have to trawl the inheritance path, accumulating modifiers,
1039 ;; _until_ we get to an absolute (pt) specifier, then combine the lot
1040 (defun hfy-flatten-style (style)
1041 "Take STYLE (see `hfy-face-to-style-i', `hfy-face-to-style') and merge
1042 any multiple attributes appropriately. Currently only font-size is merged
1043 down to a single occurrence - others may need special handling, but I
1044 haven't encountered them yet. Returns a `hfy-style-assoc'."
1045 ;;(message "(hfy-flatten-style %S)" style) ;;DBUG
1046 (let ((n 0)
1047 (m (list 1))
1048 (x nil)
1049 (r nil))
1050 (dolist (css style)
1051 (if (string= (car css) "font-size")
1052 (progn
1053 (when (not x) (setq m (nconc m (hfy-size-to-int (cdr css)))))
1054 (when (string-match "pt" (cdr css)) (setq x t)))
1055 (setq r (nconc r (list css)))))
1056 ;;(message "r: %S" r)
1057 (setq n (apply '* m))
1058 (nconc r (hfy-size (if x (round n) (* n 1.0)))) ))
1060 (defun hfy-face-resolve-face (fn)
1061 "For FN return a face specification.
1062 FN may be either a face or a face specification. If the latter,
1063 then the specification is returned unchanged."
1064 (cond
1065 ((facep fn)
1066 (hfy-face-attr-for-class fn hfy-display-class))
1067 ;; FIXME: is this necessary? Faces can be symbols, but
1068 ;; not symbols refering to other symbols?
1069 ((and (symbolp fn)
1070 (facep (symbol-value fn)))
1071 (hfy-face-attr-for-class
1072 (symbol-value fn) hfy-display-class))
1073 (t fn)))
1076 (defun hfy-face-to-style (fn)
1077 "Take FN, a font or `defface' style font specification,
1078 \(as returned by `face-attr-construct' or `hfy-face-attr-for-class')
1079 and return a `hfy-style-assoc'.\n
1080 See also `hfy-face-to-style-i', `hfy-flatten-style'."
1081 ;;(message "hfy-face-to-style");;DBUG
1082 (let* ((face-def (hfy-face-resolve-face fn))
1083 (final-style
1084 (hfy-flatten-style (hfy-face-to-style-i face-def))))
1085 ;;(message "%S" final-style)
1086 (if (not (assoc "text-decoration" final-style))
1087 (progn (setq final-style
1088 ;; Fix-me: there is no need for this since
1089 ;; text-decoration is not inherited.
1090 ;; but it's not wrong and if this ever changes it will
1091 ;; be needed, so I think it's better to leave it in? -- v
1092 (nconc final-style '(("text-decoration" . "none"))))))
1093 final-style))
1095 ;; strip redundant bits from a name. Technically, this could result in
1096 ;; a collision, but it is pretty unlikely - will fix later...
1097 ;; also handle ephemeral fonts created by overlays, which don't actually
1098 ;; have names:
1099 (defun hfy-face-or-def-to-name (fn)
1100 "Render a font symbol or `defface' font spec FN into a name (string)."
1101 ;;(message "generating name for %s" fn)
1102 (if (not (listp fn))
1103 (format "%s" fn)
1104 (let* ((key (format "%s" fn))
1105 (entry (assoc key hfy-tmpfont-stack))
1106 (base (cadr (memq :inherit fn)))
1107 (tag (cdr entry)))
1108 ;;(message "checking for key «%s» in font stack [%d]"
1109 ;; key (if entry 1 0))
1110 (if entry nil ;; noop
1111 (setq tag (format "%04d" (length hfy-tmpfont-stack))
1112 entry (cons key tag)
1113 hfy-tmpfont-stack (cons entry hfy-tmpfont-stack)))
1114 ;;(message " -> name: %s-%s" (or base 'default) tag)
1115 (format "%s-%s" (or base 'default) tag)) ))
1117 (defun hfy-css-name (fn)
1118 "Strip the boring bits from a font-name FN and return a CSS style name."
1119 ;;(message "hfy-css-name");;DBUG
1120 (let ((face-name (hfy-face-or-def-to-name fn)))
1121 (if (or (string-match "font-lock-\\(.*\\)" face-name)
1122 (string-match "cperl-\\(.*\\)" face-name)
1123 (string-match "^[Ii]nfo-\\(.*\\)" face-name))
1124 (progn
1125 (setq face-name (match-string 1 face-name))
1126 (if (string-match "\\(.*\\)-face\\'" face-name)
1127 (setq face-name (match-string 1 face-name)))
1128 face-name)
1129 face-name)) )
1131 ;; construct an assoc of (stripped-name . "{ css-stuff-here }") pairs
1132 ;; from a face:
1133 (defun hfy-face-to-css-default (fn)
1134 "Default handler for mapping faces to styles.
1135 See also `hfy-face-to-css'."
1136 ;;(message "hfy-face-to-css");;DBUG
1137 (let* ((css-list (hfy-face-to-style fn))
1138 (seen nil)
1139 (css-text
1140 (mapcar
1141 (lambda (E)
1142 (if (car E)
1143 (unless (member (car E) seen)
1144 (push (car E) seen)
1145 (format " %s: %s; " (car E) (cdr E)))))
1146 css-list)))
1147 (cons (hfy-css-name fn) (format "{%s}" (apply 'concat css-text)))) )
1149 (defvar hfy-face-to-css 'hfy-face-to-css-default
1150 "Handler for mapping faces to styles.
1151 The signature of the handler is of the form \(lambda (FN) ...).
1152 FN is a font or `defface' specification (cf
1153 `face-attr-construct'). The handler should return a cons cell of
1154 the form (STYLE-NAME . STYLE-SPEC).
1156 The default handler is `hfy-face-to-css-default'.
1158 See also `hfy-face-to-style'.")
1160 (defalias 'hfy-prop-invisible-p
1161 (if (fboundp 'invisible-p) #'invisible-p
1162 (lambda (prop)
1163 "Is text property PROP an active invisibility property?"
1164 (or (and (eq buffer-invisibility-spec t) prop)
1165 (or (memq prop buffer-invisibility-spec)
1166 (assq prop buffer-invisibility-spec))))))
1168 (defun hfy-find-invisible-ranges ()
1169 "Return a list of (start-point . end-point) cons cells of invisible regions."
1170 (save-excursion
1171 (let (invisible p i s) ;; return-value pos invisible end start
1172 (setq p (goto-char (point-min)))
1173 (when (invisible-p p) (setq s p i t))
1174 (while (< p (point-max))
1175 (if i ;; currently invisible
1176 (when (not (invisible-p p)) ;; but became visible
1177 (setq i nil
1178 invisible (cons (cons s p) invisible)))
1179 ;; currently visible:
1180 (when (invisible-p p) ;; but have become invisible
1181 (setq s p i t)))
1182 (setq p (next-char-property-change p)))
1183 ;; still invisible at buffer end?
1184 (when i
1185 (setq invisible (cons (cons s (point-max)) invisible)))
1186 invisible)))
1188 (defun hfy-invisible-name (point map)
1189 "Generate a CSS style name for an invisible section of the buffer.
1190 POINT is the point inside the invisible region.
1191 MAP is the invisibility map as returned by `hfy-find-invisible-ranges'."
1192 ;;(message "(hfy-invisible-name %S %S)" point map)
1193 (let (name)
1194 (dolist (range map)
1195 (when (and (>= point (car range))
1196 (< point (cdr range)))
1197 (setq name (format "invisible-%S-%S" (car range) (cdr range)))))
1198 name))
1200 ;; Fix-me: This function needs some cleanup by someone who understand
1201 ;; all the formats that face properties can have.
1203 ;; overlay handling should be fine. haven't tested multiple stacked overlapping
1204 ;; overlays recently, but the common case of a text property face + an overlay
1205 ;; face produces the correct merged css style (or as close to it as css can get)
1206 ;; -- v
1207 (defun hfy-face-at (p)
1208 "Find face in effect at point P.
1209 If overlays are to be considered (see `hfy-optimizations') then this may
1210 return a `defface' style list of face properties instead of a face symbol."
1211 ;;(message "hfy-face-at");;DBUG
1212 ;; Fix-me: clean up, remove face-name etc
1213 ;; not sure why we'd want to remove face-name? -- v
1214 (let ((overlay-data nil)
1215 (base-face nil)
1216 (face-name (get-text-property p 'face))
1217 ;; (face-name (hfy-get-face-at p))
1218 (prop-seen nil)
1219 (extra-props nil)
1220 (text-props (text-properties-at p)))
1221 ;;(message "face-name: %S" face-name)
1222 (when (and face-name (listp face-name) (facep (car face-name)))
1223 ;;(message "face-name is a list %S" face-name)
1224 ;;(setq text-props (cons 'face face-name))
1225 (dolist (f face-name)
1226 (setq extra-props (if (listp f)
1227 ;; for things like (variable-pitch
1228 ;; (:foreground "red"))
1229 (cons f extra-props)
1230 (cons :inherit (cons f extra-props)))))
1231 (setq base-face (car face-name)
1232 face-name nil))
1233 ;; text-properties-at => (face (:foreground "red" ...))
1234 ;; or => (face (compilation-info underline)) list of faces
1235 ;; overlay-properties
1236 ;; format= (evaporate t face ((foreground-color . "red")))
1238 ;; SO: if we have turned overlays off,
1239 ;; or if there's no overlay data
1240 ;; just bail out and return whatever face data we've accumulated so far
1241 (if (or (not (hfy-opt 'keep-overlays))
1242 (not (setq overlay-data (hfy-overlay-props-at p))))
1243 (progn
1244 ;;(message "· %d: %s; %S; %s"
1245 ;; p face-name extra-props text-props)
1246 (or face-name base-face)) ;; no overlays or extra properties
1247 ;; collect any face data and any overlay data for processing:
1248 (when text-props
1249 (push text-props overlay-data))
1250 (setq overlay-data (nreverse overlay-data))
1251 ;;(message "- %d: %s; %S; %s; %s"
1252 ;; p face-name extra-props text-props overlay-data)
1253 ;; remember the basic face name so we don't keep repeating its specs:
1254 (when face-name (setq base-face face-name))
1255 (dolist (P overlay-data)
1256 (let ((iprops (cadr (memq 'invisible P)))) ;FIXME: plist-get?
1257 ;;(message "(hfy-prop-invisible-p %S)" iprops)
1258 (when (and iprops (hfy-prop-invisible-p iprops))
1259 (setq extra-props
1260 (cons :invisible (cons t extra-props))) ))
1261 (let ((fprops (cadr (or (memq 'face P)
1262 (memq 'font-lock-face P)))))
1263 ;;(message "overlay face: %s" fprops)
1264 (if (not (listp fprops))
1265 (let ((this-face (if (stringp fprops) (intern fprops) fprops)))
1266 (when (not (eq this-face base-face))
1267 (setq extra-props
1268 (cons :inherit
1269 (cons this-face extra-props))) ))
1270 (while fprops
1271 (if (facep (car fprops))
1272 (let ((face (car fprops)))
1273 (when (stringp face) (setq face (intern fprops)))
1274 (setq extra-props
1275 (cons :inherit
1276 (cons face
1277 extra-props)))
1278 (setq fprops (cdr fprops)))
1279 (let (p v)
1280 ;; Sigh.
1281 (if (listp (car fprops))
1282 (if (nlistp (cdr (car fprops)))
1283 (progn
1284 ;; ((prop . val))
1285 (setq p (caar fprops))
1286 (setq v (cdar fprops))
1287 (setq fprops (cdr fprops)))
1288 ;; ((prop val))
1289 (setq p (caar fprops))
1290 (setq v (cadar fprops))
1291 (setq fprops (cdr fprops)))
1292 (if (listp (cdr fprops))
1293 (progn
1294 ;; (:prop val :prop val ...)
1295 (setq p (car fprops))
1296 (setq v (cadr fprops))
1297 (setq fprops (cddr fprops)))
1298 (if (and (listp fprops)
1299 (not (listp (cdr fprops))))
1300 ;;(and (consp x) (cdr (last x)))
1301 (progn
1302 ;; (prop . val)
1303 (setq p (car fprops))
1304 (setq v (cdr fprops))
1305 (setq fprops nil))
1306 (error "Eh... another format! fprops=%s" fprops) )))
1307 (setq p (case p
1308 ;; These are all the properties handled
1309 ;; in `hfy-face-to-style-i'.
1311 ;; Are these translations right?
1312 ;; yes, they are -- v
1313 (family :family )
1314 (width :width )
1315 (height :height )
1316 (weight :weight )
1317 (slant :slant )
1318 (underline :underline )
1319 (overline :overline )
1320 (strike-through :strike-through)
1321 (box :box )
1322 (foreground-color :foreground)
1323 (background-color :background)
1324 (bold :bold )
1325 (italic :italic )
1326 (t p)))
1327 (if (memq p prop-seen) nil ;; noop
1328 (setq prop-seen (cons p prop-seen)
1329 extra-props (cons p (cons v extra-props))))))))))
1330 ;;(message "+ %d: %s; %S" p face-name extra-props)
1331 (if extra-props
1332 (nconc extra-props (if (listp face-name)
1333 face-name
1334 (face-attr-construct face-name)))
1335 face-name)) ))
1337 (defun hfy-overlay-props-at (p)
1338 "Grab overlay properties at point P.
1339 The plists are returned in descending priority order."
1340 (mapcar #'overlay-properties (overlays-at p 'sorted)))
1342 ;; construct an assoc of (face-name . (css-name . "{ css-style }")) elements:
1343 (defun hfy-compile-stylesheet ()
1344 "Trawl the current buffer, construct and return a `hfy-sheet-assoc'.
1345 If `hfy-user-sheet-assoc' is currently bound then use it to
1346 collect new styles discovered during this run. Otherwise create
1347 a new assoc."
1348 ;;(message "hfy-compile-stylesheet");;DBUG
1349 (let ((pt (point-min))
1350 ;; Make the font stack stay:
1351 ;;(hfy-tmpfont-stack nil)
1352 (fn nil)
1353 (style (and (boundp 'hfy-user-sheet-assoc) hfy-user-sheet-assoc)))
1354 (save-excursion
1355 (goto-char pt)
1356 (while (< pt (point-max))
1357 (if (and (setq fn (hfy-face-at pt)) (not (assoc fn style)))
1358 (push (cons fn (funcall hfy-face-to-css fn)) style))
1359 (setq pt (next-char-property-change pt))))
1360 (unless (assoc 'default style)
1361 (push (cons 'default (funcall hfy-face-to-css 'default)) style))
1362 (when (boundp 'hfy-user-sheet-assoc)
1363 (setq hfy-user-sheet-assoc style))
1364 style))
1366 (defun hfy-fontified-p ()
1367 "`font-lock' doesn't like to say it's been fontified when in batch
1368 mode, but we want to know if we should fontify or raw copy, so in batch
1369 mode we check for non-default face properties. Otherwise we test
1370 variable `font-lock-mode' and variable `font-lock-fontified' for truth."
1371 ;;(message "font-lock-fontified: %S" font-lock-fontified)
1372 ;;(message "noninteractive : %S" noninteractive)
1373 ;;(message "font-lock-mode : %S" font-lock-mode)
1374 (and font-lock-fontified
1375 (if noninteractive
1376 (let ((pt (point-min))
1377 (face-name nil))
1378 (save-excursion
1379 (goto-char pt)
1380 (while (and (< pt (point-max)) (not face-name))
1381 (setq face-name (hfy-face-at pt))
1382 (setq pt (next-char-property-change pt))))
1383 face-name)
1384 font-lock-mode)))
1386 ;; remember, the map is in reverse point order:
1387 ;; I wrote this while suffering the effects of a cold, and maybe a
1388 ;; mild fever - I think it's correct, but it might be a little warped
1389 ;; as my minfd keeps ... where was I? Oh yes, the bunnies...
1390 (defun hfy-merge-adjacent-spans (face-map)
1391 "Where FACE-MAP is a `hfy-facemap-assoc' for the current buffer,
1392 this function merges adjacent style blocks which are of the same value
1393 and are separated by nothing more interesting than whitespace.\n
1394 <span class=\"foo\">narf</span> <span class=\"foo\">brain</span>\n
1395 \(as interpreted from FACE-MAP) would become:\n
1396 <span class=\"foo\">narf brain</span>\n
1397 Returns a modified copy of FACE-MAP."
1398 (let ((tmp-map face-map)
1399 (map-buf nil)
1400 (first-start nil)
1401 (first-stop nil)
1402 (last-start nil)
1403 (last-stop nil)
1404 (span-stop nil)
1405 (span-start nil)
1406 (reduced-map nil))
1407 ;;(push (car tmp-map) reduced-map)
1408 ;;(push (cadr tmp-map) reduced-map)
1409 (while tmp-map
1410 (setq first-start (cadddr tmp-map)
1411 first-stop (caddr tmp-map)
1412 last-start (cadr tmp-map)
1413 last-stop (car tmp-map)
1414 map-buf tmp-map
1415 span-start last-start
1416 span-stop last-stop )
1417 (while (and (equal (cdr first-start)
1418 (cdr last-start))
1419 (save-excursion
1420 (goto-char (car first-stop))
1421 (not (re-search-forward "[^ \t\n\r]" (car last-start) t))))
1422 (setq map-buf (cddr map-buf)
1423 span-start first-start
1424 first-start (cadddr map-buf)
1425 first-stop (caddr map-buf)
1426 last-start (cadr map-buf)
1427 last-stop (car map-buf)))
1428 (push span-stop reduced-map)
1429 (push span-start reduced-map)
1430 (setq tmp-map (memq last-start tmp-map))
1431 (setq tmp-map (cdr tmp-map)))
1432 (setq reduced-map (nreverse reduced-map))))
1434 ;; remember to generate 'synthetic' </span> entries -
1435 ;; emacs copes by just having a stack of styles in effect
1436 ;; and only using the top one: html has a more simplistic approach -
1437 ;; we have to explicitly end a style, there's no way of temporarily
1438 ;; overriding it w. another one... (afaik)
1439 (defun hfy-compile-face-map ()
1440 ;; no need for special <a> version.
1441 ;; IME hyperlinks don't get underlined, esp when you htmlfontify a whole
1442 ;; source tree, so the <a> version is needed -- v
1443 ;; Fix-me: save table for multi-buffer
1444 "Compile and return a `hfy-facemap-assoc' for the current buffer."
1445 ;;(message "hfy-compile-face-map");;DBUG
1446 (let* ((pt (point-min))
1447 (pt-narrow (save-restriction (widen) (point-min)))
1448 (offset (- pt pt-narrow))
1449 (fn nil)
1450 (map nil)
1451 (prev-tag nil)) ;; t if the last tag-point was a span-start
1452 ;; nil if it was a span-stop
1453 (save-excursion
1454 (goto-char pt)
1455 (while (< pt (point-max))
1456 (if (setq fn (hfy-face-at pt))
1457 (progn (if prev-tag (push (cons pt-narrow 'end) map))
1458 (push (cons pt-narrow fn) map)
1459 (setq prev-tag t))
1460 (if prev-tag (push (cons pt-narrow 'end) map))
1461 (setq prev-tag nil))
1462 (setq pt (next-char-property-change pt))
1463 (setq pt-narrow (+ offset pt)))
1464 (if (and map (not (eq 'end (cdar map))))
1465 (push (cons (1+ (- (point-max) (point-min))) 'end) map)))
1466 (if (hfy-opt 'merge-adjacent-tags) (hfy-merge-adjacent-spans map) map)))
1468 (defun hfy-buffer ()
1469 "Generate a buffer to hold the HTML output.
1470 The filename of this buffer is derived from the source (current) buffer's
1471 variable `buffer-file-name', if it is set, plus `hfy-extn'.
1472 Otherwise a plausible filename is constructed from `default-directory',
1473 `buffer-name' and `hfy-extn'."
1474 (let* ((name (concat (buffer-name) hfy-extn))
1475 (src (buffer-file-name))
1476 (buf (get-buffer-create name)))
1477 (with-current-buffer buf
1478 (setq buffer-file-name
1479 (if src (concat src hfy-extn)
1480 (expand-file-name (if (string-match "^.*/\\([^/]*\\)\\'" name)
1481 (match-string 1 name)
1482 name))))
1483 buf)))
1485 (defun hfy-lookup (face style)
1486 "Get a CSS style name for FACE from STYLE."
1487 (cadr (assoc face style)))
1489 (defun hfy-link-style (style-string)
1490 "Copy, alter and return a STYLE-STRING to make it suitable for a hyperlink.
1491 Uses `hfy-link-style-fun' to do this."
1492 (if (functionp hfy-link-style-fun)
1493 (funcall hfy-link-style-fun style-string)
1494 style-string))
1496 (defun hfy-sprintf-stylesheet (css file)
1497 "Return the inline CSS style sheet for FILE as a string."
1498 (let ((stylesheet
1499 (concat
1500 hfy-meta-tags
1501 "\n<style type=\"text/css\"><!-- \n"
1502 ;; Fix-me: Add handling of page breaks here + scan for ^L
1503 ;; where appropriate.
1504 (format "body %s\n" (cddr (assq 'default css)))
1505 (apply 'concat
1506 (mapcar
1507 (lambda (style)
1508 (format
1509 "span.%s %s\nspan.%s a %s\n"
1510 (cadr style) (cddr style)
1511 (cadr style) (hfy-link-style (cddr style))))
1512 css))
1513 " --></style>\n")))
1514 (funcall hfy-page-header file stylesheet)))
1516 ;; tag all the dangerous characters we want to escape
1517 ;; (ie any "<> chars we _didn't_ put there explicitly for css markup)
1518 (defun hfy-html-enkludge-buffer ()
1519 "Mark dangerous [\"<>] characters with the `hfy-quoteme' property.\n
1520 See also `hfy-html-dekludge-buffer'."
1521 ;;(message "hfy-html-enkludge-buffer");;DBUG
1522 (save-excursion
1523 (goto-char (point-min))
1524 (while (re-search-forward hfy-html-quote-regex nil t)
1525 (put-text-property (match-beginning 0) (point) 'hfy-quoteme t))) )
1527 ;; dangerous char -> &entity;
1528 (defun hfy-html-quote (char-string)
1529 "Map CHAR-STRING to an HTML safe string (entity) if need be."
1530 ;;(message "hfy-html-quote");;DBUG
1531 (or (cadr (assoc char-string hfy-html-quote-map)) char-string) )
1533 ;; actually entity-ise dangerous chars.
1534 ;; note that we can't do this until _after_ we have inserted the css
1535 ;; markup, since we use a position-based map to insert this, and if we
1536 ;; enter any other text before we do this, we'd have to track another
1537 ;; map of offsets, which would be tedious...
1538 (defun hfy-html-dekludge-buffer ()
1539 "Transform all dangerous characters marked with the `hfy-quoteme' property
1540 using `hfy-html-quote'.\n
1541 See also `hfy-html-enkludge-buffer'."
1542 ;;(message "hfy-html-dekludge-buffer");;DBUG
1543 (save-excursion
1544 (goto-char (point-min))
1545 (while (re-search-forward hfy-html-quote-regex nil t)
1546 (if (get-text-property (match-beginning 0) 'hfy-quoteme)
1547 (replace-match (hfy-html-quote (match-string 1))) )) ))
1549 ;; Borrowed from font-lock.el
1550 (defmacro hfy-save-buffer-state (varlist &rest body)
1551 "Bind variables according to VARLIST and eval BODY restoring buffer state.
1552 Do not record undo information during evaluation of BODY."
1553 (declare (indent 1) (debug let))
1554 (let ((modified (make-symbol "modified")))
1555 `(let* ,(append varlist
1556 `((,modified (buffer-modified-p))
1557 (buffer-undo-list t)
1558 (inhibit-read-only t)
1559 (inhibit-point-motion-hooks t)
1560 (inhibit-modification-hooks t)
1561 deactivate-mark
1562 buffer-file-name
1563 buffer-file-truename))
1564 (progn
1565 ,@body)
1566 (unless ,modified
1567 (restore-buffer-modified-p nil)))))
1569 (defun hfy-mark-trailing-whitespace ()
1570 "Tag trailing whitespace with a hfy property if it is currently highlighted."
1571 (when show-trailing-whitespace
1572 (let ((inhibit-read-only t))
1573 (save-excursion
1574 (goto-char (point-min))
1575 (hfy-save-buffer-state nil
1576 (while (re-search-forward "[ \t]+$" nil t)
1577 (put-text-property (match-beginning 0) (match-end 0)
1578 'hfy-show-trailing-whitespace t)))))))
1580 (defun hfy-unmark-trailing-whitespace ()
1581 "Undo the effect of `hfy-mark-trailing-whitespace'."
1582 (when show-trailing-whitespace
1583 (hfy-save-buffer-state nil
1584 (remove-text-properties (point-min) (point-max)
1585 '(hfy-show-trailing-whitespace)))))
1587 (defun hfy-begin-span (style text-block text-id text-begins-block-p)
1588 "Default handler to begin a span of text.
1589 Insert \"<span class=\"STYLE\" ...>\". See
1590 `hfy-begin-span-handler' for more information."
1591 (when text-begins-block-p
1592 (insert
1593 (format "<span onclick=\"toggle_invis('%s');\">…</span>" text-block)))
1595 (insert
1596 (if text-block
1597 (format "<span class=\"%s\" id=\"%s-%d\">" style text-block text-id)
1598 (format "<span class=\"%s\">" style))))
1600 (defun hfy-end-span ()
1601 "Default handler to end a span of text.
1602 Insert \"</span>\". See `hfy-end-span-handler' for more
1603 information."
1604 (insert "</span>"))
1606 (defvar hfy-begin-span-handler 'hfy-begin-span
1607 "Handler to begin a span of text.
1608 The signature of the handler is \(lambda (STYLE TEXT-BLOCK
1609 TEXT-ID TEXT-BEGINS-BLOCK-P) ...). The handler must insert
1610 appropriate tags to begin a span of text.
1612 STYLE is the name of the style that begins at point. It is
1613 derived from the face attributes as part of `hfy-face-to-css'
1614 callback. The other arguments TEXT-BLOCK, TEXT-ID,
1615 TEXT-BEGINS-BLOCK-P are non-nil only if the buffer contains
1616 invisible text.
1618 TEXT-BLOCK is a string that identifies a single chunk of visible
1619 or invisible text of which the current position is a part. For
1620 visible portions, it's value is \"nil\". For invisible portions,
1621 it's value is computed as part of `hfy-invisible-name'.
1623 TEXT-ID marks a unique position within a block. It is set to
1624 value of `point' at the current buffer position.
1626 TEXT-BEGINS-BLOCK-P is a boolean and is non-nil if the current
1627 span also begins a invisible portion of text.
1629 An implementation can use TEXT-BLOCK, TEXT-ID,
1630 TEXT-BEGINS-BLOCK-P to implement fold/unfold-on-mouse-click like
1631 behavior.
1633 The default handler is `hfy-begin-span'.")
1635 (defvar hfy-end-span-handler 'hfy-end-span
1636 "Handler to end a span of text.
1637 The signature of the handler is \(lambda () ...). The handler
1638 must insert appropriate tags to end a span of text.
1640 The default handler is `hfy-end-span'.")
1642 (defun hfy-fontify-buffer (&optional srcdir file)
1643 "Implement the guts of `htmlfontify-buffer'.
1644 SRCDIR, if set, is the directory being htmlfontified.
1645 FILE, if set, is the file name."
1646 (if srcdir (setq srcdir (directory-file-name srcdir)))
1647 (let* ( (html-buffer (hfy-buffer))
1648 (css-sheet nil)
1649 (css-map nil)
1650 (invis-ranges nil)
1651 (rovl nil)
1652 (rmin (when mark-active (region-beginning)))
1653 (rmax (when mark-active (region-end ))) )
1654 (when (and mark-active
1655 transient-mark-mode)
1656 (unless (and (= rmin (point-min))
1657 (= rmax (point-max)))
1658 (setq rovl (make-overlay rmin rmax))
1659 (overlay-put rovl 'priority 1000)
1660 (overlay-put rovl 'face 'region)))
1661 ;; copy the buffer, including fontification, and switch to it:
1662 (hfy-mark-trailing-whitespace)
1663 (setq css-sheet (hfy-compile-stylesheet )
1664 css-map (hfy-compile-face-map )
1665 invis-ranges (hfy-find-invisible-ranges))
1666 (hfy-unmark-trailing-whitespace)
1667 (when rovl
1668 (delete-overlay rovl))
1669 (copy-to-buffer html-buffer (point-min) (point-max))
1670 (set-buffer html-buffer)
1671 ;; rip out props that could interfere with our htmlization of the buffer:
1672 (remove-text-properties (point-min) (point-max) hfy-ignored-properties)
1673 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1674 ;; at this point, html-buffer retains the fontification of the parent:
1675 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1676 ;; we don't really need or want text in the html buffer to be invisible, as
1677 ;; that can make it look like we've rendered invalid xhtml when all that's
1678 ;; happened is some tags are in the invisible portions of the buffer:
1679 (setq buffer-invisibility-spec nil)
1680 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1681 ;; #####################################################################
1682 ;; if we are in etags mode, add properties to mark the anchors and links
1683 (if (and srcdir file)
1684 (progn
1685 (hfy-mark-tag-names srcdir file) ;; mark anchors
1686 (hfy-mark-tag-hrefs srcdir file))) ;; mark links
1687 ;; #####################################################################
1688 ;; mark the 'dangerous' characters
1689 ;;(message "marking dangerous characters")
1690 (hfy-html-enkludge-buffer)
1691 ;; trawl the position-based face-map, inserting span tags as we go
1692 ;; note that we cannot change any character positions before this point
1693 ;; or we will invalidate the map:
1694 ;; NB: This also means we have to trawl the map in descending file-offset
1695 ;; order, obviously.
1696 ;; ---------------------------------------------------------------------
1697 ;; Remember, inserting pushes properties to the right, which we don't
1698 ;; actually want to happen for link properties, so we have to flag
1699 ;; them and move them by hand - if you don't, you end up with
1701 ;; <span class="foo"><a href="bar">texta</span><span class="bletch"></a>...
1703 ;; instead of:
1705 ;; <span class="foo"><a href="bar">texta</a></span><span class="bletch">...
1707 ;; If my analysis of the problem is correct, we can detect link-ness by
1708 ;; either hfy-linkp or hfy-endl properties at the insertion point, but I
1709 ;; think we only need to relocate the hfy-endl property, as the hfy-linkp
1710 ;; property has already served its main purpose by this point.
1711 ;;(message "mapcar over the CSS-MAP")
1712 ;; (message "invis-ranges:\n%S" invis-ranges)
1713 (dolist (point-face css-map)
1714 (let ((pt (car point-face))
1715 (fn (cdr point-face))
1716 (move-link nil))
1717 (goto-char pt)
1718 (setq move-link
1719 (or (get-text-property pt 'hfy-linkp)
1720 (get-text-property pt 'hfy-endl )))
1721 (if (eq 'end fn)
1722 (funcall hfy-end-span-handler)
1723 (if (not (and srcdir file))
1725 (when move-link
1726 (remove-text-properties (point) (1+ (point)) '(hfy-endl nil))
1727 (put-text-property pt (1+ pt) 'hfy-endl t) ))
1728 ;; if we have invisible blocks, we need to do some extra magic:
1729 (funcall hfy-begin-span-handler
1730 (hfy-lookup fn css-sheet)
1731 (and invis-ranges
1732 (format "%s" (hfy-invisible-name pt invis-ranges)))
1733 (and invis-ranges pt)
1734 (and invis-ranges (assq pt invis-ranges)))
1735 (if (not move-link) nil
1736 ;;(message "removing prop2 @ %d" (point))
1737 (if (remove-text-properties (point) (1+ (point)) '(hfy-endl nil))
1738 (put-text-property pt (1+ pt) 'hfy-endl t))))))
1739 ;; #####################################################################
1740 ;; Invisibility
1741 ;; Maybe just make the text invisible in XHTML?
1742 ;; DONE -- big block of obsolete invisibility code elided here -- v
1743 ;; #####################################################################
1744 ;; (message "checking to see whether we should link...")
1745 (if (and srcdir file)
1746 (let ((lp 'hfy-link)
1747 (pt (point-min))
1748 (pr nil)
1749 (rr nil))
1750 ;; (message " yes we should.")
1751 ;; translate 'hfy-anchor properties to anchors
1752 (while (setq pt (next-single-property-change pt 'hfy-anchor))
1753 (if (setq pr (get-text-property pt 'hfy-anchor))
1754 (progn (goto-char pt)
1755 (remove-text-properties pt (1+ pt) '(hfy-anchor nil))
1756 (insert (concat "<a name=\"" pr "\"></a>")))))
1757 ;; translate alternate 'hfy-link and 'hfy-endl props to opening
1758 ;; and closing links. (this should avoid those spurious closes
1759 ;; we sometimes get by generating only paired tags)
1760 (setq pt (point-min))
1761 (while (setq pt (next-single-property-change pt lp))
1762 (if (not (setq pr (get-text-property pt lp))) nil
1763 (goto-char pt)
1764 (remove-text-properties pt (1+ pt) (list lp nil))
1765 (case lp
1766 (hfy-link
1767 (if (setq rr (get-text-property pt 'hfy-inst))
1768 (insert (format "<a name=\"%s\"></a>" rr)))
1769 (insert (format "<a href=\"%s\">" pr))
1770 (setq lp 'hfy-endl))
1771 (hfy-endl
1772 (insert "</a>") (setq lp 'hfy-link)) ))) ))
1774 ;; #####################################################################
1775 ;; transform the dangerous chars. This changes character positions
1776 ;; since entities have > char length.
1777 ;; note that this deletes the dangerous characters, and therefore
1778 ;; destroys any properties they may contain (such as 'hfy-endl),
1779 ;; so we have to do this after we use said properties:
1780 ;; (message "munging dangerous characters")
1781 (hfy-html-dekludge-buffer)
1782 (unless (hfy-opt 'body-text-only)
1783 ;; insert the stylesheet at the top:
1784 (goto-char (point-min))
1786 ;;(message "inserting stylesheet")
1787 (insert (hfy-sprintf-stylesheet css-sheet file))
1789 (if (hfy-opt 'div-wrapper) (insert "<div class=\"default\">"))
1790 (insert "\n<pre>")
1791 (goto-char (point-max))
1792 (insert "</pre>\n")
1793 (if (hfy-opt 'div-wrapper) (insert "</div>"))
1794 ;;(message "inserting footer")
1795 (insert (funcall hfy-page-footer file)))
1796 ;; call any post html-generation hooks:
1797 (run-hooks 'hfy-post-html-hook)
1798 ;; return the html buffer
1799 (set-buffer-modified-p nil)
1800 html-buffer))
1802 (defun htmlfontify-string (string)
1803 "Take a STRING and return a fontified version of it.
1804 It is assumed that STRING has text properties that allow it to be
1805 fontified. This is a simple convenience wrapper around
1806 `htmlfontify-buffer'."
1807 (let* ((hfy-optimizations-1 (copy-sequence hfy-optimizations))
1808 (hfy-optimizations (add-to-list 'hfy-optimizations-1
1809 'skip-refontification)))
1810 (with-temp-buffer
1811 (insert string)
1812 (htmlfontify-buffer)
1813 (buffer-string))))
1815 (defun hfy-force-fontification ()
1816 "Try to force font-locking even when it is optimized away."
1817 (run-hooks 'hfy-init-kludge-hook)
1818 (eval-and-compile (require 'font-lock))
1819 (if (boundp 'font-lock-cache-position)
1820 (or font-lock-cache-position
1821 (setq font-lock-cache-position (make-marker))))
1822 (cond
1823 (noninteractive
1824 (message "hfy batch mode (%s:%S)"
1825 (or (buffer-file-name) (buffer-name)) major-mode)
1826 (if (fboundp 'font-lock-ensure)
1827 (font-lock-ensure)
1828 (when font-lock-defaults
1829 (font-lock-fontify-buffer))))
1830 ((fboundp #'jit-lock-fontify-now)
1831 (message "hfy jit-lock mode (%S %S)" window-system major-mode)
1832 (jit-lock-fontify-now))
1834 (message "hfy interactive mode (%S %S)" window-system major-mode)
1835 ;; If jit-lock is not in use, then the buffer is already fontified!
1836 ;; (when (and font-lock-defaults
1837 ;; font-lock-mode)
1838 ;; (font-lock-fontify-region (point-min) (point-max) nil))
1841 ;;;###autoload
1842 (defun htmlfontify-buffer (&optional srcdir file)
1843 "Create a new buffer, named for the current buffer + a .html extension,
1844 containing an inline CSS-stylesheet and formatted CSS-markup HTML
1845 that reproduces the look of the current Emacs buffer as closely
1846 as possible.
1848 Dangerous characters in the existing buffer are turned into HTML
1849 entities, so you should even be able to do HTML-within-HTML
1850 fontified display.
1852 You should, however, note that random control or non-ASCII
1853 characters such as ^L (U+000C FORM FEED (FF)) or ¤ (U+00A4
1854 CURRENCY SIGN) won't get mapped yet.
1856 If the SRCDIR and FILE arguments are set, lookup etags derived
1857 entries in the `hfy-tags-cache' and add HTML anchors and
1858 hyperlinks as appropriate."
1859 (interactive)
1860 ;; pick up the file name in case we didn't receive it
1861 (if (not file)
1862 (progn (setq file (or (buffer-file-name) (buffer-name)))
1863 (if (string-match "/\\([^/]*\\)\\'" file)
1864 (setq file (match-string 1 file)))) )
1866 (if (not (hfy-opt 'skip-refontification))
1867 (save-excursion ;; Keep region
1868 (hfy-force-fontification)))
1869 (if (called-interactively-p 'any) ;; display the buffer in interactive mode:
1870 (switch-to-buffer (hfy-fontify-buffer srcdir file))
1871 (hfy-fontify-buffer srcdir file)))
1873 ;; recursive file listing
1874 (defun hfy-list-files (directory)
1875 "Return a list of files under DIRECTORY.
1876 Strips any leading \"./\" from each filename."
1877 ;;(message "hfy-list-files");;DBUG
1878 ;; FIXME: this changes the dir of the current buffer. Is that right??
1879 (cd directory)
1880 (mapcar (lambda (F) (if (string-match "^./\\(.*\\)" F) (match-string 1 F) F))
1881 (split-string (shell-command-to-string hfy-find-cmd))) )
1883 ;; strip the filename off, return a directory name
1884 ;; not a particularly thorough implementation, but it will be
1885 ;; fed pretty carefully, so it should be Ok:
1886 (defun hfy-dirname (file)
1887 "Return everything preceding the last \"/\" from a relative filename FILE,
1888 on the assumption that this will produce a relative directory name.
1889 Hardly bombproof, but good enough in the context in which it is being used."
1890 ;;(message "hfy-dirname");;DBUG
1891 (let ((f (directory-file-name file)))
1892 (and (string-match "^\\(.*\\)/" f) (match-string 1 f))))
1894 ;; create a directory, cf mkdir -p
1895 (defun hfy-make-directory (dir)
1896 "Approx. equivalent of mkdir -p DIR."
1897 ;;(message "hfy-make-directory");;DBUG
1898 (if (file-exists-p dir)
1899 (if (file-directory-p dir) t)
1900 (make-directory dir t)))
1902 (defun hfy-text-p (srcdir file)
1903 "Is SRCDIR/FILE text? Uses `hfy-istext-command' to determine this."
1904 (let* ((cmd (format hfy-istext-command (expand-file-name file srcdir)))
1905 (rsp (shell-command-to-string cmd)))
1906 (string-match "text" rsp)))
1908 ;; open a file, check fontification, if fontified, write a fontified copy
1909 ;; to the destination directory, otherwise just copy the file:
1910 (defun hfy-copy-and-fontify-file (srcdir dstdir file)
1911 "Open FILE in SRCDIR - if fontified, write a fontified copy to DSTDIR
1912 adding an extension of `hfy-extn'. Fontification is actually done by
1913 `htmlfontify-buffer'. If the buffer is not fontified, just copy it."
1914 ;;(message "hfy-copy-and-fontify-file");;DBUG
1915 (let (;;(fast-lock-minimum-size hfy-fast-lock-save)
1916 ;;(font-lock-support-mode 'fast-lock-mode)
1917 ;;(window-system (or window-system 'htmlfontify))
1918 (target nil)
1919 (source nil)
1920 (html nil))
1921 (cd srcdir)
1922 (with-current-buffer (setq source (find-file-noselect file))
1923 ;; FIXME: Shouldn't this use expand-file-name? --Stef
1924 (setq target (concat dstdir "/" file))
1925 (hfy-make-directory (hfy-dirname target))
1926 (if (not (hfy-opt 'skip-refontification)) (hfy-force-fontification))
1927 (if (or (hfy-fontified-p) (hfy-text-p srcdir file))
1928 (progn (setq html (hfy-fontify-buffer srcdir file))
1929 (set-buffer html)
1930 (write-file (concat target hfy-extn))
1931 (kill-buffer html))
1932 ;; #o0200 == 128, but emacs20 doesn't know that
1933 (if (and (file-exists-p target) (not (file-writable-p target)))
1934 (set-file-modes target (logior (file-modes target) 128)))
1935 (copy-file (buffer-file-name source) target 'overwrite))
1936 (kill-buffer source)) ))
1938 ;; list of tags in file in srcdir
1939 (defun hfy-tags-for-file (cache-hash file)
1940 "List of etags tags that have definitions in this FILE.
1941 CACHE-HASH is the tags cache."
1942 ;;(message "hfy-tags-for-file");;DBUG
1943 (let* ((tag-list nil))
1944 (if cache-hash
1945 (maphash
1946 (lambda (K V)
1947 (if (assoc file V)
1948 (setq tag-list (cons K tag-list))))
1949 cache-hash))
1950 tag-list))
1952 ;; mark the tags native to this file for anchors
1953 (defun hfy-mark-tag-names (srcdir file)
1954 "Mark tags in FILE (lookup SRCDIR in `hfy-tags-cache') with the `hfy-anchor'
1955 property, with a value of \"tag.line-number\"."
1956 ;;(message "(hfy-mark-tag-names %s %s)" srcdir file);;DBUG
1957 (let* ((cache-entry (assoc srcdir hfy-tags-cache))
1958 (cache-hash (cadr cache-entry)))
1959 (if cache-hash
1960 (mapcar
1961 (lambda (TAG)
1962 (mapcar
1963 (lambda (TLIST)
1964 (if (string= file (car TLIST))
1965 (let* ((line (cadr TLIST) )
1966 (chr (caddr TLIST) )
1967 (link (format "%s.%d" TAG line) ))
1968 (put-text-property (+ 1 chr)
1969 (+ 2 chr)
1970 'hfy-anchor link))))
1971 (gethash TAG cache-hash)))
1972 (hfy-tags-for-file cache-hash file)))))
1974 (defun hfy-relstub (file &optional start)
1975 "Return a \"../\" stub of the appropriate length for the current source
1976 tree depth, as determined from FILE (a filename).
1977 START is the offset at which to start looking for the / character in FILE."
1978 ;;(message "hfy-relstub");;DBUG
1979 (let ((c ""))
1980 (while (setq start (string-match "/" file start))
1981 (setq start (1+ start)) (setq c (concat c "../")))
1984 (defun hfy-href-stub (this-file def-files tag)
1985 "Return an href stub for a tag href in THIS-FILE.
1986 If DEF-FILES (list of files containing definitions for the tag in question)
1987 contains only one entry, the href should link straight to that file.
1988 Otherwise, the link should be to the index file.\n
1989 We are not yet concerned with the file extensions/tag line number and so on at
1990 this point.\n
1991 If `hfy-split-index' is set, and the href wil be to an index file rather than
1992 a source file, append a .X to `hfy-index-file', where X is the uppercased
1993 first character of TAG.\n
1994 See also `hfy-relstub', `hfy-index-file'."
1995 ;;(message "hfy-href-stub");;DBUG
1996 ;; FIXME: Why not use something like
1997 ;; (file-relative-name (if ...) (file-name-directory this-file)) ? --Stef
1998 (concat
1999 (hfy-relstub this-file)
2000 (if (= 1 (length def-files)) (car def-files)
2001 (if (not hfy-split-index) hfy-index-file
2002 (concat hfy-index-file "." (upcase (substring tag 0 1)))))) )
2004 (defun hfy-href (this-file def-files tag tag-map)
2005 "Return a relative href to the tag in question, based on\n
2006 THIS-FILE `hfy-link-extn' `hfy-extn' DEF-FILES TAG and TAG-MAP\n
2007 THIS-FILE is the current source file
2008 DEF-FILES is a list of file containing possible link endpoints for TAG
2009 TAG is the tag in question
2010 TAG-MAP is the entry in `hfy-tags-cache'."
2011 ;;(message "hfy-href");;DBUG
2012 (concat
2013 (hfy-href-stub this-file def-files tag)
2014 (or hfy-link-extn hfy-extn) "#" tag ;;(.src -> .html)
2015 (if (= 1 (length def-files))
2016 (concat "." (format "%d" (cadr (assoc (car def-files) tag-map)))))) )
2018 (defun hfy-word-regex (string)
2019 "Return a regex that matches STRING as the first `match-string', with non
2020 word characters on either side."
2021 ;; FIXME: Should this use [^$[:alnum:]_] instead? --Stef
2022 (concat "[^$A-Za-z_0-9]\\(" (regexp-quote string) "\\)[^A-Za-z_0-9]"))
2024 ;; mark all tags for hyperlinking, except the tags at
2025 ;; their own points of definition, iyswim:
2026 (defun hfy-mark-tag-hrefs (srcdir file)
2027 "Mark href start points with the `hfy-link' prop (value: href string).\n
2028 Mark href end points with the `hfy-endl' prop (value t).\n
2029 Avoid overlapping links, and mark links in descending length of
2030 tag name in order to prevent subtags from usurping supertags,
2031 \(eg \"term\" for \"terminal\").
2032 SRCDIR is the directory being \"published\".
2033 FILE is the specific file we are rendering."
2034 ;;(message "hfy-mark-tag-hrefs");;DBUG
2035 (let ((cache-entry (assoc srcdir hfy-tags-cache))
2036 (list-cache (assoc srcdir hfy-tags-sortl))
2037 (rmap-cache (assoc srcdir hfy-tags-rmap ))
2038 (no-comment (hfy-opt 'zap-comment-links))
2039 (no-strings (hfy-opt 'zap-string-links ))
2040 (cache-hash nil)
2041 (tags-list nil)
2042 (tags-rmap nil)
2043 (case-fold-search nil))
2044 ;; extract the tag mapping hashes (fwd and rev) and the tag list:
2045 (if (and (setq cache-hash (cadr cache-entry))
2046 (setq tags-rmap (cadr rmap-cache ))
2047 (setq tags-list (cadr list-cache )))
2048 (mapcar
2049 (lambda (TAG)
2050 (let* ((start nil)
2051 (stop nil)
2052 (href nil)
2053 (name nil)
2054 (case-fold-search nil)
2055 (tmp-point nil)
2056 (maybe-start nil)
2057 (face-at nil)
2058 (rmap-entry nil)
2059 (rnew-elt nil)
2060 (rmap-line nil)
2061 (tag-regex (hfy-word-regex TAG))
2062 (tag-map (gethash TAG cache-hash))
2063 (tag-files (mapcar #'car tag-map)))
2064 ;; find instances of TAG and do what needs to be done:
2065 (goto-char (point-min))
2066 (while (search-forward TAG nil 'NOERROR)
2067 (setq tmp-point (point)
2068 maybe-start (- (match-beginning 0) 1))
2069 (goto-char maybe-start)
2070 (if (not (looking-at tag-regex))
2072 (setq start (match-beginning 1))
2073 (setq stop (match-end 1))
2074 (setq face-at
2075 (and (or no-comment no-strings) (hfy-face-at start)))
2076 (if (listp face-at)
2077 (setq face-at (cadr (memq :inherit face-at))))
2078 (if (or (text-property-any start (1+ stop) 'hfy-linkp t)
2079 (and no-comment (eq 'font-lock-comment-face face-at))
2080 (and no-strings (eq 'font-lock-string-face face-at)))
2081 nil ;; already a link, NOOP
2083 ;; set a reverse map entry:
2084 (setq rmap-line (line-number-at-pos)
2085 rmap-entry (gethash TAG tags-rmap)
2086 rnew-elt (list file rmap-line start)
2087 rmap-entry (cons rnew-elt rmap-entry)
2088 name (format "%s.%d" TAG rmap-line))
2089 (put-text-property start (1+ start) 'hfy-inst name)
2090 (puthash TAG rmap-entry tags-rmap)
2092 ;; mark the link. link to index if the tag has > 1 def
2093 ;; add the line number to the #name if it does not:
2094 (setq href (hfy-href file tag-files TAG tag-map))
2095 (put-text-property start (1+ start) 'hfy-link href)
2096 (put-text-property stop (1+ stop ) 'hfy-endl t )
2097 (put-text-property start (1+ stop ) 'hfy-linkp t )))
2098 (goto-char tmp-point)) ))
2099 tags-list) )))
2101 (defun hfy-shell ()
2102 "Return `shell-file-name', or \"/bin/sh\" if it is a non-Bourne shell."
2103 (if (string-match "\\<bash\\>\\|\\<sh\\>\\|\\<dash\\>" shell-file-name)
2104 shell-file-name
2105 (or hfy-shell-file-name "/bin/sh")))
2107 ;; cache the #(tag => file line point) entries for files under srcdir
2108 ;; and cache the descending sorted list of tags in the relevant alist,
2109 ;; also keyed by srcdir:
2110 (defun hfy-load-tags-cache (srcdir)
2111 "Run `hfy-etags-cmd' on SRCDIR, then call `hfy-parse-tags-buffer'."
2112 ;;(message "hfy-load-tags-cache");;DBUG
2113 (let ((etags-buffer (get-buffer-create "*hfy-tags*"))
2114 (etags-command (format hfy-etags-cmd hfy-etags-bin))
2115 (shell-file-name (hfy-shell)))
2116 (cd srcdir)
2117 (shell-command etags-command etags-buffer)
2118 (hfy-parse-tags-buffer srcdir etags-buffer)) )
2120 ;; break this out from `hfy-load-tags-cache' to make the tar file
2121 ;; functionality easier to implement.
2122 ;; ( tar file functionality not merged here because it requires a
2123 ;; hacked copy of etags capable of tagging stdin: if Francesco
2124 ;; Potortì accepts a patch, or otherwise implements stdin tagging,
2125 ;; then I will provide a `htmlfontify-tar-file' defun )
2126 (defun hfy-parse-tags-buffer (srcdir buffer)
2127 "Parse a BUFFER containing etags formatted output, loading the
2128 `hfy-tags-cache' and `hfy-tags-sortl' entries for SRCDIR."
2129 (let ((cache-entry (assoc srcdir hfy-tags-cache))
2130 (tlist-cache (assoc srcdir hfy-tags-sortl))
2131 (trmap-cache (assoc srcdir hfy-tags-rmap ))
2132 (cache-hash nil) (trmap-hash nil) (tags-list nil)
2133 (hash-entry nil) (tag-string nil) (tag-line nil)
2134 (tag-point nil) (new-entry nil) (etags-file nil))
2136 ;; (re)initialize the tag reverse map:
2137 (if trmap-cache (setq trmap-hash (cadr trmap-cache))
2138 (setq trmap-hash (make-hash-table :test 'equal))
2139 (setq hfy-tags-rmap (list (list srcdir trmap-hash) hfy-tags-rmap)))
2140 (clrhash trmap-hash)
2142 ;; (re)initialize the tag cache:
2143 (if cache-entry (setq cache-hash (cadr cache-entry))
2144 (setq cache-hash (make-hash-table :test 'equal))
2145 (setq hfy-tags-cache (list (list srcdir cache-hash) hfy-tags-cache)))
2146 (clrhash cache-hash)
2148 ;; cache the TAG => ((file line point) (file line point) ... ) entries:
2149 (with-current-buffer buffer
2150 (goto-char (point-min))
2152 (while (and (looking-at "^\x0c") (= 0 (forward-line 1)))
2153 ;;(message "^L boundary")
2154 (if (and (looking-at "^\\(.+\\),\\([0-9]+\\)$")
2155 (= 0 (forward-line 1)))
2156 (progn
2157 (setq etags-file (match-string 1))
2158 ;;(message "TAGS for file: %s" etags-file)
2159 (while (and (looking-at hfy-etag-regex) (= 0 (forward-line 1)))
2160 (setq tag-string (match-string 1))
2161 (if (= 0 (length tag-string)) nil ;; noop
2162 (setq tag-line (round (string-to-number (match-string 2))))
2163 (setq tag-point (round (string-to-number (match-string 3))))
2164 (setq hash-entry (gethash tag-string cache-hash))
2165 (setq new-entry (list etags-file tag-line tag-point))
2166 (push new-entry hash-entry)
2167 ;;(message "HASH-ENTRY %s %S" tag-string new-entry)
2168 (puthash tag-string hash-entry cache-hash)))) )))
2170 ;; cache a list of tags in descending length order:
2171 (maphash (lambda (K _V) (push K tags-list)) cache-hash)
2172 (setq tags-list (sort tags-list (lambda (A B) (< (length B) (length A)))))
2174 ;; put the tag list into the cache:
2175 (if tlist-cache (setcar (cdr tlist-cache) tags-list)
2176 (push (list srcdir tags-list) hfy-tags-sortl))
2178 ;; return the number of tags found:
2179 (length tags-list) ))
2181 (defun hfy-prepare-index-i (srcdir dstdir filename &optional stub map)
2182 "Prepare a tags index buffer for SRCDIR.
2183 `hfy-tags-cache' must already have an entry for SRCDIR for this to work.
2184 `hfy-page-header', `hfy-page-footer', `hfy-link-extn' and `hfy-extn'
2185 all play a part here.\n
2186 If STUB is set, prepare an (appropriately named) index buffer
2187 specifically for entries beginning with STUB.\n
2188 If MAP is set, use that instead of `hfy-tags-cache'.
2189 FILENAME is the name of the file being indexed.
2190 DSTDIR is the output directory, where files will be written."
2191 ;;(message "hfy-write-index");;DBUG
2192 (let ((cache-entry (assoc srcdir (or map hfy-tags-cache)))
2193 (cache-hash nil)
2194 (tag-list nil)
2195 (index-file
2196 (concat filename (if stub (concat "." stub) "") hfy-extn))
2197 (index-buf nil))
2198 (if (not (and cache-entry
2199 (setq cache-hash (cadr cache-entry))
2200 (setq index-buf (get-buffer-create index-file))))
2201 nil ;; noop
2202 (maphash (lambda (K _V) (push K tag-list)) cache-hash)
2203 (setq tag-list (sort tag-list 'string<))
2204 (set-buffer index-buf)
2205 (erase-buffer)
2206 (insert (funcall hfy-page-header filename "<!-- CSS -->"))
2207 (insert "<table class=\"index\">\n")
2209 (dolist (TAG tag-list)
2210 (let ((tag-started nil))
2211 (dolist (DEF (gethash TAG cache-hash))
2212 (if (and stub (not (string-match (concat "^" stub) TAG)))
2213 nil ;; we have a stub and it didn't match: NOOP
2214 (let ((file (car DEF))
2215 (line (cadr DEF)))
2216 (insert
2217 (format
2218 (concat
2219 " <tr> \n"
2220 " <td>%s</td> \n"
2221 " <td><a href=\"%s%s\">%s</a></td> \n"
2222 " <td><a href=\"%s%s#%s.%d\">%d</a></td>\n"
2223 " </tr> \n")
2224 (if (string= TAG tag-started) "&nbsp;"
2225 (format "<a name=\"%s\">%s</a>" TAG TAG))
2226 file (or hfy-link-extn hfy-extn) file
2227 file (or hfy-link-extn hfy-extn) TAG line line))
2228 (setq tag-started TAG))))))
2229 (insert "</table>\n")
2230 (insert (funcall hfy-page-footer filename))
2231 (and dstdir (cd dstdir))
2232 (set-visited-file-name index-file)
2233 index-buf) ))
2235 (defun hfy-prepare-index (srcdir dstdir)
2236 "Return a list of index buffer(s), as determined by `hfy-split-index'.
2237 SRCDIR and DSTDIR are the source and output directories respectively."
2238 (if (not hfy-split-index)
2239 (list (hfy-prepare-index-i srcdir dstdir hfy-index-file nil))
2240 (let ((stub-list nil)
2241 (cache-hash nil)
2242 (index-list nil)
2243 (cache-entry (assoc srcdir hfy-tags-cache)))
2244 (if (and cache-entry (setq cache-hash (cadr cache-entry)))
2245 (maphash
2246 (lambda (K _V)
2247 (let ((stub (upcase (substring K 0 1))))
2248 (if (member stub stub-list)
2249 nil ;; seen this already: NOOP
2250 (setq
2251 stub-list (cons stub stub-list)
2252 index-list (cons (hfy-prepare-index-i srcdir
2253 dstdir
2254 hfy-index-file
2255 stub)
2256 index-list)) )))
2257 cache-hash) )
2258 index-list)))
2260 (defun hfy-prepare-tag-map (srcdir dstdir)
2261 "Prepare the counterpart(s) to the index buffer(s) - a list of buffers
2262 with the same structure, but listing (and linking to) instances of tags
2263 \(as opposed to their definitions).\n
2264 SRCDIR and DSTDIR are the source and output directories respectively.
2265 See also `hfy-prepare-index', `hfy-split-index'."
2266 (if (not hfy-split-index)
2267 (list (hfy-prepare-index-i srcdir
2268 dstdir
2269 hfy-instance-file
2271 hfy-tags-rmap))
2272 (let ((stub-list nil)
2273 (cache-hash nil)
2274 (index-list nil)
2275 (cache-entry (assoc srcdir hfy-tags-rmap)))
2277 (if (and cache-entry (setq cache-hash (cadr cache-entry)))
2278 (maphash
2279 (lambda (K _V)
2280 (let ((stub (upcase (substring K 0 1))))
2281 (if (member stub stub-list)
2282 nil ;; seen this already: NOOP
2283 (setq
2284 stub-list (cons stub stub-list)
2285 index-list (cons (hfy-prepare-index-i srcdir
2286 dstdir
2287 hfy-instance-file
2288 stub
2289 hfy-tags-rmap)
2290 index-list)) )))
2291 cache-hash) )
2292 index-list)))
2294 (defun hfy-subtract-maps (srcdir)
2295 "Internal function - strips definitions of tags from the instance map.
2296 SRCDIR is the directory being \"published\".
2297 See also `hfy-tags-cache', `hfy-tags-rmap'."
2298 (let ((new-list nil)
2299 (old-list nil)
2300 (def-list nil)
2301 (exc-list nil)
2302 (fwd-map (cadr (assoc srcdir hfy-tags-cache)))
2303 (rev-map (cadr (assoc srcdir hfy-tags-rmap )))
2304 (taglist (cadr (assoc srcdir hfy-tags-sortl))))
2305 (dolist (TAG taglist)
2306 (setq def-list (gethash TAG fwd-map)
2307 old-list (gethash TAG rev-map)
2308 exc-list (mapcar (lambda (P) (list (car P) (cadr P))) def-list)
2309 new-list nil)
2310 (dolist (P old-list)
2311 (or (member (list (car P) (cadr P)) exc-list)
2312 (push P new-list)))
2313 (puthash TAG new-list rev-map))))
2315 (defun htmlfontify-run-etags (srcdir)
2316 "Load the etags cache for SRCDIR.
2317 See also `hfy-load-tags-cache'."
2318 (interactive "D source directory: ")
2319 (hfy-load-tags-cache (directory-file-name srcdir)))
2321 ;;(defun hfy-test-read-args (foo bar)
2322 ;; (interactive "D source directory: \nD target directory: ")
2323 ;; (message "foo: %S\nbar: %S" foo bar))
2325 (defun hfy-save-kill-buffers (buffer-list &optional dstdir)
2326 (dolist (B buffer-list)
2327 (set-buffer B)
2328 (and dstdir (file-directory-p dstdir) (cd dstdir))
2329 (save-buffer)
2330 (kill-buffer B)))
2332 ;;;###autoload
2333 (defun htmlfontify-copy-and-link-dir (srcdir dstdir &optional f-ext l-ext)
2334 "Trawl SRCDIR and write fontified-and-hyperlinked output in DSTDIR.
2335 F-EXT and L-EXT specify values for `hfy-extn' and `hfy-link-extn'.\n
2336 You may also want to set `hfy-page-header' and `hfy-page-footer'."
2337 (interactive "D source directory: \nD output directory: ")
2338 ;;(message "htmlfontify-copy-and-link-dir")
2339 (setq srcdir (directory-file-name srcdir))
2340 (setq dstdir (directory-file-name dstdir))
2341 (let ((source-files "SETME: list of source files, relative to srcdir")
2342 (tr-cache (assoc srcdir hfy-tags-rmap))
2343 (hfy-extn (or f-ext ".html"))
2344 (hfy-link-extn (or l-ext ".html")))
2345 ;; oops, forgot to load etags for srcdir:
2346 (if tr-cache nil
2347 (message "autoload of tags cache")
2348 (hfy-load-tags-cache srcdir)
2349 (setq tr-cache (assoc srcdir hfy-tags-rmap)))
2350 ;; clear out the old cache:
2351 (clrhash (cadr tr-cache))
2352 (hfy-make-directory dstdir)
2353 (setq source-files (hfy-list-files srcdir))
2354 (dolist (file source-files)
2355 (hfy-copy-and-fontify-file srcdir dstdir file))
2356 (hfy-subtract-maps srcdir)
2357 (hfy-save-kill-buffers (hfy-prepare-index srcdir dstdir) dstdir)
2358 (hfy-save-kill-buffers (hfy-prepare-tag-map srcdir dstdir) dstdir) ))
2360 ;; name of the init file we want:
2361 (defun hfy-initfile ()
2362 "Return the expected location of the htmlfontify specific init/custom file."
2363 (let* ((file (or (getenv "HFY_INITFILE") ".hfy.el")))
2364 (expand-file-name file "~") ))
2367 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2368 ;; incomplete as yet : transfer hook settings to hfy init file:
2369 ;; (defalias 'hfy-set-hooks 'custom-set-variables)
2371 ;; (defun hfy-pp-hook (H)
2372 ;; (and (string-match "-hook\\'" (symbol-name H))
2373 ;; (boundp H)
2374 ;; (symbol-value H)
2375 ;; (insert (format "\n '(%S %S)" H (symbol-value H)))
2376 ;; )
2377 ;; )
2379 ;; (defun hfy-save-hooks ()
2380 ;; (let ((custom-file (hfy-initfile)))
2381 ;; (custom-save-delete 'hfy-set-hooks)
2382 ;; (let ((standard-output (current-buffer)))
2383 ;; (princ "(hfy-set-hooks\n;;auto-generated, only one copy allowed\n")
2384 ;; (mapatoms 'hfy-pp-hook)
2385 ;; (insert "\n)")
2386 ;; )
2387 ;; )
2388 ;; )
2389 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2391 (defalias 'hfy-init-progn 'progn)
2393 (defun hfy-save-initvar (sym)
2394 (princ (format "(setq %s\n '" sym))
2395 (pp (symbol-value sym))
2396 (princ ")\n"))
2398 (defun htmlfontify-save-initfile ()
2399 "Save the htmlfontify settings to the htmlfontify init file."
2400 (interactive)
2401 (let* ((start-pos nil)
2402 (custom-file (hfy-initfile))
2403 (standard-output (find-file-noselect custom-file 'nowarn)))
2404 (save-excursion
2405 (custom-save-delete 'hfy-init-progn)
2406 (setq start-pos (point))
2407 (princ "(hfy-init-progn\n;;auto-generated, only one copy allowed\n")
2408 ;; FIXME: This saving&restoring of global customization
2409 ;; variables can interfere with other customization settings for
2410 ;; those vars (in .emacs or in Customize).
2411 (mapc 'hfy-save-initvar
2412 '(auto-mode-alist interpreter-mode-alist))
2413 (princ ")\n")
2414 (indent-region start-pos (point) nil))
2415 (custom-save-all) ))
2417 (defun htmlfontify-load-initfile ()
2418 "Load the htmlfontify specific init/custom file."
2419 (interactive)
2420 (let ((file (hfy-initfile)))
2421 (load file 'NOERROR nil nil) ))
2423 (provide 'htmlfontify)
2425 ;;; htmlfontify.el ends here