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