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