Make called-interactively-p work for edebug or advised code.
[emacs.git] / lisp / htmlfontify.el
bloba1853a6e04b6eec8eebcd85d5c8c888753e6c2d4
1 ;;; htmlfontify.el --- htmlize a buffer/source tree with optional hyperlinks
3 ;; Copyright (C) 2002-2003, 2009-2012 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 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 (let ((white (mapcar (lambda (I) (float (1+ I))) (hfy-colour-vals "white")))
752 (rgb16 (mapcar (lambda (I) (float (1+ I))) (hfy-colour-vals colour))))
753 (if rgb16
754 ;;(apply 'format "rgb(%d, %d, %d)"
755 ;; Use #rrggbb instead, it is smaller
756 (apply 'format "#%02x%02x%02x"
757 (mapcar (lambda (X)
758 (* (/ (nth X rgb16)
759 (nth X white)) 255))
760 '(0 1 2))))))
762 (defun hfy-family (family) (list (cons "font-family" family)))
763 (defun hfy-bgcol (colour) (list (cons "background" (hfy-triplet colour))))
764 (defun hfy-colour (colour) (list (cons "color" (hfy-triplet colour))))
765 (defun hfy-width (width) (list (cons "font-stretch" (symbol-name width))))
767 (defcustom hfy-font-zoom 1.05
768 "Font scaling from Emacs to HTML."
769 :type 'float
770 :group 'htmlfontify)
772 (defun hfy-size (height)
773 "Derive a CSS font-size specifier from an Emacs font :height attribute HEIGHT.
774 Does not cope with the case where height is a function to be applied to
775 the height of the underlying font."
776 (list
777 (cond
778 ;;(t (cons "font-size" ": 1em"))
779 ((floatp height)
780 (cons "font-size" (format "%d%%" (* (* hfy-font-zoom height) 100))))
781 ((integerp height)
782 (cons "font-size" (format "%dpt" (/ (* hfy-font-zoom height) 10 )))) )) )
784 (defun hfy-slant (slant)
785 "Derive a font-style CSS specifier from the Emacs :slant attribute SLANT:
786 CSS does not define the reverse-* styles, so just maps those to the
787 regular specifiers."
788 (list (cons "font-style"
789 (or (cdr (assq slant '((italic . "italic")
790 (reverse-italic . "italic" )
791 (oblique . "oblique")
792 (reverse-oblique . "oblique"))))
793 "normal"))))
795 (defun hfy-weight (weight)
796 "Derive a font-weight CSS specifier from an Emacs weight spec symbol WEIGHT."
797 (list (cons "font-weight" (cdr (assq weight '((ultra-bold . "900")
798 (extra-bold . "800")
799 (bold . "700")
800 (semi-bold . "600")
801 (normal . "500")
802 (semi-light . "400")
803 (light . "300")
804 (extra-light . "200")
805 (ultra-light . "100")))))))
807 (defun hfy-box-to-border-assoc (spec)
808 (if spec
809 (let ((tag (car spec))
810 (val (cadr spec)))
811 (cons (case tag
812 (:color (cons "colour" val))
813 (:width (cons "width" val))
814 (:style (cons "style" val)))
815 (hfy-box-to-border-assoc (cddr spec))))))
817 (defun hfy-box-to-style (spec)
818 (let* ((css (hfy-box-to-border-assoc spec))
819 (col (cdr (assoc "colour" css)))
820 (s (cdr (assoc "style" css))))
821 (list
822 (if col (cons "border-color" (cdr (assoc "colour" css))))
823 (cons "border-width" (format "%dpx" (or (cdr (assoc "width" css)) 1)))
824 (cons "border-style" (case s
825 (released-button "outset")
826 (pressed-button "inset" )
827 (t "solid" ))))))
829 (defun hfy-box (box)
830 "Derive CSS border-* attributes from the Emacs :box attribute BOX."
831 (if box
832 (cond
833 ((integerp box) (list (cons "border-width" (format "%dpx" box))))
834 ((stringp box) (list (cons "border" (format "solid %s 1px" box))))
835 ((listp box) (hfy-box-to-style box) ))) )
837 (defun hfy-decor (tag _val)
838 "Derive CSS text-decoration specifiers from various Emacs font attributes.
839 TAG is an Emacs font attribute key (eg :underline).
840 VAL is ignored."
841 (list
842 ;; FIXME: Why not '("text-decoration" . "underline")? --Stef
843 (case tag
844 (:underline (cons "text-decoration" "underline" ))
845 (:overline (cons "text-decoration" "overline" ))
846 (:strike-through (cons "text-decoration" "line-through")))))
848 (defun hfy-invisible (&optional _val)
849 "This text should be invisible.
850 Do something in CSS to make that happen.
851 VAL is ignored here."
852 '(("display" . "none")))
854 (defun hfy-combined-face-spec (face)
855 "Return a `defface' style alist of possible specifications for FACE.
856 Entries resulting from customization (`custom-set-faces') will take
857 precedence."
858 (append
859 (if (and hfy-display-class hfy-default-face-def (eq face 'default))
860 hfy-default-face-def)
861 (get face 'saved-face)
862 (get face 'face-defface-spec)))
864 (defun hfy-face-attr-for-class (face &optional class)
865 "Return the face attributes for FACE.
866 If CLASS is set, it must be a `defface' alist key [see below],
867 in which case the first face specification returned by `hfy-combined-face-spec'
868 which *doesn't* clash with CLASS is returned.\n
869 \(A specification with a class of t is considered to match any class you
870 specify - this matches Emacs's behavior when deciding on which face attributes
871 to use, to the best of my understanding).\n
872 If CLASS is nil, then you just get whatever `face-attr-construct' returns,
873 ie the current specification in effect for FACE.\n
874 *NOTE*: This function forces any face that is not 'default and which has
875 no :inherit property to inherit from 'default (this is because 'default
876 is magical in that Emacs's fonts behave as if they inherit implicitly from
877 'default, but no such behavior exists in HTML/CSS).\n
878 See also `hfy-display-class' for details of valid values for CLASS."
879 (let ((face-spec
880 (if class
881 (let ((face-props (hfy-combined-face-spec face))
882 (face-specn nil)
883 (face-class nil)
884 (face-attrs nil)
885 (face-score -1)
886 (face-match nil))
887 (while face-props
888 (setq face-specn (car face-props)
889 face-class (car face-specn)
890 face-attrs (cdr face-specn)
891 face-props (cdr face-props))
892 ;; if the current element CEL of CLASS is t we match
893 ;; if the current face-class is t, we match
894 ;; if the cdr of CEL has a non-nil
895 ;; intersection with the cdr of the first member of
896 ;; the current face-class with the same car as CEL, we match
897 ;; if we actually clash, then we can't match
898 (let ((cbuf class)
899 (cel nil)
900 (key nil)
901 (val nil)
902 (x nil)
903 (next nil)
904 (score 0))
905 (while (and cbuf (not next))
906 (setq cel (car cbuf)
907 cbuf (cdr cbuf)
908 key (car cel)
909 val (cdr cel)
910 val (if (listp val) val (list val)))
911 (cond
912 ((or (eq cel t)
913 (memq face-class '(t default))) ;Default match.
914 (setq score 0) (ignore "t match"))
915 ((not (cdr (assq key face-class))) ;Neither good nor bad.
916 nil (ignore "non match, non collision"))
917 ((setq x (hfy-interq val (cdr (assq key face-class))))
918 (setq score (+ score (length x)))
919 (ignore "intersection"))
920 (t ;; nope.
921 (setq next t score -10) (ignore "collision")) ))
922 (if (> score face-score)
923 (progn
924 (setq face-match face-attrs
925 face-score score )
926 (ignore "%d << %S/%S" score face-class class))
927 (ignore "--- %d ---- (insufficient)" score)) ))
928 ;; matched ? last attrs : nil
929 (if face-match
930 (if (listp (car face-match)) (car face-match) face-match)
931 nil))
932 ;; Unfortunately the default face returns a
933 ;; :background. Fortunately we can remove it, but how do we do
934 ;; that in a non-system specific way?
935 (let ((spec (face-attr-construct face))
936 (new-spec nil))
937 (if (not (memq :background spec))
938 spec
939 (while spec
940 (let ((a (nth 0 spec))
941 (b (nth 1 spec)))
942 (unless (and (eq a :background)
943 (stringp b)
944 (string= b "SystemWindow"))
945 (setq new-spec (cons a (cons b new-spec)))))
946 (setq spec (cddr spec)))
947 new-spec)))))
948 (if (or (memq :inherit face-spec) (eq 'default face))
949 face-spec
950 (append face-spec (list :inherit 'default)))))
952 ;; construct an assoc of (css-tag-name . css-tag-value) pairs
953 ;; from a face or assoc of face attributes:
955 ;; Some tests etc:
956 ;; (mumamo-message-with-face "testing face" 'highlight)
957 ;; (mumamo-message-with-face "testing face" '(:foreground "red" :background "yellow"))
958 ;; (hfy-face-to-style-i '(:inherit default foreground-color "red"))
959 ;; default face=(:stipple nil :background "SystemWindow" :foreground
960 ;; "SystemWindowText" :inverse-video nil :box nil :strike-through
961 ;; nil :overline nil :underline nil :slant normal :weight normal
962 ;; :height 98 :width normal :family "outline-courier new")
963 (defun hfy-face-to-style-i (fn)
964 "The guts of `hfy-face-to-style': FN should be a `defface' font spec,
965 as returned by `face-attr-construct' or `hfy-face-attr-for-class'.
966 Note that this function does not get font-sizes right if they are based
967 on inherited modifiers (via the :inherit) attribute, and any other
968 modifiers that are cumulative if they appear multiple times need to be
969 merged by the user - `hfy-flatten-style' should do this."
970 ;;(message "hfy-face-to-style-i");;DBUG
972 ;; fn's value could be something like
973 ;; (:inherit
974 ;; ((foreground-color . "blue"))
975 ;; (foreground-color . "blue")
976 ;; nil)
978 (when fn
979 (let ((key (car fn))
980 (val (cadr fn))
981 (next (cddr fn))
982 (that nil)
983 (this nil)
984 (parent nil))
985 (if (eq key :inherit)
986 (let ((vs (if (listp val) val (list val))))
987 ;; (let ((x '(a b))) (setq x (append '(c d) x)))
988 ;; (let ((x '(a b))) (setq x (append '(c d) x)))
989 (dolist (v vs)
990 (setq parent
991 (append
992 parent
993 (hfy-face-to-style-i
994 (hfy-face-attr-for-class v hfy-display-class)) ))))
995 (setq this
996 (if val (case key
997 (:family (hfy-family val))
998 (:width (hfy-width val))
999 (:weight (hfy-weight val))
1000 (:slant (hfy-slant val))
1001 (:foreground (hfy-colour val))
1002 (:background (hfy-bgcol val))
1003 (:box (hfy-box val))
1004 (:height (hfy-size val))
1005 (:underline (hfy-decor key val))
1006 (:overline (hfy-decor key val))
1007 (:strike-through (hfy-decor key val))
1008 (:invisible (hfy-invisible val))
1009 (:bold (hfy-weight 'bold))
1010 (:italic (hfy-slant 'italic))))))
1011 (setq that (hfy-face-to-style-i next))
1012 ;;(lwarn t :warning "%S => %S" fn (nconc this that parent))
1013 (nconc this that parent))) )
1015 (defun hfy-size-to-int (spec)
1016 "Convert SPEC, a CSS font-size specifier, to an Emacs :height attribute value.
1017 Used while merging multiple font-size attributes."
1018 ;;(message "hfy-size-to-int");;DBUG
1019 (list
1020 (if (string-match "\\([0-9]+\\)\\(%\\|pt\\)" spec)
1021 (cond ((string= "%" (match-string 2 spec))
1022 (/ (string-to-number (match-string 1 spec)) 100.0))
1023 ((string= "pt" (match-string 2 spec))
1024 (* (string-to-number (match-string 1 spec)) 10)))
1025 (string-to-number spec))) )
1027 ;; size is different, in that in order to get it right at all,
1028 ;; we have to trawl the inheritance path, accumulating modifiers,
1029 ;; _until_ we get to an absolute (pt) specifier, then combine the lot
1030 (defun hfy-flatten-style (style)
1031 "Take STYLE (see `hfy-face-to-style-i', `hfy-face-to-style') and merge
1032 any multiple attributes appropriately. Currently only font-size is merged
1033 down to a single occurrence - others may need special handling, but I
1034 haven't encountered them yet. Returns a `hfy-style-assoc'."
1035 ;;(message "(hfy-flatten-style %S)" style) ;;DBUG
1036 (let ((n 0)
1037 (m (list 1))
1038 (x nil)
1039 (r nil))
1040 (dolist (css style)
1041 (if (string= (car css) "font-size")
1042 (progn
1043 (when (not x) (setq m (nconc m (hfy-size-to-int (cdr css)))))
1044 (when (string-match "pt" (cdr css)) (setq x t)))
1045 (setq r (nconc r (list css)))))
1046 ;;(message "r: %S" r)
1047 (setq n (apply '* m))
1048 (nconc r (hfy-size (if x (round n) (* n 1.0)))) ))
1050 (defun hfy-face-resolve-face (fn)
1051 (cond
1052 ((facep fn)
1053 (hfy-face-attr-for-class fn hfy-display-class))
1054 ((and (symbolp fn)
1055 (facep (symbol-value fn)))
1056 (hfy-face-attr-for-class (symbol-value fn) hfy-display-class))
1057 (t nil)))
1060 (defun hfy-face-to-style (fn)
1061 "Take FN, a font or `defface' style font specification,
1062 \(as returned by `face-attr-construct' or `hfy-face-attr-for-class')
1063 and return a `hfy-style-assoc'.\n
1064 See also `hfy-face-to-style-i', `hfy-flatten-style'."
1065 ;;(message "hfy-face-to-style");;DBUG
1066 (let* ((face-def (hfy-face-resolve-face fn))
1067 (final-style
1068 (hfy-flatten-style (hfy-face-to-style-i face-def))))
1069 ;;(message "%S" final-style)
1070 (if (not (assoc "text-decoration" final-style))
1071 (progn (setq final-style
1072 ;; Fix-me: there is no need for this since
1073 ;; text-decoration is not inherited.
1074 ;; but it's not wrong and if this ever changes it will
1075 ;; be needed, so I think it's better to leave it in? -- v
1076 (nconc final-style '(("text-decoration" . "none"))))))
1077 final-style))
1079 ;; strip redundant bits from a name. Technically, this could result in
1080 ;; a collision, but it is pretty unlikely - will fix later...
1081 ;; also handle ephemeral fonts created by overlays, which don't actually
1082 ;; have names:
1083 (defun hfy-face-or-def-to-name (fn)
1084 "Render a font symbol or `defface' font spec FN into a name (string)."
1085 ;;(message "generating name for %s" fn)
1086 (if (not (listp fn))
1087 (format "%s" fn)
1088 (let* ((key (format "%s" fn))
1089 (entry (assoc key hfy-tmpfont-stack))
1090 (base (cadr (memq :inherit fn)))
1091 (tag (cdr entry)))
1092 ;;(message "checking for key «%s» in font stack [%d]"
1093 ;; key (if entry 1 0))
1094 (if entry nil ;; noop
1095 (setq tag (format "%04d" (length hfy-tmpfont-stack))
1096 entry (cons key tag)
1097 hfy-tmpfont-stack (cons entry hfy-tmpfont-stack)))
1098 ;;(message " -> name: %s-%s" (or base 'default) tag)
1099 (format "%s-%s" (or base 'default) tag)) ))
1101 (defun hfy-css-name (fn)
1102 "Strip the boring bits from a font-name FN and return a CSS style name."
1103 ;;(message "hfy-css-name");;DBUG
1104 (let ((face-name (hfy-face-or-def-to-name fn)))
1105 (if (or (string-match "font-lock-\\(.*\\)" face-name)
1106 (string-match "cperl-\\(.*\\)" face-name)
1107 (string-match "^[Ii]nfo-\\(.*\\)" face-name))
1108 (progn
1109 (setq face-name (match-string 1 face-name))
1110 (if (string-match "\\(.*\\)-face\\'" face-name)
1111 (setq face-name (match-string 1 face-name)))
1112 face-name)
1113 face-name)) )
1115 ;; construct an assoc of (stripped-name . "{ css-stuff-here }") pairs
1116 ;; from a face:
1117 (defun hfy-face-to-css-default (fn)
1118 "Default handler for mapping faces to styles.
1119 See also `hfy-face-to-css'."
1120 ;;(message "hfy-face-to-css");;DBUG
1121 (let* ((css-list (hfy-face-to-style fn))
1122 (seen nil)
1123 (css-text
1124 (mapcar
1125 (lambda (E)
1126 (if (car E)
1127 (unless (member (car E) seen)
1128 (push (car E) seen)
1129 (format " %s: %s; " (car E) (cdr E)))))
1130 css-list)))
1131 (cons (hfy-css-name fn) (format "{%s}" (apply 'concat css-text)))) )
1133 (defvar hfy-face-to-css 'hfy-face-to-css-default
1134 "Handler for mapping faces to styles.
1135 The signature of the handler is of the form \(lambda (FN) ...\).
1136 FN is a font or `defface' specification (cf
1137 `face-attr-construct'). The handler should return a cons cell of
1138 the form (STYLE-NAME . STYLE-SPEC).
1140 The default handler is `hfy-face-to-css-default'.
1142 See also `hfy-face-to-style'.")
1144 (defalias 'hfy-prop-invisible-p
1145 (if (fboundp 'invisible-p) #'invisible-p
1146 (lambda (prop)
1147 "Is text property PROP an active invisibility property?"
1148 (or (and (eq buffer-invisibility-spec t) prop)
1149 (or (memq prop buffer-invisibility-spec)
1150 (assq prop buffer-invisibility-spec))))))
1152 (defun hfy-find-invisible-ranges ()
1153 "Return a list of (start-point . end-point) cons cells of invisible regions."
1154 (save-excursion
1155 (let (invisible p i s) ;; return-value pos invisible end start
1156 (setq p (goto-char (point-min)))
1157 (when (invisible-p p) (setq s p i t))
1158 (while (< p (point-max))
1159 (if i ;; currently invisible
1160 (when (not (invisible-p p)) ;; but became visible
1161 (setq i nil
1162 invisible (cons (cons s p) invisible)))
1163 ;; currently visible:
1164 (when (invisible-p p) ;; but have become invisible
1165 (setq s p i t)))
1166 (setq p (next-char-property-change p)))
1167 ;; still invisible at buffer end?
1168 (when i
1169 (setq invisible (cons (cons s (point-max)) invisible)))
1170 invisible)))
1172 (defun hfy-invisible-name (point map)
1173 "Generate a CSS style name for an invisible section of the buffer.
1174 POINT is the point inside the invisible region.
1175 MAP is the invisibility map as returned by `hfy-find-invisible-ranges'."
1176 ;;(message "(hfy-invisible-name %S %S)" point map)
1177 (let (name)
1178 (dolist (range map)
1179 (when (and (>= point (car range))
1180 (< point (cdr range)))
1181 (setq name (format "invisible-%S-%S" (car range) (cdr range)))))
1182 name))
1184 ;; Fix-me: This function needs some cleanup by someone who understand
1185 ;; all the formats that face properties can have.
1187 ;; overlay handling should be fine. haven't tested multiple stacked overlapping
1188 ;; overlays recently, but the common case of a text property face + an overlay
1189 ;; face produces the correct merged css style (or as close to it as css can get)
1190 ;; -- v
1191 (defun hfy-face-at (p)
1192 "Find face in effect at point P.
1193 If overlays are to be considered (see `hfy-optimisations') then this may
1194 return a `defface' style list of face properties instead of a face symbol."
1195 ;;(message "hfy-face-at");;DBUG
1196 ;; Fix-me: clean up, remove face-name etc
1197 ;; not sure why we'd want to remove face-name? -- v
1198 (let ((overlay-data nil)
1199 (base-face nil)
1200 (face-name (get-text-property p 'face))
1201 ;; (face-name (hfy-get-face-at p))
1202 (prop-seen nil)
1203 (extra-props nil)
1204 (text-props (text-properties-at p)))
1205 ;;(message "face-name: %S" face-name)
1206 (when (and face-name (listp face-name) (facep (car face-name)))
1207 ;;(message "face-name is a list %S" face-name)
1208 ;;(setq text-props (cons 'face face-name))
1209 (dolist (f face-name)
1210 (setq extra-props (if (listp f)
1211 ;; for things like (variable-pitch
1212 ;; (:foreground "red"))
1213 (cons f extra-props)
1214 (cons :inherit (cons f extra-props)))))
1215 (setq base-face (car face-name)
1216 face-name nil))
1217 ;; text-properties-at => (face (:foreground "red" ...))
1218 ;; or => (face (compilation-info underline)) list of faces
1219 ;; overlay-properties
1220 ;; format= (evaporate t face ((foreground-color . "red")))
1222 ;; SO: if we have turned overlays off,
1223 ;; or if there's no overlay data
1224 ;; just bail out and return whatever face data we've accumulated so far
1225 (if (or (not (hfy-opt 'keep-overlays))
1226 (not (setq overlay-data (hfy-overlay-props-at p))))
1227 (progn
1228 ;;(message "· %d: %s; %S; %s"
1229 ;; p face-name extra-props text-props)
1230 (or face-name base-face)) ;; no overlays or extra properties
1231 ;; collect any face data and any overlay data for processing:
1232 (when text-props
1233 (push text-props overlay-data))
1234 (setq overlay-data (nreverse overlay-data))
1235 ;;(message "- %d: %s; %S; %s; %s"
1236 ;; p face-name extra-props text-props overlay-data)
1237 ;; remember the basic face name so we don't keep repeating its specs:
1238 (when face-name (setq base-face face-name))
1239 (dolist (P overlay-data)
1240 (let ((iprops (cadr (memq 'invisible P)))) ;FIXME: plist-get?
1241 ;;(message "(hfy-prop-invisible-p %S)" iprops)
1242 (when (and iprops (hfy-prop-invisible-p iprops))
1243 (setq extra-props
1244 (cons :invisible (cons t extra-props))) ))
1245 (let ((fprops (cadr (or (memq 'face P)
1246 (memq 'font-lock-face P)))))
1247 ;;(message "overlay face: %s" fprops)
1248 (if (not (listp fprops))
1249 (let ((this-face (if (stringp fprops) (intern fprops) fprops)))
1250 (when (not (eq this-face base-face))
1251 (setq extra-props
1252 (cons :inherit
1253 (cons this-face extra-props))) ))
1254 (while fprops
1255 (if (facep (car fprops))
1256 (let ((face (car fprops)))
1257 (when (stringp face) (setq face (intern fprops)))
1258 (setq extra-props
1259 (cons :inherit
1260 (cons face
1261 extra-props)))
1262 (setq fprops (cdr fprops)))
1263 (let (p v)
1264 ;; Sigh.
1265 (if (listp (car fprops))
1266 (if (nlistp (cdr (car fprops)))
1267 (progn
1268 ;; ((prop . val))
1269 (setq p (caar fprops))
1270 (setq v (cdar fprops))
1271 (setq fprops (cdr fprops)))
1272 ;; ((prop val))
1273 (setq p (caar fprops))
1274 (setq v (cadar fprops))
1275 (setq fprops (cdr fprops)))
1276 (if (listp (cdr fprops))
1277 (progn
1278 ;; (:prop val :prop val ...)
1279 (setq p (car fprops))
1280 (setq v (cadr fprops))
1281 (setq fprops (cddr fprops)))
1282 (if (and (listp fprops)
1283 (not (listp (cdr fprops))))
1284 ;;(and (consp x) (cdr (last x)))
1285 (progn
1286 ;; (prop . val)
1287 (setq p (car fprops))
1288 (setq v (cdr fprops))
1289 (setq fprops nil))
1290 (error "Eh... another format! fprops=%s" fprops) )))
1291 (setq p (case p
1292 ;; These are all the properties handled
1293 ;; in `hfy-face-to-style-i'.
1295 ;; Are these translations right?
1296 ;; yes, they are -- v
1297 (family :family )
1298 (width :width )
1299 (height :height )
1300 (weight :weight )
1301 (slant :slant )
1302 (underline :underline )
1303 (overline :overline )
1304 (strike-through :strike-through)
1305 (box :box )
1306 (foreground-color :foreground)
1307 (background-color :background)
1308 (bold :bold )
1309 (italic :italic )
1310 (t p)))
1311 (if (memq p prop-seen) nil ;; noop
1312 (setq prop-seen (cons p prop-seen)
1313 extra-props (cons p (cons v extra-props))))))))))
1314 ;;(message "+ %d: %s; %S" p face-name extra-props)
1315 (if extra-props
1316 (nconc extra-props (if (listp face-name)
1317 face-name
1318 (face-attr-construct face-name)))
1319 face-name)) ))
1321 (defun hfy-overlay-props-at (p)
1322 "Grab overlay properties at point P.
1323 The plists are returned in descending priority order."
1324 (sort (mapcar #'overlay-properties (overlays-at p))
1325 (lambda (A B) (> (or (cadr (memq 'priority A)) 0) ;FIXME: plist-get?
1326 (or (cadr (memq 'priority B)) 0)))))
1328 ;; construct an assoc of (face-name . (css-name . "{ css-style }")) elements:
1329 (defun hfy-compile-stylesheet ()
1330 "Trawl the current buffer, construct and return a `hfy-sheet-assoc'.
1331 If `hfy-user-sheet-assoc' is currently bound then use it to
1332 collect new styles discovered during this run. Otherwise create
1333 a new assoc."
1334 ;;(message "hfy-compile-stylesheet");;DBUG
1335 (let ((pt (point-min))
1336 ;; Make the font stack stay:
1337 ;;(hfy-tmpfont-stack nil)
1338 (fn nil)
1339 (style (and (boundp 'hfy-user-sheet-assoc) hfy-user-sheet-assoc)))
1340 (save-excursion
1341 (goto-char pt)
1342 (while (< pt (point-max))
1343 (if (and (setq fn (hfy-face-at pt)) (not (assoc fn style)))
1344 (push (cons fn (funcall hfy-face-to-css fn)) style))
1345 (setq pt (next-char-property-change pt))))
1346 (unless (assoc 'default style)
1347 (push (cons 'default (funcall hfy-face-to-css 'default)) style))
1348 (when (boundp 'hfy-user-sheet-assoc)
1349 (setq hfy-user-sheet-assoc style))
1350 style))
1352 (defun hfy-fontified-p ()
1353 "`font-lock' doesn't like to say it's been fontified when in batch
1354 mode, but we want to know if we should fontify or raw copy, so in batch
1355 mode we check for non-default face properties. Otherwise we test
1356 variable `font-lock-mode' and variable `font-lock-fontified' for truth."
1357 ;;(message "font-lock-fontified: %S" font-lock-fontified)
1358 ;;(message "noninteractive : %S" noninteractive)
1359 ;;(message "font-lock-mode : %S" font-lock-mode)
1360 (and font-lock-fontified
1361 (if noninteractive
1362 (let ((pt (point-min))
1363 (face-name nil))
1364 (save-excursion
1365 (goto-char pt)
1366 (while (and (< pt (point-max)) (not face-name))
1367 (setq face-name (hfy-face-at pt))
1368 (setq pt (next-char-property-change pt))))
1369 face-name)
1370 font-lock-mode)))
1372 ;; remember, the map is in reverse point order:
1373 ;; I wrote this while suffering the effects of a cold, and maybe a
1374 ;; mild fever - I think it's correct, but it might be a little warped
1375 ;; as my minfd keeps ... where was I? Oh yes, the bunnies...
1376 (defun hfy-merge-adjacent-spans (face-map)
1377 "Where FACE-MAP is a `hfy-facemap-assoc' for the current buffer,
1378 this function merges adjacent style blocks which are of the same value
1379 and are separated by nothing more interesting than whitespace.\n
1380 <span class=\"foo\">narf</span> <span class=\"foo\">brain</span>\n
1381 \(as interpreted from FACE-MAP) would become:\n
1382 <span class=\"foo\">narf brain</span>\n
1383 Returns a modified copy of FACE-MAP."
1384 (let ((tmp-map face-map)
1385 (map-buf nil)
1386 (first-start nil)
1387 (first-stop nil)
1388 (last-start nil)
1389 (last-stop nil)
1390 (span-stop nil)
1391 (span-start nil)
1392 (reduced-map nil))
1393 ;;(push (car tmp-map) reduced-map)
1394 ;;(push (cadr tmp-map) reduced-map)
1395 (while tmp-map
1396 (setq first-start (cadddr tmp-map)
1397 first-stop (caddr tmp-map)
1398 last-start (cadr tmp-map)
1399 last-stop (car tmp-map)
1400 map-buf tmp-map
1401 span-start last-start
1402 span-stop last-stop )
1403 (while (and (equal (cdr first-start)
1404 (cdr last-start))
1405 (save-excursion
1406 (goto-char (car first-stop))
1407 (not (re-search-forward "[^ \t\n\r]" (car last-start) t))))
1408 (setq map-buf (cddr map-buf)
1409 span-start first-start
1410 first-start (cadddr map-buf)
1411 first-stop (caddr map-buf)
1412 last-start (cadr map-buf)
1413 last-stop (car map-buf)))
1414 (push span-stop reduced-map)
1415 (push span-start reduced-map)
1416 (setq tmp-map (memq last-start tmp-map))
1417 (setq tmp-map (cdr tmp-map)))
1418 (setq reduced-map (nreverse reduced-map))))
1420 ;; remember to generate 'synthetic' </span> entries -
1421 ;; emacs copes by just having a stack of styles in effect
1422 ;; and only using the top one: html has a more simplistic approach -
1423 ;; we have to explicitly end a style, there's no way of temporarily
1424 ;; overriding it w. another one... (afaik)
1425 (defun hfy-compile-face-map ()
1426 ;; no need for special <a> version.
1427 ;; IME hyperlinks don't get underlined, esp when you htmlfontify a whole
1428 ;; source tree, so the <a> version is needed -- v
1429 ;; Fix-me: save table for multi-buffer
1430 "Compile and return a `hfy-facemap-assoc' for the current buffer."
1431 ;;(message "hfy-compile-face-map");;DBUG
1432 (let* ((pt (point-min))
1433 (pt-narrow (save-restriction (widen) (point-min)))
1434 (offset (- pt pt-narrow))
1435 (fn nil)
1436 (map nil)
1437 (prev-tag nil)) ;; t if the last tag-point was a span-start
1438 ;; nil if it was a span-stop
1439 (save-excursion
1440 (goto-char pt)
1441 (while (< pt (point-max))
1442 (if (setq fn (hfy-face-at pt))
1443 (progn (if prev-tag (push (cons pt-narrow 'end) map))
1444 (push (cons pt-narrow fn) map)
1445 (setq prev-tag t))
1446 (if prev-tag (push (cons pt-narrow 'end) map))
1447 (setq prev-tag nil))
1448 (setq pt (next-char-property-change pt))
1449 (setq pt-narrow (+ offset pt)))
1450 (if (and map (not (eq 'end (cdar map))))
1451 (push (cons (1+ (- (point-max) (point-min))) 'end) map)))
1452 (if (hfy-opt 'merge-adjacent-tags) (hfy-merge-adjacent-spans map) map)))
1454 (defun hfy-buffer ()
1455 "Generate a buffer to hold the HTML output.
1456 The filename of this buffer is derived from the source (current) buffer's
1457 variable `buffer-file-name', if it is set, plus `hfy-extn'.
1458 Otherwise a plausible filename is constructed from `default-directory',
1459 `buffer-name' and `hfy-extn'."
1460 (let* ((name (concat (buffer-name) hfy-extn))
1461 (src (buffer-file-name))
1462 (buf (get-buffer-create name)))
1463 (with-current-buffer buf
1464 (setq buffer-file-name
1465 (if src (concat src hfy-extn)
1466 (expand-file-name (if (string-match "^.*/\\([^/]*\\)\\'" name)
1467 (match-string 1 name)
1468 name))))
1469 buf)))
1471 (defun hfy-lookup (face style)
1472 "Get a CSS style name for FACE from STYLE."
1473 (cadr (assoc face style)))
1475 (defun hfy-link-style (style-string)
1476 "Copy, alter and return a STYLE-STRING to make it suitable for a hyperlink.
1477 Uses `hfy-link-style-fun' to do this."
1478 (if (functionp hfy-link-style-fun)
1479 (funcall hfy-link-style-fun style-string)
1480 style-string))
1482 (defun hfy-sprintf-stylesheet (css file)
1483 "Return the inline CSS style sheet for FILE as a string."
1484 (let ((stylesheet
1485 (concat
1486 hfy-meta-tags
1487 "\n<style type=\"text/css\"><!-- \n"
1488 ;; Fix-me: Add handling of page breaks here + scan for ^L
1489 ;; where appropriate.
1490 (format "body %s\n" (cddr (assq 'default css)))
1491 (apply 'concat
1492 (mapcar
1493 (lambda (style)
1494 (format
1495 "span.%s %s\nspan.%s a %s\n"
1496 (cadr style) (cddr style)
1497 (cadr style) (hfy-link-style (cddr style))))
1498 css))
1499 " --></style>\n")))
1500 (funcall hfy-page-header file stylesheet)))
1502 ;; tag all the dangerous characters we want to escape
1503 ;; (ie any "<> chars we _didn't_ put there explicitly for css markup)
1504 (defun hfy-html-enkludge-buffer ()
1505 "Mark dangerous [\"<>] characters with the `hfy-quoteme' property.\n
1506 See also `hfy-html-dekludge-buffer'."
1507 ;;(message "hfy-html-enkludge-buffer");;DBUG
1508 (save-excursion
1509 (goto-char (point-min))
1510 (while (re-search-forward hfy-html-quote-regex nil t)
1511 (put-text-property (match-beginning 0) (point) 'hfy-quoteme t))) )
1513 ;; dangerous char -> &entity;
1514 (defun hfy-html-quote (char-string)
1515 "Map CHAR-STRING to an HTML safe string (entity) if need be."
1516 ;;(message "hfy-html-quote");;DBUG
1517 (or (cadr (assoc char-string hfy-html-quote-map)) char-string) )
1519 ;; actually entity-ise dangerous chars.
1520 ;; note that we can't do this until _after_ we have inserted the css
1521 ;; markup, since we use a position-based map to insert this, and if we
1522 ;; enter any other text before we do this, we'd have to track another
1523 ;; map of offsets, which would be tedious...
1524 (defun hfy-html-dekludge-buffer ()
1525 "Transform all dangerous characters marked with the `hfy-quoteme' property
1526 using `hfy-html-quote'.\n
1527 See also `hfy-html-enkludge-buffer'."
1528 ;;(message "hfy-html-dekludge-buffer");;DBUG
1529 (save-excursion
1530 (goto-char (point-min))
1531 (while (re-search-forward hfy-html-quote-regex nil t)
1532 (if (get-text-property (match-beginning 0) 'hfy-quoteme)
1533 (replace-match (hfy-html-quote (match-string 1))) )) ))
1535 ;; Borrowed from font-lock.el
1536 (defmacro hfy-save-buffer-state (varlist &rest body)
1537 "Bind variables according to VARLIST and eval BODY restoring buffer state.
1538 Do not record undo information during evaluation of BODY."
1539 (declare (indent 1) (debug let))
1540 (let ((modified (make-symbol "modified")))
1541 `(let* ,(append varlist
1542 `((,modified (buffer-modified-p))
1543 (buffer-undo-list t)
1544 (inhibit-read-only t)
1545 (inhibit-point-motion-hooks t)
1546 (inhibit-modification-hooks t)
1547 deactivate-mark
1548 buffer-file-name
1549 buffer-file-truename))
1550 (progn
1551 ,@body)
1552 (unless ,modified
1553 (restore-buffer-modified-p nil)))))
1555 (defun hfy-mark-trailing-whitespace ()
1556 "Tag trailing whitespace with a hfy property if it is currently highlighted."
1557 (when show-trailing-whitespace
1558 (let ((inhibit-read-only t))
1559 (save-excursion
1560 (goto-char (point-min))
1561 (hfy-save-buffer-state nil
1562 (while (re-search-forward "[ \t]+$" nil t)
1563 (put-text-property (match-beginning 0) (match-end 0)
1564 'hfy-show-trailing-whitespace t)))))))
1566 (defun hfy-unmark-trailing-whitespace ()
1567 "Undo the effect of `hfy-mark-trailing-whitespace'."
1568 (when show-trailing-whitespace
1569 (hfy-save-buffer-state nil
1570 (remove-text-properties (point-min) (point-max)
1571 '(hfy-show-trailing-whitespace)))))
1573 (defun hfy-begin-span (style text-block text-id text-begins-block-p)
1574 "Default handler to begin a span of text.
1575 Insert \"<span class=\"STYLE\" ...>\". See
1576 `hfy-begin-span-handler' for more information."
1577 (when text-begins-block-p
1578 (insert
1579 (format "<span onclick=\"toggle_invis('%s');\">…</span>" text-block)))
1581 (insert
1582 (if text-block
1583 (format "<span class=\"%s\" id=\"%s-%d\">" style text-block text-id)
1584 (format "<span class=\"%s\">" style))))
1586 (defun hfy-end-span ()
1587 "Default handler to end a span of text.
1588 Insert \"</span>\". See `hfy-end-span-handler' for more
1589 information."
1590 (insert "</span>"))
1592 (defvar hfy-begin-span-handler 'hfy-begin-span
1593 "Handler to begin a span of text.
1594 The signature of the handler is \(lambda (STYLE TEXT-BLOCK
1595 TEXT-ID TEXT-BEGINS-BLOCK-P) ...\). The handler must insert
1596 appropriate tags to begin a span of text.
1598 STYLE is the name of the style that begins at point. It is
1599 derived from the face attributes as part of `hfy-face-to-css'
1600 callback. The other arguments TEXT-BLOCK, TEXT-ID,
1601 TEXT-BEGINS-BLOCK-P are non-nil only if the buffer contains
1602 invisible text.
1604 TEXT-BLOCK is a string that identifies a single chunk of visible
1605 or invisible text of which the current position is a part. For
1606 visible portions, it's value is \"nil\". For invisible portions,
1607 it's value is computed as part of `hfy-invisible-name'.
1609 TEXT-ID marks a unique position within a block. It is set to
1610 value of `point' at the current buffer position.
1612 TEXT-BEGINS-BLOCK-P is a boolean and is non-nil if the current
1613 span also begins a invisible portion of text.
1615 An implementation can use TEXT-BLOCK, TEXT-ID,
1616 TEXT-BEGINS-BLOCK-P to implement fold/unfold-on-mouse-click like
1617 behaviour.
1619 The default handler is `hfy-begin-span'.")
1621 (defvar hfy-end-span-handler 'hfy-end-span
1622 "Handler to end a span of text.
1623 The signature of the handler is \(lambda () ...\). The handler
1624 must insert appropriate tags to end a span of text.
1626 The default handler is `hfy-end-span'.")
1628 (defun hfy-fontify-buffer (&optional srcdir file)
1629 "Implement the guts of `htmlfontify-buffer'.
1630 SRCDIR, if set, is the directory being htmlfontified.
1631 FILE, if set, is the file name."
1632 (if srcdir (setq srcdir (directory-file-name srcdir)))
1633 (let* ( (html-buffer (hfy-buffer))
1634 (css-sheet nil)
1635 (css-map nil)
1636 (invis-ranges nil)
1637 (rovl nil)
1638 (orig-ovls (overlays-in (point-min) (point-max)))
1639 (rmin (when mark-active (region-beginning)))
1640 (rmax (when mark-active (region-end ))) )
1641 (when (and mark-active
1642 transient-mark-mode)
1643 (unless (and (= rmin (point-min))
1644 (= rmax (point-max)))
1645 (setq rovl (make-overlay rmin rmax))
1646 (overlay-put rovl 'priority 1000)
1647 (overlay-put rovl 'face 'region)))
1648 ;; copy the buffer, including fontification, and switch to it:
1649 (hfy-mark-trailing-whitespace)
1650 (setq css-sheet (hfy-compile-stylesheet )
1651 css-map (hfy-compile-face-map )
1652 invis-ranges (hfy-find-invisible-ranges))
1653 (hfy-unmark-trailing-whitespace)
1654 (when rovl
1655 (delete-overlay rovl))
1656 (copy-to-buffer html-buffer (point-min) (point-max))
1657 (set-buffer html-buffer)
1658 ;; rip out props that could interfere with our htmlization of the buffer:
1659 (remove-text-properties (point-min) (point-max) hfy-ignored-properties)
1660 ;; Apply overlay invisible spec
1661 (setq orig-ovls
1662 (sort orig-ovls
1663 (lambda (A B)
1664 (> (or (cadr (memq 'priority (overlay-properties A))) 0)
1665 (or (cadr (memq 'priority (overlay-properties B))) 0)))))
1666 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1667 ;; at this point, html-buffer retains the fontification of the parent:
1668 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1669 ;; we don't really need or want text in the html buffer to be invisible, as
1670 ;; that can make it look like we've rendered invalid xhtml when all that's
1671 ;; happened is some tags are in the invisible portions of the buffer:
1672 (setq buffer-invisibility-spec nil)
1673 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1674 ;; #####################################################################
1675 ;; if we are in etags mode, add properties to mark the anchors and links
1676 (if (and srcdir file)
1677 (progn
1678 (hfy-mark-tag-names srcdir file) ;; mark anchors
1679 (hfy-mark-tag-hrefs srcdir file))) ;; mark links
1680 ;; #####################################################################
1681 ;; mark the 'dangerous' characters
1682 ;;(message "marking dangerous characters")
1683 (hfy-html-enkludge-buffer)
1684 ;; trawl the position-based face-map, inserting span tags as we go
1685 ;; note that we cannot change any character positions before this point
1686 ;; or we will invalidate the map:
1687 ;; NB: This also means we have to trawl the map in descending file-offset
1688 ;; order, obviously.
1689 ;; ---------------------------------------------------------------------
1690 ;; Remember, inserting pushes properties to the right, which we don't
1691 ;; actually want to happen for link properties, so we have to flag
1692 ;; them and move them by hand - if you don't, you end up with
1694 ;; <span class="foo"><a href="bar">texta</span><span class="bletch"></a>...
1696 ;; instead of:
1698 ;; <span class="foo"><a href="bar">texta</a></span><span class="bletch">...
1700 ;; If my analysis of the problem is correct, we can detect link-ness by
1701 ;; either hfy-linkp or hfy-endl properties at the insertion point, but I
1702 ;; think we only need to relocate the hfy-endl property, as the hfy-linkp
1703 ;; property has already served its main purpose by this point.
1704 ;;(message "mapcar over the CSS-MAP")
1705 (message "invis-ranges:\n%S" invis-ranges)
1706 (dolist (point-face css-map)
1707 (let ((pt (car point-face))
1708 (fn (cdr point-face))
1709 (move-link nil))
1710 (goto-char pt)
1711 (setq move-link
1712 (or (get-text-property pt 'hfy-linkp)
1713 (get-text-property pt 'hfy-endl )))
1714 (if (eq 'end fn)
1715 (funcall hfy-end-span-handler)
1716 (if (not (and srcdir file))
1718 (when move-link
1719 (remove-text-properties (point) (1+ (point)) '(hfy-endl nil))
1720 (put-text-property pt (1+ pt) 'hfy-endl t) ))
1721 ;; if we have invisible blocks, we need to do some extra magic:
1722 (funcall hfy-begin-span-handler
1723 (hfy-lookup fn css-sheet)
1724 (and invis-ranges
1725 (format "%s" (hfy-invisible-name pt invis-ranges)))
1726 (and invis-ranges pt)
1727 (and invis-ranges (assq pt invis-ranges)))
1728 (if (not move-link) nil
1729 ;;(message "removing prop2 @ %d" (point))
1730 (if (remove-text-properties (point) (1+ (point)) '(hfy-endl nil))
1731 (put-text-property pt (1+ pt) 'hfy-endl t))))))
1732 ;; #####################################################################
1733 ;; Invisibility
1734 ;; Maybe just make the text invisible in XHTML?
1735 ;; DONE -- big block of obsolete invisibility code elided here -- v
1736 ;; #####################################################################
1737 ;; (message "checking to see whether we should link...")
1738 (if (and srcdir file)
1739 (let ((lp 'hfy-link)
1740 (pt (point-min))
1741 (pr nil)
1742 (rr nil))
1743 ;; (message " yes we should.")
1744 ;; translate 'hfy-anchor properties to anchors
1745 (while (setq pt (next-single-property-change pt 'hfy-anchor))
1746 (if (setq pr (get-text-property pt 'hfy-anchor))
1747 (progn (goto-char pt)
1748 (remove-text-properties pt (1+ pt) '(hfy-anchor nil))
1749 (insert (concat "<a name=\"" pr "\"></a>")))))
1750 ;; translate alternate 'hfy-link and 'hfy-endl props to opening
1751 ;; and closing links. (this should avoid those spurious closes
1752 ;; we sometimes get by generating only paired tags)
1753 (setq pt (point-min))
1754 (while (setq pt (next-single-property-change pt lp))
1755 (if (not (setq pr (get-text-property pt lp))) nil
1756 (goto-char pt)
1757 (remove-text-properties pt (1+ pt) (list lp nil))
1758 (case lp
1759 (hfy-link
1760 (if (setq rr (get-text-property pt 'hfy-inst))
1761 (insert (format "<a name=\"%s\"></a>" rr)))
1762 (insert (format "<a href=\"%s\">" pr))
1763 (setq lp 'hfy-endl))
1764 (hfy-endl
1765 (insert "</a>") (setq lp 'hfy-link)) ))) ))
1767 ;; #####################################################################
1768 ;; transform the dangerous chars. This changes character positions
1769 ;; since entities have > char length.
1770 ;; note that this deletes the dangerous characters, and therefore
1771 ;; destroys any properties they may contain (such as 'hfy-endl),
1772 ;; so we have to do this after we use said properties:
1773 ;; (message "munging dangerous characters")
1774 (hfy-html-dekludge-buffer)
1775 (unless (hfy-opt 'body-text-only)
1776 ;; insert the stylesheet at the top:
1777 (goto-char (point-min))
1779 ;;(message "inserting stylesheet")
1780 (insert (hfy-sprintf-stylesheet css-sheet file))
1782 (if (hfy-opt 'div-wrapper) (insert "<div class=\"default\">"))
1783 (insert "\n<pre>")
1784 (goto-char (point-max))
1785 (insert "</pre>\n")
1786 (if (hfy-opt 'div-wrapper) (insert "</div>"))
1787 ;;(message "inserting footer")
1788 (insert (funcall hfy-page-footer file)))
1789 ;; call any post html-generation hooks:
1790 (run-hooks 'hfy-post-html-hook)
1791 ;; return the html buffer
1792 (set-buffer-modified-p nil)
1793 html-buffer))
1795 (defun htmlfontify-string (string)
1796 "Take a STRING and return a fontified version of it.
1797 It is assumed that STRING has text properties that allow it to be
1798 fontified. This is a simple convenience wrapper around
1799 `htmlfontify-buffer'."
1800 (let* ((hfy-optimisations-1 (copy-sequence hfy-optimisations))
1801 (hfy-optimisations (add-to-list 'hfy-optimisations-1
1802 'skip-refontification)))
1803 (with-temp-buffer
1804 (insert string)
1805 (htmlfontify-buffer)
1806 (buffer-string))))
1808 (defun hfy-force-fontification ()
1809 "Try to force font-locking even when it is optimized away."
1810 (run-hooks 'hfy-init-kludge-hook)
1811 (eval-and-compile (require 'font-lock))
1812 (if (boundp 'font-lock-cache-position)
1813 (or font-lock-cache-position
1814 (set 'font-lock-cache-position (make-marker))))
1815 (if (not noninteractive)
1816 (progn
1817 (message "hfy interactive mode (%S %S)" window-system major-mode)
1818 (when (and font-lock-defaults
1819 font-lock-mode)
1820 (font-lock-fontify-region (point-min) (point-max) nil)))
1821 (message "hfy batch mode (%s:%S)"
1822 (or (buffer-file-name) (buffer-name)) major-mode)
1823 (when font-lock-defaults
1824 (font-lock-fontify-buffer)) ))
1826 ;;;###autoload
1827 (defun htmlfontify-buffer (&optional srcdir file)
1828 "Create a new buffer, named for the current buffer + a .html extension,
1829 containing an inline CSS-stylesheet and formatted CSS-markup HTML
1830 that reproduces the look of the current Emacs buffer as closely
1831 as possible.
1833 Dangerous characters in the existing buffer are turned into HTML
1834 entities, so you should even be able to do HTML-within-HTML
1835 fontified display.
1837 You should, however, note that random control or eight-bit
1838 characters such as ^L (\x0c) or ¤ (\xa4) won't get mapped yet.
1840 If the SRCDIR and FILE arguments are set, lookup etags derived
1841 entries in the `hfy-tags-cache' and add HTML anchors and
1842 hyperlinks as appropriate."
1843 (interactive)
1844 ;; pick up the file name in case we didn't receive it
1845 (if (not file)
1846 (progn (setq file (or (buffer-file-name) (buffer-name)))
1847 (if (string-match "/\\([^/]*\\)\\'" file)
1848 (setq file (match-string 1 file)))) )
1850 (if (not (hfy-opt 'skip-refontification))
1851 (save-excursion ;; Keep region
1852 (hfy-force-fontification)))
1853 (if (called-interactively-p 'any) ;; display the buffer in interactive mode:
1854 (switch-to-buffer (hfy-fontify-buffer srcdir file))
1855 (hfy-fontify-buffer srcdir file)))
1857 ;; recursive file listing
1858 (defun hfy-list-files (directory)
1859 "Return a list of files under DIRECTORY.
1860 Strips any leading \"./\" from each filename."
1861 ;;(message "hfy-list-files");;DBUG
1862 ;; FIXME: this changes the dir of the current buffer. Is that right??
1863 (cd directory)
1864 (mapcar (lambda (F) (if (string-match "^./\\(.*\\)" F) (match-string 1 F) F))
1865 (split-string (shell-command-to-string hfy-find-cmd))) )
1867 ;; strip the filename off, return a directory name
1868 ;; not a particularly thorough implementation, but it will be
1869 ;; fed pretty carefully, so it should be Ok:
1870 (defun hfy-dirname (file)
1871 "Return everything preceding the last \"/\" from a relative filename FILE,
1872 on the assumption that this will produce a relative directory name.
1873 Hardly bombproof, but good enough in the context in which it is being used."
1874 ;;(message "hfy-dirname");;DBUG
1875 (let ((f (directory-file-name file)))
1876 (and (string-match "^\\(.*\\)/" f) (match-string 1 f))))
1878 ;; create a directory, cf mkdir -p
1879 (defun hfy-make-directory (dir)
1880 "Approx. equivalent of mkdir -p DIR."
1881 ;;(message "hfy-make-directory");;DBUG
1882 (if (file-exists-p dir)
1883 (if (file-directory-p dir) t)
1884 (make-directory dir t)))
1886 (defun hfy-text-p (srcdir file)
1887 "Is SRCDIR/FILE text? Uses `hfy-istext-command' to determine this."
1888 (let* ((cmd (format hfy-istext-command (expand-file-name file srcdir)))
1889 (rsp (shell-command-to-string cmd)))
1890 (string-match "text" rsp)))
1892 ;; open a file, check fontification, if fontified, write a fontified copy
1893 ;; to the destination directory, otherwise just copy the file:
1894 (defun hfy-copy-and-fontify-file (srcdir dstdir file)
1895 "Open FILE in SRCDIR - if fontified, write a fontified copy to DSTDIR
1896 adding an extension of `hfy-extn'. Fontification is actually done by
1897 `htmlfontify-buffer'. If the buffer is not fontified, just copy it."
1898 ;;(message "hfy-copy-and-fontify-file");;DBUG
1899 (let (;;(fast-lock-minimum-size hfy-fast-lock-save)
1900 ;;(font-lock-support-mode 'fast-lock-mode)
1901 ;;(window-system (or window-system 'htmlfontify))
1902 (target nil)
1903 (source nil)
1904 (html nil))
1905 (cd srcdir)
1906 (with-current-buffer (setq source (find-file-noselect file))
1907 ;; FIXME: Shouldn't this use expand-file-name? --Stef
1908 (setq target (concat dstdir "/" file))
1909 (hfy-make-directory (hfy-dirname target))
1910 (if (not (hfy-opt 'skip-refontification)) (hfy-force-fontification))
1911 (if (or (hfy-fontified-p) (hfy-text-p srcdir file))
1912 (progn (setq html (hfy-fontify-buffer srcdir file))
1913 (set-buffer html)
1914 (write-file (concat target hfy-extn))
1915 (kill-buffer html))
1916 ;; #o0200 == 128, but emacs20 doesn't know that
1917 (if (and (file-exists-p target) (not (file-writable-p target)))
1918 (set-file-modes target (logior (file-modes target) 128)))
1919 (copy-file (buffer-file-name source) target 'overwrite))
1920 (kill-buffer source)) ))
1922 ;; list of tags in file in srcdir
1923 (defun hfy-tags-for-file (cache-hash file)
1924 "List of etags tags that have definitions in this FILE.
1925 CACHE-HASH is the tags cache."
1926 ;;(message "hfy-tags-for-file");;DBUG
1927 (let* ((tag-list nil))
1928 (if cache-hash
1929 (maphash
1930 (lambda (K V)
1931 (if (assoc file V)
1932 (setq tag-list (cons K tag-list))))
1933 cache-hash))
1934 tag-list))
1936 ;; mark the tags native to this file for anchors
1937 (defun hfy-mark-tag-names (srcdir file)
1938 "Mark tags in FILE (lookup SRCDIR in `hfy-tags-cache') with the `hfy-anchor'
1939 property, with a value of \"tag.line-number\"."
1940 ;;(message "(hfy-mark-tag-names %s %s)" srcdir file);;DBUG
1941 (let* ((cache-entry (assoc srcdir hfy-tags-cache))
1942 (cache-hash (cadr cache-entry)))
1943 (if cache-hash
1944 (mapcar
1945 (lambda (TAG)
1946 (mapcar
1947 (lambda (TLIST)
1948 (if (string= file (car TLIST))
1949 (let* ((line (cadr TLIST) )
1950 (chr (caddr TLIST) )
1951 (link (format "%s.%d" TAG line) ))
1952 (put-text-property (+ 1 chr)
1953 (+ 2 chr)
1954 'hfy-anchor link))))
1955 (gethash TAG cache-hash)))
1956 (hfy-tags-for-file cache-hash file)))))
1958 (defun hfy-relstub (file &optional start)
1959 "Return a \"../\" stub of the appropriate length for the current source
1960 tree depth, as determined from FILE (a filename).
1961 START is the offset at which to start looking for the / character in FILE."
1962 ;;(message "hfy-relstub");;DBUG
1963 (let ((c ""))
1964 (while (setq start (string-match "/" file start))
1965 (setq start (1+ start)) (setq c (concat c "../")))
1968 (defun hfy-href-stub (this-file def-files tag)
1969 "Return an href stub for a tag href in THIS-FILE.
1970 If DEF-FILES (list of files containing definitions for the tag in question)
1971 contains only one entry, the href should link straight to that file.
1972 Otherwise, the link should be to the index file.\n
1973 We are not yet concerned with the file extensions/tag line number and so on at
1974 this point.\n
1975 If `hfy-split-index' is set, and the href wil be to an index file rather than
1976 a source file, append a .X to `hfy-index-file', where X is the uppercased
1977 first character of TAG.\n
1978 See also `hfy-relstub', `hfy-index-file'."
1979 ;;(message "hfy-href-stub");;DBUG
1980 ;; FIXME: Why not use something like
1981 ;; (file-relative-name (if ...) (file-name-directory this-file)) ? --Stef
1982 (concat
1983 (hfy-relstub this-file)
1984 (if (= 1 (length def-files)) (car def-files)
1985 (if (not hfy-split-index) hfy-index-file
1986 (concat hfy-index-file "." (upcase (substring tag 0 1)))))) )
1988 (defun hfy-href (this-file def-files tag tag-map)
1989 "Return a relative href to the tag in question, based on\n
1990 THIS-FILE `hfy-link-extn' `hfy-extn' DEF-FILES TAG and TAG-MAP\n
1991 THIS-FILE is the current source file
1992 DEF-FILES is a list of file containing possible link endpoints for TAG
1993 TAG is the tag in question
1994 TAG-MAP is the entry in `hfy-tags-cache'."
1995 ;;(message "hfy-href");;DBUG
1996 (concat
1997 (hfy-href-stub this-file def-files tag)
1998 (or hfy-link-extn hfy-extn) "#" tag ;;(.src -> .html)
1999 (if (= 1 (length def-files))
2000 (concat "." (format "%d" (cadr (assoc (car def-files) tag-map)))))) )
2002 (defun hfy-word-regex (string)
2003 "Return a regex that matches STRING as the first `match-string', with non
2004 word characters on either side."
2005 ;; FIXME: Should this use [^$[:alnum:]_] instead? --Stef
2006 (concat "[^$A-Za-z_0-9]\\(" (regexp-quote string) "\\)[^A-Za-z_0-9]"))
2008 ;; mark all tags for hyperlinking, except the tags at
2009 ;; their own points of definition, iyswim:
2010 (defun hfy-mark-tag-hrefs (srcdir file)
2011 "Mark href start points with the `hfy-link' prop (value: href string).\n
2012 Mark href end points with the `hfy-endl' prop (value t).\n
2013 Avoid overlapping links, and mark links in descending length of
2014 tag name in order to prevent subtags from usurping supertags,
2015 \(eg \"term\" for \"terminal\").
2016 SRCDIR is the directory being \"published\".
2017 FILE is the specific file we are rendering."
2018 ;;(message "hfy-mark-tag-hrefs");;DBUG
2019 (let ((cache-entry (assoc srcdir hfy-tags-cache))
2020 (list-cache (assoc srcdir hfy-tags-sortl))
2021 (rmap-cache (assoc srcdir hfy-tags-rmap ))
2022 (no-comment (hfy-opt 'zap-comment-links))
2023 (no-strings (hfy-opt 'zap-string-links ))
2024 (cache-hash nil)
2025 (tags-list nil)
2026 (tags-rmap nil)
2027 (case-fold-search nil))
2028 ;; extract the tag mapping hashes (fwd and rev) and the tag list:
2029 (if (and (setq cache-hash (cadr cache-entry))
2030 (setq tags-rmap (cadr rmap-cache ))
2031 (setq tags-list (cadr list-cache )))
2032 (mapcar
2033 (lambda (TAG)
2034 (let* ((start nil)
2035 (stop nil)
2036 (href nil)
2037 (name nil)
2038 (case-fold-search nil)
2039 (tmp-point nil)
2040 (maybe-start nil)
2041 (face-at nil)
2042 (rmap-entry nil)
2043 (rnew-elt nil)
2044 (rmap-line nil)
2045 (tag-regex (hfy-word-regex TAG))
2046 (tag-map (gethash TAG cache-hash))
2047 (tag-files (mapcar #'car tag-map)))
2048 ;; find instances of TAG and do what needs to be done:
2049 (goto-char (point-min))
2050 (while (search-forward TAG nil 'NOERROR)
2051 (setq tmp-point (point)
2052 maybe-start (- (match-beginning 0) 1))
2053 (goto-char maybe-start)
2054 (if (not (looking-at tag-regex))
2056 (setq start (match-beginning 1))
2057 (setq stop (match-end 1))
2058 (setq face-at
2059 (and (or no-comment no-strings) (hfy-face-at start)))
2060 (if (listp face-at)
2061 (setq face-at (cadr (memq :inherit face-at))))
2062 (if (or (text-property-any start (1+ stop) 'hfy-linkp t)
2063 (and no-comment (eq 'font-lock-comment-face face-at))
2064 (and no-strings (eq 'font-lock-string-face face-at)))
2065 nil ;; already a link, NOOP
2067 ;; set a reverse map entry:
2068 (setq rmap-line (line-number-at-pos)
2069 rmap-entry (gethash TAG tags-rmap)
2070 rnew-elt (list file rmap-line start)
2071 rmap-entry (cons rnew-elt rmap-entry)
2072 name (format "%s.%d" TAG rmap-line))
2073 (put-text-property start (1+ start) 'hfy-inst name)
2074 (puthash TAG rmap-entry tags-rmap)
2076 ;; mark the link. link to index if the tag has > 1 def
2077 ;; add the line number to the #name if it does not:
2078 (setq href (hfy-href file tag-files TAG tag-map))
2079 (put-text-property start (1+ start) 'hfy-link href)
2080 (put-text-property stop (1+ stop ) 'hfy-endl t )
2081 (put-text-property start (1+ stop ) 'hfy-linkp t )))
2082 (goto-char tmp-point)) ))
2083 tags-list) )))
2085 (defun hfy-shell ()
2086 "Return `shell-file-name', or \"/bin/sh\" if it is a non-Bourne shell."
2087 (if (string-match "\\<bash\\>\\|\\<sh\\>\\|\\<dash\\>" shell-file-name)
2088 shell-file-name
2089 (or hfy-shell-file-name "/bin/sh")))
2091 ;; cache the #(tag => file line point) entries for files under srcdir
2092 ;; and cache the descending sorted list of tags in the relevant alist,
2093 ;; also keyed by srcdir:
2094 (defun hfy-load-tags-cache (srcdir)
2095 "Run `hfy-etags-cmd' on SRCDIR, then call `hfy-parse-tags-buffer'."
2096 ;;(message "hfy-load-tags-cache");;DBUG
2097 (let ((etags-buffer (get-buffer-create "*hfy-tags*"))
2098 (etags-command (format hfy-etags-cmd hfy-etags-bin))
2099 (shell-file-name (hfy-shell)))
2100 (cd srcdir)
2101 (shell-command etags-command etags-buffer)
2102 (hfy-parse-tags-buffer srcdir etags-buffer)) )
2104 ;; break this out from `hfy-load-tags-cache' to make the tar file
2105 ;; functionality easier to implement.
2106 ;; ( tar file functionality not merged here because it requires a
2107 ;; hacked copy of etags capable of tagging stdin: if Francesco
2108 ;; Potorti accepts a patch, or otherwise implements stdin tagging,
2109 ;; then I will provide a `htmlfontify-tar-file' defun )
2110 (defun hfy-parse-tags-buffer (srcdir buffer)
2111 "Parse a BUFFER containing etags formatted output, loading the
2112 `hfy-tags-cache' and `hfy-tags-sortl' entries for SRCDIR."
2113 (let ((cache-entry (assoc srcdir hfy-tags-cache))
2114 (tlist-cache (assoc srcdir hfy-tags-sortl))
2115 (trmap-cache (assoc srcdir hfy-tags-rmap ))
2116 (cache-hash nil) (trmap-hash nil) (tags-list nil)
2117 (hash-entry nil) (tag-string nil) (tag-line nil)
2118 (tag-point nil) (new-entry nil) (etags-file nil))
2120 ;; (re)initialize the tag reverse map:
2121 (if trmap-cache (setq trmap-hash (cadr trmap-cache))
2122 (setq trmap-hash (make-hash-table :test 'equal))
2123 (setq hfy-tags-rmap (list (list srcdir trmap-hash) hfy-tags-rmap)))
2124 (clrhash trmap-hash)
2126 ;; (re)initialize the tag cache:
2127 (if cache-entry (setq cache-hash (cadr cache-entry))
2128 (setq cache-hash (make-hash-table :test 'equal))
2129 (setq hfy-tags-cache (list (list srcdir cache-hash) hfy-tags-cache)))
2130 (clrhash cache-hash)
2132 ;; cache the TAG => ((file line point) (file line point) ... ) entries:
2133 (with-current-buffer buffer
2134 (goto-char (point-min))
2136 (while (and (looking-at "^\x0c") (= 0 (forward-line 1)))
2137 ;;(message "^L boundary")
2138 (if (and (looking-at "^\\(.+\\),\\([0-9]+\\)$")
2139 (= 0 (forward-line 1)))
2140 (progn
2141 (setq etags-file (match-string 1))
2142 ;;(message "TAGS for file: %s" etags-file)
2143 (while (and (looking-at hfy-etag-regex) (= 0 (forward-line 1)))
2144 (setq tag-string (match-string 1))
2145 (if (= 0 (length tag-string)) nil ;; noop
2146 (setq tag-line (round (string-to-number (match-string 2))))
2147 (setq tag-point (round (string-to-number (match-string 3))))
2148 (setq hash-entry (gethash tag-string cache-hash))
2149 (setq new-entry (list etags-file tag-line tag-point))
2150 (push new-entry hash-entry)
2151 ;;(message "HASH-ENTRY %s %S" tag-string new-entry)
2152 (puthash tag-string hash-entry cache-hash)))) )))
2154 ;; cache a list of tags in descending length order:
2155 (maphash (lambda (K _V) (push K tags-list)) cache-hash)
2156 (setq tags-list (sort tags-list (lambda (A B) (< (length B) (length A)))))
2158 ;; put the tag list into the cache:
2159 (if tlist-cache (setcar (cdr tlist-cache) tags-list)
2160 (push (list srcdir tags-list) hfy-tags-sortl))
2162 ;; return the number of tags found:
2163 (length tags-list) ))
2165 (defun hfy-prepare-index-i (srcdir dstdir filename &optional stub map)
2166 "Prepare a tags index buffer for SRCDIR.
2167 `hfy-tags-cache' must already have an entry for SRCDIR for this to work.
2168 `hfy-page-header', `hfy-page-footer', `hfy-link-extn' and `hfy-extn'
2169 all play a part here.\n
2170 If STUB is set, prepare an (appropriately named) index buffer
2171 specifically for entries beginning with STUB.\n
2172 If MAP is set, use that instead of `hfy-tags-cache'.
2173 FILENAME is the name of the file being indexed.
2174 DSTDIR is the output directory, where files will be written."
2175 ;;(message "hfy-write-index");;DBUG
2176 (let ((cache-entry (assoc srcdir (or map hfy-tags-cache)))
2177 (cache-hash nil)
2178 (tag-list nil)
2179 (index-file
2180 (concat filename (if stub (concat "." stub) "") hfy-extn))
2181 (index-buf nil))
2182 (if (not (and cache-entry
2183 (setq cache-hash (cadr cache-entry))
2184 (setq index-buf (get-buffer-create index-file))))
2185 nil ;; noop
2186 (maphash (lambda (K _V) (push K tag-list)) cache-hash)
2187 (setq tag-list (sort tag-list 'string<))
2188 (set-buffer index-buf)
2189 (erase-buffer)
2190 (insert (funcall hfy-page-header filename "<!-- CSS -->"))
2191 (insert "<table class=\"index\">\n")
2193 (dolist (TAG tag-list)
2194 (let ((tag-started nil))
2195 (dolist (DEF (gethash TAG cache-hash))
2196 (if (and stub (not (string-match (concat "^" stub) TAG)))
2197 nil ;; we have a stub and it didn't match: NOOP
2198 (let ((file (car DEF))
2199 (line (cadr DEF)))
2200 (insert
2201 (format
2202 (concat
2203 " <tr> \n"
2204 " <td>%s</td> \n"
2205 " <td><a href=\"%s%s\">%s</a></td> \n"
2206 " <td><a href=\"%s%s#%s.%d\">%d</a></td>\n"
2207 " </tr> \n")
2208 (if (string= TAG tag-started) "&nbsp;"
2209 (format "<a name=\"%s\">%s</a>" TAG TAG))
2210 file (or hfy-link-extn hfy-extn) file
2211 file (or hfy-link-extn hfy-extn) TAG line line))
2212 (setq tag-started TAG))))))
2213 (insert "</table>\n")
2214 (insert (funcall hfy-page-footer filename))
2215 (and dstdir (cd dstdir))
2216 (set-visited-file-name index-file)
2217 index-buf) ))
2219 (defun hfy-prepare-index (srcdir dstdir)
2220 "Return a list of index buffer(s), as determined by `hfy-split-index'.
2221 SRCDIR and DSTDIR are the source and output directories respectively."
2222 (if (not hfy-split-index)
2223 (list (hfy-prepare-index-i srcdir dstdir hfy-index-file nil))
2224 (let ((stub-list nil)
2225 (cache-hash nil)
2226 (index-list nil)
2227 (cache-entry (assoc srcdir hfy-tags-cache)))
2228 (if (and cache-entry (setq cache-hash (cadr cache-entry)))
2229 (maphash
2230 (lambda (K _V)
2231 (let ((stub (upcase (substring K 0 1))))
2232 (if (member stub stub-list)
2233 nil ;; seen this already: NOOP
2234 (setq
2235 stub-list (cons stub stub-list)
2236 index-list (cons (hfy-prepare-index-i srcdir
2237 dstdir
2238 hfy-index-file
2239 stub)
2240 index-list)) )))
2241 cache-hash) )
2242 index-list)))
2244 (defun hfy-prepare-tag-map (srcdir dstdir)
2245 "Prepare the counterpart(s) to the index buffer(s) - a list of buffers
2246 with the same structure, but listing (and linking to) instances of tags
2247 \(as opposed to their definitions).\n
2248 SRCDIR and DSTDIR are the source and output directories respectively.
2249 See also `hfy-prepare-index', `hfy-split-index'."
2250 (if (not hfy-split-index)
2251 (list (hfy-prepare-index-i srcdir
2252 dstdir
2253 hfy-instance-file
2255 hfy-tags-rmap))
2256 (let ((stub-list nil)
2257 (cache-hash nil)
2258 (index-list nil)
2259 (cache-entry (assoc srcdir hfy-tags-rmap)))
2261 (if (and cache-entry (setq cache-hash (cadr cache-entry)))
2262 (maphash
2263 (lambda (K _V)
2264 (let ((stub (upcase (substring K 0 1))))
2265 (if (member stub stub-list)
2266 nil ;; seen this already: NOOP
2267 (setq
2268 stub-list (cons stub stub-list)
2269 index-list (cons (hfy-prepare-index-i srcdir
2270 dstdir
2271 hfy-instance-file
2272 stub
2273 hfy-tags-rmap)
2274 index-list)) )))
2275 cache-hash) )
2276 index-list)))
2278 (defun hfy-subtract-maps (srcdir)
2279 "Internal function - strips definitions of tags from the instance map.
2280 SRCDIR is the directory being \"published\".
2281 See also `hfy-tags-cache', `hfy-tags-rmap'."
2282 (let ((new-list nil)
2283 (old-list nil)
2284 (def-list nil)
2285 (exc-list nil)
2286 (fwd-map (cadr (assoc srcdir hfy-tags-cache)))
2287 (rev-map (cadr (assoc srcdir hfy-tags-rmap )))
2288 (taglist (cadr (assoc srcdir hfy-tags-sortl))))
2289 (dolist (TAG taglist)
2290 (setq def-list (gethash TAG fwd-map)
2291 old-list (gethash TAG rev-map)
2292 exc-list (mapcar (lambda (P) (list (car P) (cadr P))) def-list)
2293 new-list nil)
2294 (dolist (P old-list)
2295 (or (member (list (car P) (cadr P)) exc-list)
2296 (push P new-list)))
2297 (puthash TAG new-list rev-map))))
2299 (defun htmlfontify-run-etags (srcdir)
2300 "Load the etags cache for SRCDIR.
2301 See also `hfy-load-tags-cache'."
2302 (interactive "D source directory: ")
2303 (hfy-load-tags-cache (directory-file-name srcdir)))
2305 ;;(defun hfy-test-read-args (foo bar)
2306 ;; (interactive "D source directory: \nD target directory: ")
2307 ;; (message "foo: %S\nbar: %S" foo bar))
2309 (defun hfy-save-kill-buffers (buffer-list &optional dstdir)
2310 (dolist (B buffer-list)
2311 (set-buffer B)
2312 (and dstdir (file-directory-p dstdir) (cd dstdir))
2313 (save-buffer)
2314 (kill-buffer B)))
2316 ;;;###autoload
2317 (defun htmlfontify-copy-and-link-dir (srcdir dstdir &optional f-ext l-ext)
2318 "Trawl SRCDIR and write fontified-and-hyperlinked output in DSTDIR.
2319 F-EXT and L-EXT specify values for `hfy-extn' and `hfy-link-extn'.\n
2320 You may also want to set `hfy-page-header' and `hfy-page-footer'."
2321 (interactive "D source directory: \nD output directory: ")
2322 ;;(message "htmlfontify-copy-and-link-dir")
2323 (setq srcdir (directory-file-name srcdir))
2324 (setq dstdir (directory-file-name dstdir))
2325 (let ((source-files "SETME: list of source files, relative to srcdir")
2326 (tr-cache (assoc srcdir hfy-tags-rmap))
2327 (hfy-extn (or f-ext ".html"))
2328 (hfy-link-extn (or l-ext ".html")))
2329 ;; oops, forgot to load etags for srcdir:
2330 (if tr-cache nil
2331 (message "autoload of tags cache")
2332 (hfy-load-tags-cache srcdir)
2333 (setq tr-cache (assoc srcdir hfy-tags-rmap)))
2334 ;; clear out the old cache:
2335 (clrhash (cadr tr-cache))
2336 (hfy-make-directory dstdir)
2337 (setq source-files (hfy-list-files srcdir))
2338 (dolist (file source-files)
2339 (hfy-copy-and-fontify-file srcdir dstdir file))
2340 (hfy-subtract-maps srcdir)
2341 (hfy-save-kill-buffers (hfy-prepare-index srcdir dstdir) dstdir)
2342 (hfy-save-kill-buffers (hfy-prepare-tag-map srcdir dstdir) dstdir) ))
2344 ;; name of the init file we want:
2345 (defun hfy-initfile ()
2346 "Return the expected location of the htmlfontify specific init/custom file."
2347 (let* ((file (or (getenv "HFY_INITFILE") ".hfy.el")))
2348 (expand-file-name file "~") ))
2351 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2352 ;; incomplete as yet : transfer hook settings to hfy init file:
2353 ;; (defalias 'hfy-set-hooks 'custom-set-variables)
2355 ;; (defun hfy-pp-hook (H)
2356 ;; (and (string-match "-hook\\'" (symbol-name H))
2357 ;; (boundp H)
2358 ;; (symbol-value H)
2359 ;; (insert (format "\n '(%S %S)" H (symbol-value H)))
2360 ;; )
2361 ;; )
2363 ;; (defun hfy-save-hooks ()
2364 ;; (let ((custom-file (hfy-initfile)))
2365 ;; (custom-save-delete 'hfy-set-hooks)
2366 ;; (let ((standard-output (current-buffer)))
2367 ;; (princ "(hfy-set-hooks\n;;auto-generated, only one copy allowed\n")
2368 ;; (mapatoms 'hfy-pp-hook)
2369 ;; (insert "\n)")
2370 ;; )
2371 ;; )
2372 ;; )
2373 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2375 (defalias 'hfy-init-progn 'progn)
2377 (defun hfy-save-initvar (sym)
2378 (princ (format "(setq %s\n '" sym))
2379 (pp (symbol-value sym))
2380 (princ ")\n"))
2382 (defun htmlfontify-save-initfile ()
2383 "Save the htmlfontify settings to the htmlfontify init file."
2384 (interactive)
2385 (let* ((start-pos nil)
2386 (custom-file (hfy-initfile))
2387 (standard-output (find-file-noselect custom-file 'nowarn)))
2388 (save-excursion
2389 (custom-save-delete 'hfy-init-progn)
2390 (setq start-pos (point))
2391 (princ "(hfy-init-progn\n;;auto-generated, only one copy allowed\n")
2392 ;; FIXME: This saving&restoring of global customization
2393 ;; variables can interfere with other customization settings for
2394 ;; those vars (in .emacs or in Customize).
2395 (mapc 'hfy-save-initvar
2396 '(auto-mode-alist interpreter-mode-alist))
2397 (princ ")\n")
2398 (indent-region start-pos (point) nil))
2399 (custom-save-all) ))
2401 (defun htmlfontify-load-initfile ()
2402 "Load the htmlfontify specific init/custom file."
2403 (interactive)
2404 (let ((file (hfy-initfile)))
2405 (load file 'NOERROR nil nil) ))
2408 ;;;### (autoloads (hfy-fallback-colour-values htmlfontify-load-rgb-file)
2409 ;;;;;; "hfy-cmap" "hfy-cmap.el" "ef24066922f1e27b7580d572f12fabbe")
2410 ;;; Generated autoloads from hfy-cmap.el
2412 (autoload 'htmlfontify-load-rgb-file "hfy-cmap" "\
2413 Load an X11 style rgb.txt FILE.
2414 Search `hfy-rgb-load-path' if FILE is not specified.
2415 Loads the variable `hfy-rgb-txt-colour-map', which is used by
2416 `hfy-fallback-colour-values'.
2418 \(fn &optional FILE)" t nil)
2420 (autoload 'hfy-fallback-colour-values "hfy-cmap" "\
2421 Use a fallback method for obtaining the rgb values for a color.
2423 \(fn COLOUR-STRING)" nil nil)
2425 ;;;***
2428 (provide 'htmlfontify)
2430 ;; Local Variables:
2431 ;; coding: utf-8
2432 ;; End:
2434 ;;; htmlfontify.el ends here