1 ;;; htmlfontify.el --- htmlize a buffer/source tree with optional hyperlinks
3 ;; Copyright (C) 2002-2003, 2009-2015 Free Software Foundation, Inc.
5 ;; Emacs Lisp Archive Entry
6 ;; Package: htmlfontify
7 ;; Filename: htmlfontify.el
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
19 ;; This file is part of GNU Emacs.
21 ;; GNU Emacs is free software: you can redistribute it and/or modify
22 ;; it under the terms of the GNU General Public License as published by
23 ;; the Free Software Foundation, either version 3 of the License, or
24 ;; (at your option) any later version.
26 ;; GNU Emacs is distributed in the hope that it will be useful,
27 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
28 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 ;; GNU General Public License for more details.
31 ;; You should have received a copy of the GNU General Public License
32 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
35 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
36 ;; I have made some changes to make it work for Emacs 22. A lot of
37 ;; small bug fixes related to the format of text and overlay
38 ;; properties (which might have changed since the beginning of 2003
39 ;; when this file was originally written).
41 ;; The function `hfy-face-at' currently carries much of the burden of
42 ;; my lacking understanding of the formats mentioned above and should
43 ;; need some knowledgeable help.
45 ;; Another thing that maybe could be fixed is that overlay background
46 ;; colors which are now only seen where there is text (in the XHTML
47 ;; output). A bit of CSS tweaking is necessary there.
49 ;; The face 'default has a value :background "SystemWindow" for the
50 ;; background color. There is no explicit notion that this should be
51 ;; considered transparent, but I have assumed that it could be handled
52 ;; like if it was here. (I am unsure that background and foreground
53 ;; priorities are handled ok, but it looks ok in my tests now.)
55 ;; 2007-12-27 Lennart Borgman
56 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
58 ;; Here's some elisp code to html-pretty-print an Emacs buffer, preserving
59 ;; the Emacs syntax/whatever highlighting. It also knows how to drive etags
60 ;; (exuberant-ctags or Emacs etags) and hyperlink the code according
61 ;; to its (etags') output.
63 ;; NOTE: Currently the hyperlinking code only knows how to drive GNU find
64 ;; and the exuberant and GNU variants of etags : I do not know of any other
65 ;; etags variants, but mechanisms have been provided to allow htmlfontify
66 ;; to be taught how to drive them. As long as your version of find has
67 ;; the -path test and is reasonably sane, you should be fine.
69 ;; A sample of the htmlfontified / hyperlinked output of this module can be
70 ;; found at http://rtfm.etla.org/sql/dbishell/src/ - it's not perfect, but
71 ;; it's a hell of a lot faster and more thorough than I could hope to be
72 ;; doing this by hand.
74 ;; some user / horrified onlooker comments:
75 ;; What? No! There's something deeply wrong here... (R. Shufflebotham)
76 ;; You're a freak. (D. Silverstone)
77 ;; Aren't we giving you enough to do? (J. Busuttil)
78 ;; You're almost as messed up as Lexx is! (N. Graves-Morris)
81 ;; Changes: moved to changelog (CHANGES) file.
84 (eval-when-compile (require 'cl))
86 ;; (`facep' `face-attr-construct' `x-color-values' `color-values' `face-name')
88 ;; (`defgroup' `defcustom')
90 ;; (`font-lock-fontify-region')
93 (require 'htmlfontify-loaddefs)
95 (defconst htmlfontify-version 0.21)
97 (defconst hfy-meta-tags
98 (format "<meta name=\"generator\" content=\"emacs %s; htmlfontify %0.2f\" />"
99 emacs-version htmlfontify-version)
100 "The generator meta tag for this version of htmlfontify.")
102 (defconst htmlfontify-manual "Htmlfontify Manual"
103 "Copy and convert buffers and files to HTML, adding hyperlinks between files
104 \(driven by etags) if requested.
105 \nInteractive functions:
107 `htmlfontify-run-etags'
108 `htmlfontify-copy-and-link-dir'
109 `htmlfontify-load-rgb-file'
110 `htmlfontify-unload-rgb-file'\n
112 fontify a file you have open: \\[htmlfontify-buffer]
113 prepare the etags map for a directory: \\[htmlfontify-run-etags]
114 copy a directory, fontifying as you go: \\[htmlfontify-copy-and-link-dir]\n
115 The following might be useful when running non-windowed or in batch mode:
116 \(note that they shouldn't be necessary - we have a built in map)\n
117 load an X11 style rgb.txt file: \\[htmlfontify-load-rgb-file]
118 unload the current rgb.txt file: \\[htmlfontify-unload-rgb-file]\n
119 And here's a programmatic example:\n
120 \(defun rtfm-build-page-header (file style)
121 (format \"#define TEMPLATE red+black.html
123 #include <build/menu-dirlist|>\\n
124 html-css-url := /css/red+black.css
125 title := rtfm.etla.org ( %s / src/%s )
127 head <=STYLESHEET;\\n
130 main-title := rtfm / %s / src/%s\\n
131 main-content <=MAIN_CONTENT;\\n\" rtfm-section file style rtfm-section file))
133 \(defun rtfm-build-page-footer (file) \"\\nMAIN_CONTENT\\n\")
135 \(defun rtfm-build-source-docs (section srcdir destdir)
137 \"s section[eg- emacs / p4-blame]:\\nD source-dir: \\nD output-dir: \")
138 (require \\='htmlfontify)
139 (hfy-load-tags-cache srcdir)
140 (let ((hfy-page-header \\='rtfm-build-page-header)
141 (hfy-page-footer \\='rtfm-build-page-footer)
142 (rtfm-section section)
143 (hfy-index-file \"index\"))
144 (htmlfontify-run-etags srcdir)
145 (htmlfontify-copy-and-link-dir srcdir destdir \".src\" \".html\")))")
147 (defgroup htmlfontify nil
148 "Convert buffers and files to HTML."
150 :link '(variable-link htmlfontify-manual)
151 :link '(custom-manual "(htmlfontify) Top")
152 :link '(info-link "(htmlfontify) Customization")
155 (defcustom hfy-page-header 'hfy-default-header
156 "Function called to build the header of the HTML source.
157 This is called with two arguments (the filename relative to the top
158 level source directory being etag'd and fontified), and a string containing
159 the <style>...</style> text to embed in the document.
160 It should return a string that will be used as the header for the
161 htmlfontified version of the source file.\n
162 See also `hfy-page-footer'."
164 ;; FIXME: Why place such a :tag everywhere? Isn't it imposing your
165 ;; own Custom preference on your users? --Stef
169 (defcustom hfy-split-index nil
170 "Whether or not to split the index `hfy-index-file' alphabetically.
171 If non-nil, the index is split on the first letter of each tag.
172 Useful when the index would otherwise be large and take
173 a long time to render or be difficult to navigate."
178 (defcustom hfy-page-footer 'hfy-default-footer
179 "As `hfy-page-header', but generates the output footer.
180 It takes only one argument, the filename."
185 (defcustom hfy-extn ".html"
186 "File extension used for output files."
191 (defcustom hfy-src-doc-link-style "text-decoration: underline;"
192 "String to add to the `<style> a' variant of an htmlfontify CSS class."
194 :tag "src-doc-link-style"
197 (defcustom hfy-src-doc-link-unstyle " text-decoration: none;"
198 "Regex to remove from the `<style> a' variant of an htmlfontify CSS class."
200 :tag "src-doc-link-unstyle"
203 (defcustom hfy-link-extn nil
204 "File extension used for href links.
205 Useful where the htmlfontify output files are going to be processed
206 again, with a resulting change in file extension. If nil, then any
207 code using this should fall back to `hfy-extn'."
209 :tag "link-extension"
210 :type '(choice string (const nil)))
212 (defcustom hfy-link-style-fun 'hfy-link-style-string
213 "Function to customize the appearance of hyperlinks.
214 Set this to a function, which will be called with one argument
215 \(a \"{ foo: bar; ...}\" CSS style-string) - it should return a copy of
216 its argument, altered so as to make any changes you want made for text which
217 is a hyperlink, in addition to being in the class to which that style would
218 normally be applied."
220 :tag "link-style-function"
223 (defcustom hfy-index-file "hfy-index"
224 "Name (sans extension) of the tag definition index file produced during
225 fontification-and-hyperlinking."
230 (defcustom hfy-instance-file "hfy-instance"
231 "Name (sans extension) of the tag usage index file produced during
232 fontification-and-hyperlinking."
237 (defcustom hfy-html-quote-regex "\\([<\"&>]\\)"
238 "Regex to match (with a single back-reference per match) strings in HTML
239 which should be quoted with `hfy-html-quote' (and `hfy-html-quote-map')
242 :tag "html-quote-regex"
245 (define-obsolete-variable-alias 'hfy-init-kludge-hooks 'hfy-init-kludge-hook
247 (defcustom hfy-init-kludge-hook '(hfy-kludge-cperl-mode)
248 "List of functions to call when starting `htmlfontify-buffer' to do any
249 kludging necessary to get highlighting modes to behave as you want, even
250 when not running under a window system."
252 :tag "init-kludge-hooks"
255 (define-obsolete-variable-alias 'hfy-post-html-hooks 'hfy-post-html-hook "24.3")
256 (defcustom hfy-post-html-hook nil
257 "List of functions to call after creating and filling the HTML buffer.
258 These functions will be called with the HTML buffer as the current buffer."
260 :tag "post-html-hooks"
261 :options '(set-auto-mode)
264 (defcustom hfy-default-face-def nil
265 "Fallback `defface' specification for the face 'default, used when
266 `hfy-display-class' has been set (the normal htmlfontify way of extracting
267 potentially non-current face information doesn't necessarily work for
269 Example: I customize this to:\n
270 \((t :background \"black\" :foreground \"white\" :family \"misc-fixed\"))"
272 :tag "default-face-definition"
275 (defcustom hfy-etag-regex (concat ".*"
276 "\x7f" "\\([^\x01\n]+\\)"
277 "\x01" "\\([0-9]+\\)"
279 "\\|" ".*\x7f[0-9]+,[0-9]+$")
280 "Regex used to parse an etags entry: must have 3 subexps, corresponding,
284 3 - The char (point) at which the tag occurs."
289 (defcustom hfy-html-quote-map '(("\"" """)
293 "Alist of char -> entity mappings used to make the text HTML-safe."
295 :tag "html-quote-map"
296 :type '(alist :key-type (string)))
297 (defconst hfy-e2x-etags-cmd "for src in `find . -type f`;
301 *.ad[absm]|*.[CFHMSacfhlmpsty]|*.def|*.in[cs]|*.s[as]|*.src|*.cc|\\
302 *.hh|*.[chy]++|*.[ch]pp|*.[chy]xx|*.pdb|*.[ch]s|*.[Cc][Oo][Bb]|\\
303 *.[eh]rl|*.f90|*.for|*.java|*.[cem]l|*.clisp|*.lisp|*.[Ll][Ss][Pp]|\\
304 [Mm]akefile*|*.pas|*.[Pp][LlMm]|*.psw|*.lm|*.pc|*.prolog|*.oak|\\
305 *.p[sy]|*.sch|*.scheme|*.[Ss][Cc][Mm]|*.[Ss][Mm]|*.bib|*.cl[os]|\\
306 *.ltx|*.sty|*.TeX|*.tex|*.texi|*.texinfo|*.txi|*.x[bp]m|*.yy|\\
317 SHEBANG=`head -n1 ${src} | grep '#!' -c`;
318 if [ ${SHEBANG} -eq 1 ];
328 (defconst hfy-etags-cmd-alist-default
329 `(("emacs etags" . ,hfy-e2x-etags-cmd)
330 ("exuberant ctags" . "%s -R -f -" )))
332 (defcustom hfy-etags-cmd-alist
333 hfy-etags-cmd-alist-default
334 "Alist of possible shell commands that will generate etags output that
335 `htmlfontify' can use. `%s' will be replaced by `hfy-etags-bin'."
337 :tag "etags-cmd-alist"
338 :type '(alist :key-type (string) :value-type (string)))
340 (defcustom hfy-etags-bin "etags"
341 "Location of etags binary (we begin by assuming it's in your path).\n
342 Note that if etags is not in your path, you will need to alter the shell
343 commands in `hfy-etags-cmd-alist'."
348 (defcustom hfy-shell-file-name "/bin/sh"
349 "Shell (Bourne or compatible) to invoke for complex shell operations."
351 :tag "shell-file-name"
354 (defcustom hfy-ignored-properties '(read-only
357 insert-in-front-hooks
361 "Properties to omit when copying a fontified buffer for HTML transformation."
363 :tag "ignored-properties"
364 :type '(repeat symbol))
366 (defun hfy-which-etags ()
367 "Return a string indicating which flavor of etags we are using."
368 (let ((v (shell-command-to-string (concat hfy-etags-bin " --version"))))
369 (cond ((string-match "exube" v) "exuberant ctags")
370 ((string-match "GNU E" v) "emacs etags" )) ))
372 (defcustom hfy-etags-cmd
373 ;; We used to wrap this in a `eval-and-compile', but:
374 ;; - it had no effect because this expression was not seen by the
375 ;; byte-compiler (defcustom used to quote this argument).
376 ;; - it signals an error (`hfy-which-etags' is not defined at compile-time).
377 ;; - we want this auto-detection to reflect the system on which Emacs is run
378 ;; rather than the one on which it's compiled.
379 (cdr (assoc (hfy-which-etags) hfy-etags-cmd-alist))
380 "The etags equivalent command to run in a source directory to generate a tags
381 file for the whole source tree from there on down. The command should emit
382 the etags output on stdout.\n
383 Two canned commands are provided - they drive Emacs's etags and
384 exuberant-ctags' etags respectively."
387 :type (let ((clist (list '(string))))
388 (dolist (C hfy-etags-cmd-alist)
389 (push (list 'const :tag (car C) (cdr C)) clist))
390 (cons 'choice clist)))
392 (defcustom hfy-istext-command "file %s | sed -e 's@^[^:]*:[ \t]*@@'"
393 "Command to run with the name of a file, to see whether it is a text file
394 or not. The command should emit a string containing the word `text' if
395 the file is a text file, and a string not containing `text' otherwise."
397 :tag "istext-command"
400 (defcustom hfy-find-cmd
401 "find . -type f \\! -name \\*~ \\! -name \\*.flc \\! -path \\*/CVS/\\*"
402 "Find command used to harvest a list of files to attempt to fontify."
407 (defcustom hfy-display-class nil
408 "Display class to use to determine which display class to use when
409 calculating a face's attributes. This is useful when, for example, you
410 are running Emacs on a tty or in batch mode, and want htmlfontify to have
411 access to the face spec you would use if you were connected to an X display.\n
412 Some valid class specification elements are:\n
421 Multiple values for a tag may be combined, to indicate that any one or more
422 of these values in the specification key constitutes a match, eg:\n
423 '((class color grayscale) (type tty)) would match any of:\n
426 '((class color grayscale))
429 '((type tty) (class color))\n
431 :type '(alist :key-type (symbol) :value-type (symbol))
434 :options '((type (choice (const :tag "X11" x-toolkit)
435 (const :tag "Terminal" tty )
436 (const :tag "Lucid Toolkit" lucid )
437 (const :tag "Motif Toolkit" motif )))
439 (class (choice (const :tag "Color" color )
440 (const :tag "Grayscale" grayscale)))
442 (background (choice (const :tag "Dark" dark )
443 (const :tag "Bright" light ))) ))
445 (defcustom hfy-optimizations (list 'keep-overlays)
446 "Optimizations to turn on: So far, the following have been implemented:\n
447 merge-adjacent-tags: If two (or more) span tags are adjacent, identical and
448 separated by nothing more than whitespace, they will
449 be merged into one span.
450 zap-comment-links : Suppress hyperlinking of tags found in comments.
451 zap-string-links : Suppress hyperlinking of tags found in strings.
452 div-wrapper : Add <div class=\"default\"> </div> tags around the
454 keep-overlays : More of a bell (or possibly whistle) than an
455 optimization - If on, preserve overlay highlighting
456 (cf ediff or goo-font-lock) as well as basic faces.\n
457 body-text-only : Emit only body-text. In concrete terms,
458 1. Suppress calls to `hfy-page-header'and
460 2. Pretend that `div-wrapper' option above is
462 3. Don't enclose output in <pre> </pre> tags
463 And the following are planned but not yet available:\n
464 kill-context-leak : Suppress hyperlinking between files highlighted by
466 Note: like compiler optimizations, these optimize the _output_ of the code,
467 not the processing of the source itself, and are therefore likely to slow
468 htmlfontify down, at least a little. Except for skip-refontification,
469 which can never slow you down, but may result in incomplete fontification."
470 :type '(set (const :tag "merge-adjacent-tags" merge-adjacent-tags )
471 (const :tag "zap-comment-links" zap-comment-links )
472 (const :tag "zap-string-links" zap-string-links )
473 (const :tag "skip-refontification" skip-refontification)
474 (const :tag "kill-context-leak" kill-context-leak )
475 (const :tag "div-wrapper" div-wrapper )
476 (const :tag "keep-overlays" keep-overlays )
477 (const :tag "body-text-only" body-text-only ))
479 :tag "optimizations")
480 (define-obsolete-variable-alias 'hfy-optimisations 'hfy-optimizations "25.1")
482 (defvar hfy-tags-cache nil
483 "Alist of the form:\n
484 \((\"/src/dir/0\" . tag-hash0) (\"/src/dir/1\" tag-hash1) ...)\n
485 Each tag hash entry then contains entries of the form:\n
486 \"tag_string\" => ((\"file/name.ext\" line char) ... )\n
487 ie an alist mapping (relative) file paths to line and character offsets.\n
488 See also `hfy-load-tags-cache'.")
490 (defvar hfy-tags-sortl nil
491 "Alist of the form ((\"/src/dir\" . (tag0 tag1 tag2)) ... )\n
492 where the tags are stored in descending order of length.\n
493 See also `hfy-load-tags-cache'.")
495 (defvar hfy-tags-rmap nil
496 "Alist of the form ((\"/src/dir\" . tag-rmap-hash))\n
497 where tag-rmap-hash has entries of the form:
498 \"tag_string\" => ( \"file/name.ext\" line char )
499 Unlike `hfy-tags-cache' these are the locations of occurrences of
500 tagged items, not the locations of their definitions.")
502 (defvar hfy-style-assoc 'please-ignore-this-line
503 "An assoc representing/describing an Emacs face.
504 Properties may be repeated, in which case later properties should be
505 treated as if they were inherited from a `parent' font.
506 \(For some properties, only the first encountered value is of any importance,
507 for others the values might be cumulative, and for others they might be
508 cumulative in a complex way.)\n
510 \(hfy-face-to-style \\='default) =>
511 ((\"background\" . \"rgb(0, 0, 0)\")
512 (\"color\" . \"rgb(255, 255, 255)\")
513 (\"font-style\" . \"normal\")
514 (\"font-weight\" . \"500\")
515 (\"font-stretch\" . \"normal\")
516 (\"font-family\" . \"misc-fixed\")
517 (\"font-size\" . \"13pt\")
518 (\"text-decoration\" . \"none\"))\n
519 \(hfy-face-to-style \\='Info-title-3-face) =>
520 ((\"font-weight\" . \"700\")
521 (\"font-family\" . \"helv\")
522 (\"font-size\" . \"120%\")
523 (\"text-decoration\" . \"none\"))\n")
525 (defvar hfy-sheet-assoc 'please-ignore-this-line
526 "An assoc with elements of the form (face-name style-name . style-string):\n
527 '((default \"default\" . \"{background: black; color: white}\")
528 (font-lock-string-face \"string\" . \"{color: rgb(64,224,208)}\"))" )
530 (defvar hfy-facemap-assoc 'please-ignore-this-line
531 "An assoc of (point . FACE-SYMBOL) or (point . DEFFACE-LIST)
532 and (point . \\='end) elements, in descending order of point value
533 \(ie from the file's end to its beginning).\n
534 The map is in reverse order because inserting a <style> tag (or any other
535 string) at `point' invalidates the map for all entries with a greater value of
536 point. By traversing the map from greatest to least point, we still invalidate
537 the map as we go, but only those points we have already dealt with (and
538 therefore no longer care about) will be invalid at any time.\n
540 (64744 . font-lock-comment-face)
542 (64722 . font-lock-string-face)
544 (64623 . font-lock-string-face)
546 (64446 . font-lock-keyword-face)
548 (64395 . font-lock-constant-face)
550 (64386 . font-lock-keyword-face)
552 ;; big similar section elided. You get the idea.
553 (4285 . font-lock-constant-face)
555 (4221 . font-lock-comment-face)
557 (4197 . font-lock-constant-face)
559 (1 . font-lock-comment-face))")
561 (defvar hfy-tmpfont-stack nil
562 "An alist of derived fonts resulting from overlays.")
564 (defconst hfy-hex-regex "[0-9A-Fa-f]")
566 (defconst hfy-triplet-regex
568 "\\(" hfy-hex-regex hfy-hex-regex "\\)"
569 "\\(" hfy-hex-regex hfy-hex-regex "\\)"
570 "\\(" hfy-hex-regex hfy-hex-regex "\\)"))
572 (defun hfy-interq (set-a set-b)
573 "Return the intersection (using `eq') of two lists SET-A and SET-B."
574 (let ((sa set-a) (interq nil) (elt nil))
578 (if (memq elt set-b) (setq interq (cons elt interq))))
581 (defun hfy-colour-vals (colour)
582 "Where COLOUR is a color name or #XXXXXX style triplet, return a
583 list of three (16 bit) rgb values for said color.\n
584 If a window system is unavailable, calls `hfy-fallback-colour-values'."
585 (if (string-match hfy-triplet-regex colour)
587 (lambda (x) (* (string-to-number (match-string x colour) 16) 257))
589 ;;(message ">> %s" colour)
591 (if (fboundp 'color-values)
592 (color-values colour)
593 ;;(message "[%S]" window-system)
594 (x-color-values colour))
595 ;; blarg - tty colors are no good - go fetch some X colors:
596 (hfy-fallback-colour-values colour))))
598 (defvar hfy-cperl-mode-kludged-p nil)
600 (defun hfy-kludge-cperl-mode ()
601 "CPerl mode does its damnedest not to do some of its fontification when not
602 in a windowing system - try to trick it..."
603 (if (not hfy-cperl-mode-kludged-p)
604 (progn (if (not window-system)
605 (let ((window-system 'htmlfontify))
606 (eval-and-compile (require 'cperl-mode))
607 (setq cperl-syntaxify-by-font-lock t)))
608 (setq hfy-cperl-mode-kludged-p t))) )
610 (defun hfy-opt (symbol)
611 "Is option SYMBOL set."
612 (memq symbol hfy-optimizations))
614 (defun hfy-default-header (file style)
615 "Default value for `hfy-page-header'.
616 FILE is the name of the file.
617 STYLE is the inline CSS stylesheet (or tag referring to an external sheet)."
618 ;; (format "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
619 ;; <html>\n <head>\n <title>%s</title>\n %s\n </head>\n <body>\n" file style))
620 (format "<?xml version=\"1.0\" encoding=\"utf-8\"?>
621 <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"
622 \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">
623 <html xmlns=\"http://www.w3.org/1999/xhtml\">
627 <script type=\"text/javascript\"><!--
628 // this function is needed to work around
629 // a bug in IE related to element attributes
630 function hasClass(obj)
633 if (obj.getAttributeNode(\"class\") != null)
635 result = obj.getAttributeNode(\"class\").value;
642 // the flag we'll use to keep track of
643 // whether the current row is odd or even
646 // if arguments are provided to specify the colors
647 // of the even & odd rows, then use the them;
648 // otherwise use the following defaults:
649 var evenColor = arguments[1] ? arguments[1] : \"#fff\";
650 var oddColor = arguments[2] ? arguments[2] : \"#ddd\";
652 // obtain a reference to the desired table
653 // if no such table exists, abort
654 var table = document.getElementById(id);
655 if (! table) { return; }
657 // by definition, tables can have more than one tbody
658 // element, so we'll have to get the list of child
660 var tbodies = table.getElementsByTagName(\"tbody\");
662 // and iterate through them...
663 for (var h = 0; h < tbodies.length; h++)
665 // find all the <tr> elements...
666 var trs = tbodies[h].getElementsByTagName(\"tr\");
668 // ... and iterate through them
669 for (var i = 0; i < trs.length; i++)
671 // avoid rows that have a class attribute
672 // or backgroundColor style
673 if (! hasClass(trs[i]) &&
674 ! trs[i].style.backgroundColor)
676 // get all the cells in this row...
677 var tds = trs[i].getElementsByTagName(\"td\");
679 // and iterate through them...
680 for (var j = 0; j < tds.length; j++)
684 // avoid cells that have a class attribute
685 // or backgroundColor style
686 if (! hasClass(mytd) &&
687 ! mytd.style.backgroundColor)
689 mytd.style.backgroundColor =
690 even ? evenColor : oddColor;
694 // flip from odd to even, or vice-versa
700 function toggle_invis( name )
705 { var classname = node.id;
707 { var classbase = classname.substr( 0, name.length );
708 if( classbase == name ) { return NodeFilter.FILTER_ACCEPT; } }
709 return NodeFilter.FILTER_SKIP; } };
710 var walker = document.createTreeWalker( document.body ,
711 NodeFilter.SHOW_ELEMENT ,
714 while( walker.nextNode() )
716 var e = walker.currentNode;
717 if( e.style.display == \"none\" ) { e.style.display = \"inline\"; }
718 else { e.style.display = \"none\"; }
723 <body onload=\"stripe('index'); return true;\">\n"
724 (mapconcat 'hfy-html-quote (mapcar 'char-to-string file) "") style))
726 (defun hfy-default-footer (_file)
727 "Default value for `hfy-page-footer'.
728 FILE is the name of the file being rendered, in case it is needed."
729 "\n </body>\n</html>\n")
731 (defun hfy-link-style-string (style-string)
732 "Replace the end of a CSS style declaration STYLE-STRING with the contents
733 of the variable `hfy-src-doc-link-style', removing text matching the regex
734 `hfy-src-doc-link-unstyle' first, if necessary."
735 ;;(message "hfy-colour-vals");;DBUG
736 (if (string-match hfy-src-doc-link-unstyle style-string)
737 (setq style-string (replace-match "" 'fixed-case 'literal style-string)))
738 (if (and (not (string-match hfy-src-doc-link-style style-string))
739 (string-match "} *$" style-string))
740 (concat (replace-match hfy-src-doc-link-style
746 ;; utility functions - cast emacs style specification values into their
748 (defun hfy-triplet (colour)
749 "Takes a COLOUR name (string) and return a CSS rgb(R, G, B) triplet string.
750 Uses the definition of \"white\" to map the numbers to the 0-255 range, so
751 if you've redefined white, (esp. if you've redefined it to have a triplet
752 member lower than that of the color you are processing) strange things
754 ;;(message "hfy-colour-vals");;DBUG
755 ;; TODO? Can we do somehow do better than this?
757 ((equal colour "unspecified-fg") (setq colour "black"))
758 ((equal colour "unspecified-bg") (setq colour "white")))
759 (let ((white (mapcar (lambda (I) (float (1+ I))) (hfy-colour-vals "white")))
760 (rgb16 (mapcar (lambda (I) (float (1+ I))) (hfy-colour-vals colour))))
762 ;;(apply 'format "rgb(%d, %d, %d)"
763 ;; Use #rrggbb instead, it is smaller
764 (apply 'format "#%02x%02x%02x"
770 (defun hfy-family (family) (list (cons "font-family" family)))
771 (defun hfy-bgcol (colour) (list (cons "background" (hfy-triplet colour))))
772 (defun hfy-colour (colour) (list (cons "color" (hfy-triplet colour))))
773 (defun hfy-width (width) (list (cons "font-stretch" (symbol-name width))))
775 (defcustom hfy-font-zoom 1.05
776 "Font scaling from Emacs to HTML."
780 (defun hfy-size (height)
781 "Derive a CSS font-size specifier from an Emacs font :height attribute HEIGHT.
782 Does not cope with the case where height is a function to be applied to
783 the height of the underlying font."
784 ;; In ttys, the default face has :height == 1.
785 (and (not (display-graphic-p)) (equal 1 height) (setq height 100))
788 ;;(t (cons "font-size" ": 1em"))
790 (cons "font-size" (format "%d%%" (* (* hfy-font-zoom height) 100))))
792 (cons "font-size" (format "%dpt" (/ (* hfy-font-zoom height) 10 )))) )) )
794 (defun hfy-slant (slant)
795 "Derive a font-style CSS specifier from the Emacs :slant attribute SLANT:
796 CSS does not define the reverse-* styles, so just maps those to the
798 (list (cons "font-style"
799 (or (cdr (assq slant '((italic . "italic")
800 (reverse-italic . "italic" )
801 (oblique . "oblique")
802 (reverse-oblique . "oblique"))))
805 (defun hfy-weight (weight)
806 "Derive a font-weight CSS specifier from an Emacs weight spec symbol WEIGHT."
807 (list (cons "font-weight" (cdr (assq weight '((ultra-bold . "900")
814 (extra-light . "200")
815 (ultra-light . "100")))))))
817 (defun hfy-box-to-border-assoc (spec)
819 (let ((tag (car spec))
822 (:color (cons "colour" val))
823 (:width (cons "width" val))
824 (:style (cons "style" val)))
825 (hfy-box-to-border-assoc (cddr spec))))))
827 (defun hfy-box-to-style (spec)
828 (let* ((css (hfy-box-to-border-assoc spec))
829 (col (cdr (assoc "colour" css)))
830 (s (cdr (assoc "style" css))))
832 (if col (cons "border-color" (cdr (assoc "colour" css))))
833 (cons "border-width" (format "%dpx" (or (cdr (assoc "width" css)) 1)))
834 (cons "border-style" (case s
835 (released-button "outset")
836 (pressed-button "inset" )
840 "Derive CSS border-* attributes from the Emacs :box attribute BOX."
843 ((integerp box) (list (cons "border-width" (format "%dpx" box))))
844 ((stringp box) (list (cons "border" (format "solid %s 1px" box))))
845 ((listp box) (hfy-box-to-style box) ))) )
847 (defun hfy-decor (tag _val)
848 "Derive CSS text-decoration specifiers from various Emacs font attributes.
849 TAG is an Emacs font attribute key (eg :underline).
852 ;; FIXME: Why not '("text-decoration" . "underline")? --Stef
854 (:underline (cons "text-decoration" "underline" ))
855 (:overline (cons "text-decoration" "overline" ))
856 (:strike-through (cons "text-decoration" "line-through")))))
858 (defun hfy-invisible (&optional _val)
859 "This text should be invisible.
860 Do something in CSS to make that happen.
861 VAL is ignored here."
862 '(("display" . "none")))
864 (defun hfy-combined-face-spec (face)
865 "Return a `defface' style alist of possible specifications for FACE.
866 Entries resulting from customization (`custom-set-faces') will take
869 (if (and hfy-display-class hfy-default-face-def (eq face 'default))
870 hfy-default-face-def)
871 (get face 'saved-face)
872 (get face 'face-defface-spec)))
874 (defun hfy-face-attr-for-class (face &optional class)
875 "Return the face attributes for FACE.
876 If CLASS is set, it must be a `defface' alist key [see below],
877 in which case the first face specification returned by `hfy-combined-face-spec'
878 which *doesn't* clash with CLASS is returned.\n
879 \(A specification with a class of t is considered to match any class you
880 specify - this matches Emacs's behavior when deciding on which face attributes
881 to use, to the best of my understanding).\n
882 If CLASS is nil, then you just get whatever `face-attr-construct' returns,
883 ie the current specification in effect for FACE.\n
884 *NOTE*: This function forces any face that is not 'default and which has
885 no :inherit property to inherit from 'default (this is because 'default
886 is magical in that Emacs's fonts behave as if they inherit implicitly from
887 'default, but no such behavior exists in HTML/CSS).\n
888 See also `hfy-display-class' for details of valid values for CLASS."
891 (let ((face-props (hfy-combined-face-spec face))
898 (setq face-specn (car face-props)
899 face-class (car face-specn)
900 face-attrs (cdr face-specn)
901 face-props (cdr face-props))
902 ;; if the current element CEL of CLASS is t we match
903 ;; if the current face-class is t, we match
904 ;; if the cdr of CEL has a non-nil
905 ;; intersection with the cdr of the first member of
906 ;; the current face-class with the same car as CEL, we match
907 ;; if we actually clash, then we can't match
915 (while (and cbuf (not next))
920 val (if (listp val) val (list val)))
923 (memq face-class '(t default))) ;Default match.
924 (setq score 0) (ignore "t match"))
925 ((not (cdr (assq key face-class))) ;Neither good nor bad.
926 nil (ignore "non match, non collision"))
927 ((setq x (hfy-interq val (cdr (assq key face-class))))
928 (setq score (+ score (length x)))
929 (ignore "intersection"))
931 (setq next t score -10) (ignore "collision")) ))
932 (if (> score face-score)
934 (setq face-match face-attrs
936 (ignore "%d << %S/%S" score face-class class))
937 (ignore "--- %d ---- (insufficient)" score)) ))
938 ;; matched ? last attrs : nil
940 (if (listp (car face-match)) (car face-match) face-match)
942 ;; Unfortunately the default face returns a
943 ;; :background. Fortunately we can remove it, but how do we do
944 ;; that in a non-system specific way?
945 (let ((spec (face-attr-construct face))
947 (if (not (memq :background spec))
950 (let ((a (nth 0 spec))
952 (unless (and (eq a :background)
954 (string= b "SystemWindow"))
955 (setq new-spec (cons a (cons b new-spec)))))
956 (setq spec (cddr spec)))
958 (if (or (memq :inherit face-spec) (eq 'default face))
960 (append face-spec (list :inherit 'default)))))
962 ;; construct an assoc of (css-tag-name . css-tag-value) pairs
963 ;; from a face or assoc of face attributes:
966 ;; (mumamo-message-with-face "testing face" 'highlight)
967 ;; (mumamo-message-with-face "testing face" '(:foreground "red" :background "yellow"))
968 ;; (hfy-face-to-style-i '(:inherit default foreground-color "red"))
969 ;; default face=(:stipple nil :background "SystemWindow" :foreground
970 ;; "SystemWindowText" :inverse-video nil :box nil :strike-through
971 ;; nil :overline nil :underline nil :slant normal :weight normal
972 ;; :height 98 :width normal :family "outline-courier new")
973 (defun hfy-face-to-style-i (fn)
974 "The guts of `hfy-face-to-style': FN should be a `defface' font spec,
975 as returned by `face-attr-construct' or `hfy-face-attr-for-class'.
976 Note that this function does not get font-sizes right if they are based
977 on inherited modifiers (via the :inherit) attribute, and any other
978 modifiers that are cumulative if they appear multiple times need to be
979 merged by the user - `hfy-flatten-style' should do this."
980 ;;(message "hfy-face-to-style-i");;DBUG
982 ;; fn's value could be something like
984 ;; ((foreground-color . "blue"))
985 ;; (foreground-color . "blue")
995 (if (eq key :inherit)
996 (let ((vs (if (listp val) val (list val))))
997 ;; (let ((x '(a b))) (setq x (append '(c d) x)))
998 ;; (let ((x '(a b))) (setq x (append '(c d) x)))
1003 (hfy-face-to-style-i
1004 (hfy-face-attr-for-class v hfy-display-class)) ))))
1007 (:family (hfy-family val))
1008 (:width (hfy-width val))
1009 (:weight (hfy-weight val))
1010 (:slant (hfy-slant val))
1011 (:foreground (hfy-colour val))
1012 (:background (hfy-bgcol val))
1013 (:box (hfy-box val))
1014 (:height (hfy-size val))
1015 (:underline (hfy-decor key val))
1016 (:overline (hfy-decor key val))
1017 (:strike-through (hfy-decor key val))
1018 (:invisible (hfy-invisible val))
1019 (:bold (hfy-weight 'bold))
1020 (:italic (hfy-slant 'italic))))))
1021 (setq that (hfy-face-to-style-i next))
1022 ;;(lwarn t :warning "%S => %S" fn (nconc this that parent))
1023 (nconc this that parent))) )
1025 (defun hfy-size-to-int (spec)
1026 "Convert SPEC, a CSS font-size specifier, to an Emacs :height attribute value.
1027 Used while merging multiple font-size attributes."
1028 ;;(message "hfy-size-to-int");;DBUG
1030 (if (string-match "\\([0-9]+\\)\\(%\\|pt\\)" spec)
1031 (cond ((string= "%" (match-string 2 spec))
1032 (/ (string-to-number (match-string 1 spec)) 100.0))
1033 ((string= "pt" (match-string 2 spec))
1034 (* (string-to-number (match-string 1 spec)) 10)))
1035 (string-to-number spec))) )
1037 ;; size is different, in that in order to get it right at all,
1038 ;; we have to trawl the inheritance path, accumulating modifiers,
1039 ;; _until_ we get to an absolute (pt) specifier, then combine the lot
1040 (defun hfy-flatten-style (style)
1041 "Take STYLE (see `hfy-face-to-style-i', `hfy-face-to-style') and merge
1042 any multiple attributes appropriately. Currently only font-size is merged
1043 down to a single occurrence - others may need special handling, but I
1044 haven't encountered them yet. Returns a `hfy-style-assoc'."
1045 ;;(message "(hfy-flatten-style %S)" style) ;;DBUG
1051 (if (string= (car css) "font-size")
1053 (when (not x) (setq m (nconc m (hfy-size-to-int (cdr css)))))
1054 (when (string-match "pt" (cdr css)) (setq x t)))
1055 (setq r (nconc r (list css)))))
1056 ;;(message "r: %S" r)
1057 (setq n (apply '* m))
1058 (nconc r (hfy-size (if x (round n) (* n 1.0)))) ))
1060 (defun hfy-face-resolve-face (fn)
1063 (hfy-face-attr-for-class fn hfy-display-class))
1065 (facep (symbol-value fn)))
1066 (hfy-face-attr-for-class (symbol-value fn) hfy-display-class))
1070 (defun hfy-face-to-style (fn)
1071 "Take FN, a font or `defface' style font specification,
1072 \(as returned by `face-attr-construct' or `hfy-face-attr-for-class')
1073 and return a `hfy-style-assoc'.\n
1074 See also `hfy-face-to-style-i', `hfy-flatten-style'."
1075 ;;(message "hfy-face-to-style");;DBUG
1076 (let* ((face-def (hfy-face-resolve-face fn))
1078 (hfy-flatten-style (hfy-face-to-style-i face-def))))
1079 ;;(message "%S" final-style)
1080 (if (not (assoc "text-decoration" final-style))
1081 (progn (setq final-style
1082 ;; Fix-me: there is no need for this since
1083 ;; text-decoration is not inherited.
1084 ;; but it's not wrong and if this ever changes it will
1085 ;; be needed, so I think it's better to leave it in? -- v
1086 (nconc final-style '(("text-decoration" . "none"))))))
1089 ;; strip redundant bits from a name. Technically, this could result in
1090 ;; a collision, but it is pretty unlikely - will fix later...
1091 ;; also handle ephemeral fonts created by overlays, which don't actually
1093 (defun hfy-face-or-def-to-name (fn)
1094 "Render a font symbol or `defface' font spec FN into a name (string)."
1095 ;;(message "generating name for %s" fn)
1096 (if (not (listp fn))
1098 (let* ((key (format "%s" fn))
1099 (entry (assoc key hfy-tmpfont-stack))
1100 (base (cadr (memq :inherit fn)))
1102 ;;(message "checking for key «%s» in font stack [%d]"
1103 ;; key (if entry 1 0))
1104 (if entry nil ;; noop
1105 (setq tag (format "%04d" (length hfy-tmpfont-stack))
1106 entry (cons key tag)
1107 hfy-tmpfont-stack (cons entry hfy-tmpfont-stack)))
1108 ;;(message " -> name: %s-%s" (or base 'default) tag)
1109 (format "%s-%s" (or base 'default) tag)) ))
1111 (defun hfy-css-name (fn)
1112 "Strip the boring bits from a font-name FN and return a CSS style name."
1113 ;;(message "hfy-css-name");;DBUG
1114 (let ((face-name (hfy-face-or-def-to-name fn)))
1115 (if (or (string-match "font-lock-\\(.*\\)" face-name)
1116 (string-match "cperl-\\(.*\\)" face-name)
1117 (string-match "^[Ii]nfo-\\(.*\\)" face-name))
1119 (setq face-name (match-string 1 face-name))
1120 (if (string-match "\\(.*\\)-face\\'" face-name)
1121 (setq face-name (match-string 1 face-name)))
1125 ;; construct an assoc of (stripped-name . "{ css-stuff-here }") pairs
1127 (defun hfy-face-to-css-default (fn)
1128 "Default handler for mapping faces to styles.
1129 See also `hfy-face-to-css'."
1130 ;;(message "hfy-face-to-css");;DBUG
1131 (let* ((css-list (hfy-face-to-style fn))
1137 (unless (member (car E) seen)
1139 (format " %s: %s; " (car E) (cdr E)))))
1141 (cons (hfy-css-name fn) (format "{%s}" (apply 'concat css-text)))) )
1143 (defvar hfy-face-to-css 'hfy-face-to-css-default
1144 "Handler for mapping faces to styles.
1145 The signature of the handler is of the form \(lambda (FN) ...).
1146 FN is a font or `defface' specification (cf
1147 `face-attr-construct'). The handler should return a cons cell of
1148 the form (STYLE-NAME . STYLE-SPEC).
1150 The default handler is `hfy-face-to-css-default'.
1152 See also `hfy-face-to-style'.")
1154 (defalias 'hfy-prop-invisible-p
1155 (if (fboundp 'invisible-p) #'invisible-p
1157 "Is text property PROP an active invisibility property?"
1158 (or (and (eq buffer-invisibility-spec t) prop)
1159 (or (memq prop buffer-invisibility-spec)
1160 (assq prop buffer-invisibility-spec))))))
1162 (defun hfy-find-invisible-ranges ()
1163 "Return a list of (start-point . end-point) cons cells of invisible regions."
1165 (let (invisible p i s) ;; return-value pos invisible end start
1166 (setq p (goto-char (point-min)))
1167 (when (invisible-p p) (setq s p i t))
1168 (while (< p (point-max))
1169 (if i ;; currently invisible
1170 (when (not (invisible-p p)) ;; but became visible
1172 invisible (cons (cons s p) invisible)))
1173 ;; currently visible:
1174 (when (invisible-p p) ;; but have become invisible
1176 (setq p (next-char-property-change p)))
1177 ;; still invisible at buffer end?
1179 (setq invisible (cons (cons s (point-max)) invisible)))
1182 (defun hfy-invisible-name (point map)
1183 "Generate a CSS style name for an invisible section of the buffer.
1184 POINT is the point inside the invisible region.
1185 MAP is the invisibility map as returned by `hfy-find-invisible-ranges'."
1186 ;;(message "(hfy-invisible-name %S %S)" point map)
1189 (when (and (>= point (car range))
1190 (< point (cdr range)))
1191 (setq name (format "invisible-%S-%S" (car range) (cdr range)))))
1194 ;; Fix-me: This function needs some cleanup by someone who understand
1195 ;; all the formats that face properties can have.
1197 ;; overlay handling should be fine. haven't tested multiple stacked overlapping
1198 ;; overlays recently, but the common case of a text property face + an overlay
1199 ;; face produces the correct merged css style (or as close to it as css can get)
1201 (defun hfy-face-at (p)
1202 "Find face in effect at point P.
1203 If overlays are to be considered (see `hfy-optimizations') then this may
1204 return a `defface' style list of face properties instead of a face symbol."
1205 ;;(message "hfy-face-at");;DBUG
1206 ;; Fix-me: clean up, remove face-name etc
1207 ;; not sure why we'd want to remove face-name? -- v
1208 (let ((overlay-data nil)
1210 (face-name (get-text-property p 'face))
1211 ;; (face-name (hfy-get-face-at p))
1214 (text-props (text-properties-at p)))
1215 ;;(message "face-name: %S" face-name)
1216 (when (and face-name (listp face-name) (facep (car face-name)))
1217 ;;(message "face-name is a list %S" face-name)
1218 ;;(setq text-props (cons 'face face-name))
1219 (dolist (f face-name)
1220 (setq extra-props (if (listp f)
1221 ;; for things like (variable-pitch
1222 ;; (:foreground "red"))
1223 (cons f extra-props)
1224 (cons :inherit (cons f extra-props)))))
1225 (setq base-face (car face-name)
1227 ;; text-properties-at => (face (:foreground "red" ...))
1228 ;; or => (face (compilation-info underline)) list of faces
1229 ;; overlay-properties
1230 ;; format= (evaporate t face ((foreground-color . "red")))
1232 ;; SO: if we have turned overlays off,
1233 ;; or if there's no overlay data
1234 ;; just bail out and return whatever face data we've accumulated so far
1235 (if (or (not (hfy-opt 'keep-overlays))
1236 (not (setq overlay-data (hfy-overlay-props-at p))))
1238 ;;(message "· %d: %s; %S; %s"
1239 ;; p face-name extra-props text-props)
1240 (or face-name base-face)) ;; no overlays or extra properties
1241 ;; collect any face data and any overlay data for processing:
1243 (push text-props overlay-data))
1244 (setq overlay-data (nreverse overlay-data))
1245 ;;(message "- %d: %s; %S; %s; %s"
1246 ;; p face-name extra-props text-props overlay-data)
1247 ;; remember the basic face name so we don't keep repeating its specs:
1248 (when face-name (setq base-face face-name))
1249 (dolist (P overlay-data)
1250 (let ((iprops (cadr (memq 'invisible P)))) ;FIXME: plist-get?
1251 ;;(message "(hfy-prop-invisible-p %S)" iprops)
1252 (when (and iprops (hfy-prop-invisible-p iprops))
1254 (cons :invisible (cons t extra-props))) ))
1255 (let ((fprops (cadr (or (memq 'face P)
1256 (memq 'font-lock-face P)))))
1257 ;;(message "overlay face: %s" fprops)
1258 (if (not (listp fprops))
1259 (let ((this-face (if (stringp fprops) (intern fprops) fprops)))
1260 (when (not (eq this-face base-face))
1263 (cons this-face extra-props))) ))
1265 (if (facep (car fprops))
1266 (let ((face (car fprops)))
1267 (when (stringp face) (setq face (intern fprops)))
1272 (setq fprops (cdr fprops)))
1275 (if (listp (car fprops))
1276 (if (nlistp (cdr (car fprops)))
1279 (setq p (caar fprops))
1280 (setq v (cdar fprops))
1281 (setq fprops (cdr fprops)))
1283 (setq p (caar fprops))
1284 (setq v (cadar fprops))
1285 (setq fprops (cdr fprops)))
1286 (if (listp (cdr fprops))
1288 ;; (:prop val :prop val ...)
1289 (setq p (car fprops))
1290 (setq v (cadr fprops))
1291 (setq fprops (cddr fprops)))
1292 (if (and (listp fprops)
1293 (not (listp (cdr fprops))))
1294 ;;(and (consp x) (cdr (last x)))
1297 (setq p (car fprops))
1298 (setq v (cdr fprops))
1300 (error "Eh... another format! fprops=%s" fprops) )))
1302 ;; These are all the properties handled
1303 ;; in `hfy-face-to-style-i'.
1305 ;; Are these translations right?
1306 ;; yes, they are -- v
1312 (underline :underline )
1313 (overline :overline )
1314 (strike-through :strike-through)
1316 (foreground-color :foreground)
1317 (background-color :background)
1321 (if (memq p prop-seen) nil ;; noop
1322 (setq prop-seen (cons p prop-seen)
1323 extra-props (cons p (cons v extra-props))))))))))
1324 ;;(message "+ %d: %s; %S" p face-name extra-props)
1326 (nconc extra-props (if (listp face-name)
1328 (face-attr-construct face-name)))
1331 (defun hfy-overlay-props-at (p)
1332 "Grab overlay properties at point P.
1333 The plists are returned in descending priority order."
1334 (mapcar #'overlay-properties (overlays-at p 'sorted)))
1336 ;; construct an assoc of (face-name . (css-name . "{ css-style }")) elements:
1337 (defun hfy-compile-stylesheet ()
1338 "Trawl the current buffer, construct and return a `hfy-sheet-assoc'.
1339 If `hfy-user-sheet-assoc' is currently bound then use it to
1340 collect new styles discovered during this run. Otherwise create
1342 ;;(message "hfy-compile-stylesheet");;DBUG
1343 (let ((pt (point-min))
1344 ;; Make the font stack stay:
1345 ;;(hfy-tmpfont-stack nil)
1347 (style (and (boundp 'hfy-user-sheet-assoc) hfy-user-sheet-assoc)))
1350 (while (< pt (point-max))
1351 (if (and (setq fn (hfy-face-at pt)) (not (assoc fn style)))
1352 (push (cons fn (funcall hfy-face-to-css fn)) style))
1353 (setq pt (next-char-property-change pt))))
1354 (unless (assoc 'default style)
1355 (push (cons 'default (funcall hfy-face-to-css 'default)) style))
1356 (when (boundp 'hfy-user-sheet-assoc)
1357 (setq hfy-user-sheet-assoc style))
1360 (defun hfy-fontified-p ()
1361 "`font-lock' doesn't like to say it's been fontified when in batch
1362 mode, but we want to know if we should fontify or raw copy, so in batch
1363 mode we check for non-default face properties. Otherwise we test
1364 variable `font-lock-mode' and variable `font-lock-fontified' for truth."
1365 ;;(message "font-lock-fontified: %S" font-lock-fontified)
1366 ;;(message "noninteractive : %S" noninteractive)
1367 ;;(message "font-lock-mode : %S" font-lock-mode)
1368 (and font-lock-fontified
1370 (let ((pt (point-min))
1374 (while (and (< pt (point-max)) (not face-name))
1375 (setq face-name (hfy-face-at pt))
1376 (setq pt (next-char-property-change pt))))
1380 ;; remember, the map is in reverse point order:
1381 ;; I wrote this while suffering the effects of a cold, and maybe a
1382 ;; mild fever - I think it's correct, but it might be a little warped
1383 ;; as my minfd keeps ... where was I? Oh yes, the bunnies...
1384 (defun hfy-merge-adjacent-spans (face-map)
1385 "Where FACE-MAP is a `hfy-facemap-assoc' for the current buffer,
1386 this function merges adjacent style blocks which are of the same value
1387 and are separated by nothing more interesting than whitespace.\n
1388 <span class=\"foo\">narf</span> <span class=\"foo\">brain</span>\n
1389 \(as interpreted from FACE-MAP) would become:\n
1390 <span class=\"foo\">narf brain</span>\n
1391 Returns a modified copy of FACE-MAP."
1392 (let ((tmp-map face-map)
1401 ;;(push (car tmp-map) reduced-map)
1402 ;;(push (cadr tmp-map) reduced-map)
1404 (setq first-start (cadddr tmp-map)
1405 first-stop (caddr tmp-map)
1406 last-start (cadr tmp-map)
1407 last-stop (car tmp-map)
1409 span-start last-start
1410 span-stop last-stop )
1411 (while (and (equal (cdr first-start)
1414 (goto-char (car first-stop))
1415 (not (re-search-forward "[^ \t\n\r]" (car last-start) t))))
1416 (setq map-buf (cddr map-buf)
1417 span-start first-start
1418 first-start (cadddr map-buf)
1419 first-stop (caddr map-buf)
1420 last-start (cadr map-buf)
1421 last-stop (car map-buf)))
1422 (push span-stop reduced-map)
1423 (push span-start reduced-map)
1424 (setq tmp-map (memq last-start tmp-map))
1425 (setq tmp-map (cdr tmp-map)))
1426 (setq reduced-map (nreverse reduced-map))))
1428 ;; remember to generate 'synthetic' </span> entries -
1429 ;; emacs copes by just having a stack of styles in effect
1430 ;; and only using the top one: html has a more simplistic approach -
1431 ;; we have to explicitly end a style, there's no way of temporarily
1432 ;; overriding it w. another one... (afaik)
1433 (defun hfy-compile-face-map ()
1434 ;; no need for special <a> version.
1435 ;; IME hyperlinks don't get underlined, esp when you htmlfontify a whole
1436 ;; source tree, so the <a> version is needed -- v
1437 ;; Fix-me: save table for multi-buffer
1438 "Compile and return a `hfy-facemap-assoc' for the current buffer."
1439 ;;(message "hfy-compile-face-map");;DBUG
1440 (let* ((pt (point-min))
1441 (pt-narrow (save-restriction (widen) (point-min)))
1442 (offset (- pt pt-narrow))
1445 (prev-tag nil)) ;; t if the last tag-point was a span-start
1446 ;; nil if it was a span-stop
1449 (while (< pt (point-max))
1450 (if (setq fn (hfy-face-at pt))
1451 (progn (if prev-tag (push (cons pt-narrow 'end) map))
1452 (push (cons pt-narrow fn) map)
1454 (if prev-tag (push (cons pt-narrow 'end) map))
1455 (setq prev-tag nil))
1456 (setq pt (next-char-property-change pt))
1457 (setq pt-narrow (+ offset pt)))
1458 (if (and map (not (eq 'end (cdar map))))
1459 (push (cons (1+ (- (point-max) (point-min))) 'end) map)))
1460 (if (hfy-opt 'merge-adjacent-tags) (hfy-merge-adjacent-spans map) map)))
1462 (defun hfy-buffer ()
1463 "Generate a buffer to hold the HTML output.
1464 The filename of this buffer is derived from the source (current) buffer's
1465 variable `buffer-file-name', if it is set, plus `hfy-extn'.
1466 Otherwise a plausible filename is constructed from `default-directory',
1467 `buffer-name' and `hfy-extn'."
1468 (let* ((name (concat (buffer-name) hfy-extn))
1469 (src (buffer-file-name))
1470 (buf (get-buffer-create name)))
1471 (with-current-buffer buf
1472 (setq buffer-file-name
1473 (if src (concat src hfy-extn)
1474 (expand-file-name (if (string-match "^.*/\\([^/]*\\)\\'" name)
1475 (match-string 1 name)
1479 (defun hfy-lookup (face style)
1480 "Get a CSS style name for FACE from STYLE."
1481 (cadr (assoc face style)))
1483 (defun hfy-link-style (style-string)
1484 "Copy, alter and return a STYLE-STRING to make it suitable for a hyperlink.
1485 Uses `hfy-link-style-fun' to do this."
1486 (if (functionp hfy-link-style-fun)
1487 (funcall hfy-link-style-fun style-string)
1490 (defun hfy-sprintf-stylesheet (css file)
1491 "Return the inline CSS style sheet for FILE as a string."
1495 "\n<style type=\"text/css\"><!-- \n"
1496 ;; Fix-me: Add handling of page breaks here + scan for ^L
1497 ;; where appropriate.
1498 (format "body %s\n" (cddr (assq 'default css)))
1503 "span.%s %s\nspan.%s a %s\n"
1504 (cadr style) (cddr style)
1505 (cadr style) (hfy-link-style (cddr style))))
1508 (funcall hfy-page-header file stylesheet)))
1510 ;; tag all the dangerous characters we want to escape
1511 ;; (ie any "<> chars we _didn't_ put there explicitly for css markup)
1512 (defun hfy-html-enkludge-buffer ()
1513 "Mark dangerous [\"<>] characters with the `hfy-quoteme' property.\n
1514 See also `hfy-html-dekludge-buffer'."
1515 ;;(message "hfy-html-enkludge-buffer");;DBUG
1517 (goto-char (point-min))
1518 (while (re-search-forward hfy-html-quote-regex nil t)
1519 (put-text-property (match-beginning 0) (point) 'hfy-quoteme t))) )
1521 ;; dangerous char -> &entity;
1522 (defun hfy-html-quote (char-string)
1523 "Map CHAR-STRING to an HTML safe string (entity) if need be."
1524 ;;(message "hfy-html-quote");;DBUG
1525 (or (cadr (assoc char-string hfy-html-quote-map)) char-string) )
1527 ;; actually entity-ise dangerous chars.
1528 ;; note that we can't do this until _after_ we have inserted the css
1529 ;; markup, since we use a position-based map to insert this, and if we
1530 ;; enter any other text before we do this, we'd have to track another
1531 ;; map of offsets, which would be tedious...
1532 (defun hfy-html-dekludge-buffer ()
1533 "Transform all dangerous characters marked with the `hfy-quoteme' property
1534 using `hfy-html-quote'.\n
1535 See also `hfy-html-enkludge-buffer'."
1536 ;;(message "hfy-html-dekludge-buffer");;DBUG
1538 (goto-char (point-min))
1539 (while (re-search-forward hfy-html-quote-regex nil t)
1540 (if (get-text-property (match-beginning 0) 'hfy-quoteme)
1541 (replace-match (hfy-html-quote (match-string 1))) )) ))
1543 ;; Borrowed from font-lock.el
1544 (defmacro hfy-save-buffer-state (varlist &rest body)
1545 "Bind variables according to VARLIST and eval BODY restoring buffer state.
1546 Do not record undo information during evaluation of BODY."
1547 (declare (indent 1) (debug let))
1548 (let ((modified (make-symbol "modified")))
1549 `(let* ,(append varlist
1550 `((,modified (buffer-modified-p))
1551 (buffer-undo-list t)
1552 (inhibit-read-only t)
1553 (inhibit-point-motion-hooks t)
1554 (inhibit-modification-hooks t)
1557 buffer-file-truename))
1561 (restore-buffer-modified-p nil)))))
1563 (defun hfy-mark-trailing-whitespace ()
1564 "Tag trailing whitespace with a hfy property if it is currently highlighted."
1565 (when show-trailing-whitespace
1566 (let ((inhibit-read-only t))
1568 (goto-char (point-min))
1569 (hfy-save-buffer-state nil
1570 (while (re-search-forward "[ \t]+$" nil t)
1571 (put-text-property (match-beginning 0) (match-end 0)
1572 'hfy-show-trailing-whitespace t)))))))
1574 (defun hfy-unmark-trailing-whitespace ()
1575 "Undo the effect of `hfy-mark-trailing-whitespace'."
1576 (when show-trailing-whitespace
1577 (hfy-save-buffer-state nil
1578 (remove-text-properties (point-min) (point-max)
1579 '(hfy-show-trailing-whitespace)))))
1581 (defun hfy-begin-span (style text-block text-id text-begins-block-p)
1582 "Default handler to begin a span of text.
1583 Insert \"<span class=\"STYLE\" ...>\". See
1584 `hfy-begin-span-handler' for more information."
1585 (when text-begins-block-p
1587 (format "<span onclick=\"toggle_invis('%s');\">…</span>" text-block)))
1591 (format "<span class=\"%s\" id=\"%s-%d\">" style text-block text-id)
1592 (format "<span class=\"%s\">" style))))
1594 (defun hfy-end-span ()
1595 "Default handler to end a span of text.
1596 Insert \"</span>\". See `hfy-end-span-handler' for more
1600 (defvar hfy-begin-span-handler 'hfy-begin-span
1601 "Handler to begin a span of text.
1602 The signature of the handler is \(lambda (STYLE TEXT-BLOCK
1603 TEXT-ID TEXT-BEGINS-BLOCK-P) ...). The handler must insert
1604 appropriate tags to begin a span of text.
1606 STYLE is the name of the style that begins at point. It is
1607 derived from the face attributes as part of `hfy-face-to-css'
1608 callback. The other arguments TEXT-BLOCK, TEXT-ID,
1609 TEXT-BEGINS-BLOCK-P are non-nil only if the buffer contains
1612 TEXT-BLOCK is a string that identifies a single chunk of visible
1613 or invisible text of which the current position is a part. For
1614 visible portions, it's value is \"nil\". For invisible portions,
1615 it's value is computed as part of `hfy-invisible-name'.
1617 TEXT-ID marks a unique position within a block. It is set to
1618 value of `point' at the current buffer position.
1620 TEXT-BEGINS-BLOCK-P is a boolean and is non-nil if the current
1621 span also begins a invisible portion of text.
1623 An implementation can use TEXT-BLOCK, TEXT-ID,
1624 TEXT-BEGINS-BLOCK-P to implement fold/unfold-on-mouse-click like
1627 The default handler is `hfy-begin-span'.")
1629 (defvar hfy-end-span-handler 'hfy-end-span
1630 "Handler to end a span of text.
1631 The signature of the handler is \(lambda () ...). The handler
1632 must insert appropriate tags to end a span of text.
1634 The default handler is `hfy-end-span'.")
1636 (defun hfy-fontify-buffer (&optional srcdir file)
1637 "Implement the guts of `htmlfontify-buffer'.
1638 SRCDIR, if set, is the directory being htmlfontified.
1639 FILE, if set, is the file name."
1640 (if srcdir (setq srcdir (directory-file-name srcdir)))
1641 (let* ( (html-buffer (hfy-buffer))
1646 (rmin (when mark-active (region-beginning)))
1647 (rmax (when mark-active (region-end ))) )
1648 (when (and mark-active
1649 transient-mark-mode)
1650 (unless (and (= rmin (point-min))
1651 (= rmax (point-max)))
1652 (setq rovl (make-overlay rmin rmax))
1653 (overlay-put rovl 'priority 1000)
1654 (overlay-put rovl 'face 'region)))
1655 ;; copy the buffer, including fontification, and switch to it:
1656 (hfy-mark-trailing-whitespace)
1657 (setq css-sheet (hfy-compile-stylesheet )
1658 css-map (hfy-compile-face-map )
1659 invis-ranges (hfy-find-invisible-ranges))
1660 (hfy-unmark-trailing-whitespace)
1662 (delete-overlay rovl))
1663 (copy-to-buffer html-buffer (point-min) (point-max))
1664 (set-buffer html-buffer)
1665 ;; rip out props that could interfere with our htmlization of the buffer:
1666 (remove-text-properties (point-min) (point-max) hfy-ignored-properties)
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)
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>...
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))
1713 (or (get-text-property pt 'hfy-linkp)
1714 (get-text-property pt 'hfy-endl )))
1716 (funcall hfy-end-span-handler)
1717 (if (not (and srcdir file))
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)
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 ;; #####################################################################
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)
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
1758 (remove-text-properties pt (1+ pt) (list lp nil))
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))
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\">"))
1785 (goto-char (point-max))
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-hook)
1792 ;; return the html buffer
1793 (set-buffer-modified-p nil)
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-optimizations-1 (copy-sequence hfy-optimizations))
1802 (hfy-optimizations (add-to-list 'hfy-optimizations-1
1803 'skip-refontification)))
1806 (htmlfontify-buffer)
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 (setq font-lock-cache-position (make-marker))))
1818 (message "hfy batch mode (%s:%S)"
1819 (or (buffer-file-name) (buffer-name)) major-mode)
1820 (if (fboundp 'font-lock-ensure)
1822 (when font-lock-defaults
1823 (font-lock-fontify-buffer))))
1824 ((fboundp #'jit-lock-fontify-now)
1825 (message "hfy jit-lock mode (%S %S)" window-system major-mode)
1826 (jit-lock-fontify-now))
1828 (message "hfy interactive mode (%S %S)" window-system major-mode)
1829 ;; If jit-lock is not in use, then the buffer is already fontified!
1830 ;; (when (and font-lock-defaults
1832 ;; (font-lock-fontify-region (point-min) (point-max) nil))
1836 (defun htmlfontify-buffer (&optional srcdir file)
1837 "Create a new buffer, named for the current buffer + a .html extension,
1838 containing an inline CSS-stylesheet and formatted CSS-markup HTML
1839 that reproduces the look of the current Emacs buffer as closely
1842 Dangerous characters in the existing buffer are turned into HTML
1843 entities, so you should even be able to do HTML-within-HTML
1846 You should, however, note that random control or eight-bit
1847 characters such as ^L (\x0c) or ¤ (\xa4) won't get mapped yet.
1849 If the SRCDIR and FILE arguments are set, lookup etags derived
1850 entries in the `hfy-tags-cache' and add HTML anchors and
1851 hyperlinks as appropriate."
1853 ;; pick up the file name in case we didn't receive it
1855 (progn (setq file (or (buffer-file-name) (buffer-name)))
1856 (if (string-match "/\\([^/]*\\)\\'" file)
1857 (setq file (match-string 1 file)))) )
1859 (if (not (hfy-opt 'skip-refontification))
1860 (save-excursion ;; Keep region
1861 (hfy-force-fontification)))
1862 (if (called-interactively-p 'any) ;; display the buffer in interactive mode:
1863 (switch-to-buffer (hfy-fontify-buffer srcdir file))
1864 (hfy-fontify-buffer srcdir file)))
1866 ;; recursive file listing
1867 (defun hfy-list-files (directory)
1868 "Return a list of files under DIRECTORY.
1869 Strips any leading \"./\" from each filename."
1870 ;;(message "hfy-list-files");;DBUG
1871 ;; FIXME: this changes the dir of the current buffer. Is that right??
1873 (mapcar (lambda (F) (if (string-match "^./\\(.*\\)" F) (match-string 1 F) F))
1874 (split-string (shell-command-to-string hfy-find-cmd))) )
1876 ;; strip the filename off, return a directory name
1877 ;; not a particularly thorough implementation, but it will be
1878 ;; fed pretty carefully, so it should be Ok:
1879 (defun hfy-dirname (file)
1880 "Return everything preceding the last \"/\" from a relative filename FILE,
1881 on the assumption that this will produce a relative directory name.
1882 Hardly bombproof, but good enough in the context in which it is being used."
1883 ;;(message "hfy-dirname");;DBUG
1884 (let ((f (directory-file-name file)))
1885 (and (string-match "^\\(.*\\)/" f) (match-string 1 f))))
1887 ;; create a directory, cf mkdir -p
1888 (defun hfy-make-directory (dir)
1889 "Approx. equivalent of mkdir -p DIR."
1890 ;;(message "hfy-make-directory");;DBUG
1891 (if (file-exists-p dir)
1892 (if (file-directory-p dir) t)
1893 (make-directory dir t)))
1895 (defun hfy-text-p (srcdir file)
1896 "Is SRCDIR/FILE text? Uses `hfy-istext-command' to determine this."
1897 (let* ((cmd (format hfy-istext-command (expand-file-name file srcdir)))
1898 (rsp (shell-command-to-string cmd)))
1899 (string-match "text" rsp)))
1901 ;; open a file, check fontification, if fontified, write a fontified copy
1902 ;; to the destination directory, otherwise just copy the file:
1903 (defun hfy-copy-and-fontify-file (srcdir dstdir file)
1904 "Open FILE in SRCDIR - if fontified, write a fontified copy to DSTDIR
1905 adding an extension of `hfy-extn'. Fontification is actually done by
1906 `htmlfontify-buffer'. If the buffer is not fontified, just copy it."
1907 ;;(message "hfy-copy-and-fontify-file");;DBUG
1908 (let (;;(fast-lock-minimum-size hfy-fast-lock-save)
1909 ;;(font-lock-support-mode 'fast-lock-mode)
1910 ;;(window-system (or window-system 'htmlfontify))
1915 (with-current-buffer (setq source (find-file-noselect file))
1916 ;; FIXME: Shouldn't this use expand-file-name? --Stef
1917 (setq target (concat dstdir "/" file))
1918 (hfy-make-directory (hfy-dirname target))
1919 (if (not (hfy-opt 'skip-refontification)) (hfy-force-fontification))
1920 (if (or (hfy-fontified-p) (hfy-text-p srcdir file))
1921 (progn (setq html (hfy-fontify-buffer srcdir file))
1923 (write-file (concat target hfy-extn))
1925 ;; #o0200 == 128, but emacs20 doesn't know that
1926 (if (and (file-exists-p target) (not (file-writable-p target)))
1927 (set-file-modes target (logior (file-modes target) 128)))
1928 (copy-file (buffer-file-name source) target 'overwrite))
1929 (kill-buffer source)) ))
1931 ;; list of tags in file in srcdir
1932 (defun hfy-tags-for-file (cache-hash file)
1933 "List of etags tags that have definitions in this FILE.
1934 CACHE-HASH is the tags cache."
1935 ;;(message "hfy-tags-for-file");;DBUG
1936 (let* ((tag-list nil))
1941 (setq tag-list (cons K tag-list))))
1945 ;; mark the tags native to this file for anchors
1946 (defun hfy-mark-tag-names (srcdir file)
1947 "Mark tags in FILE (lookup SRCDIR in `hfy-tags-cache') with the `hfy-anchor'
1948 property, with a value of \"tag.line-number\"."
1949 ;;(message "(hfy-mark-tag-names %s %s)" srcdir file);;DBUG
1950 (let* ((cache-entry (assoc srcdir hfy-tags-cache))
1951 (cache-hash (cadr cache-entry)))
1957 (if (string= file (car TLIST))
1958 (let* ((line (cadr TLIST) )
1959 (chr (caddr TLIST) )
1960 (link (format "%s.%d" TAG line) ))
1961 (put-text-property (+ 1 chr)
1963 'hfy-anchor link))))
1964 (gethash TAG cache-hash)))
1965 (hfy-tags-for-file cache-hash file)))))
1967 (defun hfy-relstub (file &optional start)
1968 "Return a \"../\" stub of the appropriate length for the current source
1969 tree depth, as determined from FILE (a filename).
1970 START is the offset at which to start looking for the / character in FILE."
1971 ;;(message "hfy-relstub");;DBUG
1973 (while (setq start (string-match "/" file start))
1974 (setq start (1+ start)) (setq c (concat c "../")))
1977 (defun hfy-href-stub (this-file def-files tag)
1978 "Return an href stub for a tag href in THIS-FILE.
1979 If DEF-FILES (list of files containing definitions for the tag in question)
1980 contains only one entry, the href should link straight to that file.
1981 Otherwise, the link should be to the index file.\n
1982 We are not yet concerned with the file extensions/tag line number and so on at
1984 If `hfy-split-index' is set, and the href wil be to an index file rather than
1985 a source file, append a .X to `hfy-index-file', where X is the uppercased
1986 first character of TAG.\n
1987 See also `hfy-relstub', `hfy-index-file'."
1988 ;;(message "hfy-href-stub");;DBUG
1989 ;; FIXME: Why not use something like
1990 ;; (file-relative-name (if ...) (file-name-directory this-file)) ? --Stef
1992 (hfy-relstub this-file)
1993 (if (= 1 (length def-files)) (car def-files)
1994 (if (not hfy-split-index) hfy-index-file
1995 (concat hfy-index-file "." (upcase (substring tag 0 1)))))) )
1997 (defun hfy-href (this-file def-files tag tag-map)
1998 "Return a relative href to the tag in question, based on\n
1999 THIS-FILE `hfy-link-extn' `hfy-extn' DEF-FILES TAG and TAG-MAP\n
2000 THIS-FILE is the current source file
2001 DEF-FILES is a list of file containing possible link endpoints for TAG
2002 TAG is the tag in question
2003 TAG-MAP is the entry in `hfy-tags-cache'."
2004 ;;(message "hfy-href");;DBUG
2006 (hfy-href-stub this-file def-files tag)
2007 (or hfy-link-extn hfy-extn) "#" tag ;;(.src -> .html)
2008 (if (= 1 (length def-files))
2009 (concat "." (format "%d" (cadr (assoc (car def-files) tag-map)))))) )
2011 (defun hfy-word-regex (string)
2012 "Return a regex that matches STRING as the first `match-string', with non
2013 word characters on either side."
2014 ;; FIXME: Should this use [^$[:alnum:]_] instead? --Stef
2015 (concat "[^$A-Za-z_0-9]\\(" (regexp-quote string) "\\)[^A-Za-z_0-9]"))
2017 ;; mark all tags for hyperlinking, except the tags at
2018 ;; their own points of definition, iyswim:
2019 (defun hfy-mark-tag-hrefs (srcdir file)
2020 "Mark href start points with the `hfy-link' prop (value: href string).\n
2021 Mark href end points with the `hfy-endl' prop (value t).\n
2022 Avoid overlapping links, and mark links in descending length of
2023 tag name in order to prevent subtags from usurping supertags,
2024 \(eg \"term\" for \"terminal\").
2025 SRCDIR is the directory being \"published\".
2026 FILE is the specific file we are rendering."
2027 ;;(message "hfy-mark-tag-hrefs");;DBUG
2028 (let ((cache-entry (assoc srcdir hfy-tags-cache))
2029 (list-cache (assoc srcdir hfy-tags-sortl))
2030 (rmap-cache (assoc srcdir hfy-tags-rmap ))
2031 (no-comment (hfy-opt 'zap-comment-links))
2032 (no-strings (hfy-opt 'zap-string-links ))
2036 (case-fold-search nil))
2037 ;; extract the tag mapping hashes (fwd and rev) and the tag list:
2038 (if (and (setq cache-hash (cadr cache-entry))
2039 (setq tags-rmap (cadr rmap-cache ))
2040 (setq tags-list (cadr list-cache )))
2047 (case-fold-search nil)
2054 (tag-regex (hfy-word-regex TAG))
2055 (tag-map (gethash TAG cache-hash))
2056 (tag-files (mapcar #'car tag-map)))
2057 ;; find instances of TAG and do what needs to be done:
2058 (goto-char (point-min))
2059 (while (search-forward TAG nil 'NOERROR)
2060 (setq tmp-point (point)
2061 maybe-start (- (match-beginning 0) 1))
2062 (goto-char maybe-start)
2063 (if (not (looking-at tag-regex))
2065 (setq start (match-beginning 1))
2066 (setq stop (match-end 1))
2068 (and (or no-comment no-strings) (hfy-face-at start)))
2070 (setq face-at (cadr (memq :inherit face-at))))
2071 (if (or (text-property-any start (1+ stop) 'hfy-linkp t)
2072 (and no-comment (eq 'font-lock-comment-face face-at))
2073 (and no-strings (eq 'font-lock-string-face face-at)))
2074 nil ;; already a link, NOOP
2076 ;; set a reverse map entry:
2077 (setq rmap-line (line-number-at-pos)
2078 rmap-entry (gethash TAG tags-rmap)
2079 rnew-elt (list file rmap-line start)
2080 rmap-entry (cons rnew-elt rmap-entry)
2081 name (format "%s.%d" TAG rmap-line))
2082 (put-text-property start (1+ start) 'hfy-inst name)
2083 (puthash TAG rmap-entry tags-rmap)
2085 ;; mark the link. link to index if the tag has > 1 def
2086 ;; add the line number to the #name if it does not:
2087 (setq href (hfy-href file tag-files TAG tag-map))
2088 (put-text-property start (1+ start) 'hfy-link href)
2089 (put-text-property stop (1+ stop ) 'hfy-endl t )
2090 (put-text-property start (1+ stop ) 'hfy-linkp t )))
2091 (goto-char tmp-point)) ))
2095 "Return `shell-file-name', or \"/bin/sh\" if it is a non-Bourne shell."
2096 (if (string-match "\\<bash\\>\\|\\<sh\\>\\|\\<dash\\>" shell-file-name)
2098 (or hfy-shell-file-name "/bin/sh")))
2100 ;; cache the #(tag => file line point) entries for files under srcdir
2101 ;; and cache the descending sorted list of tags in the relevant alist,
2102 ;; also keyed by srcdir:
2103 (defun hfy-load-tags-cache (srcdir)
2104 "Run `hfy-etags-cmd' on SRCDIR, then call `hfy-parse-tags-buffer'."
2105 ;;(message "hfy-load-tags-cache");;DBUG
2106 (let ((etags-buffer (get-buffer-create "*hfy-tags*"))
2107 (etags-command (format hfy-etags-cmd hfy-etags-bin))
2108 (shell-file-name (hfy-shell)))
2110 (shell-command etags-command etags-buffer)
2111 (hfy-parse-tags-buffer srcdir etags-buffer)) )
2113 ;; break this out from `hfy-load-tags-cache' to make the tar file
2114 ;; functionality easier to implement.
2115 ;; ( tar file functionality not merged here because it requires a
2116 ;; hacked copy of etags capable of tagging stdin: if Francesco
2117 ;; Potortì accepts a patch, or otherwise implements stdin tagging,
2118 ;; then I will provide a `htmlfontify-tar-file' defun )
2119 (defun hfy-parse-tags-buffer (srcdir buffer)
2120 "Parse a BUFFER containing etags formatted output, loading the
2121 `hfy-tags-cache' and `hfy-tags-sortl' entries for SRCDIR."
2122 (let ((cache-entry (assoc srcdir hfy-tags-cache))
2123 (tlist-cache (assoc srcdir hfy-tags-sortl))
2124 (trmap-cache (assoc srcdir hfy-tags-rmap ))
2125 (cache-hash nil) (trmap-hash nil) (tags-list nil)
2126 (hash-entry nil) (tag-string nil) (tag-line nil)
2127 (tag-point nil) (new-entry nil) (etags-file nil))
2129 ;; (re)initialize the tag reverse map:
2130 (if trmap-cache (setq trmap-hash (cadr trmap-cache))
2131 (setq trmap-hash (make-hash-table :test 'equal))
2132 (setq hfy-tags-rmap (list (list srcdir trmap-hash) hfy-tags-rmap)))
2133 (clrhash trmap-hash)
2135 ;; (re)initialize the tag cache:
2136 (if cache-entry (setq cache-hash (cadr cache-entry))
2137 (setq cache-hash (make-hash-table :test 'equal))
2138 (setq hfy-tags-cache (list (list srcdir cache-hash) hfy-tags-cache)))
2139 (clrhash cache-hash)
2141 ;; cache the TAG => ((file line point) (file line point) ... ) entries:
2142 (with-current-buffer buffer
2143 (goto-char (point-min))
2145 (while (and (looking-at "^\x0c") (= 0 (forward-line 1)))
2146 ;;(message "^L boundary")
2147 (if (and (looking-at "^\\(.+\\),\\([0-9]+\\)$")
2148 (= 0 (forward-line 1)))
2150 (setq etags-file (match-string 1))
2151 ;;(message "TAGS for file: %s" etags-file)
2152 (while (and (looking-at hfy-etag-regex) (= 0 (forward-line 1)))
2153 (setq tag-string (match-string 1))
2154 (if (= 0 (length tag-string)) nil ;; noop
2155 (setq tag-line (round (string-to-number (match-string 2))))
2156 (setq tag-point (round (string-to-number (match-string 3))))
2157 (setq hash-entry (gethash tag-string cache-hash))
2158 (setq new-entry (list etags-file tag-line tag-point))
2159 (push new-entry hash-entry)
2160 ;;(message "HASH-ENTRY %s %S" tag-string new-entry)
2161 (puthash tag-string hash-entry cache-hash)))) )))
2163 ;; cache a list of tags in descending length order:
2164 (maphash (lambda (K _V) (push K tags-list)) cache-hash)
2165 (setq tags-list (sort tags-list (lambda (A B) (< (length B) (length A)))))
2167 ;; put the tag list into the cache:
2168 (if tlist-cache (setcar (cdr tlist-cache) tags-list)
2169 (push (list srcdir tags-list) hfy-tags-sortl))
2171 ;; return the number of tags found:
2172 (length tags-list) ))
2174 (defun hfy-prepare-index-i (srcdir dstdir filename &optional stub map)
2175 "Prepare a tags index buffer for SRCDIR.
2176 `hfy-tags-cache' must already have an entry for SRCDIR for this to work.
2177 `hfy-page-header', `hfy-page-footer', `hfy-link-extn' and `hfy-extn'
2178 all play a part here.\n
2179 If STUB is set, prepare an (appropriately named) index buffer
2180 specifically for entries beginning with STUB.\n
2181 If MAP is set, use that instead of `hfy-tags-cache'.
2182 FILENAME is the name of the file being indexed.
2183 DSTDIR is the output directory, where files will be written."
2184 ;;(message "hfy-write-index");;DBUG
2185 (let ((cache-entry (assoc srcdir (or map hfy-tags-cache)))
2189 (concat filename (if stub (concat "." stub) "") hfy-extn))
2191 (if (not (and cache-entry
2192 (setq cache-hash (cadr cache-entry))
2193 (setq index-buf (get-buffer-create index-file))))
2195 (maphash (lambda (K _V) (push K tag-list)) cache-hash)
2196 (setq tag-list (sort tag-list 'string<))
2197 (set-buffer index-buf)
2199 (insert (funcall hfy-page-header filename "<!-- CSS -->"))
2200 (insert "<table class=\"index\">\n")
2202 (dolist (TAG tag-list)
2203 (let ((tag-started nil))
2204 (dolist (DEF (gethash TAG cache-hash))
2205 (if (and stub (not (string-match (concat "^" stub) TAG)))
2206 nil ;; we have a stub and it didn't match: NOOP
2207 (let ((file (car DEF))
2214 " <td><a href=\"%s%s\">%s</a></td> \n"
2215 " <td><a href=\"%s%s#%s.%d\">%d</a></td>\n"
2217 (if (string= TAG tag-started) " "
2218 (format "<a name=\"%s\">%s</a>" TAG TAG))
2219 file (or hfy-link-extn hfy-extn) file
2220 file (or hfy-link-extn hfy-extn) TAG line line))
2221 (setq tag-started TAG))))))
2222 (insert "</table>\n")
2223 (insert (funcall hfy-page-footer filename))
2224 (and dstdir (cd dstdir))
2225 (set-visited-file-name index-file)
2228 (defun hfy-prepare-index (srcdir dstdir)
2229 "Return a list of index buffer(s), as determined by `hfy-split-index'.
2230 SRCDIR and DSTDIR are the source and output directories respectively."
2231 (if (not hfy-split-index)
2232 (list (hfy-prepare-index-i srcdir dstdir hfy-index-file nil))
2233 (let ((stub-list nil)
2236 (cache-entry (assoc srcdir hfy-tags-cache)))
2237 (if (and cache-entry (setq cache-hash (cadr cache-entry)))
2240 (let ((stub (upcase (substring K 0 1))))
2241 (if (member stub stub-list)
2242 nil ;; seen this already: NOOP
2244 stub-list (cons stub stub-list)
2245 index-list (cons (hfy-prepare-index-i srcdir
2253 (defun hfy-prepare-tag-map (srcdir dstdir)
2254 "Prepare the counterpart(s) to the index buffer(s) - a list of buffers
2255 with the same structure, but listing (and linking to) instances of tags
2256 \(as opposed to their definitions).\n
2257 SRCDIR and DSTDIR are the source and output directories respectively.
2258 See also `hfy-prepare-index', `hfy-split-index'."
2259 (if (not hfy-split-index)
2260 (list (hfy-prepare-index-i srcdir
2265 (let ((stub-list nil)
2268 (cache-entry (assoc srcdir hfy-tags-rmap)))
2270 (if (and cache-entry (setq cache-hash (cadr cache-entry)))
2273 (let ((stub (upcase (substring K 0 1))))
2274 (if (member stub stub-list)
2275 nil ;; seen this already: NOOP
2277 stub-list (cons stub stub-list)
2278 index-list (cons (hfy-prepare-index-i srcdir
2287 (defun hfy-subtract-maps (srcdir)
2288 "Internal function - strips definitions of tags from the instance map.
2289 SRCDIR is the directory being \"published\".
2290 See also `hfy-tags-cache', `hfy-tags-rmap'."
2291 (let ((new-list nil)
2295 (fwd-map (cadr (assoc srcdir hfy-tags-cache)))
2296 (rev-map (cadr (assoc srcdir hfy-tags-rmap )))
2297 (taglist (cadr (assoc srcdir hfy-tags-sortl))))
2298 (dolist (TAG taglist)
2299 (setq def-list (gethash TAG fwd-map)
2300 old-list (gethash TAG rev-map)
2301 exc-list (mapcar (lambda (P) (list (car P) (cadr P))) def-list)
2303 (dolist (P old-list)
2304 (or (member (list (car P) (cadr P)) exc-list)
2306 (puthash TAG new-list rev-map))))
2308 (defun htmlfontify-run-etags (srcdir)
2309 "Load the etags cache for SRCDIR.
2310 See also `hfy-load-tags-cache'."
2311 (interactive "D source directory: ")
2312 (hfy-load-tags-cache (directory-file-name srcdir)))
2314 ;;(defun hfy-test-read-args (foo bar)
2315 ;; (interactive "D source directory: \nD target directory: ")
2316 ;; (message "foo: %S\nbar: %S" foo bar))
2318 (defun hfy-save-kill-buffers (buffer-list &optional dstdir)
2319 (dolist (B buffer-list)
2321 (and dstdir (file-directory-p dstdir) (cd dstdir))
2326 (defun htmlfontify-copy-and-link-dir (srcdir dstdir &optional f-ext l-ext)
2327 "Trawl SRCDIR and write fontified-and-hyperlinked output in DSTDIR.
2328 F-EXT and L-EXT specify values for `hfy-extn' and `hfy-link-extn'.\n
2329 You may also want to set `hfy-page-header' and `hfy-page-footer'."
2330 (interactive "D source directory: \nD output directory: ")
2331 ;;(message "htmlfontify-copy-and-link-dir")
2332 (setq srcdir (directory-file-name srcdir))
2333 (setq dstdir (directory-file-name dstdir))
2334 (let ((source-files "SETME: list of source files, relative to srcdir")
2335 (tr-cache (assoc srcdir hfy-tags-rmap))
2336 (hfy-extn (or f-ext ".html"))
2337 (hfy-link-extn (or l-ext ".html")))
2338 ;; oops, forgot to load etags for srcdir:
2340 (message "autoload of tags cache")
2341 (hfy-load-tags-cache srcdir)
2342 (setq tr-cache (assoc srcdir hfy-tags-rmap)))
2343 ;; clear out the old cache:
2344 (clrhash (cadr tr-cache))
2345 (hfy-make-directory dstdir)
2346 (setq source-files (hfy-list-files srcdir))
2347 (dolist (file source-files)
2348 (hfy-copy-and-fontify-file srcdir dstdir file))
2349 (hfy-subtract-maps srcdir)
2350 (hfy-save-kill-buffers (hfy-prepare-index srcdir dstdir) dstdir)
2351 (hfy-save-kill-buffers (hfy-prepare-tag-map srcdir dstdir) dstdir) ))
2353 ;; name of the init file we want:
2354 (defun hfy-initfile ()
2355 "Return the expected location of the htmlfontify specific init/custom file."
2356 (let* ((file (or (getenv "HFY_INITFILE") ".hfy.el")))
2357 (expand-file-name file "~") ))
2360 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2361 ;; incomplete as yet : transfer hook settings to hfy init file:
2362 ;; (defalias 'hfy-set-hooks 'custom-set-variables)
2364 ;; (defun hfy-pp-hook (H)
2365 ;; (and (string-match "-hook\\'" (symbol-name H))
2368 ;; (insert (format "\n '(%S %S)" H (symbol-value H)))
2372 ;; (defun hfy-save-hooks ()
2373 ;; (let ((custom-file (hfy-initfile)))
2374 ;; (custom-save-delete 'hfy-set-hooks)
2375 ;; (let ((standard-output (current-buffer)))
2376 ;; (princ "(hfy-set-hooks\n;;auto-generated, only one copy allowed\n")
2377 ;; (mapatoms 'hfy-pp-hook)
2382 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2384 (defalias 'hfy-init-progn 'progn)
2386 (defun hfy-save-initvar (sym)
2387 (princ (format "(setq %s\n '" sym))
2388 (pp (symbol-value sym))
2391 (defun htmlfontify-save-initfile ()
2392 "Save the htmlfontify settings to the htmlfontify init file."
2394 (let* ((start-pos nil)
2395 (custom-file (hfy-initfile))
2396 (standard-output (find-file-noselect custom-file 'nowarn)))
2398 (custom-save-delete 'hfy-init-progn)
2399 (setq start-pos (point))
2400 (princ "(hfy-init-progn\n;;auto-generated, only one copy allowed\n")
2401 ;; FIXME: This saving&restoring of global customization
2402 ;; variables can interfere with other customization settings for
2403 ;; those vars (in .emacs or in Customize).
2404 (mapc 'hfy-save-initvar
2405 '(auto-mode-alist interpreter-mode-alist))
2407 (indent-region start-pos (point) nil))
2408 (custom-save-all) ))
2410 (defun htmlfontify-load-initfile ()
2411 "Load the htmlfontify specific init/custom file."
2413 (let ((file (hfy-initfile)))
2414 (load file 'NOERROR nil nil) ))
2416 (provide 'htmlfontify)
2418 ;;; htmlfontify.el ends here