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