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