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