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