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