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