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