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