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