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