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