(vc-bzr-annotate-command): Make operation asynchronous.
[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 }
696--> </script>
697 </head>
698 <body onload=\"stripe('index'); return true;\">\n"
699 file style))
700
701(defun hfy-default-footer (file)
702 "Default value for `hfy-page-footer'.
703FILE is the name of the file being rendered, in case it is needed."
704 "\n </body>\n</html>\n")
705
706(defun hfy-link-style-string (style-string)
707 "Replace the end of a css style declaration STYLE-STRING with the contents
708of the variable `hfy-src-doc-link-style', removing text matching the regex
709`hfy-src-doc-link-unstyle' first, if necessary."
710 ;;(message "hfy-colour-vals");;DBUG
711 (if (string-match hfy-src-doc-link-unstyle style-string)
712 (setq style-string (replace-match "" 'fixed-case 'literal style-string)))
713 (if (and (not (string-match hfy-src-doc-link-style style-string))
714 (string-match "} *$" style-string))
715 (concat (replace-match hfy-src-doc-link-style
716 'fixed-case
717 'literal
718 style-string) " }") style-string))
719
720;; utility functions - cast emacs style specification values into their
721;; css2 equivalents:
722(defun hfy-triplet (colour)
723 "Takes a COLOUR name \(string\) and return a CSS rgb(R, G, B) triplet string.
724Uses the definition of \"white\" to map the numbers to the 0-255 range, so
725if you\'ve redefined white, \(esp if you've redefined it to have a triplet
726member lower than that of the colour you are processing, strange things
727may happen\)."
728 ;;(message "hfy-colour-vals");;DBUG
729 (let ((white (mapcar (lambda (I) (float (1+ I))) (hfy-colour-vals "white")))
730 (rgb16 (mapcar (lambda (I) (float (1+ I))) (hfy-colour-vals colour))))
731 (if rgb16
732 ;;(apply 'format "rgb(%d, %d, %d)"
733 ;; Use #rrggbb instead, it is smaller
734 (apply 'format "#%02x%02x%02x"
735 (mapcar (lambda (X)
736 (* (/ (nth X rgb16)
737 (nth X white)) 255)) '(0 1 2))))) )
738
739(defun hfy-family (family) (list (cons "font-family" family)))
740(defun hfy-bgcol (colour) (list (cons "background" (hfy-triplet colour))))
741(defun hfy-colour (colour) (list (cons "color" (hfy-triplet colour))))
742(defun hfy-width (width) (list (cons "font-stretch" (symbol-name width))))
743
744(defcustom hfy-font-zoom 1.05
745 "Font scaling from Emacs to HTML."
746 :type 'float
747 :group 'htmlfontify)
748
749(defun hfy-size (height)
750 "Derive a CSS font-size specifier from an Emacs font :height attribute HEIGHT.
751Does not cope with the case where height is a function to be applied to
752the height of the underlying font."
753 (list
754 (cond
755 ;;(t (cons "font-size" ": 1em"))
756 ((floatp height)
757 (cons "font-size" (format "%d%%" (* (* hfy-font-zoom height) 100))))
758 ((integerp height)
759 (cons "font-size" (format "%dpt" (/ (* hfy-font-zoom height) 10 )))) )) )
760
761(defun hfy-slant (slant)
762 "Derive a font-style css specifier from the Emacs :slant attribute SLANT:
763CSS does not define the reverse-* styles, so just maps those to the
764regular specifiers."
765 (list (cons "font-style" (cond ((eq 'italic slant) "italic" )
766 ((eq 'reverse-italic slant) "italic" )
767 ((eq 'oblique slant) "oblique")
768 ((eq 'reverse-oblique slant) "oblique")
769 (t "normal" )))) )
770
771(defun hfy-weight (weight)
772 "Derive a font-weight css specifier from an Emacs weight spec symbol WEIGHT."
773 (list (cons "font-weight" (cond ((eq 'ultra-bold weight) "900")
774 ((eq 'extra-bold weight) "800")
775 ((eq 'bold weight) "700")
776 ((eq 'semi-bold weight) "600")
777 ((eq 'normal weight) "500")
778 ((eq 'semi-light weight) "400")
779 ((eq 'light weight) "300")
780 ((eq 'extra-light weight) "200")
781 ((eq 'ultra-light weight) "100")))) )
782
783(defun hfy-box-to-border-assoc (spec)
784 (if spec
785 (let ((tag (car spec))
786 (val (cadr spec)))
787 (cons (cond ((eq tag :color) (cons "colour" val))
788 ((eq tag :width) (cons "width" val))
789 ((eq tag :style) (cons "style" val)))
790 (hfy-box-to-border-assoc (cddr spec))))) )
791
792(defun hfy-box-to-style (spec)
793 (let* ((css (hfy-box-to-border-assoc spec))
794 (col (cdr (assoc "colour" css)))
795 (s (cdr (assoc "style" css))))
796 (list
797 (if col (cons "border-color" (cdr (assoc "colour" css))))
798 (cons "border-width" (format "%dpx" (or (cdr (assoc "width" css)) 1)))
799 (cons "border-style" (cond ((eq s 'released-button) "outset")
800 ((eq s 'pressed-button ) "inset" )
801 (t "solid" ))))) )
802
803(defun hfy-box (box)
804 "Derive CSS border-* attributes from the Emacs :box attribute BOX."
805 (if box
806 (cond
807 ((integerp box) (list (cons "border-width" (format "%dpx" box))))
808 ((stringp box) (list (cons "border" (format "solid %s 1px" box))))
809 ((listp box) (hfy-box-to-style box) ))) )
810
811(defun hfy-decor (tag val)
812 "Derive CSS text-decoration specifiers from various Emacs font attributes.
813TAG is an Emacs font attribute key (eg :underline).
814VAL is ignored."
815 (list
e3353a78 816 ;; FIXME: Why not '("text-decoration" . "underline")? --Stef
acca02b0
SM
817 (cond ((eq tag :underline ) (cons "text-decoration" "underline" ))
818 ((eq tag :overline ) (cons "text-decoration" "overline" ))
819 ((eq tag :strike-through) (cons "text-decoration" "line-through")))))
820
821(defun hfy-invisible (&optional val)
822 "This text should be invisible.
823Do something in CSS to make that happen.
824VAL is ignored here."
825 '(("display" . "none")))
826
827(defun hfy-combined-face-spec (face)
828 "Return a `defface' style alist of possible specifications for FACE.
829Entries resulting from customisation \(`custom-set-faces'\) will take
830precedence."
831 (let ((spec nil))
832 (setq spec (append (or (get face 'saved-face) (list))
833 (or (get face 'face-defface-spec) (list))))
834 (if (and hfy-display-class hfy-default-face-def (eq face 'default))
835 (setq spec (append hfy-default-face-def spec))) spec))
836
837(defun hfy-face-attr-for-class (face &optional class)
838 "Return the face attributes for FACE.
839If CLASS is set, it must be a `defface' alist key \[see below\],
840in which case the first face specification returned by `hfy-combined-face-spec'
841which *doesn\'t* clash with CLASS is returned.\n
842\(A specification with a class of t is considered to match any class you
843specify - this matches Emacs\' behaviour when deciding on which face attributes
844to use, to the best of my understanding\).\n
845If CLASS is nil, then you just get get whatever `face-attr-construct' returns,
846ie the current specification in effect for FACE.\n
847*NOTE* This function forces any face that is not \'default and which has
848no :inherit property to inherit from \'default \( this is because \'default
849is magical in that Emacs' fonts behave as if they inherit implicitly from
850\'default, but no such behaviour exists in HTML/CSS \).\n
851See `hfy-display-class' for details of valid values for CLASS."
852 (let ((face-spec nil))
853 (setq
854 face-spec
855 (if class
856 (let ((face-props (hfy-combined-face-spec face))
857 (face-specn nil)
858 (face-class nil)
859 (face-attrs nil)
860 (face-score -1)
861 (face-match nil))
862 (while face-props
863 (setq face-specn (car face-props)
864 face-class (car face-specn)
865 face-attrs (cdr face-specn)
866 face-props (cdr face-props))
867 ;; if the current element CEL of CLASS is t we match
868 ;; if the current face-class is t, we match
869 ;; if the cdr of CEL has a non-nil
870 ;; intersection with the cdr of the first member of
871 ;; the current face-class with the same car as CEL, we match
872 ;; if we actually clash, then we can't match
873 (let ((cbuf class)
874 (cel nil)
875 (key nil)
876 (val nil)
877 (x nil)
878 (next nil)
879 (score 0))
880 (while (and cbuf (not next))
881 (setq cel (car cbuf)
882 cbuf (cdr cbuf)
883 key (car cel)
884 val (cdr cel)
885 val (if (listp val) val (list val)))
886 (cond
887 ((or (eq cel t) (memq face-class '(t default)));;default match
888 (setq score 0) (ignore "t match"))
889 ((not (cdr (assq key face-class))) ;; neither good nor bad
890 nil (ignore "non match, non collision"))
891 ((setq x (hfy-interq val (cdr (assq key face-class))))
892 (setq score (+ score (length x)))
893 (ignore "intersection"))
894 (t ;; nope.
895 (setq next t score -10) (ignore "collision")) ))
896 (if (> score face-score)
897 (progn
898 (setq face-match face-attrs
899 face-score score )
900 (ignore "%d << %S/%S" score face-class class))
901 (ignore "--- %d ---- (insufficient)" score)) ))
902 ;; matched ? last attrs : nil
903 (if face-match
904 (if (listp (car face-match)) (car face-match) face-match) nil))
905 ;; Unfortunately the default face returns a
906 ;; :background. Fortunately we can remove it, but how do we do
907 ;; that in a non-system specific way?
908 (let ((spec (face-attr-construct face))
909 (new-spec nil))
910 (if (not (memq :background spec))
911 spec
912 (while spec
913 (let ((a (nth 0 spec))
914 (b (nth 1 spec)))
915 (unless (and (eq a :background)
916 (stringp b)
917 (string= b "SystemWindow"))
918 (setq new-spec (cons a (cons b new-spec)))))
919 (setq spec (cddr spec)))
920 new-spec)) ))
921 (if (or (memq :inherit face-spec) (eq 'default face))
922 face-spec
923 (nconc face-spec (list :inherit 'default))) ))
924
925;; construct an assoc of (css-tag-name . css-tag-value) pairs
926;; from a face or assoc of face attributes:
927
928;; Some tests etc:
929;; (mumamo-message-with-face "testing face" 'highlight)
930;; (mumamo-message-with-face "testing face" '(:foreground "red" :background "yellow"))
931;; (hfy-face-to-style-i '(:inherit default foreground-color "red"))
932;; default face=(:stipple nil :background "SystemWindow" :foreground
933;; "SystemWindowText" :inverse-video nil :box nil :strike-through
934;; nil :overline nil :underline nil :slant normal :weight normal
935;; :height 98 :width normal :family "outline-courier new")
936(defun hfy-face-to-style-i (fn)
937 "The guts of `hfy-face-to-style': FN should be a `defface' font spec,
938as returned by `face-attr-construct' or `hfy-face-attr-for-class'. Note
939that this function does not get font-sizes right if they are based on
940inherited modifiers \(via the :inherit\) attribute, and any other
941modifiers that are cumulative if they appear multiple times need to be
942merged by the user - `hfy-flatten-style' should do this."
943 ;;(message "hfy-face-to-style-i");;DBUG
944
945 ;; fn's value could be something like
946 ;; (:inherit
947 ;; ((foreground-color . "blue"))
948 ;; (foreground-color . "blue")
949 ;; nil)
950
951 (when fn
952 (let ((key (car fn))
953 (val (cadr fn))
954 (next (cddr fn))
955 (that nil)
956 (this nil)
957 (parent nil))
958 (if (eq key :inherit)
959 (let ((vs (if (listp val) val (list val))))
960 ;; (let ((x '(a b))) (setq x (append '(c d) x)))
961 ;; (let ((x '(a b))) (setq x (append '(c d) x)))
962 (dolist (v vs)
963 (setq parent
964 (append
965 parent
966 (hfy-face-to-style-i
967 (hfy-face-attr-for-class v hfy-display-class)) ))))
968 (setq this
969 (if val (cond
970 ((eq key :family ) (hfy-family val))
971 ((eq key :width ) (hfy-width val))
972 ((eq key :weight ) (hfy-weight val))
973 ((eq key :slant ) (hfy-slant val))
974 ((eq key :foreground ) (hfy-colour val))
975 ((eq key :background ) (hfy-bgcol val))
976 ((eq key :box ) (hfy-box val))
977 ((eq key :height ) (hfy-size val))
978 ((eq key :underline ) (hfy-decor key val))
979 ((eq key :overline ) (hfy-decor key val))
980 ((eq key :strike-through) (hfy-decor key val))
981 ((eq key :invisible ) (hfy-invisible val))
982 ((eq key :bold ) (hfy-weight 'bold))
983 ((eq key :italic ) (hfy-slant 'italic))))))
984 (setq that (hfy-face-to-style-i next))
985 ;;(lwarn t :warning "%S => %S" fn (nconc this that parent))
986 (nconc this that parent))) )
987
988(defun hfy-size-to-int (spec)
989 "Convert SPEC, a css font-size specifier, back to an Emacs :height attribute
990value. Used while merging multiple font-size attributes."
991 ;;(message "hfy-size-to-int");;DBUG
992 (list
993 (if (string-match "\\([0-9]+\\)\\(%\\|pt\\)" spec)
994 (cond ((string= "%" (match-string 2 spec))
995 (/ (string-to-number (match-string 1 spec)) 100.0))
996 ((string= "pt" (match-string 2 spec))
997 (* (string-to-number (match-string 1 spec)) 10)))
998 (string-to-number spec))) )
999
1000;; size is different, in that in order to get it right at all,
1001;; we have to trawl the inheritance path, accumulating modifiers,
1002;; _until_ we get to an absolute (pt) specifier, then combine the lot
1003(defun hfy-flatten-style (style)
1004 "Take STYLE (see `hfy-face-to-style-i', `hfy-face-to-style') and merge
1005any multiple attributes appropriately. Currently only font-size is merged
1006down to a single occurrence - others may need special handling, but I
1007haven\'t encountered them yet. Returns a `hfy-style-assoc'."
1008 ;;(message "(hfy-flatten-style %S)" style) ;;DBUG
1009 (let ((n 0)
1010 (m (list 1))
1011 (x nil)
1012 (r nil))
1013 (mapc
1014 (lambda (css)
1015 (if (string= (car css) "font-size")
1016 (progn
1017 (when (not x) (setq m (nconc m (hfy-size-to-int (cdr css)))))
1018 (when (string-match "pt" (cdr css)) (setq x t)))
1019 (setq r (nconc r (list css))) )) style)
1020 ;;(message "r: %S" r)
1021 (setq n (apply '* m))
1022 (nconc r (hfy-size (if x (round n) (* n 1.0)))) ))
1023
1024(defun hfy-face-to-style (fn)
1025 "Take FN, a font or `defface' style font specification,
1026\(as returned by `face-attr-construct' or `hfy-face-attr-for-class'\)
1027and return a `hfy-style-assoc'.\n
1028See also: `hfy-face-to-style-i', `hfy-flatten-style'."
1029 ;;(message "hfy-face-to-style");;DBUG
1030 (let ((face-def (if (facep fn)
1031 (hfy-face-attr-for-class fn hfy-display-class) fn))
1032 (final-style nil))
1033
1034 (setq final-style (hfy-flatten-style (hfy-face-to-style-i face-def)))
1035 ;;(message "%S" final-style)
1036 (if (not (assoc "text-decoration" final-style))
1037 (progn (setq final-style
1038 ;; Fix-me: there is no need for this since
1039 ;; text-decoration is not inherited.
1040 ;; but it's not wrong and if this ever changes it will
1041 ;; be needed, so I think it's better to leave it in? -- v
1042 (nconc final-style '(("text-decoration"."none"))))))
1043 final-style))
1044
1045;; strip redundant bits from a name. Technically, this could result in
1046;; a collision, but it is pretty unlikely - will fix later...
1047;; also handle ephemeral fonts created by overlays, which don't actually
1048;; have names:
1049(defun hfy-face-or-def-to-name (fn)
1050 "Render a font symbol or `defface' font spec FN into a name \(string\)."
1051 ;;(message "generating name for %s" fn)
1052 (if (not (listp fn))
1053 (format "%s" fn)
1054 (let* ((key (format "%s" fn))
1055 (entry (assoc key hfy-tmpfont-stack))
1056 (base (cadr (memq :inherit fn)))
1057 (tag (cdr entry)))
1058 ;;(message "checking for key «%s» in font stack [%d]"
1059 ;; key (if entry 1 0))
1060 (if entry nil ;; noop
1061 (setq tag (format "%04d" (length hfy-tmpfont-stack))
1062 entry (cons key tag)
1063 hfy-tmpfont-stack (cons entry hfy-tmpfont-stack)))
1064 ;;(message " -> name: %s-%s" (or base 'default) tag)
1065 (format "%s-%s" (or base 'default) tag)) ))
1066
1067(defun hfy-css-name (fn)
1068 "Strip the boring bits from a font-name FN and return a CSS style name."
1069 ;;(message "hfy-css-name");;DBUG
1070 (let ((face-name (hfy-face-or-def-to-name fn)))
1071 (if (or (string-match "font-lock-\\(.*\\)" face-name)
1072 (string-match "cperl-\\(.*\\)" face-name)
1073 (string-match "^[Ii]nfo-\\(.*\\)" face-name))
1074 (progn
1075 (setq face-name (match-string 1 face-name))
1076 (if (string-match "\\(.*\\)-face$" face-name)
1077 (setq face-name (match-string 1 face-name))) face-name)
1078 face-name)) )
1079
1080;; construct an assoc of (stripped-name . "{ css-stuff-here }") pairs
1081;; from a face:
1082(defun hfy-face-to-css (fn)
1083 "Take FN, a font or `defface' specification \(cf `face-attr-construct'\)
1084and return a CSS style specification.\n
1085See also: `hfy-face-to-style'"
1086 ;;(message "hfy-face-to-css");;DBUG
1087 (let ((css-list nil)
1088 (css-text nil)
acca02b0
SM
1089 (seen nil))
1090 ;;(message "(hfy-face-to-style %S)" fn)
1091 (setq css-list (hfy-face-to-style fn))
1092 (setq css-text
1093 (nconc
1094 (mapcar
1095 (lambda (E)
1096 (if (car E)
1097 (if (not (member (car E) seen))
1098 (progn
1099 (setq seen (cons (car E) seen))
1100 (format " %s: %s; " (car E) (cdr E)))))) css-list)))
1101 (cons (hfy-css-name fn) (format "{%s}" (apply 'concat css-text)))) )
1102
1103;; extract a face from a list of char properties, if there is one:
1104(defun hfy-p-to-face (props)
1105 "Given PROPS, a list of text-properties, return the value of the face
1106property, or nil."
1107 (if props
1108 (if (string= (car props) "face")
1109 (let ((propval (cadr props)))
1110 (if (and (listp propval) (not (cdr propval)))
1111 (car propval)
1112 propval))
1113 (hfy-p-to-face (cddr props)))
1114 nil))
1115
1116(defun hfy-p-to-face-lennart (props)
1117 "Given PROPS, a list of text-properties, return the value of the face
1118property, or nil."
1119 (when props
1120 (let ((face (plist-get props 'face))
1121 (font-lock-face (plist-get props 'font-lock-face))
1122 (button (plist-get props 'button))
1123 ;;(face-rec (memq 'face props))
1124 ;;(button-rec (memq 'button props)))
1125 )
1126 (if button
1127 (let* ((category (plist-get props 'category))
1128 (face (when category (plist-get (symbol-plist category) 'face))))
1129 face)
1130 (if font-lock-face
1131 font-lock-face
1132 face)))))
1133
1134;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1135;; (defun hfy-get-face-at (pos)
1136;; ;; (let ((face (get-char-property-and-overlay pos 'face)))
1137;; ;; (when (and face (listp face)) (setq face (car face)))
1138;; ;; (unless (listp face)
1139;; ;; face)))
1140;; ;;(get-char-property pos 'face)
1141;; ;; Overlays are handled later
1142;; (if (or (not show-trailing-whitespace)
1143;; (not (get-text-property pos 'hfy-show-trailing-whitespace)))
1144;; (get-text-property pos 'face)
1145;; (list 'trailing-whitespace (get-text-property pos 'face)))
1146;; )
1147
1148(defun hfy-prop-invisible-p (prop)
1149 "Is text property PROP an active invisibility property?"
1150 (or (and (eq buffer-invisibility-spec t) prop)
1151 (or (memq prop buffer-invisibility-spec)
1152 (assq prop buffer-invisibility-spec))))
1153
1154(defun hfy-find-invisible-ranges ()
1155 "Return a list of (start-point . end-point) cons cells of invisible regions."
1156 (let (invisible p i e s) ;; return-value pos invisible end start
1157 (save-excursion
1158 (setq p (goto-char (point-min)))
1159 (when (invisible-p p) (setq s p i t))
1160 (while (< p (point-max))
1161 (if i ;; currently invisible
1162 (when (not (invisible-p p)) ;; but became visible
1163 (setq e p
1164 i nil
1165 invisible (cons (cons s e) invisible)))
1166 ;; currently visible:
1167 (when (invisible-p p) ;; but have become invisible
1168 (setq s p i t)))
1169 (setq p (next-char-property-change p)))
1170 ;; still invisible at buffer end?
1171 (when i
1172 (setq e (point-max)
1173 invisible (cons (cons s e) invisible))) ) invisible))
1174
1175(defun hfy-invisible-name (point map)
1176 "Generate a CSS style name for an invisible section of the buffer.
1177POINT is the point inside the invisible region.
1178MAP is the invisibility map as returned by `hfy-find-invisible-ranges'."
1179 ;;(message "(hfy-invisible-name %S %S)" point map)
1180 (let (name)
1181 (mapc
1182 (lambda (range)
1183 (when (and (>= point (car range))
1184 (< point (cdr range)))
1185 (setq name (format "invisible-%S-%S" (car range) (cdr range))))) map)
1186 name))
1187
1188;; Fix-me: This function needs some cleanup by someone who understand
1189;; all the formats that face properties can have.
1190;;
1191;; overlay handling should be fine. haven't tested multiple stacked overlapping
1192;; overlays recently, but the common case of a text property face + an overlay
1193;; face produces the correct merged css style (or as close to it as css can get)
1194;; -- v
1195(defun hfy-face-at (p)
1196 "Find face in effect at point P.
1197If overlays are to be considered \(see `hfy-optimisations'\) then this may
1198return a defface style list of face properties instead of a face symbol."
1199 ;;(message "hfy-face-at");;DBUG
1200 ;; Fix-me: clean up, remove face-name etc
1201 ;; not sure why we'd want to remove face-name? -- v
1202 (let ((overlay-data nil)
1203 (base-face nil)
1204 ;; restored hfy-p-to-face as it handles faces like (bold) as
1205 ;; well as face like 'bold - hfy-get-face-at doesn't dtrt -- v
1206 (face-name (hfy-p-to-face (text-properties-at p)))
1207 ;; (face-name (hfy-get-face-at p))
1208 (prop-seen nil)
acca02b0
SM
1209 (extra-props nil)
1210 (text-props (text-properties-at p)))
1211 ;;(message "face-name: %S" face-name)
1212 (when (and face-name (listp face-name) (facep (car face-name)))
1213 ;;(message "face-name is a list %S" face-name)
1214 ;;(setq text-props (cons 'face face-name))
1215 (dolist (f face-name)
1216 (if (listp f) ;; for things like (variable-pitch (:foreground "red"))
1217 (setq extra-props (cons f extra-props))
1218 (setq extra-props (cons :inherit (cons f extra-props)))))
1219 (setq face-name nil))
1220 ;; text-properties-at => (face (:foreground "red" ...))
1221 ;; or => (face (compilation-info underline)) list of faces
1222 ;; overlay-properties
1223 ;; format= (evaporate t face ((foreground-color . "red")))
1224
1225 ;; SO: if we have turned overlays off,
1226 ;; or if there's no overlay data
1227 ;; just bail out and return whatever face data we've accumulated so far
1228 (if (or (not (hfy-opt 'keep-overlays))
1229 (not (setq overlay-data (hfy-overlay-props-at p))))
1230 (progn
1231 ;;(message "· %d: %s; %S; %s"
1232 ;; p face-name extra-props text-props)
1233 face-name) ;; no overlays or extra properties
1234 ;; collect any face data and any overlay data for processing:
1235 (when text-props
1236 (setq overlay-data (cons text-props overlay-data)))
1237 (setq overlay-data (nreverse overlay-data))
1238 ;;(message "- %d: %s; %S; %s; %s"
1239 ;; p face-name extra-props text-props overlay-data)
1240 ;; remember the basic face name so we don't keep repeating its specs:
1241 (when face-name (setq base-face face-name))
1242 (mapc
1243 (lambda (P)
1244 (let ((iprops (cadr (memq 'invisible P))))
1245 ;;(message "(hfy-prop-invisible-p %S)" iprops)
1246 (when (hfy-prop-invisible-p iprops)
1247 (setq extra-props
1248 (cons :invisible (cons t extra-props))) ))
1249 (let ((fprops (cadr (or (memq 'face P)
1250 (memq 'font-lock-face P)))))
1251 ;;(message "overlay face: %s" fprops)
1252 (if (not (listp fprops))
1253 (let ((this-face (if (stringp fprops) (intern fprops) fprops)))
1254 (when (not (eq this-face base-face))
1255 (setq extra-props
1256 (cons :inherit
1257 (cons this-face extra-props))) ))
1258 (while fprops
1259 (if (facep (car fprops))
1260 (let ((face (car fprops)))
1261 (when (stringp face) (setq face (intern fprops)))
1262 (setq extra-props
1263 (cons :inherit
1264 (cons face
1265 extra-props)))
1266 (setq fprops (cdr fprops)))
1267 (let (p v)
1268 ;; Sigh.
1269 (if (listp (car fprops))
1270 (if (nlistp (cdr (car fprops)))
1271 (progn
1272 ;; ((prop . val))
1273 (setq p (caar fprops))
1274 (setq v (cdar fprops))
1275 (setq fprops (cdr fprops)))
1276 ;; ((prop val))
1277 (setq p (caar fprops))
1278 (setq v (cadar fprops))
1279 (setq fprops (cdr fprops)))
1280 (if (listp (cdr fprops))
1281 (progn
1282 ;; (:prop val :prop val ...)
1283 (setq p (car fprops))
1284 (setq v (cadr fprops))
1285 (setq fprops (cddr fprops)))
1286 (if (and (listp fprops)
1287 (not (listp (cdr fprops))))
1288 ;;(and (consp x) (cdr (last x)))
1289 (progn
1290 ;; (prop . val)
1291 (setq p (car fprops))
1292 (setq v (cdr fprops))
1293 (setq fprops nil))
1294 (error "Eh... another format! fprops=%s" fprops) )))
1295 (setq p (case p
1296 ;; These are all the properties handled
1297 ;; in `hfy-face-to-style-i'.
1298 ;;
1299 ;; Are these translations right?
1300 ;; yes, they are -- v
1301 ('family :family )
1302 ('width :width )
1303 ('height :height )
1304 ('weight :weight )
1305 ('slant :slant )
1306 ('underline :underline )
1307 ('overline :overline )
1308 ('strike-through :strike-through)
1309 ('box :box )
1310 ('foreground-color :foreground)
1311 ('background-color :background)
1312 ('bold :bold )
1313 ('italic :italic )
1314 (t p)))
1315 (if (memq p prop-seen) nil ;; noop
1316 (setq prop-seen (cons p prop-seen)
acca02b0
SM
1317 extra-props (cons p (cons v extra-props)))) ))))))
1318 overlay-data)
1319 ;;(message "+ %d: %s; %S" p face-name extra-props)
1320 (if extra-props
1321 (if (listp face-name)
1322 (nconc extra-props face-name)
1323 (nconc extra-props (face-attr-construct face-name)))
1324 face-name)) ))
1325
1326(defun hfy-overlay-props-at (p)
1327 "Grab overlay properties at point P.
1328The plists are returned in descending priority order."
1329 (sort (mapcar (lambda (O) (overlay-properties O)) (overlays-at p))
1330 (lambda (A B) (> (or (cadr (memq 'priority A)) 0)
1331 (or (cadr (memq 'priority B)) 0)) ) ) )
1332
1333;; construct an assoc of (face-name . (css-name . "{ css-style }")) elements:
1334(defun hfy-compile-stylesheet ()
1335 "Trawl the current buffer, construct and return a `hfy-sheet-assoc'."
1336 ;;(message "hfy-compile-stylesheet");;DBUG
1337 (let ((pt (point-min))
1338 ;; Make the font stack stay:
1339 ;;(hfy-tmpfont-stack nil)
1340 (fn nil)
acca02b0
SM
1341 (style nil))
1342 (save-excursion
1343 (goto-char pt)
1344 (while (< pt (point-max))
1345 (if (and (setq fn (hfy-face-at pt)) (not (assoc fn style)))
1346 (setq style (cons (cons fn (hfy-face-to-css fn)) style)))
1347 (setq pt (next-char-property-change pt))) )
1348 (setq style (cons (cons 'default (hfy-face-to-css 'default)) style))) )
1349
1350(defun hfy-fontified-p ()
1351 "`font-lock' doesn't like to say it\'s been fontified when in batch
1352mode, but we want to know if we should fontify or raw copy, so in batch
1353mode we check for non-default face properties. Otherwise we test
1354variable `font-lock-mode' and variable `font-lock-fontified' for truth."
1355 ;;(message "font-lock-fontified: %S" font-lock-fontified)
1356 ;;(message "noninteractive : %S" noninteractive)
1357 ;;(message "font-lock-mode : %S" font-lock-mode)
1358 (and font-lock-fontified
1359 (if noninteractive
1360 (let ((pt (point-min))
1361 (face-name nil))
1362 (save-excursion
1363 (goto-char pt)
1364 (while (and (< pt (point-max)) (not face-name))
1365 (setq face-name (hfy-face-at pt))
1366 (setq pt (next-char-property-change pt)))) face-name)
1367 font-lock-mode)))
1368
1369;; remember, the map is in reverse point order:
1370;; I wrote this while suffering the effects of a cold, and maybe a
1371;; mild fever - I think it's correct, but it might be a little warped
1372;; as my minfd keeps ... where was I? Oh yes, the bunnies...
1373(defun hfy-merge-adjacent-spans (face-map)
1374 "Where FACE-MAP is a `hfy-facemap-assoc' for the current buffer,
1375this function merges adjacent style blocks which are of the same value
1376and are separated by nothing more interesting than whitespace.\n
1377 <span class=\"foo\">narf</span> <span class=\"foo\">brain</span>\n
1378\(as interpreted from FACE-MAP\) would become:\n
1379 <span class=\"foo\">narf brain</span>\n
1380Returns a modified copy of FACE-MAP."
1381 (let ((tmp-map face-map)
1382 (map-buf nil)
1383 (first-start nil)
1384 (first-stop nil)
1385 (last-start nil)
1386 (last-stop nil)
1387 (span-stop nil)
1388 (span-start nil)
1389 (reduced-map nil))
1390 ;;(setq reduced-map (cons (car tmp-map) reduced-map))
1391 ;;(setq reduced-map (cons (cadr tmp-map) reduced-map))
1392 (while tmp-map
1393 (setq first-start (cadddr tmp-map)
1394 first-stop (caddr tmp-map)
1395 last-start (cadr tmp-map)
1396 last-stop (car tmp-map)
1397 map-buf tmp-map
1398 span-start last-start
1399 span-stop last-stop )
1400 (while (and (equal (cdr first-start)
1401 (cdr last-start))
1402 (save-excursion
1403 (goto-char (car first-stop))
1404 (not (re-search-forward "[^ \t\n\r]" (car last-start) t))))
1405 (setq map-buf (cddr map-buf)
1406 span-start first-start
1407 first-start (cadddr map-buf)
1408 first-stop (caddr map-buf)
1409 last-start (cadr map-buf)
1410 last-stop (car map-buf)))
1411 (setq reduced-map (cons span-stop reduced-map))
1412 (setq reduced-map (cons span-start reduced-map))
1413 (setq tmp-map (memq last-start tmp-map))
1414 (setq tmp-map (cdr tmp-map)))
1415 (setq reduced-map (nreverse reduced-map))))
1416
1417;; remember to generate 'synthetic' </span> entries -
1418;; emacs copes by just having a stack of styles in effect
1419;; and only using the top one: html has a more simplistic approach -
1420;; we have to explicitly end a style, there's no way of temporarily
1421;; overriding it w. another one... (afaik)
1422(defun hfy-compile-face-map ()
1423;; no need for special <a> version.
1424;; IME hyperlinks don't get underlined, esp when you htmlfontify a whole
1425;; source tree, so the <a> version is needed -- v
1426;; Fix-me: save table for multi-buffer
1427 "Compile and return a `hfy-facemap-assoc' for the current buffer."
1428 ;;(message "hfy-compile-face-map");;DBUG
1429 (let ((pt (point-min))
1430 (pt-narrow 1)
1431 (fn nil)
1432 (map nil)
1433 (prev-tag nil)) ;; t if the last tag-point was a span-start
1434 ;; nil if it was a span-stop
1435 (save-excursion
1436 (goto-char pt)
1437 (while (< pt (point-max))
1438 (if (setq fn (hfy-face-at pt))
1439 (progn (if prev-tag (setq map (cons (cons pt-narrow 'end) map)))
1440 (setq map (cons (cons pt-narrow fn) map))
1441 (setq prev-tag t))
1442 (if prev-tag (setq map (cons (cons pt-narrow 'end) map)))
1443 (setq prev-tag nil))
1444 (setq pt (next-char-property-change pt))
1445 (setq pt-narrow (1+ (- pt (point-min)))))
1446 (if (and map (not (eq 'end (cdar map))))
1447 (setq map (cons (cons (- (point-max) (point-min)) 'end) map))))
1448 (if (hfy-opt 'merge-adjacent-tags) (hfy-merge-adjacent-spans map) map)))
1449
1450(defun hfy-buffer ()
1451 "Generate a buffer to hold the html output.
1452The filename of this buffer is derived from the source \(current\) buffer\'s
1453variable `buffer-file-name', if it is set, plus `hfy-extn'.
1454Otherwise a plausible filename is constructed from `default-directory',
1455`buffer-name' and `hfy-extn'."
1456 (let* ((name (concat (buffer-name) hfy-extn))
1457 (src (buffer-file-name))
1458 (buf (get-buffer-create name)))
e3353a78
SM
1459 (with-current-buffer buf
1460 (setq buffer-file-name
1461 (if src (concat src hfy-extn)
1462 (expand-file-name (if (string-match "^.*/\\([^/]*\\)$" name)
1463 (match-string 1 name)
1464 name))))
acca02b0
SM
1465 buf)))
1466
1467(defun hfy-lookup (face style)
1468 "Get a CSS style name for FACE from STYLE."
1469 (cadr (assoc face style)))
1470
1471(defun hfy-link-style (style-string)
1472 "Copy, alter and return a STYLE-STRING to make it suitable for a hyperlink.
1473Uses `hfy-link-style-fun' to do this."
1474 (if (functionp hfy-link-style-fun)
1475 (funcall hfy-link-style-fun style-string)
1476 style-string))
1477
1478(defun hfy-sprintf-stylesheet (css file)
1479 "Return the inline CSS style sheet for FILE as a string."
1480 (let ((stylesheet nil))
1481 (setq stylesheet
1482 (concat
1483 hfy-meta-tags
1484 "\n<style type=\"text/css\"><!-- \n"
1485 ;; Fix-me: Add handling of page breaks here + scan for ^L
1486 ;; where appropriate.
1487 (format "body %s\n" (cddr (assq 'default css)))
1488 (apply 'concat
1489 (mapcar
1490 (lambda (style)
1491 (format
1492 "span.%s %s\nspan.%s a %s\n"
1493 (cadr style) (cddr style)
1494 (cadr style) (hfy-link-style (cddr style)))) css))
1495 " --></style>\n"))
1496 (funcall hfy-page-header file stylesheet)))
1497
1498(defconst hfy-javascript "
1499 <script type=\"text/javascript\">
1500 // <![CDATA[
1501function toggle_invis( name )
1502{
1503 var filter =
1504 { acceptNode:
1505 function( node )
1506 { var classname = node.id;
1507 if( classname )
1508 { var classbase = classname.substr( 0, name.length );
1509 if( classbase == name ) { return NodeFilter.FILTER_ACCEPT; } }
1510 return NodeFilter.FILTER_SKIP; } };
1511 var walker = document.createTreeWalker( document.body ,
1512 NodeFilter.SHOW_ELEMENT ,
1513 filter ,
1514 false );
1515 while( walker.nextNode() )
1516 {
1517 var e = walker.currentNode;
1518 if( e.style.display == \"none\" ) { e.style.display = \"inline\"; }
1519 else { e.style.display = \"none\"; }
1520 }
1521}
1522 // ]]>
1523 </script>\n")
1524
1525;; tag all the dangerous characters we want to escape
1526;; (ie any "<> chars we _didn't_ put there explicitly for css markup)
1527(defun hfy-html-enkludge-buffer ()
1528 "Mark dangerous [\"\<\>] characters with the \'hfy-quoteme property.\n
1529See also `hfy-html-dekludge-buffer'."
1530 ;;(message "hfy-html-enkludge-buffer");;DBUG
1531 (save-excursion
1532 (goto-char (point-min))
1533 (while (re-search-forward hfy-html-quote-regex nil t)
1534 (put-text-property (match-beginning 0) (point) 'hfy-quoteme t))) )
1535
1536;; dangerous char -> &entity;
1537(defun hfy-html-quote (char-string)
1538 "Map CHAR-STRING to an html safe string (entity) if need be."
1539 ;;(message "hfy-html-quote");;DBUG
1540 (or (cadr (assoc char-string hfy-html-quote-map)) char-string) )
1541
1542;; actually entity-ise dangerous chars.
1543;; note that we can't do this until _after_ we have inserted the css
1544;; markup, since we use a position-based map to insert this, and if we
1545;; enter any other text before we do this, we'd have to track another
1546;; map of offsets, which would be tedious...
1547(defun hfy-html-dekludge-buffer ()
1548 "Transform all dangerous characters marked with the \'hfy-quoteme property
1549using `hfy-html-quote'\n
1550See also `hfy-html-enkludge-buffer'."
1551 ;;(message "hfy-html-dekludge-buffer");;DBUG
1552 (save-excursion
1553 (goto-char (point-min))
1554 (while (re-search-forward hfy-html-quote-regex nil t)
1555 (if (get-text-property (match-beginning 0) 'hfy-quoteme)
1556 (replace-match (hfy-html-quote (match-string 1))) )) ))
1557
1558;; Borrowed from font-lock.el
1559(defmacro hfy-save-buffer-state (varlist &rest body)
1560 "Bind variables according to VARLIST and eval BODY restoring buffer state.
1561Do not record undo information during evaluation of BODY."
1562 (declare (indent 1) (debug let))
1563 (let ((modified (make-symbol "modified")))
1564 `(let* ,(append varlist
1565 `((,modified (buffer-modified-p))
1566 (buffer-undo-list t)
1567 (inhibit-read-only t)
1568 (inhibit-point-motion-hooks t)
1569 (inhibit-modification-hooks t)
1570 deactivate-mark
1571 buffer-file-name
1572 buffer-file-truename))
1573 (progn
1574 ,@body)
1575 (unless ,modified
1576 (restore-buffer-modified-p nil)))))
1577
1578(defun hfy-mark-trailing-whitespace ()
1579 "Tag trailing whitespace with a hfy property if it is currently highlighted."
1580 (when show-trailing-whitespace
1581 (let ((inhibit-read-only t))
1582 (save-excursion
1583 (goto-char (point-min))
1584 (hfy-save-buffer-state nil
1585 (while (re-search-forward "[ \t]+$" nil t)
1586 (put-text-property (match-beginning 0) (match-end 0)
1587 'hfy-show-trailing-whitespace t)))))))
1588
1589(defun hfy-unmark-trailing-whitespace ()
1590 "Undo the effect of `hfy-mark-trailing-whitespace'."
1591 (when show-trailing-whitespace
1592 (hfy-save-buffer-state nil
1593 (remove-text-properties (point-min) (point-max)
1594 '(hfy-show-trailing-whitespace)))))
1595
1596(defun hfy-fontify-buffer (&optional srcdir file)
1597 "Implement the guts of `htmlfontify-buffer'.
1598SRCDIR, if set, is the directory being htmlfontified.
1599FILE, if set, is the file name."
1600 (if srcdir (setq srcdir (directory-file-name srcdir)))
e3353a78 1601 (let* ( (html-buffer (hfy-buffer))
acca02b0
SM
1602 (css-sheet nil)
1603 (css-map nil)
1604 (invis-ranges nil)
1605 (rovl nil)
1606 (orig-ovls (overlays-in (point-min) (point-max)))
1607 (rmin (when mark-active (region-beginning)))
1608 (rmax (when mark-active (region-end ))) )
1609 (when (and mark-active
1610 transient-mark-mode)
1611 (unless (and (= rmin (point-min))
1612 (= rmax (point-max)))
1613 (setq rovl (make-overlay rmin rmax))
1614 (overlay-put rovl 'priority 1000)
1615 (overlay-put rovl 'face 'region)))
1616 ;; copy the buffer, including fontification, and switch to it:
1617 (hfy-mark-trailing-whitespace)
1618 (setq css-sheet (hfy-compile-stylesheet )
1619 css-map (hfy-compile-face-map )
1620 invis-ranges (hfy-find-invisible-ranges))
1621 (hfy-unmark-trailing-whitespace)
1622 (when rovl
1623 (delete-overlay rovl))
1624 (copy-to-buffer html-buffer (point-min) (point-max))
1625 (set-buffer html-buffer)
1626 ;; Apply overlay invisible spec
1627 (setq orig-ovls
1628 (sort orig-ovls
1629 (lambda (A B)
1630 (> (or (cadr (memq 'priority (overlay-properties A))) 0)
1631 (or (cadr (memq 'priority (overlay-properties B))) 0)))))
1632 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1633 ;; at this point, html-buffer retains the fontification of the parent:
1634 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1635 ;; we don't really need or want text in the html buffer to be invisible, as
1636 ;; that can make it look like we've rendered invalid xhtml when all that's
1637 ;; happened is some tags are in the invisible portions of the buffer:
1638 (setq buffer-invisibility-spec nil)
1639 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1640 ;; #####################################################################
1641 ;; if we are in etags mode, add properties to mark the anchors and links
1642 (if (and srcdir file)
1643 (progn
1644 (hfy-mark-tag-names srcdir file) ;; mark anchors
1645 (hfy-mark-tag-hrefs srcdir file))) ;; mark links
1646 ;; #####################################################################
1647 ;; mark the 'dangerous' characters
1648 ;;(message "marking dangerous characters")
1649 (hfy-html-enkludge-buffer)
1650 ;; trawl the position-based face-map, inserting span tags as we go
1651 ;; note that we cannot change any character positions before this point
1652 ;; or we will invalidate the map:
1653 ;; NB: This also means we have to trawl the map in descending file-offset
1654 ;; order, obviously.
1655 ;; ---------------------------------------------------------------------
1656 ;; Remember, inserting pushes properties to the right, which we don't
1657 ;; actually want to happen for link properties, so we have to flag
1658 ;; them and move them by hand - if you don't, you end up with
1659 ;;
1660 ;; <span class="foo"><a href="bar">texta</span><span class="bletch"></a>...
1661 ;;
1662 ;; instead of:
1663 ;;
1664 ;; <span class="foo"><a href="bar">texta</a></span><span class="bletch">...
1665 ;;
1666 ;; If my analysis of the problem is correct, we can detect link-ness by
1667 ;; either hfy-linkp or hfy-endl properties at the insertion point, but I
1668 ;; think we only need to relocate the hfy-endl property, as the hfy-linkp
1669 ;; property has already served its main purpose by this point.
1670 ;;(message "mapcar over the CSS-MAP")
1671 (message "invis-ranges:\n%S" invis-ranges)
1672 (mapc
1673 (lambda (point-face)
1674 (let ((pt (car point-face))
1675 (fn (cdr point-face))
1676 (move-link nil))
1677 (goto-char pt)
1678 (setq move-link
1679 (or (get-text-property pt 'hfy-linkp)
1680 (get-text-property pt 'hfy-endl )))
1681 (if (eq 'end fn)
1682 (insert "</span>")
1683 (if (not (and srcdir file))
1684 nil
1685 (when move-link
1686 (remove-text-properties (point) (1+ (point)) '(hfy-endl nil))
1687 (put-text-property pt (1+ pt) 'hfy-endl t) ))
1688 ;; if we have invisible blocks, we need to do some extra magic:
1689 (if invis-ranges
1690 (let ((iname (hfy-invisible-name pt invis-ranges))
1691 (fname (hfy-lookup fn css-sheet )))
1692 (when (assq pt invis-ranges)
1693 (insert
1694 (format "<span onclick=\"toggle_invis('%s');\">" iname))
1695 (insert "…</span>"))
1696 (insert
1697 (format "<span class=\"%s\" id=\"%s-%d\">" fname iname pt)))
1698 (insert (format "<span class=\"%s\">" (hfy-lookup fn css-sheet))))
1699 (if (not move-link) nil
1700 ;;(message "removing prop2 @ %d" (point))
1701 (if (remove-text-properties (point) (1+ (point)) '(hfy-endl nil))
1702 (put-text-property pt (1+ pt) 'hfy-endl t))) )))
1703 css-map)
1704 ;; #####################################################################
1705 ;; Invisibility
1706 ;; Maybe just make the text invisible in XHTML?
1707 ;; DONE -- big block of obsolete invisibility code elided here -- v
1708 ;; #####################################################################
1709 ;; (message "checking to see whether we should link...")
1710 (if (and srcdir file)
1711 (let ((lp 'hfy-link)
1712 (pt nil)
1713 (pr nil)
1714 (rr nil))
1715 ;; (message " yes we should.")
1716 ;; translate 'hfy-anchor properties to anchors
1717 (setq pt (point-min))
1718 (while (setq pt (next-single-property-change pt 'hfy-anchor))
1719 (if (setq pr (get-text-property pt 'hfy-anchor))
1720 (progn (goto-char pt)
1721 (remove-text-properties pt (1+ pt) '(hfy-anchor nil))
1722 (insert (concat "<a name=\"" pr "\"></a>")))))
1723 ;; translate alternate 'hfy-link and 'hfy-endl props to opening
1724 ;; and closing links. (this should avoid those spurious closes
1725 ;; we sometimes get by generating only paired tags)
1726 (setq pt (point-min))
1727 (while (setq pt (next-single-property-change pt lp))
1728 (if (not (setq pr (get-text-property pt lp))) nil
1729 (goto-char pt)
1730 (remove-text-properties pt (1+ pt) (list lp nil))
1731 (cond
1732 ((eq lp 'hfy-link)
1733 (if (setq rr (get-text-property pt 'hfy-inst))
1734 (insert (format "<a name=\"%s\"></a>" rr)))
1735 (insert (format "<a href=\"%s\">" pr))
1736 (setq lp 'hfy-endl))
1737 ((eq lp 'hfy-endl)
1738 (insert "</a>") (setq lp 'hfy-link)) ))) ))
1739
1740 ;; #####################################################################
1741 ;; transform the dangerous chars. This changes character positions
1742 ;; since entities have > char length.
1743 ;; note that this deletes the dangerous characters, and therefore
1744 ;; destroys any properties they may contain (such as 'hfy-endl),
1745 ;; so we have to do this after we use said properties:
1746 ;; (message "munging dangerous characters")
1747 (hfy-html-dekludge-buffer)
1748 ;; insert the stylesheet at the top:
1749 (goto-char (point-min))
1750 ;;(message "inserting stylesheet")
1751 (insert (hfy-sprintf-stylesheet css-sheet file))
1752 (insert hfy-javascript)
1753 (if (hfy-opt 'div-wrapper) (insert "<div class=\"default\">"))
1754 (insert "\n<pre>")
1755 (goto-char (point-max))
1756 (insert "</pre>\n")
1757 (if (hfy-opt 'div-wrapper) (insert "</div>"))
1758 ;;(message "inserting footer")
1759 (insert (funcall hfy-page-footer file))
1760 ;; call any post html-generation hooks:
1761 (run-hooks 'hfy-post-html-hooks)
1762 ;; return the html buffer
1763 (set-buffer-modified-p nil)
1764 html-buffer))
1765
1766(defun hfy-force-fontification ()
1767 "Try to force font-locking even when it is optimised away."
1768 (mapc (lambda (fun) (funcall fun)) hfy-init-kludge-hooks)
1769 (eval-and-compile (require 'font-lock))
1770 (if (boundp 'font-lock-cache-position)
1771 (or font-lock-cache-position
1772 (set 'font-lock-cache-position (make-marker))))
1773 (if (not noninteractive)
1774 (progn
1775 (message "hfy interactive mode (%S %S)" window-system major-mode)
1776 (when (and font-lock-defaults
1777 font-lock-mode)
1778 (font-lock-fontify-region (point-min) (point-max) nil)))
1779 (message "hfy batch mode (%s:%S)"
1780 (or (buffer-file-name) (buffer-name)) major-mode)
1781 (when font-lock-defaults
1782 (font-lock-fontify-buffer)) ))
1783
1784(defun htmlfontify-buffer (&optional srcdir file)
1785 "Create a new buffer, named for the current buffer + a .html extension,
1786containing an inline css-stylesheet and formatted css-markup html
1787that reproduces the look of the current Emacs buffer as closely
1788as possible.
1789
1790Dangerous characters in the existing buffer are turned into html
1791entities, so you should even be able to do html-within-html
1792fontified display.
1793
1794You should, however, note that random control or eight-bit
1795characters such as ^L (\x0c) or ¤ (\xa4) won't get mapped yet.
1796
1797If the SRCDIR and FILE arguments are set, lookup etags derived
1798entries in the `hfy-tags-cache' and add html anchors and
1799hyperlinks as appropriate."
1800 (interactive)
1801 ;; pick up the file name in case we didn't receive it
1802 (if (not file)
1803 (progn (setq file (or (buffer-file-name) (buffer-name)))
1804 (if (string-match "/\\([^/]*\\)$" file)
1805 (setq file (match-string 1 file)))) )
1806
1807 (if (not (hfy-opt 'skip-refontification))
1808 (save-excursion ;; Keep region
1809 (hfy-force-fontification)))
1810 (if (interactive-p) ;; display the buffer in interactive mode:
1811 (switch-to-buffer (hfy-fontify-buffer srcdir file))
1812 (hfy-fontify-buffer srcdir file)))
1813
1814;; recursive file listing
1815(defun hfy-list-files (directory)
1816 "Return a list of files under DIRECTORY.
1817Strips any leading \"./\" from each filename."
1818 ;;(message "hfy-list-files");;DBUG
1819 (cd directory)
1820 (mapcar (lambda (F) (if (string-match "^./\\(.*\\)" F) (match-string 1 F) F))
1821 (split-string (shell-command-to-string hfy-find-cmd))) )
1822
1823;; strip the filename off, return a directiry name
1824;; not a particularly thorough implementaion, but it will be
1825;; fed pretty carefully, so it should be Ok:
1826(defun hfy-dirname (file)
1827 "Return everything preceding the last \"/\" from a relative filename FILE,
1828on the assumption that this will produce a relative directory name. Hardly
1829bombproof, but good enough in the context in which it is being used."
1830 ;;(message "hfy-dirname");;DBUG
1831 (let ((f (directory-file-name file)))
1832 (and (string-match "^\\(.*\\)/" f) (match-string 1 f))))
1833
1834;; create a directory, cf mkdir -p
1835(defun hfy-make-directory (dir)
1836 "Approx equivalent of mkdir -p DIR."
1837 ;;(message "hfy-make-directory");;DBUG
1838 (if (file-exists-p dir)
1839 (if (file-directory-p dir) t)
1840 (make-directory dir t)))
1841
1842(defun hfy-text-p (srcdir file)
1843 "Is SRCDIR/FILE text? Uses `hfy-istext-command' to determine this."
e3353a78
SM
1844 (let* ((cmd (format hfy-istext-command (expand-file-name file srcdir)))
1845 (rsp (shell-command-to-string cmd)))
acca02b0
SM
1846 (if (string-match "text" rsp) t nil)))
1847
1848;; open a file, check fontification, if fontified, write a fontified copy
1849;; to the destination directory, otherwise just copy the file:
1850(defun hfy-copy-and-fontify-file (srcdir dstdir file)
1851 "Open FILE in SRCDIR - if fontified, write a fontified copy to DSTDIR
1852adding an extension of `hfy-extn'. Fontification is actually done by
1853`htmlfontify-buffer'. If the buffer is not fontified, just copy it."
1854 ;;(message "hfy-copy-and-fontify-file");;DBUG
1855 (let (;;(fast-lock-minimum-size hfy-fast-lock-save)
1856 ;;(font-lock-support-mode 'fast-lock-mode)
1857 ;;(window-system (or window-system 'htmlfontify))
1858 (target nil)
1859 (source nil)
1860 (html nil))
1861 (cd srcdir)
e3353a78
SM
1862 (with-current-buffer (setq source (find-file-noselect file))
1863 ;; FIXME: Shouldn't this use expand-file-name? --Stef
acca02b0
SM
1864 (setq target (concat dstdir "/" file))
1865 (hfy-make-directory (hfy-dirname target))
1866 (if (not (hfy-opt 'skip-refontification)) (hfy-force-fontification))
1867 (if (or (hfy-fontified-p) (hfy-text-p srcdir file))
1868 (progn (setq html (hfy-fontify-buffer srcdir file))
1869 (set-buffer html)
1870 (write-file (concat target hfy-extn))
1871 (kill-buffer html))
1872 ;; #o0200 == 128, but emacs20 doesn't know that
1873 (if (and (file-exists-p target) (not (file-writable-p target)))
1874 (set-file-modes target (logior (file-modes target) 128)))
1875 (copy-file (buffer-file-name source) target 'overwrite))
1876 (kill-buffer source)) ))
1877
1878;; list of tags in file in srcdir
1879(defun hfy-tags-for-file (srcdir file)
1880 "List of etags tags that have definitions in this FILE.
1881Looks up the tags cache in `hfy-tags-cache' using SRCDIR as the key."
1882 ;;(message "hfy-tags-for-file");;DBUG
1883 (let ((cache-entry (assoc srcdir hfy-tags-cache))
1884 (cache-hash nil)
1885 (tag-list nil))
1886 (if (setq cache-hash (cadr cache-entry))
1887 (maphash
1888 (lambda (K V)
1889 (if (assoc file V)
1890 (setq tag-list (cons K tag-list)))) cache-hash))
1891 tag-list))
1892
1893;; mark the tags native to this file for anchors
1894(defun hfy-mark-tag-names (srcdir file)
1895 "Mark tags in FILE (lookup SRCDIR in `hfy-tags-cache') with the \'hfy-anchor
1896property, with a value of \"tag.line-number\"."
1897 ;;(message "(hfy-mark-tag-names %s %s)" srcdir file);;DBUG
1898 (let ((cache-entry (assoc srcdir hfy-tags-cache))
1899 (cache-hash nil))
1900 (if (setq cache-hash (cadr cache-entry))
1901 (mapcar
1902 (lambda (TAG)
1903 (mapcar
1904 (lambda (TLIST)
1905 (if (string= file (car TLIST))
1906 (let* ((line (cadr TLIST) )
1907 (chr (caddr TLIST) )
1908 (link (format "%s.%d" TAG line) ))
1909 (put-text-property (+ 1 chr)
1910 (+ 2 chr)
1911 'hfy-anchor link))))
1912 (gethash TAG cache-hash)))
1913 (hfy-tags-for-file srcdir file)))))
1914
1915(defun hfy-relstub (file &optional start)
1916 "Return a \"../\" stub of the appropriate length for the current source
1917tree depth \(as determined from FILE \(a filename\)\).
1918START is the offset at which to start looking for the / character in FILE."
1919 ;;(message "hfy-relstub");;DBUG
1920 (let ((c ""))
1921 (while (setq start (string-match "/" file start))
1922 (setq start (1+ start)) (setq c (concat c "../"))) c))
1923
1924(defun hfy-href-stub (this-file def-files tag)
1925 "Return an href stub for a tag href i THIS-FILE:
1926If DEF-FILES \(list of files containing definitions for the tag in question\)
1927contains only one entry, the href should link straight to that file.
1928Otherwise, the link should be to the index file.\n
1929We are not yet concerned with the file extensions/tag line number and so on at
1930this point.\n
1931If `hfy-split-index' is set, and the href wil be to an index file rather than
1932a source file, append a .X to `hfy-index-file', where X is the uppercased
1933first character of TAG.\n
1934See also: `hfy-relstub', `hfy-index-file'`'."
1935 ;;(message "hfy-href-stub");;DBUG
e3353a78
SM
1936 ;; FIXME: Why not use something like
1937 ;; (file-relative-name (if ...) (file-name-directory this-file)) ? --Stef
acca02b0
SM
1938 (concat
1939 (hfy-relstub this-file)
1940 (if (= 1 (length def-files)) (car def-files)
1941 (if (not hfy-split-index) hfy-index-file
1942 (concat hfy-index-file "." (upcase (substring tag 0 1)))))) )
1943
1944(defun hfy-href (this-file def-files tag tag-map)
1945 "Return a relative href to the tag in question, based on\n
1946THIS-FILE `hfy-link-extn' `hfy-extn' DEF-FILES TAG and TAG-MAP\n
1947THIS-FILE is the current source file
1948DEF-FILES is a list of file containing possible link endpoints for TAG
1949TAG is the TAG in question
1950TAG-MAP is the entry in `hfy-tags-cache'."
1951 ;;(message "hfy-href");;DBUG
1952 (concat
1953 (hfy-href-stub this-file def-files tag)
1954 (or hfy-link-extn hfy-extn) "#" tag ;;(.src -> .html)
1955 (if (= 1 (length def-files))
1956 (concat "." (format "%d" (cadr (assoc (car def-files) tag-map)))))) )
1957
1958(defun hfy-word-regex (string)
1959 "Return a regex that matches STRING as the first `match-string', with non
1960word characters on either side."
e3353a78 1961 ;; FIXME: Should this use [^$[:alnum:]_] instead? --Stef
acca02b0
SM
1962 (concat "[^$A-Za-z_0-9]\\(" (regexp-quote string) "\\)[^A-Za-z_0-9]"))
1963
1964;; mark all tags for hyperlinking, except the tags at
1965;; their own points of definition, iyswim:
1966(defun hfy-mark-tag-hrefs (srcdir file)
1967 "Mark href start points with the \'hfy-link prop \(value: href string\)\n
1968Mark href end points with the \'hfy-endl prop \(value t\)\n
1969Avoid overlapping links, and mark links in descending length of
1970tag name in order to prevent subtags from usurping supertags,
1971\(eg \"term\" for \"terminal\").
1972SRCDIR is the directory being \"published\".
1973FILE is the specific file we are rendering."
1974 ;;(message "hfy-mark-tag-hrefs");;DBUG
1975 (let ((cache-entry (assoc srcdir hfy-tags-cache))
1976 (list-cache (assoc srcdir hfy-tags-sortl))
1977 (rmap-cache (assoc srcdir hfy-tags-rmap ))
1978 (no-comment (hfy-opt 'zap-comment-links))
1979 (no-strings (hfy-opt 'zap-string-links ))
1980 (cache-hash nil)
1981 (tags-list nil)
1982 (tags-rmap nil)
1983 (case-fold-search nil))
1984 ;; extract the tag mapping hashes (fwd and rev) and the tag list:
1985 (if (and (setq cache-hash (cadr cache-entry))
1986 (setq tags-rmap (cadr rmap-cache ))
1987 (setq tags-list (cadr list-cache )))
1988 (mapcar
1989 (lambda (TAG)
1990 (let* ((start nil)
1991 (stop nil)
1992 (href nil)
1993 (name nil)
1994 (case-fold-search nil)
1995 (tmp-point nil)
1996 (maybe-start nil)
1997 (face-at nil)
1998 (rmap-entry nil)
1999 (rnew-elt nil)
2000 (rmap-line nil)
2001 (tag-regex (hfy-word-regex TAG))
2002 (tag-map (gethash TAG cache-hash))
2003 (tag-files (mapcar (lambda (X) (car X)) tag-map)))
2004 ;; find instances of TAG and do what needs to be done:
2005 (goto-char (point-min))
2006 (while (search-forward TAG nil 'NOERROR)
2007 (setq tmp-point (point)
2008 maybe-start (- (match-beginning 0) 1))
2009 (goto-char maybe-start)
2010 (if (not (looking-at tag-regex))
2011 nil
2012 (setq start (match-beginning 1))
2013 (setq stop (match-end 1))
2014 (setq face-at
2015 (and (or no-comment no-strings) (hfy-face-at start)))
2016 (if (listp face-at)
2017 (setq face-at (cadr (memq :inherit face-at))))
2018 (if (or (text-property-any start (1+ stop) 'hfy-linkp t)
2019 (and no-comment (eq 'font-lock-comment-face face-at))
2020 (and no-strings (eq 'font-lock-string-face face-at)))
2021 nil ;; already a link, NOOP
2022
2023 ;; set a reverse map entry:
2024 (setq rmap-line (line-number-at-pos)
2025 rmap-entry (gethash TAG tags-rmap)
2026 rnew-elt (list file rmap-line start)
2027 rmap-entry (cons rnew-elt rmap-entry)
2028 name (format "%s.%d" TAG rmap-line))
2029 (put-text-property start (1+ start) 'hfy-inst name)
2030 (puthash TAG rmap-entry tags-rmap)
2031
2032 ;; mark the link. link to index if the tag has > 1 def
2033 ;; add the line number to the #name if it does not:
2034 (setq href (hfy-href file tag-files TAG tag-map))
2035 (put-text-property start (1+ start) 'hfy-link href)
2036 (put-text-property stop (1+ stop ) 'hfy-endl t )
2037 (put-text-property start (1+ stop ) 'hfy-linkp t )))
2038 (goto-char tmp-point)) ))
2039 tags-list) )))
2040
2041(defun hfy-shell ()
2042 "Return `shell-file-name', or \"/bin/sh\" if it is a non-bourne shell."
2043 (if (string-match "\\<bash\\>\\|\\<sh\\>\\|\\<dash\\>" shell-file-name)
2044 shell-file-name
2045 (or hfy-shell-file-name "/bin/sh")))
2046
2047;; cache the #(tag => file line point) entries for files under srcdir
2048;; and cache the descending sorted list of tags in the relevant alist,
2049;; also keyed by srcdir:
2050(defun hfy-load-tags-cache (srcdir)
2051 "Run `hfy-etags-cmd' on SRCDIR, then call `hfy-parse-tags-buffer'."
2052 ;;(message "hfy-load-tags-cache");;DBUG
2053 (let ((etags-buffer (get-buffer-create "*hfy-tags*"))
2054 (etags-command (format hfy-etags-cmd hfy-etags-bin))
2055 (shell-file-name (hfy-shell)))
2056 (cd srcdir)
2057 (shell-command etags-command etags-buffer)
2058 (hfy-parse-tags-buffer srcdir etags-buffer)) )
2059
2060;; break this out from `hfy-load-tags-cache' to make the tar file
2061;; functionality easier to implement.
2062;; ( tar file functionality not merged here because it requires a
2063;; hacked copy of etags capable of tagging stdin: if Francesco
2064;; Potorti accepts a patch, or otherwise implements stdin tagging,
2065;; then I will provide a `htmlfontify-tar-file' defun )
2066(defun hfy-parse-tags-buffer (srcdir buffer)
2067 "Parse a BUFFER containing etags formatted output, loading the
2068`hfy-tags-cache' and `hfy-tags-sortl' entries for SRCDIR."
2069 (let ((cache-entry (assoc srcdir hfy-tags-cache))
2070 (tlist-cache (assoc srcdir hfy-tags-sortl))
2071 (trmap-cache (assoc srcdir hfy-tags-rmap ))
2072 (cache-hash nil) (trmap-hash nil) (tags-list nil)
2073 (hash-entry nil) (tag-string nil) (tag-line nil)
2074 (tag-point nil) (new-entry nil) (etags-file nil))
2075
2076 ;; (re)initialise the tag reverse map:
2077 (if trmap-cache (setq trmap-hash (cadr trmap-cache))
2078 (setq trmap-hash (make-hash-table :test 'equal))
2079 (setq hfy-tags-rmap (list (list srcdir trmap-hash) hfy-tags-rmap)))
2080 (clrhash trmap-hash)
2081
2082 ;; (re)initialise the tag cache:
2083 (if cache-entry (setq cache-hash (cadr cache-entry))
2084 (setq cache-hash (make-hash-table :test 'equal))
2085 (setq hfy-tags-cache (list (list srcdir cache-hash) hfy-tags-cache)))
2086 (clrhash cache-hash)
2087
2088 ;; cache the TAG => ((file line point) (file line point) ... ) entries:
e3353a78 2089 (with-current-buffer buffer
acca02b0
SM
2090 (goto-char (point-min))
2091
2092 (while (and (looking-at "^\x0c") (= 0 (forward-line 1)))
2093 ;;(message "^L boundary")
2094 (if (and (looking-at "^\\(.+\\),\\([0-9]+\\)$")
2095 (= 0 (forward-line 1)))
2096 (progn
2097 (setq etags-file (match-string 1))
2098 ;;(message "TAGS for file: %s" etags-file)
2099 (while (and (looking-at hfy-etag-regex) (= 0 (forward-line 1)))
2100 (setq tag-string (match-string 1))
2101 (if (= 0 (length tag-string)) nil ;; noop
2102 (setq tag-line (round (string-to-number (match-string 2))))
2103 (setq tag-point (round (string-to-number (match-string 3))))
2104 (setq hash-entry (gethash tag-string cache-hash))
2105 (setq new-entry (list etags-file tag-line tag-point))
2106 (setq hash-entry (cons new-entry hash-entry))
2107 ;;(message "HASH-ENTRY %s %S" tag-string new-entry)
2108 (puthash tag-string hash-entry cache-hash)))) )))
2109
2110 ;; cache a list of tags in descending length order:
2111 (maphash (lambda (K V) (setq tags-list (cons K tags-list))) cache-hash)
2112 (setq tags-list (sort tags-list (lambda (A B) (< (length B) (length A)))))
2113
2114 ;; put the tag list into the cache:
2115 (if tlist-cache (setcar (cdr tlist-cache) tags-list)
2116 (setq hfy-tags-sortl (cons (list srcdir tags-list) hfy-tags-sortl)))
2117
2118 ;; return the number of tags found:
2119 (length tags-list) ))
2120
2121(defun hfy-prepare-index-i (srcdir dstdir filename &optional stub map)
2122 "Prepare a tags index buffer for SRCDIR.
2123`hfy-tags-cache' must already have an entry for SRCDIR for this to work.
2124`hfy-page-header', `hfy-page-footer', `hfy-link-extn' and `hfy-extn'
2125all play a part here.\n
2126If STUB is set, prepare an \(appropriately named\) index buffer
2127specifically for entries beginning with STUB.\n
2128If MAP is set, use that instead of `hfy-tags-cache'.
2129FILENAME is the name of the file being indexed.
2130DSTDIR is the output directory, where files will be written."
2131 ;;(message "hfy-write-index");;DBUG
2132 (let ((cache-entry (assoc srcdir (or map hfy-tags-cache)))
2133 (cache-hash nil)
2134 (tag-list nil)
2135 (index-file
2136 (concat filename (if stub (concat "." stub) "") hfy-extn))
2137 (index-buf nil))
2138 (if (not (and cache-entry
2139 (setq cache-hash (cadr cache-entry))
2140 (setq index-buf (get-buffer-create index-file))))
2141 nil ;; noop
2142 (maphash (lambda (K V) (setq tag-list (cons K tag-list))) cache-hash)
2143 (setq tag-list (sort tag-list 'string<))
2144 (set-buffer index-buf)
2145 (erase-buffer)
2146 (insert (funcall hfy-page-header filename "<!-- CSS -->"))
2147 (insert "<table class=\"index\">\n")
2148
2149 (mapc
2150 (lambda (TAG)
2151 (let ((tag-started nil))
2152 (mapc
2153 (lambda (DEF)
2154 (if (and stub (not (string-match (concat "^" stub) TAG)))
2155 nil ;; we have a stub and it didn't match: NOOP
2156 (let ((file (car DEF))
2157 (line (cadr DEF)))
2158 (insert
2159 (format
2160 (concat
2161 " <tr> \n"
2162 " <td>%s</td> \n"
2163 " <td><a href=\"%s%s\">%s</a></td> \n"
2164 " <td><a href=\"%s%s#%s.%d\">%d</a></td>\n"
2165 " </tr> \n")
2166 (if (string= TAG tag-started) "&nbsp;"
2167 (format "<a name=\"%s\">%s</a>" TAG TAG))
2168 file (or hfy-link-extn hfy-extn) file
2169 file (or hfy-link-extn hfy-extn) TAG line line))
2170 (setq tag-started TAG))))
2171 (gethash TAG cache-hash)))) tag-list)
2172 (insert "</table>\n")
2173 (insert (funcall hfy-page-footer filename))
2174 (and dstdir (cd dstdir))
2175 (set-visited-file-name index-file)
2176 index-buf) ))
2177
2178(defun hfy-prepare-index (srcdir dstdir)
2179 "Return a list of index buffer\(s\), as determined by `hfy-split-index'.
2180SRCDIR and DSTDIR are the source and output directories respectively."
2181 (if (not hfy-split-index)
2182 (list (hfy-prepare-index-i srcdir dstdir hfy-index-file nil))
2183 (let ((stub-list nil)
2184 (cache-hash nil)
2185 (index-list nil)
2186 (cache-entry (assoc srcdir hfy-tags-cache)))
2187 (if (and cache-entry (setq cache-hash (cadr cache-entry)))
2188 (maphash
2189 (lambda (K V)
2190 (let ((stub (upcase (substring K 0 1))))
2191 (if (member stub stub-list)
2192 nil ;; seen this already: NOOP
2193 (setq
2194 stub-list (cons stub stub-list)
2195 index-list (cons (hfy-prepare-index-i srcdir
2196 dstdir
2197 hfy-index-file
2198 stub)
2199 index-list)) ))) cache-hash) ) index-list)))
2200
2201(defun hfy-prepare-tag-map (srcdir dstdir)
2202 "Prepare the counterpart\(s\) to the index buffer\(s\) - a list of buffers
2203with the same structure, but listing \( and linking to \) instances of tags
2204\( as opposed to their definitions \).\n
2205SRCDIR and DSTDIR are the source and output directories respectively.
2206See: `hfy-prepare-index'
2207 `hfy-split-index'."
2208 (if (not hfy-split-index)
2209 (list (hfy-prepare-index-i srcdir
2210 dstdir
2211 hfy-instance-file
2212 nil
2213 hfy-tags-rmap))
2214 (let ((stub-list nil)
2215 (cache-hash nil)
2216 (index-list nil)
2217 (cache-entry (assoc srcdir hfy-tags-rmap)))
2218
2219 (if (and cache-entry (setq cache-hash (cadr cache-entry)))
2220 (maphash
2221 (lambda (K V)
2222 (let ((stub (upcase (substring K 0 1))))
2223 (if (member stub stub-list)
2224 nil ;; seen this already: NOOP
2225 (setq
2226 stub-list (cons stub stub-list)
2227 index-list (cons (hfy-prepare-index-i srcdir
2228 dstdir
2229 hfy-instance-file
2230 stub
2231 hfy-tags-rmap)
2232 index-list)) ))) cache-hash) ) index-list)))
2233
2234(defun hfy-subtract-maps (srcdir)
2235 "Internal function - strips definitions of tags from the instance map.
2236SRCDIR is the directory being \"published\".
2237See: `hfy-tags-cache' and `hfy-tags-rmap'"
2238 (let ((new-list nil)
2239 (old-list nil)
2240 (def-list nil)
2241 (exc-list nil)
2242 (fwd-map (cadr (assoc srcdir hfy-tags-cache)))
2243 (rev-map (cadr (assoc srcdir hfy-tags-rmap )))
2244 (taglist (cadr (assoc srcdir hfy-tags-sortl))))
2245 (mapc
2246 (lambda (TAG)
2247 (setq def-list (gethash TAG fwd-map)
2248 old-list (gethash TAG rev-map)
2249 new-list nil
2250 exc-list nil)
2251 (mapc
2252 (lambda (P)
2253 (setq exc-list (cons (list (car P) (cadr P)) exc-list))) def-list)
2254 (mapc
2255 (lambda (P)
2256 (or (member (list (car P) (cadr P)) exc-list)
2257 (setq new-list (cons P new-list)))) old-list)
2258 (puthash TAG new-list rev-map)) taglist) ))
2259
2260(defun htmlfontify-run-etags (srcdir)
2261 "Load the etags cache for SRCDIR.
2262See `hfy-load-tags-cache'."
2263 (interactive "D source directory: ")
2264 (setq srcdir (directory-file-name srcdir))
2265 (hfy-load-tags-cache srcdir))
2266
2267;;(defun hfy-test-read-args (foo bar)
2268;; (interactive "D source directory: \nD target directory: ")
2269;; (message "foo: %S\nbar: %S" foo bar))
2270
2271(defun hfy-save-kill-buffers (buffer-list &optional dstdir)
2272 (mapc (lambda (B)
2273 (set-buffer B)
2274 (and dstdir (file-directory-p dstdir) (cd dstdir))
2275 (save-buffer)
2276 (kill-buffer B)) buffer-list) )
2277
2278(defun htmlfontify-copy-and-link-dir (srcdir dstdir &optional f-ext l-ext)
2279 "Trawl SRCDIR and write fontified-and-hyperlinked output in DSTDIR.
2280F-EXT and L-EXT specify values for `hfy-extn' and `hfy-link-extn'.\n
2281You may also want to set `hfy-page-header' and `hfy-page-footer'."
2282 (interactive "D source directory: \nD output directory: ")
2283 ;;(message "htmlfontify-copy-and-link-dir")
2284 (setq srcdir (directory-file-name srcdir))
2285 (setq dstdir (directory-file-name dstdir))
2286 (let ((source-files "SETME: list of source files, relative to srcdir")
2287 (tr-cache (assoc srcdir hfy-tags-rmap))
2288 (hfy-extn (or f-ext ".html"))
2289 (hfy-link-extn (or l-ext ".html")))
2290 ;; oops, forgot to load etags for srcdir:
2291 (if tr-cache nil
2292 (message "autoload of tags cache")
2293 (hfy-load-tags-cache srcdir)
2294 (setq tr-cache (assoc srcdir hfy-tags-rmap)))
2295 ;; clear out the old cache:
2296 (clrhash (cadr tr-cache))
2297 (hfy-make-directory dstdir)
2298 (setq source-files (hfy-list-files srcdir))
2299 (mapc (lambda (file)
2300 (hfy-copy-and-fontify-file srcdir dstdir file)) source-files)
2301 (hfy-subtract-maps srcdir)
2302 (hfy-save-kill-buffers (hfy-prepare-index srcdir dstdir) dstdir)
2303 (hfy-save-kill-buffers (hfy-prepare-tag-map srcdir dstdir) dstdir) ))
2304
2305;; name of the init file we want:
2306(defun hfy-initfile ()
2307 "Return the expected location of the htmlfontify specific init/custom file."
2308 (let* ((file (or (getenv "HFY_INITFILE") ".hfy.el")))
2309 (expand-file-name file "~") ))
2310
2311
2312;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2313;; incomplete as yet : transfer hook settings to hfy init file:
2314;; (defalias 'hfy-set-hooks 'custom-set-variables)
2315
2316;; (defun hfy-pp-hook (H)
2317;; (and (string-match "-hook$" (symbol-name H))
2318;; (boundp H)
2319;; (symbol-value H)
2320;; (insert (format "\n '(%S %S)" H (symbol-value H)))
2321;; )
2322;; )
2323
2324;; (defun hfy-save-hooks ()
2325;; (let ((custom-file (hfy-initfile)))
2326;; (custom-save-delete 'hfy-set-hooks)
2327;; (let ((standard-output (current-buffer)))
2328;; (princ "(hfy-set-hooks\n;;auto-generated, only one copy allowed\n")
2329;; (mapatoms 'hfy-pp-hook)
2330;; (insert "\n)")
2331;; )
2332;; )
2333;; )
2334;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2335
2336(defalias 'hfy-init-progn 'progn)
2337
2338(defun hfy-save-initvar (sym)
2339 (princ (format "(setq %s\n '" sym))
2340 (pp (symbol-value sym))
2341 (princ ")\n"))
2342
2343(defun htmlfontify-save-initfile ()
2344 "Save the htmlfontify settings to the htmlfontify init file."
2345 (interactive)
2346 (let* ((start-pos nil)
2347 (custom-file (hfy-initfile))
2348 (standard-output (find-file-noselect custom-file 'nowarn)))
2349 (save-excursion
2350 (custom-save-delete 'hfy-init-progn)
2351 (setq start-pos (point))
2352 (princ "(hfy-init-progn\n;;auto-generated, only one copy allowed\n")
2353 (mapc 'hfy-save-initvar
2354 (list 'auto-mode-alist 'interpreter-mode-alist))
2355 (princ ")\n")
2356 (indent-region start-pos (point) nil))
2357 (custom-save-all) ))
2358
2359(defun htmlfontify-load-initfile ()
2360 "Load the htmlfontify specific init/custom file."
2361 (interactive)
2362 (let ((file (hfy-initfile)))
2363 (load file 'NOERROR nil nil) ))
2364
2365(provide 'htmlfontify)
2366;;; htmlfontify.el ends here
2367