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