]> git.rkrishnan.org Git - .emacs.d.git/blob - emacs/quack.el
remove toolbar and menubar
[.emacs.d.git] / emacs / quack.el
1 ;;; quack.el --- enhanced support for editing and running Scheme code
2
3 (defconst quack-copyright    "Copyright (C) 2002-2012 Neil Van Dyke")
4 (defconst quack-copyright-2  "Portions Copyright (C) Free Software Foundation")
5 ;; Emacs-style font-lock specs adapted from GNU Emacs 21.2 scheme.el.
6 ;; Scheme Mode menu adapted from GNU Emacs 21.2 cmuscheme.el.
7
8 (defconst quack-version      "0.44")
9 (defconst quack-author-name  "Neil Van Dyke")
10 (defconst quack-author-email "neil@neilvandyke.org")
11 (defconst quack-web-page     "http://www.neilvandyke.org/quack/")
12
13 (defconst quack-legal-notice
14   "This is free software; you can redistribute it and/or modify it under the
15 terms of the GNU General Public License as published by the Free Software
16 Foundation; either version 2, or (at your option) any later version.  This is
17 distributed in the hope that it will be useful, but without any warranty;
18 without even the implied warranty of merchantability or fitness for a
19 particular purpose.  See the GNU General Public License for more details.  See
20 http://www.gnu.org/licenses/ for details.  For other licenses and consulting,
21 please contact Neil Van Dyke.")
22
23 (defconst quack-cvsid "$Id: quack.el,v 1.481 2012-04-11 17:42:25 user Exp $")
24
25 ;;; Commentary:
26
27 ;; INTRODUCTION:
28 ;;
29 ;;     Quack enhances Emacs support for Scheme programming.
30 ;;
31 ;;     Install Quack rather than following non-Quack-based tutorials on how to
32 ;;     set up Emacs for Scheme.
33 ;;
34 ;;     The name "Quack" was a play on "DrScheme".
35 ;;
36 ;;     Quack is dedicated to Yosh, naturally.
37
38 ;; COMPATIBILITY:
39 ;;
40 ;;     GNU Emacs 23 and 22 -- Yes.  Quack is now developed under GNU Emacs 23
41 ;;     on a GNU/Linux system, which is the preferred platform for Quacksmokers.
42 ;;     Quack should work under GNU Emacs 23 on any Un*x-like OS.  Reportedly,
43 ;;     Quack also works with GNU Emacs 22 on Apple Mac OS X and Microsoft
44 ;;     Windows (NT, 2000, XP), but the author has no means of testing on those
45 ;;     platforms.
46 ;;
47 ;;     GNU Emacs 21 -- Probably, but no longer tested.
48 ;;
49 ;;     GNU Emacs 20 -- Probably mostly.  When last tested. Some of the menus do
50 ;;     not work properly, due to a bug in easymenu.el (which the FSF will not
51 ;;     fix, since they no longer support Emacs 20).  Nested block comments are
52 ;;     not fontified correctly.  Pretty-lambda does not work.  Quack runs less
53 ;;     efficiently in 20 than 21, due to the lack of standard hash tables.
54 ;;
55 ;;     XEmacs 21 -- Probably mostly, but no longer tested.  Block comment
56 ;;     fontification is not yet supported under XEmacs 21, due to what appears
57 ;;     to be a bug in 21.4 font-lock.  Pretty-lambda does not work.  XEmacs
58 ;;     Quacksmokers who always want the latest and greatest Quack should
59 ;;     consider GNU Emacs 21 -- Quack treats XEmacs like a high-maintenance
60 ;;     redheaded stepchild.
61
62 ;; INSTALLATION:
63 ;;
64 ;;     To install, put this file (`quack.el') somewhere in your Emacs load
65 ;;     path, and add the following line to your `.emacs' file:
66 ;;
67 ;;         (require 'quack)
68 ;;
69 ;;     If you don't know what your Emacs load path is, try invoking the command
70 ;;     "C-h v load-path RET" or consulting the Emacs manual.
71 ;;
72 ;;     Note to advanced Emacsers: Byte-compiled `quack.elc' files generally are
73 ;;     *not* portable between Emacs implementations, nor between different
74 ;;     versions of the same implementation.
75 ;;
76 ;;     You will also need the GNU `wget' program, which Quack uses for
77 ;;     downloading SRFI indexes.  This popular program is included in most
78 ;;     GNU/Linux distributions and is available for most other platforms.
79 ;;
80 ;;     Note to PLT Scheme users: If you do not already have the PLT manuals
81 ;;     installed, they can be downloaded from 
82 ;;     `http://download.plt-scheme.org/doc/' and installed in your PLT `doc'
83 ;;     collection.  If Quack is not finding installed PLT manuals, then be sure
84 ;;     that the `quack-pltcollect-dirs' variable contains the appropriate
85 ;;     collection directory (if it does not, then either set the `PLTHOME'
86 ;;     and/or `PLTCOLLECTS' environment variables appropriately, or set
87 ;;     `quack-pltcollect-dirs').
88
89 ;; KEY BINDINGS:
90 ;;
91 ;;     The key bindings that Quack adds to `scheme-mode' include:
92 ;;
93 ;;         C-c C-q m   View a manual in your Web browser.
94 ;;         C-c C-q k   View the manual documentation for a keyword
95 ;;                     (currently only works for PLT manuals).
96 ;;         C-c C-q s   View an SRFI.
97 ;;         C-c C-q r   Run an inferior Scheme process.
98 ;;         C-c C-q f   Find a file using context of point for default.
99 ;;         C-c C-q l   Toggle `lambda' syntax of `define'-like form.
100 ;;         C-c C-q t   Tidy the formatting of the buffer.
101 ;;
102 ;;     One additional command that does not currently have a standard binding
103 ;;     is `quack-dired-pltcollect', which prompts for a PLT collection name and
104 ;;     creates a Dired buffer on the collection's directory.  (A future version
105 ;;     of Quack may integrate this functionality into a more generalized
106 ;;     documentation navigation interface.)
107
108 ;; RELEASE ANNOUNCEMENTS EMAIL:
109 ;;
110 ;;     To receive email notification when a new Quack version is released, ask
111 ;;     neil@neilvandyke.org to add you to the moderated `scheme-announce' list.
112
113 ;; HISTORY:
114 ;;
115 ;;     Version 0.44 (2012-04-11):
116 ;;         * Added indent and fontify for `struct', `module+', `module*'.
117 ;;         * Changed intent for `module' from `defun' to 2.
118 ;;         * Added fontify for `define-syntax-class',
119 ;;           `define-splicing-syntax-class', `begin-for-syntax'.
120 ;;         * Changed `define-struct' fontify.
121 ;;
122 ;;     Version 0.43 (2011-08-23):
123 ;;         * Add indent and fontify for "syntax-parse".
124 ;;         * Added another compile error regexp for Racket backtraces.
125 ;;
126 ;;     Version 0.42 (2011-07-30):
127 ;;         * Added compile error regexp for "raco".
128 ;;
129 ;;     Version 0.41 (2011-06-04)
130 ;;         * Added `sxml-match' to `scheme-indent-function'.
131 ;;
132 ;;     Version 0.40 (2010-12-22)
133 ;;         * Added indent rules for Racket `let:', `let*:', and `match'.  And
134 ;;           a provisional rule for `define:'.
135 ;;
136 ;;     Version 0.39 (2010-10-18)
137 ;;         * Renamed "typed/scheme" to "typed/racket".
138 ;;
139 ;;     Version 0.38 (2010-10-14)
140 ;;         * Replaced old PLT Scheme programs in `quack-programs' with Racket.
141 ;;         * Added Racket ".rkt" and ".rktd" filename extensions.
142 ;;         * Added some Racket keywords for fontifying.
143 ;;
144 ;;     Version 0.37 (2009-06-29)
145 ;;         * Disabled highlighting of "Compilation started at" lines.
146 ;;
147 ;;     Version 0.36 (2009-05-27)
148 ;;         * Made `#:' ``colon keywords'' fontify in PLT-ish mode.
149 ;;         * Added PLT `r6rs' and `typed-scheme' languages to `quack-programs'.
150 ;;
151 ;;     Version 0.35 (2009-02-24)
152 ;;         * Added `interpreter-mode-alist' support, so Scheme scripts with "#!"
153 ;;           start in `scheme-mode'.
154 ;;         * Added PLT `parameterize-break'.
155 ;;         * Improved `compile' mode for PLT 4.x tracebacks when there is only
156 ;;           file, line, and column, but no additional information.
157 ;;
158 ;;     Version 0.34 (2009-02-19)
159 ;;         * Added fontify and indent support for PLT `define/kw', `lambda/kw',
160 ;;          `parameterize*'.
161 ;;         * Fontify Unix "#!" cookie in PLT-ish font-lock.
162 ;;         * Changed reference to `quack-announce' email list to
163 ;;           `scheme-announce'.
164 ;;         * Added PLT `default-load-handler' to
165 ;;          `quack-compilation-error-regexp-alist-additions'
166 ;;         * Changed some face ":height" attributes.
167 ;;
168 ;;     Version 0.33 (2008-07-31)
169 ;;         * Added handlers for some PLT 4.0.1 "setup-plt" messages.
170 ;;
171 ;;     Version 0.32 (2008-06-19)
172 ;;         * Added to `quack-programs'.
173 ;;         * Updated compatibility comments.
174 ;;         * Added indent rule for `for/fold'.
175 ;;
176 ;;     Version 0.31 (2008-05-03)
177 ;;         * Added `defvar' for `quack-pltish-font-lock-keywords', so that the
178 ;;           GNU Emacs 22.1 compiler doesn't complain about assignment to a free
179 ;;           variable.
180 ;;         * Changed banner regexp for MzScheme for v3.99.x.
181 ;;         * Set `dynamic-wind' `scheme-indent-function to 0, when the default
182 ;;           is 3.  It was just taking up too much space.  DrScheme's
183 ;;           indentation seems to be equivalent -1, so there is precedent for
184 ;;           something different.  We generally respect Emacs indentation
185 ;;           convention.
186 ;;         * Added fontifying and indent for PLT `define-for-syntax',
187 ;;           `define-values-for-syntax', `quasisyntax', `quasisyntax/loc',
188 ;;           `syntax', `syntax/loc', `define-parameters'.
189 ;;         * Advise `scheme-interactively-start-process' for GNU Emacs 22.
190 ;;         * Removed TODO comment that mentioned using `(current-eventspace
191 ;;           (make-eventspace))' under `mred', as Robby Findler has indicated
192 ;;           that is not good advice.
193 ;;
194 ;;     Version 0.30 (2007-06-27)
195 ;;         * Emacs 22 compatibility change: `string-to-number' instead of
196 ;;           `string-to-int'.  Thanks to Charles Comstock.
197 ;;
198 ;;     Version 0.29 (2006-11-12)
199 ;;         * Fixed `quack-bar-syntax-string', which caused vertical bar
200 ;;           characters to be treated as whitespace.  Thanks to Eric Hanchrow
201 ;;           for reporting.
202 ;;
203 ;;     Version 0.28 (2005-05-14)
204 ;;         * Added `quack-smart-open-paren-p'.
205 ;;         * Changed `scheme-indent-function' for `parameterize' from `defun'
206 ;;           to `1'.
207 ;;         * In `quack-pltish-keywords-to-fontify': added `quasiquote',
208 ;;           `unquote', and `unquote-splicing'.
209 ;;         * Added ".mzschemerc" to `auto-mode-alist'.
210 ;;         * Added a little extra threesemi fontification for Funcelit and
211 ;;           similar Texinfo markup formats.
212 ;;
213 ;;     Version 0.27 (2004-12-19)
214 ;;         * For Gambit-C, added REPL banner fontifying, `quack-manuals' entry,
215 ;;           and "gsi ~~/syntax-case.scm -" `quack-programs' entry.
216 ;;         * Changed "[PLT]" prefix on PLT manuals to "PLT", to make it easier
217 ;;           to type.
218 ;;         * Minor changes to reflect "MIT Scheme" becoming "MIT/GNU Scheme".
219 ;;
220 ;;     Version 0.26 (2004-07-14)
221 ;;         * Added fontifying of a bunch of "define-"* syntax from Chicken.
222 ;;
223 ;;     Version 0.25 (2004-07-09)
224 ;;         * Added `define-record-type' to `quack-pltish-keywords-to-fontify'.
225 ;;         * Added "csi -hygienic" to `quack-programs'.
226 ;;         * In `quack-manuals', replaced PLT-specific `r5rs' and `t-y-scheme'
227 ;;           with generic ones.
228 ;;         * Updated URL in `quack-manuals' for 3rd ed. of `tspl'.
229 ;;         * `quack-view-manual' completions no longer include symbols.
230 ;;         * `quack-view-manual' completion default is now "R5RS".
231 ;;
232 ;;     Version 0.24 (2004-05-09)
233 ;;         * Made `quack-pltish-keywords-to-fontify' and
234 ;;           `quack-emacs-keywords-to-fontify' custom changes update
235 ;;           immediately.  Bug reported by Taylor Campbell.
236 ;;         * Removed some non-syntax names from  
237 ;;           `quack-pltish-keywords-to-fontify'.
238 ;;         * Documentation changes.
239 ;;
240 ;;     Version 0.23 (2003-11-11)
241 ;;         * `quack-local-keywords-for-remote-manuals-p' can now have the value
242 ;;           of the symbol `always', to work around a defect in some versions
243 ;;           of Microsoft Windows.  Thanks to Bill Clementson.
244 ;;         * `quack-w3m-browse-url-other-window' no longer splits a `*w3m*'
245 ;;           buffer.
246 ;;         * Added indent and `quack-pltish-keywords-to-fontify' rules for
247 ;;           `c-lambda' and `c-declare'.
248 ;;
249 ;;     Version 0.22 (2003-07-03)
250 ;;         * `quack-newline-behavior' controls the RET key behavior in Scheme
251 ;;           buffers.
252 ;;         * In `quack-manuals', added Chez Scheme, and updated Chicken.
253 ;;         * Added error message navigation to `compile' for PLT `setup-plt'.
254 ;;         * Partial fix for Quack global menu disappearing from the main menu
255 ;;           bar in XEmacs.  Thought it used to work, but it doesn't in XEmacs
256 ;;           21.4.12.
257 ;;
258 ;;     Version 0.21 (2003-05-28)
259 ;;         * `quack-find-file' is faster in many cases due to fix to
260 ;;           `quack-backward-sexp'.
261 ;;         * Added auto-mode-alist for `.ccl', `.stk', and `.stklos' files.
262 ;;         * Indent rule additions/changes for `chicken-setup' and `unit/sig'.
263 ;;
264 ;;     Version 0.20 (2003-05-04)
265 ;;         * Added indent and fontify for SRFI-8 "receive".
266 ;;         * Added indent and fontify for additional PLT syntax.
267 ;;         * Added `quack-fontify-threesemi-p'.
268 ;;         * `quack-tidy-buffer' sets `fill-prefix' to nil when running.
269 ;;         * Added messages to `run-scheme', if only to get rid of annoying 
270 ;;           "Mark set" message.
271 ;;         * Added "mzscheme -M errortrace" to `quack-programs'.
272 ;;         * `quack-dired-pltcollect' prompt defaults to `mzlib'.
273 ;;         * "Update SRFI Index" menu item has moved to top of menu, mainly to
274 ;;           avoid usability issue in a particular Emacs menu implementation.
275 ;;         * Several code quality improvements sent by Stefan Monnier will be
276 ;;           in the next release.
277 ;;
278 ;;     Version 0.19 (2003-03-04)
279 ;;         * Commands such as `scheme-load-file' now start a Scheme process if
280 ;;           none is found.
281 ;;         * Bugfix for using `match-string-no-properties' when we meant
282 ;;           `quack-match-string-no-properties'.  (Thanks to Noel Welsh.)
283 ;;
284 ;;     Version 0.18 (2003-05-02)
285 ;;         * Removed uses of `(regexp-opt LIST t)', since XEmacs21 does not
286 ;;           create match data.  (Thanks to Garrett Mitchener for debugging.)
287 ;;         * Added to `quack-programs' and `quack-manuals'.
288 ;;         * Added pretty-case-lambda.
289 ;;         * Changed PLT documentation URL function.
290 ;;
291 ;;     Version 0.17 (2003-01-03)
292 ;;         * Pretty-lambda is supported well under GNU Emacs 21, when using PLT
293 ;;           Style fontification.  Enable via the Options menu.  (Based on
294 ;;           approach by Stefan Monnier; suggested by Ray Racine.)
295 ;;         * Various faces now have separate defaults for `light' and `dark'
296 ;;           backgrounds, so may now look better on dark backgrounds.
297 ;;           (Suggested by Eli Barzilay.)
298 ;;         * `quack-find-file' now respects `insert-default-directory' when
299 ;;           there is no default file.  (Thanks to Eli Barzilay.)
300 ;;         * Most of the special w3m support has been moved to a separate
301 ;;           package, `w3mnav' (`http://www.neilvandyke.org/w3mnav/').
302 ;;           `quack-w3m-browse-url-other-window' has been added.
303 ;;
304 ;;     Version 0.16 (2002-12-16)
305 ;;         * `quack-insert-closing' now calls `blink-paren-function'.  (Thanks
306 ;;           to Guillaume Marceau and Steve Elkins for reporting this.)
307 ;;         * Now uses PLT 202 manuals.  Added "PLT Framework" manual.
308 ;;         * Added `quack-pltish-module-defn-face'.
309 ;;         * Added some PLTish font-lock keywords.
310 ;;
311 ;;     Version 0.15 (2002-11-21)
312 ;;         * "Keywords" are now fontified in PLT Style fontification mode.
313 ;;         * Definition names are now blue by default in PLT Style.
314 ;;         * Symbol literals with vertical bars are now fontified in PLT Style.
315 ;;         * New `quack-manuals-webjump-sites' function for people who prefer
316 ;;           to use the `webjump' package for invoking manuals.
317 ;;         * New `quack-quiet-warnings-p' option.
318 ;;         * New `quack-pltish-class-defn-face' face.
319 ;;
320 ;;     Version 0.14 (2002-10-18)
321 ;;         * Fix for `quack-view-manual' interactive prompting (thanks to Marko
322 ;;           Slyz for reporting this).
323 ;;         * `quack-emacsw3m-go-next' and `quack-emacsw3m-go-prev' now work
324 ;;           with GTK reference documentation (not that this has anything to do
325 ;;           with Scheme).
326 ;;         * Added SLIB to `quack-manuals'.
327 ;;         * Added comment about installing PLT manuals (thanks to Marko).
328 ;;         * We now call the canonical version of Emacs "GNU Emacs," instead of
329 ;;           "FSF Emacs".
330 ;;
331 ;;     Version 0.13 (2002-09-21)
332 ;;         * Bugfix: No longer drop SRFI index entries on the floor.
333 ;;
334 ;;     Version 0.12 (2002-09-20)
335 ;;         * New "View SRFI" menu.  Select "Update SRFI Index" if the submenus
336 ;;           "Draft", "Final", and "Withdrawn" are disabled.
337 ;;         * Most options are now settable via "Options" menu.
338 ;;         * PLT collections are no longer scanned when building "View Manuals"
339 ;;           menu.
340 ;;         * "View Keyword Docs..." back on Scheme Mode menu in addition to
341 ;;           Quack menu.
342 ;;         * Various `defcustom' variables have been made to dynamically update
343 ;;           relevant program state when changed.
344 ;;         * Under GNU Emacs 20, dynamic menus still do not work -- they now
345 ;;           display, but do not perform the selected action.  Will do more
346 ;;           debugging after this release.
347 ;;         * '[' and ']' keys work in emacs-w3m of MIT Scheme manuals.
348 ;;
349 ;;     Version 0.11 (2002-09-17)
350 ;;         * Menus now work under XEmacs.  Also now partly broken for Emacs 20.
351 ;;         * New global "Quack" menu.  Disable with `quack-global-menu-p'.
352 ;;         * New "View Manual" submenu under GNU Emacs 21 and XEmacs (GNU Emacs
353 ;;           20 is stuck with the old "View Manual..." menu item).
354 ;;         * Fix for `quack-pltcollects-alist' to include PLT `doc' collection,
355 ;;           which was preventing local manuals from being used.
356 ;;         * `quack-manuals' now includes `t-y-scheme'.
357 ;;         * `quack-view-in-different-browser' command that spawns alternative
358 ;;           Web browser from the special emacs-w3m support, bound to `B'.  For
359 ;;           when you normally view manuals in an Emacs window, but
360 ;;           occasionally want to view a particular page in normal Web browser.
361 ;;         * More `scheme-indent-function' properties set.
362 ;;         * `quack-about' command.
363 ;;         * Fix to `quack-keyword-at-point'.
364 ;;
365 ;;     Version 0.10 (2002-09-11)
366 ;;         * `quack-view-srfi' now prompts with completion, including titles
367 ;;           for all SRFIs.  The SRFI titles are fetched from the official SRFI
368 ;;           Web site using the GNU Wget program, and cached locally.
369 ;;         * `quack-view-srfi' also now defaults to the SRFI number at or near
370 ;;           the point.
371 ;;         * `quack-dir' variable specifies a directory where Quack should
372 ;;           store its persistent data files (e.g., cached SRFI indexes), and
373 ;;           defaults to "~/.quack/".
374 ;;         * New `quack-tidy-buffer' command.  [C-c C-q t] is now bound to
375 ;;           this; [C-c C-q l] ("l" as in "lambda) is now the official binding
376 ;;           for `quack-toggle-lambda'.
377 ;;         * `quack-find-file' now recognizes PLT `dynamic-require' form.
378 ;;         * Fix to make `quack-looking-at-backward' preserve match data.
379 ;;         * Fix for benign bug in `quack-parent-sexp-search'.
380 ;;
381 ;;     Version 0.9 (2002-09-04)
382 ;;         * Quack now works under XEmacs 21, except no menus are currently
383 ;;           defined (that will come in a later version) and block comments
384 ;;           aren't fontified.
385 ;;         * `quack-toggle-lambda' command toggles a `define' form between
386 ;;           explicit and implicit `lambda' syntax.
387 ;;         * `quack-dired-pltcollect' feature prompts for a PLT collection name
388 ;;           and creates a Dired on the collection.
389 ;;         * `)' and `]' keys are bound to insert a closing character that
390 ;;           agrees with the opening character of the sexp.
391 ;;         * Nested `#|' comment blocks are now fontified mostly correctly
392 ;;           under GNU Emacs 21.
393 ;;         * Fix to `quack-parent-sexp-search'.
394 ;;         * Fix for PLT manual keywords lookup under Emacs 20.
395 ;;         * `quack-manuals' URLs for assorted implementation manuals now point
396 ;;           to canonical Web copies.
397 ;;         * No longer warns about PLT manual keywords file found without HTML.
398 ;;         * `find-file' key bindings are automatically remapped to
399 ;;           `quack-find-file' in Scheme buffers.
400 ;;         * Both PLT-style and Emacs-style fontification now work with the
401 ;;           `noweb-mode' package.  Tested under GNU Emacs 21 with
402 ;;           Debian `nowebm' package version 2.10c-1.
403 ;;         * Added to `quack-emacsish-keywords-to-fontify'.
404 ;;         * Disabled fontification of named `let'.
405 ;;         * Renamed "collect" in PLT identifiers to "pltcollect".
406 ;;         * `auto-mode-alist' set more aggressively.
407 ;;
408 ;;     Version 0.8 (2002-08-25)
409 ;;         * PLT package file viewing mode.  This is mainly used to easily
410 ;;           inspect a ".plt" package before installing it via DrScheme or
411 ;;           "setup-plt".
412 ;;         * No longer warns about `font-lock-keywords' when `noweb-mode'
413 ;;           package is installed.
414 ;;
415 ;;     Version 0.7 (2002-08-22)
416 ;;         * Now works on GNU Emacs 20 (though people are still encouraged to
417 ;;           upgrade to GNU Emacs 21 if they are able).
418 ;;         * `quack-manuals' now includes MIT Scheme and Chicken manuals
419 ;;           (currently where Debian GNU/Linux puts them).
420 ;;         * `quack-view-srfi' command.
421 ;;         * Named-`let' name is fontified like a PLTish definition name.
422 ;;         * `define-record' and `define-opt' fontified.
423 ;;         * Scheme Mode is forced in `auto-mode-alist' for ".sch" files.
424 ;;         * Fix to `quack-backward-sexp'.
425 ;;         * `quack-warning' messages get your attention.
426 ;;         * `quack-pltrequire-at-point-data-1' search depth limited.
427 ;;
428 ;;     Version 0.6 (2002-08-20)
429 ;;         * `quack-find-file' now supports multi-line PLT `require' forms.
430 ;;         * When `emacs-w3m' is used, the keys "[", "]", and "t" are bound to
431 ;;           navigate through PLT manuals like in Info mode.
432 ;;         * Names highlighted in PLT-style fontification of `defmacro',
433 ;;           `defmacro-public', `defsyntax'.
434 ;;         * Advised `run-scheme' no longer prompts when there is already a
435 ;;           running Scheme.
436 ;;         * "csi" (Chicken interpreter) added to `quack-programs' default.
437 ;;         * Forces `auto-mode-alist' for ".scm" files to `scheme-mode'
438 ;;           (two can play at that game, `bee-mode'!).
439 ;;         * To-do comments moved from the top of the file to throughout code.
440 ;;
441 ;;     Version 0.5 (2002-08-15)
442 ;;         * New `quack-find-file' permits quick navigation to files indicated
443 ;;           by a PLT Scheme `require' form under the point.  Currently only
444 ;;           works when the "(require" string is on the same line as point.
445 ;;         * Improved PLT-style fontification.  Most noticeable difference is
446 ;;           that names in many definition forms are boldfaced.  See
447 ;;           `quack-pltish-fontify-definition-names-p' option.
448 ;;         * `quack-collects-alist' added.
449 ;;         * "~/plt/" has been removed from `quack-collect-dirs' default.
450 ;;         * Unnecessary syntax table settings have been removed.
451 ;;         * Reduced memory usage in some cases, via explicit GC calls.
452 ;;
453 ;;     Version 0.4 (2002-08-07)
454 ;;         * Functionality adapted from author's `giguile.el' package:
455 ;;             - Enhanced `run-scheme' behavior.  `quack-run-mzscheme',
456 ;;               `quack-run-mred', and `quack-remove-run-scheme-menu-item-p'
457 ;;               are obsolete.
458 ;;             - Enhanced `switch-to-scheme' behavior.
459 ;;             - Options menu.
460 ;;             - Indent rules for a few Guile-isms.
461 ;;         * Inferior Scheme Mode now uses the preferred fontification method.
462 ;;         * Now uses the PLT-bundled version of R5RS manual, which permits
463 ;;           keyword searching.
464 ;;         * `quack-banner-face' for the MzScheme/MrEd banner in REPL buffer.
465 ;;         * This code includes a start on toolbars and XEmacs21 portability,
466 ;;           but neither feature is yet functional.
467 ;;
468 ;;     Version 0.3 (2002-08-01)
469 ;;         * PLT-style fontification added, except for quoted lists.  Emacs-
470 ;;           style fontification still available; see `quack-fontify-style'.
471 ;;         * `emacs-w3m' package support for lightweight viewing of PLT manuals
472 ;;           in Emacs window.  If you install the `emacs-w3m' package, then you
473 ;;           can change the new `quack-browse-url-browser-function' option to
474 ;;           use it.
475 ;;         * Quack menu items added to Scheme Mode menu.  "Run Scheme" item
476 ;;           is removed by default; see `quack-remove-run-scheme-menu-item-p'.
477 ;;         * MrEd REPL supported with `quack-run-mred'.
478 ;;         * Better default for `quack-collect-dirs'.
479 ;;         * More `scheme-indent-function' settings.
480 ;;         * Bugfix for `quack-prompt-for-kwmatch-choice'.
481 ;;         * Bugfix for font-lock keywords getting set too early.
482 ;;         * Now byte-compiles without warnings/errors.
483 ;;
484 ;;     Version 0.2 (2002-07-28)
485 ;;         * Manual keywords lookup.
486 ;;         * Other minor changes.
487 ;;
488 ;;     Version 0.1 (2002-07-18)
489 ;;         * Initial release.
490
491 ;; ADMONISHMENT TO IMPRESSIONABLE YOUNG SCHEME STUDENTS:
492 ;;
493 ;;     Quack should by no means be construed as a model of good programming,
494 ;;     much less of good software engineering.  Emacs is by nature a complex
495 ;;     system of interacting kludges.  To get Emacs to do useful new things is
496 ;;     to artfully weave one's extensions into a rich tapestry of sticky duct
497 ;;     tape.  Also, Quack usually only got hacked on when I was stuck in a busy
498 ;;     lobby for an hour with a laptop and unable to do real work.
499
500 ;;; Code:
501
502 ;; Dependencies:
503
504 (require 'advice)
505 (require 'cmuscheme)
506 (require 'compile)
507 (require 'custom)
508 (require 'easymenu)
509 (require 'font-lock)
510 (require 'scheme)
511 (require 'thingatpt)
512
513 (unless (fboundp 'customize-save-variable)
514   (autoload 'customize-save-variable "cus-edit"))
515
516 ;; Custom Variables:
517
518 (defgroup quack nil
519   "Enhanced support for editing and running Scheme code."
520   :group  'scheme
521   :prefix "quack-"
522   :link   '(url-link "http://www.neilvandyke.org/quack/"))
523
524 (defcustom quack-dir "~/.quack"
525   "*Directory where Quack stores various persistent data in file format."
526   :type  'string
527   :group 'quack)
528
529 (defcustom quack-scheme-mode-keymap-prefix "\C-c\C-q"
530   "*Keymap prefix string for `quack-scheme-mode-keymap'.
531
532 One of the nice things about having C-q in the prefix is that it is unlikely to
533 be already be in use, due to the historical reality of software flow control
534 \(and the fact that it is hard to type).  If your C-q doesn't seem to be going
535 through, then you have several options: disable flow control (if it is safe to
536 do so), change the value of this variable, or see the Emacs documentation for
537 `enable-flow-control-on'."
538   :type  'string
539   :group 'quack)
540
541 (defcustom quack-remap-find-file-bindings-p t
542   "Whether to remap `find-file' key bindings to `quack-find-file'.
543 The local map in Scheme Mode and Inferior Scheme Mode buffers is used."
544   :type  'boolean
545   :group 'quack)
546
547 (defcustom quack-global-menu-p t
548   "*Whether to have a \"Quack\" menu always on the menu bar."
549   :type  'boolean  :group 'quack)
550
551 (defcustom quack-tabs-are-evil-p t
552   "*Whether Quack should avoid use of Tab characters in indentation."
553   :type  'boolean
554   :group 'quack)
555
556 (defcustom quack-browse-url-browser-function nil
557   "*Optional override for `browse-url-browser-function'.
558
559 If non-nil, overrides that variable for URLs viewed by `quack-browse-url'."
560   :type '(choice (const    :tag "Do Not Override" nil)
561                  (function :tag "Function")
562                  (alist    :tag "Regexp/Function Association List"
563                            :key-type regexp :value-type function))
564   :group 'quack)
565
566 (defcustom quack-manuals                ; TODO: Options menu.
567
568   ;; TODO: If we make this so users are likely to want to override parts of it,
569   ;;       then introduce `quack-manuals-defaults' variable with this in it,
570   ;;       and let users edit `quack-manuals-overrides' which are keyed on the
571   ;;       ID symbol.
572
573   ;; TODO: Have a way for finding docs on the local filesystem, and/or
574   ;;       permitting a user to easily specify location.
575
576   ;; TODO: Provide a way of specifying alternative access means so that, for
577   ;;       example, we can look for R5RS first in locally-installed PLT
578   ;;       collection, then in one of various non-PLT directories it might be
579   ;;       mirrored, then remote PLT copy using local PLT keywords file, then
580   ;;       the canonical HTML copy on the Web...  Maybe even permit Info
581   ;;       format.  Let's just reinvent the Web, while we're at it.
582
583   '(
584
585     (r5rs "R5RS"
586           "http://www.schemers.org/Documents/Standards/R5RS/HTML/"
587           nil)
588
589     (bigloo
590      "Bigloo"
591      "http://www-sop.inria.fr/mimosa/fp/Bigloo/doc/bigloo.html"
592      ;;"file:///usr/share/doc/bigloo/manuals/bigloo.html"
593      nil)
594
595     (chez
596      "Chez Scheme User's Guide"
597      "http://www.scheme.com/csug/index.html"
598      nil)
599
600     (chicken
601      "Chicken User's Manual"
602      "http://www.call-with-current-continuation.org/manual/manual.html"
603      ;;"file:///usr/share/doc/chicken/manual.html"
604      nil)
605
606     (gambit
607      "Gambit-C home page"
608      "http://www.iro.umontreal.ca/~gambit/")
609
610     (gauche
611      "Gauche Reference Manual"
612      "http://www.shiro.dreamhost.com/scheme/gauche/man/gauche-refe.html"
613      nil)
614
615     (mitgnu-ref
616      "MIT/GNU Scheme Reference"
617      "http://www.gnu.org/software/mit-scheme/documentation/scheme.html"
618      ;;"http://www.swiss.ai.mit.edu/projects/scheme/documentation/scheme.html"
619
620      ;;"file:///usr/share/doc/mit-scheme/html/scheme.html"
621      nil)
622
623     (mitgnu-user
624      "MIT/GNU Scheme User's Manual"
625      "http://www.gnu.org/software/mit-scheme/documentation/user.html"
626      ;;"http://www.swiss.ai.mit.edu/projects/scheme/documentation/user.html"
627      ;;"file:///usr/share/doc/mit-scheme/html/user.html"
628      nil)
629
630     (mitgnu-sos
631      "MIT/GNU Scheme SOS Reference Manual"
632      "http://www.gnu.org/software/mit-scheme/documentation/sos.html"
633      ;;"http://www.swiss.ai.mit.edu/projects/scheme/documentation/sos.html"
634      ;;"file:///usr/share/doc/mit-scheme/html/sos.html"
635      nil)
636
637     (plt-mzscheme  "PLT MzScheme: Language Manual"                plt t)
638     (plt-mzlib     "PLT MzLib: Libraries Manual"                  plt t)
639     (plt-mred      "PLT MrEd: Graphical Toolbox Manual"           plt t)
640     (plt-framework "PLT Framework: GUI Application Framework"     plt t)
641     (plt-drscheme  "PLT DrScheme: Programming Environment Manual" plt nil)
642     (plt-insidemz  "PLT Inside PLT MzScheme"                      plt nil)
643     (plt-tools     "PLT Tools: DrScheme Extension Manual"         plt nil)
644     (plt-mzc       "PLT mzc: MzScheme Compiler Manual"            plt t)
645     (plt-r5rs      "PLT R5RS"                                     plt t)
646
647     (scsh
648      "Scsh Reference Manual"
649      "http://www.scsh.net/docu/html/man-Z-H-1.html"
650      ;;"file:///usr/share/doc/scsh-doc/scsh-manual/man-Z-H-1.html"
651      nil)
652
653     (sisc
654      "SISC for Seasoned Schemers"
655      "http://sisc.sourceforge.net/manual/html/"
656      nil)
657
658     (htdp       "How to Design Programs"
659                 "http://www.htdp.org/"
660                 nil)
661     (htus       "How to Use Scheme"
662                 "http://www.htus.org/"
663                 nil)
664     (t-y-scheme "Teach Yourself Scheme in Fixnum Days"
665                 "http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme.html"
666                 nil)
667     (tspl       "Scheme Programming Language (Dybvig)"
668                 "http://www.scheme.com/tspl/"
669                 nil)
670     (sicp       "Structure and Interpretation of Computer Programs"
671                 "http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-4.html"
672                 nil)
673     (slib       "SLIB"
674                 "http://swissnet.ai.mit.edu/~jaffer/SLIB.html"
675                 nil)
676     (faq        "Scheme Frequently Asked Questions"
677                 "http://www.schemers.org/Documents/FAQ/"
678                 nil))
679   "*List of specifications of manuals that can be viewed.
680
681 Each manual specification is a list of four elements:
682
683     (SYMBOL TITLE LOCATION USE-KEYWORDS-P)
684
685 where SYMBOL is a short symbol that identifies the manual, TITLE is a string,
686 LOCATION is either a string with the URL of the manual or the symbol `plt',
687 and USE-KEYWORDS-P is `t' or `nil'.
688
689 If LOCATION is `plt', then Quack treats it as a PLT bundled manual, looking for
690 the HTML and keyword files in `quack-pltcollect-dirs', and optionally providing
691 keyword lookup if USE-KEYWORDS-P is `t'.  Remote canonical copies of the
692 manuals will be used if local copies cannot be found.
693
694 If LOCATION is a URL, then USE-KEYWORDS-P must be `nil'."
695   :type  '(repeat (list (symbol :tag "Identifying Symbol")
696                         (string :tag "Title String")
697                         (choice :tag "Location"
698                                 (string :tag "URL")
699                                 (const  :tag "PLT Bundled Manual" plt))
700                         (boolean :tag "Use Keywords?")))
701   :group 'quack)
702
703 (defcustom quack-local-keywords-for-remote-manuals-p t
704   "*If non-nil, Quack will use canonical remote Web URLs when there is a local
705 keyword file for a PLT manual but no local HTML files.  (This feature was
706 prompted by the Debian 200.2-3 package for MzScheme, which includes keyword
707 files but not HTML files.)  If the symbol `always', then Quack will always use
708 remote Web manuals for keywords lookup, even if local HTML files exist, as a
709 workaround for how some versions of Emacs interact with some versions of
710 Microsoft Windows \(inexplicably discarding the fragment identifier from `file'
711 scheme URI\)."
712   :type       '(choice (const :tag "Permit"    t)
713                        (const :tag "Forbid"     nil)
714                        (const :tag "Always" always))
715   :group      'quack
716   :set        'quack-custom-set
717   :initialize 'custom-initialize-default)
718
719 (defcustom quack-srfi-master-base-url "http://srfi.schemers.org/"
720   ;; Note: Intentionally not letting user change this through the options menu.
721   "*The base URL for the master SRFI Web pages.
722 The SRFI index files should be immediately beneath this."
723   :type   'string
724   :group  'quack)
725
726 (defcustom quack-pltcollect-dirs
727   (let ((good '()))
728     (mapcar (function (lambda (dir)
729                         (and dir
730                              (not (assoc dir good))
731                              (file-directory-p dir)
732                              (setq good (nconc good (list dir))))))
733             `(,@(let ((v (getenv "PLTCOLLECTS")))
734                   (and v (split-string v ":")))
735                 ,(let ((v (getenv "PLTHOME")))
736                    (and v (expand-file-name "collects" v)))
737                 ,@(mapcar 'expand-file-name
738                           '("/usr/lib/plt/collects"
739                             "/usr/local/lib/plt/collects"))))
740     good)
741   "*PLT collection directories.
742 Listed in order of priority."
743   :type       '(repeat directory)
744   :group      'quack
745   :set        'quack-custom-set
746   :initialize 'custom-initialize-default)
747
748 (defcustom quack-fontify-style 'plt
749   "*Which font-lock fontification style to use.
750
751 If symbol `plt', an approximation of PLT DrScheme 200 Check Syntax
752 fontification will be used.  If symbol `emacs', then fontification in the style
753 of GNU Emacs' Scheme Mode with extensions will be used.  If nil, then Quack
754 will not override the default Scheme Mode fontification."
755   :type       '(choice (const :tag "PLT Style"                plt)
756                        (const :tag "Extended GNU Emacs Style" emacs)
757                        (const :tag "Emacs Default"            nil))
758   :group      'quack
759   :set        'quack-custom-set
760   :initialize 'custom-initialize-default)
761
762 (defcustom quack-pltish-fontify-definition-names-p t
763   "*If non-nil, fontify names in definition forms for PLT-style fontification.
764
765 This only has effect when `quack-fontify-style' is `plt'."
766   :type       'boolean
767   :group      'quack
768   :set        'quack-custom-set
769   :initialize 'custom-initialize-default)
770
771 (defcustom quack-pltish-fontify-keywords-p t
772   ;; TODO: Rename this from "keywords" to "syntax-keywords", here, and in for
773   ;; face names.
774   "*If non-nil, fontify keywords in PLT-style fontification.
775
776 This only has effect when `quack-fontify-style' is `plt'."
777   :type       'boolean
778   :group      'quack
779   :set        'quack-custom-set
780   :initialize 'custom-initialize-default)
781
782 (defcustom quack-pltish-keywords-to-fontify
783   ;; TODO: These are currently R5RS and some SRFI special syntax plus a bunch
784   ;; of PLT, especially PLT 200 class.ss, and some "define-"* variants from
785   ;; various dialects, plus some Racket 5.0.2...  The dumbness of this kind of
786   ;; highlighting without regard to context is not really satisfactory.
787   '(
788
789     "and" "begin" "begin-for-syntax"
790     "begin0" "c-declare" "c-lambda" "case" "case-lambda" "class"
791     "class*" "class*/names" "class100" "class100*" "compound-unit/sig" "cond"
792     "cond-expand" "define" "define-class" "define-compound-unit"
793     "define-const-structure"
794     "define-constant" "define-embedded" "define-entry-point" "define-external"
795     "define-for-syntax" "define-foreign-record" "define-foreign-type"
796     "define-foreign-variable" "define-generic" "define-generic-procedure"
797     "define-inline" "define-location" "define-macro" "define-method"
798     "define-module" "define-opt" "define-public" "define-reader-ctor"
799     "define-record" "define-record-printer" "define-record-type"
800     "define-signature"
801     "define-splicing-syntax-class"
802     "define-struct"
803     "define-structure"
804     "define-syntax"
805     "define-syntax-class"
806     "define-syntax-set" "define-values" "define-values-for-syntax"
807     "define-values/invoke-unit/infer"
808     "define-values/invoke-unit/sig" "define/contract" "define/override"
809     "define/private" "define/public" "define/kw"
810     "delay" "do" "else" "exit-handler" "field"
811     "if" "import" "inherit" "inherit-field" "init" "init-field" "init-rest"
812     "instantiate" "interface" "lambda" "lambda/kw" "let" "let*" "let*-values"
813     "let+"
814     "let-syntax" "let-values" "let/ec" "letrec" "letrec-values" "letrec-syntax"
815     "match-lambda" "match-lambda*" "match-let" "match-let*" "match-letrec"
816     "match-define" "mixin" "module" "module*" "module+" "opt-lambda" "or" "override" "override*"
817     "namespace-variable-bind/invoke-unit/sig" "parameterize" "parameterize*"
818     "parameterize-break" "private"
819     "private*" "protect" "provide" "provide-signature-elements"
820     "provide/contract" "public" "public*" "quasiquote" 
821     "quasisyntax" "quasisyntax/loc" "quote" "receive"
822     "rename" "require" "require-for-syntax" "send" "send*" "set!" "set!-values"
823     "signature->symbols" "super-instantiate" "syntax" "syntax/loc"
824     "syntax-case" "syntax-case*" "syntax-error" "syntax-parse" "syntax-rules"
825     "unit/sig"
826     "unless" "unquote" "unquote-splicing" "when" "with-handlers" "with-method"
827     "with-syntax"
828     "define-type-alias"
829     "define-struct:"
830     "define:"
831     "let:"
832     "letrec:"
833     "let*:"
834     "lambda:"
835     "plambda:"
836     "case-lambda:"
837     "pcase-lambda:"
838     "require/typed"
839     "require/opaque-type"
840     "require-typed-struct"
841     "struct"
842     "inst"
843     "ann"
844
845     )
846   "*Scheme keywords to fontify when `quack-fontify-style' is `plt'."
847   :type       '(repeat string)
848   :group      'quack
849   :set        'quack-custom-set
850   :initialize 'custom-initialize-default)
851
852 (defcustom quack-emacsish-keywords-to-fontify
853   '("and" "begin" "begin0" "call-with-current-continuation"
854     "call-with-input-file" "call-with-output-file" "call/cc" "case"
855     "case-lambda" "class" "cond" "delay" "do" "else" "exit-handler" "field"
856     "for-each" "if" "import" "inherit" "init-field" "interface" "lambda" "let"
857     "let*" "let*-values" "let-values" "let-syntax" "let/ec" "letrec"
858     "letrec-syntax" "map" "mixin" "opt-lambda" "or" "override" "protect"
859     "provide" "public" "rename" "require" "require-for-syntax" "syntax"
860     "syntax-case" "syntax-error" "syntax-rules" "unit/sig" "unless" "when"
861     "with-syntax")
862   "*Scheme keywords to fontify when `quack-fontify-style' is `emacs'."
863   :type       '(repeat string)
864   :group      'quack
865   :set        'quack-custom-set
866   :initialize 'custom-initialize-default)
867
868 (defcustom quack-fontify-threesemi-p t
869   "*Whether three-semicolon comments should be fontified differently."
870   :type       'boolean
871   :group      'quack
872   :set        'quack-custom-set
873   :initialize 'custom-initialize-default)
874
875 (defcustom quack-pretty-lambda-p nil
876   "*Whether Quack should display \"lambda\" as the lambda character.
877
878 `quack-fontify-style' must be `plt'.  Only supported under GNU Emacs version
879 21\; not under XEmacs or older GNU Emacs.
880
881 Note: Pretty lambda requires that suitable iso8859-7 fonts be available.  Under
882 Debian/GNU Linux, for example, these can be downloaded and installed with the
883 shell command \"apt-get install 'xfonts-greek-*'\".  If iso8859-7 fonts are
884 unavailable for your system, please notify the Quack author."
885   :type       'boolean
886   :group      'quack
887   :set        'quack-custom-set
888   :initialize 'custom-initialize-default)
889
890 (defcustom quack-programs
891   '("bigloo" "csi" "csi -hygienic" "gosh" "gracket" "gsi"
892     "gsi ~~/syntax-case.scm -" "guile" "kawa" "mit-scheme" "racket"
893     "racket -il typed/racket" "rs" "scheme" "scheme48" "scsh" "sisc" "stklos"
894     "sxi")
895   "List of Scheme interpreter programs that can be used with `run-scheme'.
896
897 These names will be accessible via completion when `run-scheme' prompts for
898 which program to run."
899   :group      'quack
900   :type       '(repeat string)
901   :set        'quack-custom-set
902   :initialize 'custom-initialize-default)
903
904 (defcustom quack-default-program "mzscheme"
905   "Default Scheme interpreter program to use with `run-scheme'."
906   :group 'quack
907   :type  'string)
908
909 (defcustom quack-run-scheme-always-prompts-p t
910   "`run-scheme' should always prompt for which program to run.
911
912 If nil, `run-scheme' will always use `quack-default-program' when invoked
913 interactively without a prefix argument; this is closest to the behavior of the
914 `cmuscheme' package."
915   :group 'quack
916   :type  'boolean)
917
918 (defcustom quack-run-scheme-prompt-defaults-to-last-p t
919   "If non-nil, `run-scheme' prompt should default to the last program run."
920   :group 'quack
921   :type  'boolean)
922
923 (defcustom quack-remember-new-programs-p t
924   "Programs are added to `quack-programs' automatically."
925   :group 'gigule
926   :type  'boolean)
927
928 (defcustom quack-switch-to-scheme-method 'other-window
929   "Method to use for choosing a window and frame for the process buffer.
930
931 One of three symbols:
932 `other-window' will split display in a different window in the current frame,
933 splitting the current window if necessary.
934 `own-frame' will display the process buffer in its own frame.
935 `cmuscheme' will use the normal behavior of the `cmuscheme' package."
936   :group  'quack
937   :type   '(choice (const :tag "Other Window"       other-window)
938                    (const :tag "Own Frame"          own-frame)
939                    (const :tag "Cmuscheme Behavior" cmuscheme)))
940
941 (defcustom quack-warp-pointer-to-frame-p t
942   "Warp mouse pointer to frame with Scheme process buffer.
943
944 When `quack-switch-to-scheme-method' is `own-frame', `switch-to-scheme' will
945 warp the mouse pointer to the frame displaying the Scheme process buffer."
946   :group 'quack
947   :type  'boolean)
948
949 (defcustom quack-newline-behavior 'newline-indent
950   "*Behavior of the RET key in Scheme-Mode buffers.  The value is one of three
951 symbols: `newline' inserts a normal newline, `newline-indent' \(the default\)
952 inserts a newline and leaves the point properly indented on the new line, and
953 `indent-newline-indent' indents the current line before inserting a newline and
954 indenting the new one."
955   :type '(choice (const 'newline)
956                  (const 'newline-indent)
957                  (const 'indent-newline-indent))
958   :group 'quack)
959
960 (defcustom quack-smart-open-paren-p nil
961   "The `[' can be used to insert `(' characters.
962 Actually, this just makes the `(' and '[' keys both insert `(', unless given a
963 prefix argument.  This makes typing parens easier on typical keyboards for
964 which `(' requires a shift modifier but `[' does not.  A later version of Quack
965 might add actual \"smart\" support for automatic PLT-esque insertion of `['
966 instead of `(' in some syntactic contexts."
967   :group 'quack
968   :type  'boolean)
969
970 (defcustom quack-options-persist-p t
971   "Option menu settings and programs persist using the `custom' facility.
972
973 Note that the value of this option itself cannot be set persistently via the
974 option menu -- you must use the `customize' interface or set it manually in an
975 Emacs startup file.  This is by design, to avoid the risk of users accidentally
976 disabling their ability to set persistent options via the option menu."
977   :group 'quack
978   :type  'boolean)
979
980 (defcustom quack-quiet-warnings-p t     ; TODO: Options menu.
981   "Warning messages are quiet and subtle."
982   :group 'quack
983   :type  'boolean)
984
985 (defconst quack-pltish-comment-face 'quack-pltish-comment-face)
986 (defface  quack-pltish-comment-face
987   '((((class color) (background light)) (:foreground "cyan4"))
988     (((class color) (background dark))  (:foreground "cyan1"))
989     (t                                  (:slant italic)))
990   "Face used for comments when `quack-fontify-style' is `plt'."
991   :group 'quack)
992
993 (defconst quack-pltish-selfeval-face 'quack-pltish-selfeval-face)
994 (defface  quack-pltish-selfeval-face
995   '((((class color) (background light)) (:foreground "green4"))
996     (((class color) (background dark))  (:foreground "green2"))
997     (t                                  ()))
998   "Face used for self-evaluating forms when `quack-fontify-style' is `plt'."
999   :group 'quack)
1000
1001 (defconst quack-pltish-paren-face 'quack-pltish-paren-face)
1002 (defface  quack-pltish-paren-face
1003   '((((class color) (background light)) (:foreground "red3"))
1004     (((class color) (background dark))  (:foreground "red1"))
1005     (((class grayscale))                (:foreground "gray"))
1006     (t                                  ()))
1007   "Face used for parentheses when `quack-fontify-style' is `plt'."
1008   :group 'quack)
1009
1010 (defconst quack-pltish-colon-keyword-face 'quack-pltish-colon-keyword-face)
1011 (defface  quack-pltish-colon-keyword-face
1012   '((t (:bold t :foreground "gray50")))
1013   "Face used for `#:' keywords when `quack-fontify-style' is `plt'.
1014 Note that this isn't based on anything in PLT."
1015   :group 'quack)
1016
1017 (defconst quack-pltish-paren-face 'quack-pltish-paren-face)
1018 (defface  quack-pltish-paren-face
1019   '((((class color) (background light)) (:foreground "red3"))
1020     (((class color) (background dark))  (:foreground "red1"))
1021     (((class grayscale))                (:foreground "gray"))
1022     (t                                  ()))
1023   "Face used for parentheses when `quack-fontify-style' is `plt'."
1024   :group 'quack)
1025
1026 (defconst quack-banner-face 'quack-banner-face)
1027 (defface  quack-banner-face
1028   '((t (:family "Helvetica")))
1029   "Face used in the inferior process buffer for the MzScheme banner.
1030
1031 Currently only takes effect when `quack-fontify-style' is `plt'."
1032   :group 'quack)
1033
1034 (defconst quack-pltish-defn-face 'quack-pltish-defn-face)
1035 (defface  quack-pltish-defn-face
1036   '((((class color) (background light)) (:bold t :foreground "blue3"))
1037     (((class color) (background dark))  (:bold t :foreground "blue1"))
1038     (t                                  (:bold t :underline t)))
1039   "Face used for names in toplevel definitions.
1040
1041 For PLT-style when `quack-pltish-fontify-definition-names-p' is non-nil."
1042   :group 'quack)
1043
1044 (defconst quack-pltish-class-defn-face 'quack-pltish-class-defn-face)
1045 (defface  quack-pltish-class-defn-face
1046   '((((class color) (background light))
1047      (:foreground "purple3" :inherit quack-pltish-defn-face))
1048     (((class color) (background dark))
1049      (:foreground "purple1" :inherit quack-pltish-defn-face))
1050     (t (:inherit quack-pltish-defn-face)))
1051   "Face used for class names in toplevel definitions.
1052
1053 For PLT-style when `quack-pltish-fontify-definition-names-p' is non-nil."
1054   :group 'quack)
1055
1056 (defconst quack-pltish-module-defn-face 'quack-pltish-module-defn-face)
1057 (defface  quack-pltish-module-defn-face
1058   '((((class color) (background light))
1059      (:foreground "purple3" :inherit quack-pltish-defn-face))
1060     (((class color) (background dark))
1061      (:foreground "purple1" :inherit quack-pltish-defn-face))
1062     (t (:inherit quack-pltish-defn-face)))
1063   "Face used for module names in toplevel definitions.
1064
1065 For PLT-style when `quack-pltish-fontify-definition-names-p' is non-nil."
1066   :group 'quack)
1067
1068 (defconst quack-pltish-keyword-face 'quack-pltish-keyword-face)
1069 (defface  quack-pltish-keyword-face
1070   '((t (:bold t)))
1071   "Face used for keywords in PLT Style fontification.
1072
1073 For PLT-style when `quack-pltish-fontify-keywords-p' is non-nil."
1074   :group 'quack)
1075
1076 (defconst quack-threesemi-semi-face 'quack-threesemi-semi-face)
1077 (defface  quack-threesemi-semi-face
1078   '((((class color) (background light))
1079      (:foreground "#a0ffff":background "#c0ffff"))
1080     (((class color) (background dark))
1081      (:foreground "cyan2" :background "cyan4"))
1082     (t (:slant italic)))
1083   "Face used for `;;;' semicolons when `quack-fontify-threesemi-p' is non-nil."
1084   :group 'quack)
1085
1086 (defconst quack-threesemi-text-face 'quack-threesemi-text-face)
1087 (defface  quack-threesemi-text-face
1088   '((((class color) (background light))
1089      (:foreground "cyan4" :background "#c0ffff"))
1090     (((class color) (background dark))
1091      (:foreground "white" :background "cyan4"))
1092     (t (:slant italic)))
1093   "Face used for `;;;' text when `quack-fontify-threesemi-p' is non-nil."
1094   :group 'quack)
1095
1096 (defconst quack-threesemi-h1-face 'quack-threesemi-h1-face)
1097 (defface  quack-threesemi-h1-face
1098   '((t (:bold t :family "Helvetica" :height 1.4 :size "20pt")))
1099   "Face used for H1 headings in `;;;' text."
1100   :group 'quack)
1101
1102 (defconst quack-threesemi-h2-face 'quack-threesemi-h2-face)
1103 (defface  quack-threesemi-h2-face
1104   '((t (:bold t :family "Helvetica" :height 1.2 :size "16pt")))
1105   "Face used for H2 headings in `;;;' text."
1106   :group 'quack)
1107
1108 (defconst quack-threesemi-h3-face 'quack-threesemi-h3-face)
1109 (defface  quack-threesemi-h3-face
1110   '((t (:bold t :family "Helvetica")))
1111   "Face used for H3 headings in `;;;' text."
1112   :group 'quack)
1113
1114 (defconst quack-pltfile-prologue-face 'quack-pltfile-prologue-face)
1115 (defface  quack-pltfile-prologue-face
1116   '((((class color))     (:foreground "black" :background "gray66"))
1117     (((class grayscale)) (:foreground "black" :background "gray66"))
1118     (t                   ()))
1119   "Face used for the prologue in a decoded PLT package buffer."
1120   :group 'quack)
1121
1122 (defconst quack-pltfile-dir-face 'quack-pltfile-dir-face)
1123 (defface  quack-pltfile-dir-face
1124   '((((class color))     (:bold t :foreground "white" :background "gray33"
1125                                 :family "Helvetica" :height 1.2 :size "20pt"))
1126     (((class grayscale)) (:bold t :foreground "white" :background "gray33"
1127                                 :family "Helvetica" :height 1.2 :size "20pt"))
1128     (t                   (:bold t :inverse-video t)))
1129   "Face used for directory headers in a decoded PLT package buffer."
1130   :group 'quack)
1131
1132 (defconst quack-pltfile-file-face 'quack-pltfile-file-face)
1133 (defface  quack-pltfile-file-face
1134   '((((class color))     (:bold t :foreground "black" :background "gray66"
1135                                 :family "Helvetica" :height 1.2 :size "20pt"))
1136     (((class grayscale)) (:bold t :foreground "black" :background "gray66"
1137                                 :family "Helvetica" :height 1.2 :size "20pt"))
1138     (t                   (:bold t :inverse-video t)))
1139   "Face used for file headers in a decoded PLT package buffer."
1140   :group 'quack)
1141
1142 (defconst quack-about-title-face 'quack-about-title-face)
1143 (defface  quack-about-title-face
1144   '((((class color) (background light))
1145      (:bold t :family "Helvetica" :foreground "#008000"
1146             :height 2.0 :size "24pt"))
1147     (((class color) (background dark))
1148      (:bold t :family "Helvetica" :foreground "#00f000"
1149             :height 2.0 :size "24pt"))
1150     (t               (:bold t :family "Helvetica"
1151                             :height 2.0 :size "24pt")))
1152   "Face used for Quack name in About Quack."
1153   :group 'quack)
1154
1155 (defconst quack-about-face 'quack-about-face)
1156 (defface  quack-about-face
1157   '((t (:family "Helvetica")))
1158   "Face used for the body text in About Quack."
1159   :group 'quack)
1160
1161 (defconst quack-smallprint-face 'quack-smallprint-face)
1162 (defface  quack-smallprint-face
1163   '((t (:family "Courier" :height 0.8 :size "8pt")))
1164   "Face used for the \"small print\" in About Quack."
1165   :group 'quack)
1166
1167 ;; Compatibility/Portability Misc. Kludges:
1168
1169 ;; Note: Some compatibility gotchas found while porting Quack that aren't
1170 ;; addressed by macros and functions:
1171 ;;
1172 ;;   * `defface' in Emacs 21 supports ":weight bold", but this is silently
1173 ;;     ignored under older Emacsen, so ":bold t" must be used instead.
1174 ;;
1175 ;;   * Third argument of `detect-coding-region' is different in Emacs 21 and
1176 ;;     XEmacs 21, so only use the first two args.
1177 ;;
1178 ;;   * Under XEmacs 21, characters are `equal' but not `eq' to their integer
1179 ;;     ASCII values
1180 ;;
1181 ;;   * GNU Emacs 21 faces have `:height' property that is either absolute
1182 ;;     decipoints or relative scaling factor.  XEmacs 21 faces instead have
1183 ;;     `:size' property, which appears to be absolute point or mm size.
1184 ;;
1185 ;;   * XEmacs 21 text properties appear to be front-sticky, and there did not
1186 ;;     seem to be any documentation references to stickiness.
1187 ;;
1188 ;;   * XEmacs 21 `local-variable-p' has second argument mandatory.
1189 ;;
1190 ;;   * XEmacs 21 does not display submenu labels at all unless the submenu has
1191 ;;     content.  For inactive submenus, an empty string suffices for content.
1192 ;;
1193 ;;   * XEmacs 21 doesn't support composite characters (which we use for very
1194 ;;     nice pretty lambda under GNU Emacs).
1195
1196 (eval-and-compile
1197   (defvar quack-xemacs-p (eval '(and (boundp 'running-xemacs) running-xemacs)))
1198   (defvar quack-gnuemacs-p (not quack-xemacs-p)))
1199
1200 (defmacro quack-when-xemacs (&rest args)
1201   (if quack-xemacs-p (cons 'progn args) 'nil))
1202
1203 (defmacro quack-when-gnuemacs (&rest args)
1204   (if quack-gnuemacs-p (cons 'progn args) 'nil))
1205
1206 (defmacro quack-define-key-after (keymap key definition &optional after)
1207   (if quack-gnuemacs-p
1208       `(define-key-after ,keymap ,key ,definition ,after)
1209     `(define-key ,keymap ,key (prog1 ,definition ,after))))
1210
1211 (defmacro quack-delete-horizontal-space (&rest args)
1212   (if (and quack-gnuemacs-p (>= emacs-major-version 21))
1213       `(delete-horizontal-space ,@args)
1214     `(delete-horizontal-space)))
1215
1216 (defmacro quack-match-string-no-properties (&rest args)
1217   `(,(if quack-xemacs-p 'match-string 'match-string-no-properties) ,@args))
1218
1219 (defmacro quack-menufilter-return (name form)
1220   (if (= emacs-major-version 20)
1221       ;; Note: This isn't working in Emacs 20.  Menu displays now but actions
1222       ;;       are not executed.  No answer to test case posted to comp.emacs
1223       ;;       and then to gnu.emacs.help.  In response to my subsequent bug
1224       ;;       report against Emacs, RMS says that, if this is indeed a bug,
1225       ;;       then nothing will be done, since 20 is no longer supported.  I'm
1226       ;;       going to let this quietly not work unless someone emails me that
1227       ;;       they're actually using Emacs 20.
1228       `(easy-menu-filter-return (easy-menu-create-menu ,name ,form))
1229     form))
1230
1231 (defmacro quack-propertize (obj &rest props)
1232   (if (and quack-gnuemacs-p (>= emacs-major-version 21))
1233       `(propertize ,obj ,@props)
1234     (let ((obj-var 'quack-propertize-G-obj))
1235       `(let ((,obj-var ,obj))
1236          (add-text-properties 0 (length ,obj-var) (list ,@props) ,obj-var)
1237          ,obj-var))))
1238
1239 (eval-when-compile
1240   (when quack-xemacs-p
1241     (defvar inhibit-eol-conversion)
1242     (defvar minibuffer-allow-text-properties)))
1243
1244 ;; Compatibility/Portability Hash Table:
1245
1246 (eval-and-compile
1247   (defmacro quack-make-hash-table (&rest args)
1248     `(,(if (>= emacs-major-version 21)
1249            'make-hash-table
1250          'quack-fake-make-hash-table)
1251       ,@args)))
1252
1253 (defmacro quack-puthash (key value table)
1254   (list (if (>= emacs-major-version 21) 'puthash 'quack-fake-puthash)
1255         key value table))
1256
1257 (defmacro quack-gethash (key table &optional dflt)
1258   (list (if (>= emacs-major-version 21) 'gethash 'quack-fake-gethash)
1259         key table dflt))
1260
1261 (defun quack-fake-make-hash-table (&rest args)
1262   ;; TODO: Parse the keyword args and make this do 'assoc or 'assq, as
1263   ;;       appropriate.  Currently, this package only needs 'assoc.
1264   (vector 'assoc '()))
1265
1266 (defun quack-fake-puthash (key value table)
1267   (let ((pair (funcall (aref table 0) key (aref table 1))))
1268     (if pair
1269         (setcdr pair value)
1270       (aset table 1 (cons (cons key value) (aref table 1))))))
1271
1272 (defun quack-fake-gethash (key table &optional dflt)
1273   (let ((pair (funcall (aref table 0) key (aref table 1))))
1274     (if pair (cdr pair) dflt)))
1275
1276 ;; Compatibility/Portability Overlays/Extents:
1277
1278 ;; TODO: Maybe get rid of overlays (and the XEmacs extent kludge), and just use
1279 ;;       text properties instead.
1280
1281 (defmacro quack-make-face-ovlext (beg end face)
1282   (if quack-xemacs-p
1283       `(set-extent-property (make-extent ,beg ,end) 'face ,face)
1284     `(overlay-put (make-overlay ,beg ,end) 'face ,face)))
1285
1286 (defmacro quack-make-hiding-ovlext (beg end)
1287   (if quack-xemacs-p
1288       `(set-extent-property (make-extent ,beg ,end) 'invisible t)
1289     `(overlay-put (make-overlay ,beg ,end) 'category 'quack-hiding-ovlcat)))
1290
1291 ;; Messages, Errors, Warnings:
1292
1293 (defmacro quack-activity (what &rest body)
1294   (let ((var-what (make-symbol "quack-activity-G-what")))
1295     `(let ((,var-what ,what))
1296        (message (concat ,var-what "..."))
1297        (prog1 (progn ,@body)
1298          (message (concat ,var-what "...done"))))))
1299
1300 (defun quack-internal-error (&optional format &rest args)
1301   (if format
1302       (apply 'error (concat "Quack Internal Error: " format) args)
1303     (error "Quack Internal Error.")))
1304
1305 (defun quack-warning (format &rest args)
1306   (apply 'message (concat "Quack Warning: " format) args)
1307   (unless quack-quiet-warnings-p
1308     (beep)
1309     (sleep-for 1)))
1310
1311 ;; Regular Expressions:
1312
1313 (defun quack-re-alt (&rest regexps)
1314   (concat "\\(" (mapconcat 'identity regexps "\\|") "\\)"))
1315
1316 (defun quack-re-optional (&rest regexps)
1317   (concat "\\("
1318           (apply 'concat regexps)
1319           "\\)?"))
1320
1321 ;; Misc.:
1322
1323 ;; (defun quack-abbreviate-file-name (file-name)
1324 ;;   (let ((directory-abbrev-alist '()))
1325 ;;     (abbreviate-file-name file-name)))
1326
1327 (defun quack-delete-file-if-can (file)
1328   (condition-case nil (delete-file file) (error nil)))
1329
1330 (defun quack-expand-file-name (name-or-names &optional directory)
1331   ;; Note: This only works for systems with Unix-like filenames.
1332   (expand-file-name (if (listp name-or-names)
1333                         (mapconcat 'identity name-or-names "/")
1334                       name-or-names)
1335                     directory))
1336
1337 (defun quack-kill-current-buffer ()
1338   (interactive)
1339   (kill-buffer (current-buffer)))
1340
1341 (defun quack-line-at-point ()
1342   (save-excursion
1343     (buffer-substring-no-properties
1344      (progn (beginning-of-line) (point))
1345      (progn (end-of-line)       (point)))))
1346
1347 (defun quack-looking-at-backward (re &optional limit)
1348   (save-excursion
1349     (save-restriction
1350       (let ((start-pt (point)))
1351         (narrow-to-region (point-min) (point))
1352         (and (re-search-backward re limit t)
1353              (= (match-end 0) start-pt)
1354              (match-beginning 0))))))
1355
1356 (defun quack-looking-at-close-paren-backward ()
1357   (save-match-data
1358     (quack-looking-at-backward "[])][ \t\r\n\f]*")))
1359
1360 (defun quack-looking-at-open-paren-backward ()
1361   (save-match-data
1362     (quack-looking-at-backward "[[(][ \t\r\n\f]*")))
1363
1364 (defun quack-make-directory (dir)
1365   (setq dir (file-name-as-directory dir))
1366   (unless (file-directory-p dir)
1367     (make-directory dir t)))
1368
1369 (defun quack-make-directory-for-file (file)
1370   (let ((dir (file-name-directory file)))
1371     (when dir (quack-make-directory dir))))
1372
1373 (defun quack-propertize-bold (str)
1374   (quack-propertize str 'face 'bold))
1375
1376 (defun quack-propertize-face (str face)
1377   (quack-propertize str 'face face))
1378
1379 (defun quack-propertize-italic (str)
1380   (quack-propertize str 'face 'italic))
1381
1382 (defun quack-sort-string-list-copy (lst)
1383   (sort (copy-sequence lst) 'string<))
1384
1385 (defun quack-uncomment-region (beg end)
1386   ;; TODO: Make a quack-toggle-commentout-region.
1387   (interactive "r")
1388   (comment-region beg end '(4)))
1389
1390 (defun quack-without-side-whitespace (str)
1391   ;; Copied from `padr-str-trim-ws' by author.
1392   ;;
1393   ;; TODO: Don't make an intermediate string.  Use regexp match start position.
1394   (save-match-data
1395     (if (string-match "^[ \t\n\r]+" str)
1396         (setq str (substring str (match-end 0))))
1397     (if (string-match "[ \t\n\r]+$" str)
1398         (setq str (substring str 0 (match-beginning 0))))
1399     str))
1400
1401 ;; Kludgey Sexp Buffer Operations:
1402
1403 (defconst quack-backward-sexp-re
1404   (concat "\\`"
1405           (quack-re-alt "[^\";\\\\]"
1406                         "\\\\\\."
1407                         (concat "\""
1408                                 (quack-re-alt "[^\"\\\\]"
1409                                               "\\\\\\.")
1410                                 "*\""))
1411           "*\\([\"\\\\]\\)?"))
1412
1413 (defun quack-backward-sexp ()
1414   ;; Returns non-nil iff point was in a string literal or comment.
1415   (interactive)
1416   (when (bobp)
1417     (error "beginning of buffer"))
1418   (save-match-data
1419     (let* ((orig (point))
1420            (bol  (progn (beginning-of-line) (point))))
1421       (if (string-match quack-backward-sexp-re
1422                         (buffer-substring-no-properties bol orig))
1423           (if (match-beginning 3)
1424               ;; We're in what appears to be a comment or unterminated string
1425               ;; literal (though might not be, due to multi-line string
1426               ;; literals and block comments), so move point to the beginning.
1427               (progn (goto-char (+ bol (match-beginning 3)))
1428                      t)
1429             ;; We don't appear to be in a comment or string literal, so just
1430             ;; let `backward-sexp' do its thing.
1431             (goto-char orig)
1432             (backward-sexp)
1433             nil)))))
1434
1435 (defun quack-parent-sexp-search (name-regexp &optional max-depth max-breadth)
1436   (save-match-data
1437     (save-excursion
1438       (let ((max-depth   (or max-depth   100))
1439             (max-breadth (or max-breadth 100))
1440             (orig-point  (point))
1441             (found       'looking)
1442             (depth       0)
1443             (child-start nil))
1444         (while (and (eq found 'looking) (< depth max-depth))
1445           (condition-case nil
1446               (let ((breadth 0))
1447                 ;; Loop until we hit max breadth or error.
1448                 (while (< breadth max-breadth)
1449                   (when (and (quack-backward-sexp) (not child-start))
1450                     (setq child-start (point)))
1451                   (setq breadth (1+ breadth)))
1452                 ;; We hit our max breadth without erroring, so set the found
1453                 ;; flag to indicate failure and then fall out of our loop.
1454                 (setq found nil))
1455             (error                      ; scan-error
1456              ;; We probably hit the beginning of the enclosing sexp, and point
1457              ;; should be on the first sexp, which will most often be the form
1458              ;; name, so first check that there really is an open paren to our
1459              ;; left, and then check if it matches our regexp.
1460              (let ((paren-start (quack-looking-at-open-paren-backward)))
1461                (if paren-start
1462                    ;; There is a paren, so check the name of the form.
1463                    (if (and (looking-at name-regexp)
1464                             (quack-not-symbol-char-at-point-p (match-end 0)))
1465                        ;; Found it, so set the result to a list (lexeme, lexeme
1466                        ;; end point, last nested child sexp start point, parent
1467                        ;; paren start point) and then fall out of our loop.
1468                        ;; Note that we return the original point if no child
1469                        ;; point was found, on the assumption that point was at
1470                        ;; the beginning of the child sexp (unless it was within
1471                        ;; the found form name, in which case child sexp start
1472                        ;; is nil).
1473                        (setq found (list (quack-match-string-no-properties 0)
1474                                          (match-end 0)
1475                                          (or child-start
1476                                              (if (> orig-point (match-end 0))
1477                                                  orig-point))
1478                                          paren-start))
1479                      ;; This form name didn't match, so try to move up in the
1480                      ;; paren syntax (which will usually mean moving left one
1481                      ;; character).
1482                      (condition-case nil
1483                          (progn (up-list -1)
1484                                 (setq child-start (point))
1485                                 (setq depth (1+ depth)))
1486                        (error           ; scan-error
1487                         ;; We can't go up here, so set found flag to indicate
1488                         ;; failure and then fall out of the loop.
1489                         (setq found nil))))
1490                  ;; There wasn't a paren, which means we hit a scan error for
1491                  ;; some reason other than being at the beginning of the sexp,
1492                  ;; so consider the search a failure
1493                  (setq found nil))))))
1494         (if (eq found 'looking)
1495             nil
1496           found)))))
1497
1498 ;; TODO: We really need a global definition of what are Scheme symbol
1499 ;;       constituent characters (or a whole-symbol regexp)!
1500
1501 (defun quack-not-symbol-char-at-point-p (pt)
1502   ;; This is used to check for a symbol boundary point.
1503   (save-match-data
1504     (or (= pt (point-max))
1505         (if (string-match "[^-a-zA-Z0-9!+<=>$%&*./:@^_~]"
1506                           (buffer-substring-no-properties pt (1+ pt)))
1507             t))))
1508
1509 ;; String Constant Hashtable:
1510
1511 (eval-and-compile
1512   (if (< emacs-major-version 21)
1513
1514       (defun quack-strconst (str) str)
1515
1516     (defvar quack-strconst-hashtable
1517       (if (>= emacs-major-version 21)
1518           (quack-make-hash-table :test 'equal :size 1000)))
1519
1520     (defun quack-strconst (str)
1521       (unless (stringp str)
1522         (error "Non-string object passed to quack-strconst: %s" str))
1523       (or (quack-gethash str quack-strconst-hashtable nil)
1524           (quack-puthash str str quack-strconst-hashtable)
1525           str))))
1526
1527 ;; Web URLs:
1528
1529 (defun quack-quote-url-substring (str &optional quote-slash-p always-new-p)
1530   (save-match-data
1531     (let ((regexp (if quote-slash-p "[^-_.A-Za-z0-9]" "[^-_.A-Za-z0-9/]"))
1532           (subs   '())
1533           (len    (length str))
1534           (start  0))
1535       (while (and (> len start)
1536                   (string-match regexp str start))
1537         (let ((beg (match-beginning 0))
1538               (end (match-end       0)))
1539           (when (> beg start)
1540             (setq subs (cons (substring str start beg) subs)))
1541           (setq subs (cons (format "%%%X" (aref str beg)) subs))
1542           (setq start end)))
1543       (if subs
1544           (apply 'concat (reverse (if (> len start)
1545                                       (cons (substring str start len) subs)
1546                                     subs)))
1547         (if always-new-p (copy-sequence str) str)))))
1548
1549 (defun quack-file-url (dir file)
1550   ;; TODO: This is Unix-centric and a little fragile.  Rewrite eventually.
1551   (concat "file:"
1552           (quack-quote-url-substring dir)
1553           "/"
1554           (or (quack-quote-url-substring file) "")))
1555
1556 (defun quack-build-url (base path)
1557   (let ((base-slash-p (= (aref base (1- (length base))) ?\/)))
1558     (if path
1559         (mapconcat 'identity
1560                    (cons (if base-slash-p
1561                              (substring base 0 -1)
1562                            base)
1563                          path)
1564                    "/")
1565       (if base-slash-p
1566           base
1567         (concat base "/")))))
1568
1569 ;; Web Browsing:
1570
1571 (defun quack-browse-url (url)
1572   (require 'browse-url)
1573   (message "Quack viewing URL: %s" url)
1574   (let ((browse-url-browser-function (or quack-browse-url-browser-function
1575                                          browse-url-browser-function)))
1576     (browse-url url)))
1577
1578 (defun quack-browse-quack-web-page ()
1579   (interactive)
1580   (quack-browse-url quack-web-page))
1581
1582 (defun quack-w3m-browse-url-other-window (url &optional new-window)
1583   (interactive (eval '(browse-url-interactive-arg "URL: ")))
1584   (unless (string= (buffer-name) "*w3m*")
1585     (switch-to-buffer-other-window (current-buffer)))
1586   ;; TODO: If `*w3m*' buffer is visible in current frame or other frame,
1587   ;;       switch to that, for Emacsen that don't do that by default.
1588   (eval '(w3m-browse-url url nil)))
1589
1590 ;; Web Getting:
1591
1592 (defconst quack-web-get-log-buffer-name "*quack-web-get*")
1593
1594 (defun quack-web-get-to-file (url out-file)
1595   ;; TODO: Support other getting tools, such as "lynx -source", "links
1596   ;;       -source", "w3m -dump_source", and the Emacs w3 package.  Most of
1597   ;;       these send the Web content to stdout, so, unlike for wget, it will
1598   ;;       be easier to insert directly to a buffer and send stderr to a temp
1599   ;;       file.  We should have *-to-file-* and *-insert-via-* functions for
1600   ;;       each external downloader program anyway.
1601   (quack-make-directory-for-file out-file)
1602   (quack-web-get-to-file-via-wget url out-file))
1603
1604 ;;(defun quack-web-get-to-temp-file (url)
1605 ;;  (let ((temp-file (quack-make-temp-file "web-get")))
1606 ;;    (quack-web-get-to-file url temp-file)
1607 ;;    temp-file))
1608
1609 (defun quack-web-get-to-file-via-wget (url out-file)
1610   ;; TODO: Make this initially download to a temp file; replace any
1611   ;;       pre-existing out-file after successful download.  Do this for any
1612   ;;       external downloader programs that write to the specified output file
1613   ;;       before the download is complete.
1614   (let ((window    (selected-window))
1615         (saved-buf (current-buffer))
1616         (log-buf   (get-buffer-create quack-web-get-log-buffer-name)))
1617     (unwind-protect
1618         (progn
1619           ;; Prepare the log buffer.
1620           (set-buffer log-buf)
1621           (widen)
1622           (buffer-disable-undo)
1623           (goto-char (point-min))
1624           (delete-region (point-min) (point-max))
1625           (set-window-buffer window log-buf)
1626           ;; Do the wget.
1627           (quack-activity
1628            (format "Getting %S via wget" url)
1629            (let ((status (call-process "wget" nil t t
1630                                        "-O" out-file "-t" "1" "--" url)))
1631              (unless (= status 0)
1632                (quack-delete-file-if-can out-file)
1633                (error "Could not get %S via wget." url))
1634              (kill-buffer log-buf)
1635              out-file)))
1636       ;; unwind-protect cleanup
1637       (set-window-buffer window saved-buf)
1638       (set-buffer saved-buf))))
1639
1640 ;; HTML Kludges:
1641
1642 (defun quack-strip-limited-html-tags (str)
1643   (save-match-data
1644     (let ((case-fold-search t)
1645           (str-len          (length str))
1646           (frags            '())
1647           (start            0))
1648       (while (string-match "</?[a-z]+[ \r\n]*>" str start)
1649         (when (> (match-beginning 0) start)
1650           (setq frags (cons (substring str start (match-beginning 0)) frags)))
1651         (setq start (match-end 0)))
1652       (if frags
1653           (progn (when (< start str-len)
1654                    (setq frags (cons (substring str start) frags)))
1655                  (apply 'concat (reverse frags)))
1656         str))))
1657
1658 ;; Temp Files:
1659
1660 (defun quack-temp-dir ()
1661   (file-name-as-directory (expand-file-name "tmp" quack-dir)))
1662
1663 ;; TODO: Make sure this gets executed in load phase even if byte-compiled.
1664
1665 (random t)
1666
1667 (defun quack-make-temp-file (purpose-str)
1668   ;; Note: There is an obvious race condition here.  But we're trying to do
1669   ;;       this in portable Elisp, and if user's `quack-dir' is writable by
1670   ;;       someone other than user, then user has bigger problems.
1671   (save-excursion
1672     (let* ((buf (generate-new-buffer "*quack-make-temp-file*"))
1673            (dir (quack-temp-dir))
1674            file)
1675       (set-buffer buf)
1676       (quack-make-directory dir)
1677       (while (progn (setq file (expand-file-name (format "%d-%s-%d"
1678                                                          (emacs-pid)
1679                                                          purpose-str
1680                                                          (random 10000))
1681                                                  dir))
1682                     (file-exists-p file)))
1683       (set-visited-file-name file)
1684       (save-buffer 0)
1685       (kill-buffer buf)
1686       file)))
1687
1688 ;; About:
1689
1690 (defun quack-about ()
1691   (interactive)
1692   (let* ((buf-name "*About Quack*")
1693          (buf      (get-buffer buf-name)))
1694     (when buf (kill-buffer buf))
1695     (setq buf (get-buffer-create buf-name))
1696     (switch-to-buffer buf)
1697     (setq buffer-read-only nil)
1698     (widen)
1699     (fundamental-mode)
1700     (when font-lock-mode
1701       ;;(quack-warning "Font-lock mode mysteriously on in fundamental-mode.")
1702       (font-lock-mode -1))
1703     (buffer-disable-undo)
1704     ;;(delete-region (point-min) (point-max))
1705     (erase-buffer)
1706     (insert
1707      "\n"
1708      (quack-propertize-face (copy-sequence "Quack") 'quack-about-title-face)
1709      "   Version "
1710      (quack-propertize-bold (copy-sequence quack-version))
1711      "\n"
1712      (quack-propertize-italic
1713       (copy-sequence "Enhanced Emacs support for Scheme programming"))
1714      "\n\n"
1715      "You can email bug reports and feature requests to the author,\n"
1716      quack-author-name
1717      " <"
1718      quack-author-email
1719      ">.  Mention that\n"
1720      "you are using "
1721      (quack-propertize-bold
1722       (copy-sequence
1723        (cond (quack-gnuemacs-p "GNU Emacs")
1724              (quack-xemacs-p   "XEmacs")
1725              (t                "*an unrecognized Emacs kind*"))))
1726      " "
1727      (quack-propertize-bold
1728       (format "%d.%d" emacs-major-version emacs-minor-version))
1729      " on "
1730      (quack-propertize-bold (copy-sequence system-configuration))
1731      ".\n\n"
1732      "To be notified via email when new Quack versions are released,\n"
1733      "ask Neil to add you to the moderated "
1734      (quack-propertize-bold "scheme-announce")
1735      " list.\n\n"
1736      "Visit the Web page:  "
1737      quack-web-page
1738      "\n")
1739     (insert "\n\n"
1740             (quack-propertize-face (copy-sequence quack-copyright)
1741                                    'quack-smallprint-face)
1742             "\n"
1743             (quack-propertize-face (copy-sequence quack-copyright-2)
1744                                    'quack-smallprint-face)
1745             "\n\n"
1746             (quack-propertize-face (concat quack-legal-notice "\n")
1747                                    'quack-smallprint-face))
1748     (goto-char (point-min))
1749     (set-buffer-modified-p nil)
1750     (setq buffer-read-only t)
1751     (local-set-key "q" 'quack-kill-current-buffer)
1752     (local-set-key "w" 'quack-browse-quack-web-page)
1753     (message
1754      "Press `q' to quit *About Quack*, `w' to visit the Quack Web page.")))
1755
1756 ;; PLT Collections:
1757
1758 (defvar quack-pltcollects-alist-cache nil)
1759
1760 (defun quack-invalidate-pltcollects-caches ()
1761   (setq quack-pltcollects-alist-cache nil)
1762   (quack-invalidate-manuals-caches))
1763
1764 (defun quack-pltcollects-alist ()
1765   (or quack-pltcollects-alist-cache
1766       (quack-activity
1767        "Scanning PLT collection directories"
1768        (let ((result '()))
1769          (mapcar (function
1770                   (lambda (dir)
1771                     (mapcar (function
1772                              (lambda (subdir)
1773                                (unless (member subdir '("." ".." "CVS" "RCS"))
1774                                  (let ((subdir-path (expand-file-name subdir
1775                                                                       dir)))
1776                                    (when (file-directory-p subdir-path)
1777                                      (setq result
1778                                            (cons (cons subdir subdir-path)
1779                                                  result)))))))
1780                             (condition-case nil
1781                                 (directory-files dir)
1782                               (file-error nil)))))
1783                  quack-pltcollect-dirs)
1784          (setq quack-pltcollects-alist-cache (reverse result))))))
1785
1786 (defun quack-dir-for-pltcollect (name)
1787   (cdr (assoc name (quack-pltcollects-alist))))
1788
1789 (defun quack-dired-pltcollect ()
1790   (interactive)
1791   (let* ((alist   (quack-pltcollects-alist))
1792          (default (if (assoc "mzlib" alist) "mzlib" nil))
1793          (dir (cdr (assoc
1794                     (completing-read
1795                      (if default 
1796                          (format "Dired for PLT collection (default %S): "
1797                                  default)
1798                        "Dired for PLT collection: ")
1799                      alist nil t nil nil default)
1800                     alist))))
1801     (and dir (dired dir))))
1802
1803 ;; Find File:
1804
1805 (defun quack-shorter-file-relative-name (filename &optional directory)
1806   (let ((absolute (expand-file-name   filename directory))
1807         (relative (file-relative-name filename directory)))
1808     (if (< (length relative) (length absolute))
1809         relative
1810       absolute)))
1811
1812 ;; TODO: Also write `quack-find-file-other-window' and
1813 ;;       `quack-find-file-other-frame' and steal appropriate key bindings.
1814
1815 (defun quack-find-file ()
1816   ;; TODO: Hangup/delay problems in mega-huge files.
1817   ;;
1818   ;; TODO: Handle `(load <filename>)'
1819   (interactive)
1820   (let* ((default (quack-find-file-default))
1821          (entry   (let ((insert-default-directory (if default
1822                                                       nil
1823                                                     insert-default-directory)))
1824                     (read-file-name
1825                      (if default
1826                          (format "Quack find file (default %S): "
1827                                  (quack-shorter-file-relative-name
1828                                   default
1829                                   default-directory))
1830                        "Quack find file: ")
1831                      default-directory
1832                      default))))
1833     (find-file (if (string= entry "")
1834                    (or default "")
1835                  entry))))
1836
1837 (defun quack-find-file-default ()
1838   (or (quack-pltrequire-at-point-filename)
1839       ;; TODO: Add support for syntax from Guile, SLIB, Chicken, etc.
1840       ))
1841
1842 ;; TODO: Guile `:use-module' support.  Forget about 1.4, and do 1.6.
1843 ;;
1844 ;; (defun quack-guilecolonusemodule-at-point-data ()
1845 ;;   (save-match-data
1846 ;;     (when (thing-at-point-looking-at
1847 ;;            ":use-module[ \t]+\\(([^][()\"#'`,]+)\\)")
1848 ;;       (condition-case nil
1849 ;;           (car (read-from-string (buffer-substring-no-properties
1850 ;;                                   (match-beginning 1) (match-end 1))))
1851 ;;         (error nil)))))
1852 ;;
1853 ;; ;; (define-module (ice-9 expect) :use-module (ice-9 regex))
1854
1855 ;; TODO: Guile 1.6 `use-modules' and `use-syntax' support.
1856 ;;
1857 ;; (use-modules (ice-9 regex))
1858 ;;
1859 ;; (use-modules ((ice-9 popen)
1860 ;;               :select  ((open-pipe . pipe-open) close-pipe)
1861 ;;               :renamer (symbol-prefix-proc 'unixy:)))
1862 ;;
1863 ;; (use-modules { SPEC }+ )
1864 ;;
1865 ;; SPEC ::= MODULE-NAME | (MODULE-NAME [:select SELECTION] [:renamer RENAMER])
1866 ;;
1867 ;; (use-syntax MODULE-NAME)
1868
1869 ;; TODO: Support SLIB-style `require' forms:
1870 ;;
1871 ;; (require 'foo)
1872
1873 ;; TODO: Bigloo `import' and maybe `extern' support.
1874 ;;
1875 ;; ;; /usr/share/doc/bigloo-examples/examples/Foreign/
1876 ;; (module example
1877 ;;   (import (bis foreign2 "foreign2.scm"))
1878 ;;   ...)
1879 ;;
1880 ;; ;; /usr/share/doc/bigloo-examples/examples/Fork/
1881 ;; (module sys-example
1882 ;;   (extern (include "sys/types.h")
1883 ;;           (include "wait.h")
1884 ;;           (include "unistd.h")
1885 ;;           ...))
1886
1887 ;; TODO: PLT module language syntax: (module info (lib "infotab.ss" "setup")
1888
1889 (defconst quack-pltrequire-at-point-data-re
1890   (quack-re-alt "dynamic-require"
1891                 (concat "require"
1892                         (quack-re-alt "-for-syntax"
1893                                       ""))))
1894
1895 (defconst quack-pltrequire-at-point-data-1-re
1896   (concat quack-pltrequire-at-point-data-re
1897           "\\>"))
1898
1899 (defconst quack-pltrequire-at-point-data-2-re
1900   (concat "[^\r\n]*[[(]"
1901           quack-pltrequire-at-point-data-re
1902           "[ \t]+\\([^\r\n]+\\)"))
1903
1904 (defun quack-pltrequire-at-point-data-1 ()
1905   (save-match-data
1906     (let ((qpss (quack-parent-sexp-search quack-pltrequire-at-point-data-1-re
1907                                           4)))
1908       (when qpss
1909         (let ((child-start (nth 2 qpss)))
1910           (when child-start
1911             (save-excursion
1912               (goto-char child-start)
1913               (condition-case nil
1914                   ;; Note: It is normally OK to use the Elisp reader here.
1915                   (read (current-buffer))
1916                 (error nil)))))))))
1917
1918 (defun quack-pltrequire-at-point-data-2 ()
1919   (save-match-data
1920     (when (thing-at-point-looking-at quack-pltrequire-at-point-data-2-re)
1921       (let* ((read-start (match-beginning 2))
1922              (parts-pt   (- (point) read-start))
1923              (parts      (buffer-substring-no-properties read-start
1924                                                          (match-end 2)))
1925              (parts-len  (length parts))
1926              (start      0)
1927              (result     '()))
1928         (condition-case nil
1929             (while (< start parts-len)
1930               ;; Note: It is normally OK to use the Elisp reader here.
1931               (let ((r (read-from-string parts start)))
1932                 (when (or (not result) (> parts-pt start))
1933                   (setq result (car r)))
1934                 (setq start (cdr r))))
1935           (error nil))
1936         result))))
1937
1938 (defun quack-pltrequire-at-point-filename (&optional silent)
1939   (let* ((d (or (quack-pltrequire-at-point-data-1)
1940                 (quack-pltrequire-at-point-data-2)))
1941          (m (cond
1942              ((not     d) nil)
1943              ((stringp d) d)
1944              ((listp   d)
1945               (let ((f (car d)))
1946                 (when (symbolp f)
1947                   (cond ((memq f '(file lib))                 d)
1948                         ((memq f '(all-except rename))        (nth 1 d))
1949                         ((memq f '(prefix prefix-all-except)) (nth 2 d)))))))))
1950     (cond
1951      ((stringp m) m)
1952      ((listp   m)
1953       (let ((f (car m)))
1954         (when (symbolp f)
1955           (cond ((eq f 'file) (nth 1 f))
1956                 ((eq f 'lib)
1957                  (let* ((file        (nth 1 m))
1958                         (collect     (or (nth 2 m) "mzlib"))
1959                         (collect-dir (quack-dir-for-pltcollect collect))
1960                         (subs        (nthcdr 3 m)))
1961                    (when file
1962                      (if collect-dir
1963                          (quack-expand-file-name (nconc subs (list file))
1964                                                  collect-dir)
1965                        (unless silent
1966                          (quack-warning "Cannot find collection %S" collect))
1967                        nil)))))))))))
1968
1969 ;; Indenting Newline:
1970
1971 (defun quack-newline (&optional arg)
1972   (interactive "*P")
1973   (if (eq quack-newline-behavior 'newline)
1974       (newline arg)
1975     (if (eq quack-newline-behavior 'indent-newline-indent)
1976         (lisp-indent-line)
1977       (unless (eq quack-newline-behavior 'newline-indent)
1978         (error "invalid quack-newline-behavior value: %s"
1979                quack-newline-behavior)))
1980     (let ((n (prefix-numeric-value arg)))
1981       (when (> n 0)
1982         (while (> n 0)
1983           (setq n (1- n))
1984           (quack-delete-horizontal-space t)
1985           (newline))
1986         (lisp-indent-line)))))
1987
1988 ;; Agreeing-Paren Insert:
1989
1990 ;; TODO: Make paren-matching within comments limit seaching to within comments,
1991 ;;       not skip back and try to match code.  One workaround is to prefix
1992 ;;       parents/brackets in comments with backslash.
1993
1994 (defun quack-insert-closing (prefix default-close other-open other-close)
1995   (insert default-close)
1996   (unless prefix
1997     (let ((open-pt (condition-case nil
1998                        (scan-sexps (point) -1)
1999                      (error (beep) nil))))
2000       (when open-pt
2001         (let ((open-char (aref (buffer-substring-no-properties
2002                                 open-pt (1+ open-pt))
2003                                0)))
2004           (when (= open-char other-open)
2005             (delete-backward-char 1)
2006             (insert other-close))))))
2007   (when blink-paren-function (funcall blink-paren-function)))
2008
2009 (defun quack-insert-closing-paren (&optional prefix)
2010   (interactive "P")
2011   (quack-insert-closing prefix ?\) ?\[ ?\]))
2012
2013 (defun quack-insert-closing-bracket (&optional prefix)
2014   (interactive "P")
2015   (quack-insert-closing prefix ?\] ?\( ?\)))
2016
2017 ;; Opening-Paren Insert:
2018
2019 (defun quack-insert-opening (prefix char)
2020   (insert (if (or prefix (not quack-smart-open-paren-p)) char ?\())
2021   (when blink-paren-function (funcall blink-paren-function)))
2022
2023 (defun quack-insert-opening-paren (&optional prefix)
2024   (interactive "P")
2025   (quack-insert-opening prefix ?\())
2026
2027 (defun quack-insert-opening-bracket (&optional prefix)
2028   (interactive "P")
2029   (quack-insert-opening prefix ?\[))
2030
2031 ;; Definition Lambda Syntax Toggling:
2032
2033 (defconst quack-toggle-lambda-re-1
2034   (concat "define\\*?"
2035           (quack-re-alt "-for-syntax"
2036                         "-public"
2037                         "/override"
2038                         "/private"
2039                         "/public"
2040                         "")))
2041
2042 (defconst quack-toggle-lambda-re-2
2043   (let ((ws-opt      "[ \t\r\n\f]*")
2044         (symbol      "[^][() \t\r\n\f]+")
2045         (open-paren  "[[(]")
2046         (close-paren "[])]"))
2047     (concat ws-opt
2048             (quack-re-alt               ; #=1
2049              (concat "\\("              ; #<2 `NAME (lambda ('
2050                      "\\("              ; #<3 name
2051                      symbol
2052                      "\\)"              ; #>3
2053                      ws-opt
2054                      open-paren
2055                      ws-opt
2056                      "lambda"
2057                      ws-opt
2058                      open-paren
2059                      ws-opt
2060                      "\\)")
2061              (concat "\\("              ; #<4 `(NAME'
2062                      open-paren
2063                      ws-opt
2064                      "\\("              ; #<5 name
2065                      symbol
2066                      "\\)"              ; #>5
2067                      ws-opt
2068                      "\\)"))
2069             "\\("                       ; #<6 optional close paren
2070             close-paren
2071             "\\)?"                      ; #>6
2072             )))
2073
2074 (defun quack-toggle-lambda ()
2075   (interactive)
2076   (save-match-data
2077     (let ((found (quack-parent-sexp-search quack-toggle-lambda-re-1))
2078           last-paren-marker
2079           leave-point-marker)
2080       (unless found
2081         (error "Sorry, this does not appear to be a definition form."))
2082       (unwind-protect
2083           (let ((lexeme-end (nth 1 found))
2084                 (define-beg (nth 3 found)))
2085
2086             ;; Make the markers.
2087             (setq last-paren-marker  (make-marker))
2088             (setq leave-point-marker (point-marker))
2089
2090             ;; Move to right after the define form keyword, and match the
2091             ;; pattern of the two possible syntaxes.  Error if no match.
2092             (goto-char lexeme-end)
2093             (unless (looking-at quack-toggle-lambda-re-2)
2094               (error "Sorry, we can't grok this definition syntax."))
2095
2096             ;; Pattern matched, so find the closing paren of the define form.
2097             (let ((pt (condition-case nil
2098                           (scan-sexps define-beg 1)
2099                         (error          ; scan-error
2100                          nil))))
2101               (if pt
2102                   (set-marker last-paren-marker (1- pt))
2103                 (quack-warning
2104                  "This definition form sexp is unclosed.  Consider undo.")))
2105
2106             ;; Now act based on which syntax we saw.
2107             (cond
2108
2109              ((match-beginning 2)
2110               ;; We saw the syntax `NAME (lambda ('.
2111               (let ((name (quack-match-string-no-properties 3)))
2112                 (when (marker-position last-paren-marker)
2113                   (goto-char last-paren-marker)
2114                   (let ((victim-beg (quack-looking-at-close-paren-backward)))
2115                     (unless victim-beg
2116                       (error "This definition form should end with `))'."))
2117                     (delete-region victim-beg (point))))
2118                 (goto-char lexeme-end)
2119                 (delete-region lexeme-end (match-end 2))
2120                 (insert " (" name (if (match-beginning 6) "" " "))))
2121
2122              ((match-beginning 4)
2123               ;; We saw the syntax `(NAME'.
2124               (let ((name (quack-match-string-no-properties 5)))
2125                 (when (marker-position last-paren-marker)
2126                   (goto-char last-paren-marker)
2127                   (insert ")"))
2128                 (goto-char lexeme-end)
2129                 (delete-region lexeme-end (match-end 4))
2130                 (insert " " name "\n")
2131                 (set-marker leave-point-marker (point))
2132                 (insert "(lambda (")
2133                 (set-marker-insertion-type leave-point-marker t)))
2134
2135              (t (quack-internal-error)))
2136
2137             ;; Reindent, which also takes care of font-lock updating of deleted
2138             ;; and inserted text.
2139             (indent-region define-beg
2140                            (or (marker-position last-paren-marker)
2141                                (max (marker-position leave-point-marker)
2142                                     (point)))
2143                            nil))
2144
2145         ;; unwind-protect cleanup
2146         (goto-char (marker-position leave-point-marker))
2147         (set-marker leave-point-marker nil)))))
2148
2149 ;; Buffer Tidying:
2150
2151 ;; TODO: Maybe have an option to automatically tidy the buffer on save.  Make
2152 ;;       default off.  This can be slow for larger buffers on older computers,
2153 ;;       especially if font-lock is activated.  It can also annoy people who
2154 ;;       have a CM system full of improperly formatted files, or who like
2155 ;;       things like formfeed characters in their files.
2156
2157 (defun quack-delete-all-in-buffer (regexp &optional subexp)
2158   (unless subexp (setq subexp 0))
2159   ;; Note: This moves the point and changes the match data.
2160   (goto-char (point-min))
2161   (while (re-search-forward regexp nil t)
2162     (goto-char (match-end subexp))
2163     (delete-region (match-beginning subexp) (point))))
2164
2165 (defun quack-tidy-buffer ()
2166
2167   ;; TODO: Make sure this works with odd eol conventions and the various
2168   ;;       codeset representations in various versions of Emacs.
2169
2170   ;; TODO: Maybe detect DrScheme ASCII-art "big letters" and protect them from
2171   ;;       reindenting.
2172
2173   "Tidy the formatting of the current Scheme buffer.
2174
2175 This reindents, converts tabs to spaces, removes trailing whitespace on lines,
2176 removes formfeed characters, removes extraneous blank lines, and makes sure
2177 the buffer ends with a newline.
2178
2179 This can conceivably corrupt multi-line string literals, but not in any way
2180 they wouldn't be corrupted by Usenet, various mailers, typesetting for print,
2181 etc.
2182
2183 This may also result in large diffs when the tidied file is commited back to a
2184 version control or configuration management system.  Consider making a VC or CM
2185 delta that consists only of changes made by `quack-tidy-buffer'."
2186   (interactive)
2187   (if (= (point-min) (point-max))
2188       (message "Buffer is empty; no tidying necessary.")
2189     (let ((marker      (point-marker))
2190           (fill-prefix nil))
2191       (unwind-protect
2192           (save-excursion
2193             (save-match-data
2194               (quack-activity
2195                "Tidying buffer"
2196
2197                ;; Make sure last character is a newline.
2198                (unless (string= "\n" (buffer-substring-no-properties
2199                                       (1- (point-max))
2200                                       (point-max)))
2201                  (goto-char (point-max))
2202                  (insert "\n"))
2203
2204                ;; Remove form-feed characters.
2205                (quack-delete-all-in-buffer "\f")
2206
2207                ;; Reindent buffer (without inserting any new tabs).
2208                ;; Note: This is the time-consuming pass.
2209                (let ((saved-indent-tabs-mode indent-tabs-mode))
2210                  (unwind-protect
2211                      (progn (setq indent-tabs-mode nil)
2212                             (indent-region (point-min) (point-max) nil))
2213                    ;; unwind-protect cleanup
2214                    (setq indent-tabs-mode saved-indent-tabs-mode)))
2215
2216                ;; Expand any remaining tabs.
2217                (untabify (point-min) (point-max))
2218
2219                ;; Remove trailing whitespace on each line.
2220                (quack-delete-all-in-buffer "\\([ \t\r]+\\)\n" 1)
2221
2222                ;; Remove blank lines from top.
2223                (goto-char (point-min))
2224                (when (looking-at "[ \t\r\n]+")
2225                  (delete-region (match-beginning 0) (match-end 0)))
2226
2227                ;; Remove excess adjacent blank lines.
2228                (quack-delete-all-in-buffer "\n\n\\(\n+\\)" 1)
2229
2230                ;; Remove blank lines from bottom.
2231                (goto-char (point-max))
2232                (when (quack-looking-at-backward
2233                       "\n\\(\n\\)"
2234                       (max (point-min) (- (point-max) 3)))
2235                  (delete-region (match-beginning 1) (match-end 1))))))
2236
2237         ;; unwind-protect cleanup
2238         (goto-char (marker-position marker))
2239         (set-marker marker nil)))))
2240
2241 ;; SRFIs:
2242
2243 ;; TODO: Archive local copies of SRFIs?  Have to update them when modified, but
2244 ;;       without unnecessarily downloading from the master site.  This is
2245 ;;       doable with wget mirroring, but not with things like "lynx -source".
2246
2247 (defconst quack-srfi-subindex-kinds '(draft final withdrawn)
2248   "List of symbols representing the three possible states of an SRFI (`draft',
2249 `final', and `withdrawn'), in order of increasing precedence (e.g., final
2250 follows draft,since a final version supercedes a draft version).")
2251
2252 (defvar quack-srfi-completes-cache 'invalid)
2253 (defvar quack-srfi-menu-cache      'invalid)
2254
2255 (defun quack-srfi-completes ()
2256   (when (eq quack-srfi-completes-cache 'invalid)
2257     (quack-process-srfi-subindex-files))
2258   quack-srfi-completes-cache)
2259
2260 (defun quack-srfi-menu (&optional noninteractive)
2261   (when (eq quack-srfi-menu-cache 'invalid)
2262     (quack-process-srfi-subindex-files noninteractive))
2263   quack-srfi-menu-cache)
2264
2265 (defun quack-srfi-master-url (path)
2266   (quack-build-url quack-srfi-master-base-url path))
2267
2268 (defun quack-srfi-subindex-master-url (kind)
2269   (quack-srfi-master-url (list (quack-srfi-subindex-basename kind))))
2270
2271 (defun quack-srfi-dir ()
2272   (file-name-as-directory (expand-file-name "srfi" quack-dir)))
2273
2274 (defun quack-srfi-subindex-file (kind)
2275   (expand-file-name (quack-srfi-subindex-basename kind) (quack-srfi-dir)))
2276
2277 (defun quack-srfi-subindex-basename (kind)
2278   (format "%S-srfis.html" kind))
2279
2280 (defun quack-invalidate-srfi-index-caches ()
2281   (setq quack-srfi-completes-cache 'invalid)
2282   (setq quack-srfi-menu-cache      'invalid))
2283
2284 (defun quack-update-srfi-index ()
2285   (interactive)
2286   (quack-activity
2287    "Updating SRFI index"
2288    (quack-download-srfi-subindex-files)))
2289
2290 (defun quack-download-srfi-subindex-files ()
2291   (quack-invalidate-srfi-index-caches)
2292   (mapcar (function
2293            (lambda (kind)
2294              (quack-activity
2295               (format "Downloading %s SRFI subindex" kind)
2296               (quack-web-get-to-file (quack-srfi-subindex-master-url kind)
2297                                      (quack-srfi-subindex-file       kind)))))
2298           quack-srfi-subindex-kinds))
2299
2300 (defun quack-download-srfi-subindex-files-if-missing ()
2301   (let ((missing '()))
2302     (mapcar (function
2303              (lambda (kind)
2304                (unless (file-exists-p (quack-srfi-subindex-file kind))
2305                  (setq missing (nconc missing (list kind))))))
2306             quack-srfi-subindex-kinds)
2307     (when (and missing
2308                (y-or-n-p "Some cached SRFI subindexes are missing. Update? "))
2309       (quack-update-srfi-index))))
2310
2311 (defun quack-process-srfi-subindex-files (&optional noninteractive)
2312   (let ((index      '())
2313         (completes  '())
2314         (menu       (mapcar (function (lambda (kind) (cons kind nil)))
2315                             quack-srfi-subindex-kinds)))
2316
2317     ;; Invalidate dependent caches.
2318     (quack-invalidate-srfi-index-caches)
2319
2320     ;; Give user a chance to download any missing cache files all at once,
2321     ;; instead of prompting individually later.
2322     (unless noninteractive
2323       (quack-download-srfi-subindex-files-if-missing))
2324
2325     ;; Parse the index files, letting entries for successive states supercede.
2326     (mapcar (function
2327              (lambda (kind)
2328                (mapcar (function
2329                         (lambda (new)
2330                           (let (old)
2331                             (if (setq old (assq (car new) index))
2332                                 (setcdr old (cdr new))
2333                               (setq index (cons new index))))))
2334                        (quack-parse-srfi-subindex-file kind noninteractive))))
2335             quack-srfi-subindex-kinds)
2336
2337     ;; Sort the parse form in reverse order, since the cache-building functions
2338     ;; will reverse this.
2339     (setq index (sort index (function (lambda (a b) (>= (car a) (car b))))))
2340
2341     ;; Build the completions and menu caches.
2342     (let ((fmt (concat "%"
2343                        (if index
2344                            (number-to-string
2345                             (length (number-to-string (car (car index)))))
2346                          "")
2347                        "d  %s")))
2348       (mapcar (function
2349                (lambda (n)
2350                  (let ((num      (nth 0 n))
2351                        (kind     (nth 1 n))
2352                        (title    (nth 2 n)))
2353                    (unless kind (quack-internal-error))
2354                    (setq completes
2355                          (cons (cons (if (eq kind 'final)
2356                                          (format "%d  %s" num title)
2357                                        (format "%d  [%s] %s" num kind title))
2358                                      num)
2359                                completes))
2360                    (let ((pair (or (assq kind menu)
2361                                    (quack-internal-error))))
2362                      (setcdr pair (cons `[,(format fmt num title)
2363                                           (quack-view-srfi ,num)]
2364                                         (cdr pair)))))))
2365               index))
2366
2367     ;; Finish the menu.
2368     (mapcar (function (lambda (n)
2369                         (setcar n (cdr (assoc (car n)
2370                                               '((draft     . "Draft")
2371                                                 (final     . "Final")
2372                                                 (withdrawn . "Withdrawn")))))
2373                         ;; Add dummy content so that XEmacs 21 will display
2374                         ;; the submenu label.
2375                         (unless (cdr n)
2376                           (setcdr n (cons "(None)" nil)))))
2377             menu)
2378     (setq menu `(["Update SRFI Index" quack-update-srfi-index]
2379                  "---"
2380                  ,@menu
2381                  ["Other SRFI..." quack-view-srfi]))
2382
2383     ;; Store the results.
2384     (setq quack-srfi-menu-cache      menu)
2385     (setq quack-srfi-completes-cache completes)))
2386
2387 (defun quack-parse-srfi-subindex-file (kind &optional noninteractive)
2388   (save-excursion
2389     (let ((file (quack-srfi-subindex-file kind)))
2390       (unless (file-exists-p file)
2391         (error "No SRFI index file %S" file))
2392       (let* ((buf                (get-file-buffer file))
2393              (already-visiting-p buf))
2394         (unless buf
2395           (setq buf (find-file-noselect file t t)))
2396         (unwind-protect
2397             (progn (set-buffer buf)
2398                    (quack-parse-srfi-subindex-buffer kind))
2399           ;; unwind-protect-cleanup
2400           (unless already-visiting-p
2401             (kill-buffer buf)))))))
2402
2403 (defconst quack-parse-srfi-index-buffer-re-1
2404   (concat
2405    "<LI><A HREF=\"?srfi-[0-9]+/?\"?>SRFI[ \t]+"
2406    "\\([0-9]+\\)"                       ; #=1 srfi number
2407    "</A>:?[ \t]*"
2408    "\\("                                ; #<2 srfi title
2409                                         ; #=3
2410    (quack-re-alt "[^\r\n<>]" "</?[a-z]+>")
2411    "+"
2412    "\\)"))
2413
2414 (defun quack-parse-srfi-subindex-buffer (kind)
2415   (save-excursion
2416     (let ((case-fold-search t)
2417           (alist            '()))
2418       (goto-char (point-min))
2419       (while (re-search-forward quack-parse-srfi-index-buffer-re-1 nil t)
2420         (let ((number (string-to-number (quack-match-string-no-properties 1)))
2421               (title  (quack-without-side-whitespace
2422                        (quack-strip-limited-html-tags
2423                         (quack-match-string-no-properties 2)))))
2424           (setq alist (cons
2425
2426                        ;;(cons number
2427                        ;;      (if (and kind (not (eq kind 'final)))
2428                        ;;          (format "[%s] %s" kind title)
2429                        ;;        title))
2430                        (list number kind title)
2431
2432                        alist))))
2433       (setq alist (reverse alist)))))
2434
2435 (defun quack-srfi-num-url (num)
2436   (quack-srfi-master-url (list (format "srfi-%d"      num)
2437                                (format "srfi-%d.html" num))))
2438
2439 (defconst quack-srfi-num-at-point-re-1
2440   "srfi[-: \t]*\\([0-9]+\\)")
2441
2442 (defconst quack-srfi-num-at-point-re-2
2443   ;; Note: We can't have "[^\r\n]*" as a prefix, since it's too slow.
2444   (concat quack-srfi-num-at-point-re-1 "[^\r\n]*"))
2445
2446 (defun quack-srfi-num-at-point ()
2447   ;; TODO: Make this get the nearest SRFI number in all cases.
2448   (save-match-data
2449     (let ((case-fold-search t))
2450       (cond ((thing-at-point-looking-at quack-srfi-num-at-point-re-1)
2451              (string-to-number (quack-match-string-no-properties 1)))
2452             ((thing-at-point-looking-at "[0-9]+")
2453              (string-to-number (quack-match-string-no-properties 0)))
2454             ((thing-at-point-looking-at quack-srfi-num-at-point-re-2)
2455              (string-to-number (quack-match-string-no-properties 1)))
2456             ((let ((str (quack-line-at-point)))
2457                (when (string-match quack-srfi-num-at-point-re-1 str)
2458                  (string-to-number
2459                   (quack-match-string-no-properties 1 str)))))))))
2460
2461 (defun quack-view-srfi (num)
2462   (interactive (list (quack-srfi-num-prompt "View SRFI number")))
2463   (when num
2464     (unless (and (integerp num) (>= num 0))
2465       (error "Not a valid SRFI number: %S" num))
2466     (quack-browse-url (quack-srfi-num-url num))))
2467
2468 (defun quack-srfi-num-prompt (prompt)
2469   (let* ((completes (quack-srfi-completes))
2470          (default   (quack-srfi-num-at-point))
2471          (input     (quack-without-side-whitespace
2472                      (completing-read
2473                       (if default
2474                           (format "%s (default %d): " prompt default)
2475                         (concat prompt ": "))
2476                       completes)))
2477          v)
2478     (cond ((or (not input) (string= "" input)) default)
2479           ((setq v (assoc input completes))      (cdr v))
2480           ((and (setq v (condition-case nil
2481                             (string-to-number input)
2482                           (error nil)))
2483                 (integerp v)
2484                 (>= v 0))
2485            v)
2486           (t (error "Invalid SRFI number: %s" input)))))
2487
2488 ;; Doc Keyword Value Object:
2489
2490 (defmacro quack-kw-get-syntax   (o) `(aref ,o 0))
2491 (defmacro quack-kw-get-file     (o) `(aref ,o 1))
2492 (defmacro quack-kw-get-fragment (o) `(aref ,o 2))
2493
2494 (defmacro quack-kw-set-syntax   (o v) `(aset ,o 0 ,v))
2495 (defmacro quack-kw-set-file     (o v) `(aset ,o 1 ,v))
2496 (defmacro quack-kw-set-fragment (o v) `(aset ,o 2 ,v))
2497
2498 ;; Documentation Object:
2499
2500 ;; TODO: Rework these document representations once we know the different kinds
2501 ;;       of documents with which we'll be dealing.
2502
2503 (defmacro quack-doc-get-type         (o) `(aref ,o 0))
2504 (defmacro quack-doc-get-sym          (o) `(aref ,o 1))
2505 (defmacro quack-doc-get-title        (o) `(aref ,o 2))
2506 (defmacro quack-doc-get-loc          (o) `(aref ,o 3))
2507 (defmacro quack-doc-get-kw-p         (o) `(aref ,o 4))
2508 (defmacro quack-doc-get-start-url    (o) `(aref ,o 5))
2509 (defmacro quack-doc-get-kw-base-url  (o) `(aref ,o 6))
2510 (defmacro quack-doc-get-kw-file      (o) `(aref ,o 7))
2511 (defmacro quack-doc-get-kw-hashtable (o) `(aref ,o 8))
2512
2513 (defmacro quack-doc-set-type         (o v) `(aset ,o 0 ,v))
2514 (defmacro quack-doc-set-sym          (o v) `(aset ,o 1 ,v))
2515 (defmacro quack-doc-set-title        (o v) `(aset ,o 2 ,v))
2516 (defmacro quack-doc-set-loc          (o v) `(aset ,o 3 ,v))
2517 (defmacro quack-doc-set-kw-p         (o v) `(aset ,o 4 ,v))
2518 (defmacro quack-doc-set-start-url    (o v) `(aset ,o 5 ,v))
2519 (defmacro quack-doc-set-kw-base-url  (o v) `(aset ,o 6 ,v))
2520 (defmacro quack-doc-set-kw-file      (o v) `(aset ,o 7 ,v))
2521 (defmacro quack-doc-set-kw-hashtable (o v) `(aset ,o 8 ,v))
2522
2523 (defun quack-manual-to-doc (manual)
2524   ;; Accepts a user's manual preference object of the list form:
2525   ;;
2526   ;;     (SYM TITLE LOC KW-P)
2527   ;;
2528   ;; and creates a manual doc object of the vector form:
2529   ;;
2530   ;;     [manual SYM TITLE LOC KW-P START-URL KW-BASE-URL KW-FILE KW-P
2531   ;;      KEYWORDS]
2532   ;;
2533   ;; KEYWORDS is not populated here -- keywords importing for a manual happens
2534   ;; the first time keyword searching is done for the manual."
2535   (let ((sym       (nth 0 manual))
2536         (title     (nth 1 manual))
2537         (loc       (nth 2 manual))
2538         (kw-p      (nth 3 manual))
2539         (start-url nil)
2540         (kw-file   nil)
2541         (kw-base   nil))
2542     (cond
2543      ;; If the location is a string, then handle manual as simple URL.
2544      ((stringp loc)
2545       (setq start-url loc)
2546       (when kw-p
2547         (quack-warning "Quack can only use keywords for PLT manuals.")
2548         (setq kw-p nil)))
2549      ;; If the location is a symbol, handle manual as special.
2550      ((symbolp loc)
2551       (cond
2552        ;; If the location is symbol `plt', handle manual as PLT bundled.
2553        ((eq loc 'plt)
2554         (let* ((plt-name (let ((s (symbol-name sym)))
2555                            (if (string-match "\\`plt-\\(.+\\)\\'" s)
2556                                (match-string 1 s)
2557                              s)))
2558                (web-base   (concat
2559                            "http://download.plt-scheme.org/doc/"
2560                            plt-name
2561                            "/"))
2562               (index-name "index.htm")
2563               (col-dirs   quack-pltcollect-dirs))
2564           ;; Search from the collection directories for keywords and index
2565           ;; files.  Note that we currently look for keywords files even if
2566           ;; `kw-p' is false since we want to allow the user to dynamically
2567           ;; enable and disable keywords searching for a particular manual
2568           ;; without us having to change `quack-docs'.
2569           (while (and col-dirs (not (and kw-file kw-base start-url)))
2570             (let ((dir (expand-file-name plt-name
2571                                          (expand-file-name "doc"
2572                                                            (car col-dirs)))))
2573               (setq col-dirs (cdr col-dirs))
2574               (when (file-directory-p dir)
2575                 (let* ((k-f (expand-file-name "keywords" dir))
2576                        (i-f (expand-file-name index-name dir))
2577                        (i-r (file-readable-p i-f)))
2578                   (if (file-readable-p k-f)
2579                       ;; Keywords file.
2580                       (if i-r
2581                           ;; Keywords file and index file.  So, unless we
2582                           ;; already found a keywords base URL, set everything
2583                           ;; based on this directory.  Note that we override
2584                           ;; any existing start URL because we prefer to use
2585                           ;; the same manual version for both keywords and
2586                           ;; non-keywords access.
2587                           (unless kw-base
2588                             (setq kw-file   k-f)
2589                             (setq kw-base   (quack-file-url dir nil))
2590                             (setq start-url (quack-file-url dir index-name)))
2591                         ;; Keywords file, but no index file.  So, unless we
2592                         ;; already have a keywords file, set it to this one.
2593                         (unless kw-file
2594                           (setq kw-file k-f)))
2595                     ;; No keywords file.  So, if there is an index file, and we
2596                     ;; don't already have one, then use this one.
2597                     (when (and i-r (not start-url))
2598                       (setq start-url (quack-file-url dir index-name))))))))
2599           ;; If we didn't find a start URL, use the Web one.
2600           (unless start-url
2601             (setq start-url (concat web-base index-name)))
2602           ;; Do we have a keywords file?
2603           (if kw-file
2604               ;; We have a keywords file, so set the keywords base to the Web
2605               ;; if needed and desired.  Note that we never use the keywords
2606               ;; file from one directory with the HTML files from a different
2607               ;; directory, on the assumption that a local copy of HTML missing
2608               ;; a keywords file is suspect, and that the Web version is
2609               ;; therefore preferable.
2610               (when (or (eq quack-local-keywords-for-remote-manuals-p 'always)
2611                         (and (not kw-base)
2612                              quack-local-keywords-for-remote-manuals-p))
2613                 (setq kw-base web-base))
2614             ;; We don't have a keywords file, so warn if the user wanted
2615             ;; keywords for this manual.
2616             (when kw-p
2617               (quack-warning "Could not find keywords file for manual %S."
2618                              plt-name)))))
2619        ;; The location is an unrecognized symbol, so just barf.
2620        (t (quack-internal-error))))
2621      ;; The location is something other than a string or symbol, so just barf.
2622      (t (quack-internal-error)))
2623     ;; We've populated all the variables for the location type, so return the
2624     ;; representation.
2625     (vector 'manual sym title loc kw-p start-url kw-base kw-file nil)))
2626
2627 (defun quack-doc-keyword-lookup (doc keyword)
2628   (let ((ht (or (quack-doc-get-kw-hashtable doc)
2629                 (progn (quack-doc-import-keywords doc)
2630                        (quack-doc-get-kw-hashtable doc)))))
2631     (if ht
2632         (quack-gethash keyword ht nil)
2633       (quack-warning "No keywords for document \"%S\"."
2634                      (quack-doc-get-sym doc))
2635       nil)))
2636
2637 (defun quack-doc-import-keywords (doc)
2638   (if (eq (quack-doc-get-loc doc) 'plt)
2639       (quack-doc-import-plt-manual-keywords doc)
2640     (quack-internal-error)))
2641
2642 (defun quack-doc-import-plt-manual-keywords (doc)
2643   ;; Reads in the predetermined keywords file for PLT manual `doc' object,
2644   ;; populating the `kw-hashtable' field of the `doc' object.  The format of
2645   ;; each entry in the PLT keywords file is a list of 5 strings:
2646   ;;
2647   ;;     (KEYWORD SYNTAX FILE FRAGMENT SECTION)
2648   ;;
2649   ;; The hashtable is keyed on the KEYWORD string, for which the value is
2650   ;; usually a vector:
2651   ;;
2652   ;;     [SYNTAX FILE-CONST FRAGMENT]
2653   ;;
2654   ;; where FILE-CONST is the FILE string registered with the `quack-strconst'
2655   ;; to save memory on redundant strings.
2656   ;;
2657   ;; When more there is more than one entry for a given keyword, then the value
2658   ;; of the hashtable entry for that keyword is a list of vectors, in the order
2659   ;; in which they were derived from the original keywords file.
2660   ;;
2661   ;; These duplicate values may be duplicated or conflicting, as in:
2662   ;;
2663   ;;     (["(regexp-match pattern input-port [start-k end-k output-port])"
2664   ;;       "mzscheme-Z-H-10.html" "%_kw_definitionregexp-match"]
2665   ;;      ["(regexp-match pattern string [start-k end-k output-port])"
2666   ;;       "mzscheme-Z-H-10.html" "%_kw_definitionregexp-match"])
2667   ;;
2668   ;; No attempt is made here to weed out any duplicate/conflicting entries --
2669   ;; that behavior left up to the code that accesses the hashtable.  For the
2670   ;; example above, a command to display the syntax for the keyword would need
2671   ;; to display both values.  However, a command to view the documentation for
2672   ;; the keyword would need only to display one Web page without querying the
2673   ;; user, since both entries above point to the same page and fragment.
2674   (quack-activity
2675    (format "Importing keywords for manual %S" (quack-doc-get-sym doc))
2676    (let (sexp)
2677      (garbage-collect)
2678      (condition-case err
2679          (setq sexp (quack-read-sexp-file
2680                      (or (quack-doc-get-kw-file doc)
2681                          (quack-warning "Manual %S has no keywords file."
2682                                         (quack-doc-get-sym doc)))))
2683        (error (quack-warning "Problem importing keywords for manual %S: %s"
2684                              (quack-doc-get-sym doc) err)))
2685      (when sexp
2686        (garbage-collect)
2687        (let ((ht (quack-make-hash-table :test             'equal
2688                                         :size             (length sexp)
2689                                         :rehash-threshold 1.0)))
2690          ;; Note: We make the hashtable equal to the length of the read list of
2691          ;; keyword forms so that it will be at least large enough for all the
2692          ;; keywords without being excessively overlarge, and without having to
2693          ;; do resizes or a counting pass or intermediate representation.  The
2694          ;; hashtable will be a little larger than necessary when there are
2695          ;; multiple keyword forms for the same keyword.  In a test with
2696          ;; MzScheme 200.2, the hashtable used/size for "mzscheme" manual was
2697          ;; 489/502; for "mzlib", 245/257.
2698          (quack-doc-set-kw-hashtable doc ht)
2699          (mapcar (function
2700                   (lambda (raw-entry)
2701                     (let* ((kw  (nth 0 raw-entry))
2702                            (new (vector (nth 1 raw-entry)
2703                                         (quack-strconst (nth 2 raw-entry))
2704                                         (nth 3 raw-entry)))
2705                            (old (quack-gethash kw ht nil)))
2706                       (quack-puthash
2707                        kw
2708                        (cond ((not     old) new)
2709                              ((vectorp old) (list  old new))
2710                              ((listp   old) (nconc old (list new))))
2711                        ht))))
2712                  sexp))))))
2713
2714 (defun quack-read-sexp-file (filename)
2715   (save-excursion
2716     (let* ((buf (generate-new-buffer "*quack-read-sexp-file*")))
2717       (set-buffer buf)
2718       (unwind-protect
2719           (progn (insert-file-contents-literally filename)
2720                  (goto-char (point-min))
2721                  (read buf))
2722         ;; unwind-protect cleanup
2723         (kill-buffer buf)))))
2724
2725 ;; Documentation Database:
2726
2727 (defvar quack-docs 'invalid)
2728
2729 (defun quack-docs ()
2730   (when (eq quack-docs 'invalid)
2731     (quack-docs-build))
2732   quack-docs)
2733
2734 (defun quack-docs-build ()
2735   (quack-activity
2736    "Building Quack docs database"
2737    (quack-invalidate-manuals-caches)
2738    (setq quack-docs (mapcar 'quack-manual-to-doc quack-manuals))))
2739
2740 (defun quack-docs-manual-lookup (sym)
2741   (let ((docs  (quack-docs))
2742         (found nil))
2743     (while (and docs (not found))
2744       (let ((doc (car docs)))
2745         (setq docs (cdr docs))
2746         (when (eq (quack-doc-get-sym doc) sym)
2747           (setq found doc))))
2748     found))
2749
2750 (defun quack-docs-manual-keyword-lookup (keyword)
2751   (let ((results '()))
2752     (mapcar (function
2753              (lambda (doc)
2754                (cond
2755                 ((not (quack-doc-get-kw-p doc)) nil)
2756                 ((not (quack-doc-get-kw-base-url doc))
2757                  (quack-warning "Manual %S has no HTML."
2758                                 (quack-doc-get-sym doc)))
2759                 (t (let ((match (quack-doc-keyword-lookup doc keyword)))
2760                      (cond
2761                       ((not match) nil)
2762                       ((vectorp match)
2763                        (setq results (cons (cons doc match) results)))
2764                       ((listp match)
2765                        (mapcar (function
2766                                 (lambda (m)
2767                                   (setq results (cons (cons doc m) results))))
2768                                match))
2769                       (t (quack-internal-error))))))))
2770             (quack-docs))
2771     (reverse results)))
2772
2773 ;; Keyword Lookup Match Object:
2774
2775 (defmacro quack-kwmatch-get-doc (o) `(car ,o))
2776 (defmacro quack-kwmatch-get-kw  (o) `(cdr ,o))
2777
2778 (defun quack-kwmatch-url (kwmatch)
2779   (let ((doc (car kwmatch))
2780         (kw  (cdr kwmatch)))
2781     (concat (quack-doc-get-kw-base-url doc)
2782             (quack-quote-url-substring (quack-kw-get-file kw))
2783             "#"
2784             (quack-quote-url-substring (quack-kw-get-fragment kw) t))))
2785
2786 ;; Manual Viewing:
2787
2788 (defun quack-view-manual (&optional sym)
2789   "View a manual."
2790   (interactive
2791    (list
2792     (let* ((completes (or (quack-manuals-completes)
2793                           (error
2794                            "Sorry, variable \"quack-manuals\" is empty.")))
2795            (default   "R5RS")
2796            (input     (let ((completion-ignore-case t))
2797                         (completing-read
2798                          (format "Quack Manual (default %S): " default)
2799                          completes nil t nil nil default))))
2800       (cdr (or (assoc input completes)
2801                (error "No manual %S." input))))))
2802   (quack-activity
2803    (format "Viewing manual \"%S\"" sym)
2804    (quack-browse-url (or (quack-doc-get-start-url
2805                           (or (quack-docs-manual-lookup sym)
2806                               (error "Manual \"%S\" not found." sym)))
2807                          (error "Don't know a URL for manual \"%S\"." sym)))))
2808
2809 (defvar quack-manuals-menu-cache      'invalid)
2810 (defvar quack-manuals-completes-cache 'invalid)
2811
2812 (defun quack-invalidate-manuals-caches ()
2813   (setq quack-docs                    'invalid)
2814   (setq quack-manuals-completes-cache 'invalid)
2815   (setq quack-manuals-menu-cache      'invalid))
2816
2817 ;;(quack-invalidate-manuals-caches)
2818
2819 ;; This version maps completion strings to URLs.
2820 ;; (defun quack-manuals-completes ()
2821 ;;   (when (eq quack-manuals-completes-cache 'invalid)
2822 ;;     (let ((completes '()))
2823 ;;       (mapcar (function
2824 ;;                (lambda (doc)
2825 ;;                  (let ((sym (quack-doc-get-sym doc))
2826 ;;                        (url (quack-doc-get-start-url doc)))
2827 ;;                    (setq completes
2828 ;;                          (cons (cons (quack-doc-get-title doc) url)
2829 ;;                                (cons (cons (symbol-name sym) url)
2830 ;;                                      completes))))))
2831 ;;               (quack-docs))
2832 ;;       (setq quack-manuals-completes-cache (reverse completes))))
2833 ;;   quack-manuals-completes-cache)
2834
2835 (defun quack-manuals-completes ()
2836   (when (eq quack-manuals-completes-cache 'invalid)
2837     (let ((completes '()))
2838       (mapcar (function
2839                (lambda (doc)
2840                  (let ((sym (quack-doc-get-sym doc))
2841                        ;;(url (quack-doc-get-start-url doc))
2842                        )
2843                    (setq completes
2844                          (cons (cons (quack-doc-get-title doc) sym)
2845                                ;;(cons (cons (symbol-name sym) sym)
2846                                      completes
2847                                      ;;)
2848                                      )))))
2849               (quack-docs))
2850       (setq quack-manuals-completes-cache (reverse completes))))
2851   quack-manuals-completes-cache)
2852
2853 (defun quack-manuals-menu ()
2854   (when (eq quack-manuals-menu-cache 'invalid)
2855     (setq quack-manuals-menu-cache
2856           (mapcar (function
2857                    (lambda (manual)
2858                      (let ((sym   (nth 0 manual))
2859                            (title (nth 1 manual)))
2860                        `[,title (quack-view-manual (quote ,sym))])))
2861                   quack-manuals)))
2862   quack-manuals-menu-cache)
2863
2864 (defun quack-manuals-webjump-sites ()
2865   "Returns `webjump' entries for manuals in `quack-manuals'.
2866
2867 Can be used in your `~/.emacs' file something like this:
2868
2869     (require 'quack)
2870     (require 'webjump)
2871     (require 'webjump-plus)
2872     (setq webjump-sites
2873           (append my-own-manually-maintained-webjump-sites
2874                   (quack-manuals-webjump-sites)
2875                   webjump-plus-sites
2876                   webjump-sample-sites))"
2877   ;; TODO: Note what they should do if they are adding to plt collectsion dirs
2878   ;;       via custom settings but quack-manuals-webjump-sites is getting
2879   ;;       called before then.
2880   (let ((result                 '())
2881         (quack-quiet-warnings-p t))
2882     (mapcar (function
2883              (lambda (doc)
2884                (let ((url (quack-doc-get-start-url doc)))
2885                  (when url
2886                    (setq result (cons (cons (quack-doc-get-title doc) url)
2887                                       result))))))
2888             (quack-docs))
2889     result))
2890
2891 ;; Keyword Docs Viewing:
2892
2893 ;; TODO: Add doc lookup in PLT "doc.txt" files.  A little tricky.  Maybe make
2894 ;;       sure doc.txt is a long-term format first.
2895
2896 (defun quack-view-keyword-docs (keyword)
2897   ;; TODO: Don't prompt if all choices would result in the same URL.
2898   (interactive (list (quack-prompt-for-keyword "View docs for keyword")))
2899   (when (and keyword (stringp keyword) (not (string= keyword "")))
2900     (let ((matches (quack-docs-manual-keyword-lookup keyword)))
2901       (if (not matches)
2902           (message "Sorry, no documentation found for keyword %S." keyword)
2903         (quack-browse-url
2904          (quack-kwmatch-url
2905           (if (cdr matches)
2906               (quack-prompt-for-kwmatch-choice "Which" matches)
2907             (car matches))))))))
2908
2909 (defun quack-keyword-at-point ()
2910   ;; TODO: Make sure this reads all Scheme symbols -- it may currently only
2911   ;;       read valid Elisp symbols.
2912   (let ((bounds (bounds-of-thing-at-point 'symbol)))
2913     ;; In some cases (point at beginning of empty buffer?), `bounds' will be
2914     ;; the bounds of an empty string, so check this.
2915     (when bounds
2916       (let ((beg (car bounds))
2917             (end (cdr bounds)))
2918         (when (/= beg end)
2919           (buffer-substring-no-properties beg end))))))
2920
2921 (defun quack-prompt-for-keyword (prompt)
2922   (let* ((default (quack-keyword-at-point))
2923          (history (list default)))
2924     (read-string (if default
2925                      (format "%s (default %S): " prompt default)
2926                    (concat prompt ": "))
2927                  nil
2928                  ;; Note: Gratuitous reference to `history' eliminates warning
2929                  ;;       from XEmacs 21 byte-compiler.
2930                  (if (and default history) 'history nil)
2931                  default)))
2932
2933 (defun quack-prompt-for-kwmatch-choice (prompt kwmatch-list)
2934   (let ((completes '()))
2935     ;; Build the completion alist, ensure each key is unique.
2936     (mapcar
2937      (function
2938       (lambda (kwmatch)
2939         (let* ((kw         (quack-kwmatch-get-kw kwmatch))
2940                (orig-name  (or (quack-kw-get-syntax kw)
2941                                (progn (quack-warning "No keyword syntax: %s"
2942                                                      kw)
2943                                       "???")))
2944                (name       orig-name)
2945                (name-tries 1))
2946           ;; Ensure the name is unique within the completion list thus far.
2947           (while (assoc name completes)
2948             (setq name-tries (1+ name-tries))
2949             (setq name (format "%s #%d" orig-name name-tries)))
2950           ;; Prepend to the completion list (we'll reverse the list later).
2951           (setq completes (cons (cons name kwmatch) completes)))))
2952      kwmatch-list)
2953     (setq completes (reverse completes))
2954     ;; Prompt user and return selection.
2955     (let* ((default (car (car completes)))
2956            (read    (let ((completion-ignore-case t))
2957                       (completing-read
2958                        (format "%s (default %S): " prompt default)
2959                        completes nil t nil nil default))))
2960       (cdr (assoc read completes)))))
2961
2962 ;; Inferior Process:
2963
2964 (defvar quack-run-scheme-prompt-history '())
2965
2966 (defun quack-remember-program-maybe (program)
2967   (when (and quack-remember-new-programs-p
2968              (not (member program quack-programs)))
2969     (quack-option-set 'quack-programs (cons program quack-programs) t)
2970     (message "Remembering program %S." program)))
2971
2972 (defun quack-run-scheme-prompt ()
2973   (let* ((last    (car quack-run-scheme-prompt-history))
2974          (default (or (and quack-run-scheme-prompt-defaults-to-last-p
2975                            last)
2976                       quack-default-program
2977                       scheme-program-name
2978                       last
2979                       "mzscheme"))
2980          (program (let ((minibuffer-allow-text-properties nil))
2981                     (completing-read
2982                      (concat "Run Scheme"
2983                              (if default
2984                                  (format " (default %S)" default)
2985                                "")
2986                              ": ")
2987                      (quack-run-scheme-prompt-completion-collection)
2988                      nil nil nil
2989                      'quack-run-scheme-prompt-history
2990                      default))))
2991     (quack-remember-program-maybe program)
2992     program))
2993
2994 (defun quack-run-scheme-prompt-completion-collection ()
2995   (let ((program-list quack-programs))
2996     (mapcar (function (lambda (program)
2997                         (and program
2998                              (not (member program program-list))
2999                              (setq program-list (cons program program-list)))))
3000             (list quack-default-program
3001                   scheme-program-name))
3002     (mapcar (function (lambda (program) (cons program nil)))
3003             program-list)))
3004
3005 (defadvice run-scheme (around quack-ad-run first nil activate)
3006   "Adds prompting for which Scheme interpreter program to run."
3007   ;; We don't want to prompt if there's already a Scheme running, but it's
3008   ;; possible for process to die between the comint check in `interactive' form
3009   ;; of this advice and the comint check in the `run-scheme' function.  We
3010   ;; should override `run-scheme' altogether, but for now let's only call the
3011   ;; original in the case that we do not detect a running Scheme.
3012   (interactive (list (cond ((comint-check-proc "*scheme*") nil)
3013                            ((or current-prefix-arg
3014                                 quack-run-scheme-always-prompts-p)
3015                             (quack-run-scheme-prompt))
3016                            (t quack-default-program))))
3017   (if cmd
3018       ;; We will assume there is no running Scheme, so...  Since `run-scheme'
3019       ;; calls `pop-to-buffer' rather than `switch-to-scheme', our options for
3020       ;; Scheme process window management, such as putting the process buffer
3021       ;; window in its own frame, do not take effect when the process buffer is
3022       ;; displayed by `run-scheme'.  So, unless we are using the `cmuscheme'
3023       ;; window management behavior, we attempt to undo whatever window changes
3024       ;; and buffer changes `run-scheme' makes, then just call
3025       ;; `switch-to-scheme'.  (This code will be revisited once we decide how
3026       ;; to handle multiple Schemes, if not before then.)
3027       (let ((buf (current-buffer))
3028             (wg  (current-window-configuration)))
3029         ad-do-it
3030         (unless (or (not quack-switch-to-scheme-method)
3031                     (eq quack-switch-to-scheme-method 'cmuscheme))
3032           (set-window-configuration wg)
3033           (set-buffer buf)
3034           (switch-to-scheme t))
3035         (message "Started Scheme: %s" scheme-program-name))
3036     ;; There is a running Scheme, so don't call the `run-scheme' function at
3037     ;; all -- just call `switch-to-scheme' or duplicate the `cmuscheme'
3038     ;; package's `pop-to-buffer' behavior.
3039     (if (or (not quack-switch-to-scheme-method)
3040             (eq quack-switch-to-scheme-method 'cmuscheme))
3041         (pop-to-buffer "*scheme*")
3042       (switch-to-scheme t))
3043     (message "Switched to running Scheme: %s" scheme-program-name)))
3044
3045 (defadvice scheme-interactively-start-process (around
3046                                                quack-ad-sisp 
3047                                                first
3048                                                (&optional cmd)
3049                                                activate)
3050   ;; (save-window-excursion
3051   (call-interactively 'run-scheme)
3052   ;; )
3053   )
3054
3055 (defadvice scheme-proc (around quack-ad-scheme-proc first nil activate)
3056   (condition-case nil
3057       ad-do-it
3058     (error (message "Oops, we must start a Scheme process!")
3059            (call-interactively 'run-scheme)
3060            (setq ad-return-value (scheme-proc)))))
3061
3062 ;; Switch-to-Scheme:
3063
3064 (defun quack-force-frame-switch-to-window (win)
3065   (let ((frame (window-frame win)))
3066     (unless (eq frame (selected-frame))
3067       (and window-system
3068            quack-warp-pointer-to-frame-p
3069            (set-mouse-position frame 0 0))
3070       (select-frame frame))
3071     (select-window win)))
3072
3073 (defadvice switch-to-scheme (before quack-ad-switch last nil activate)
3074   "Adds support for the `quack-switch-to-scheme-method' option."
3075   ;; This can be done as before-advice since the `pop-to-buffer' that
3076   ;; `switch-to-scheme' is using appears to always be a no-op when the target
3077   ;; buffer is already the current buffer.
3078   (require 'cmuscheme)
3079   ;; The `eval' below is to avoid problems with the byte-compiler and advising.
3080   ;; It doesn't seem to like: (and (boundp 'SYM) SYM)
3081   (let ((repl-buf (eval '(and (boundp 'scheme-buffer)
3082                               scheme-buffer
3083                               (get-buffer scheme-buffer)))))
3084     (cond ((not repl-buf)
3085            (error (concat "No process current buffer."
3086                           " Set `scheme-buffer' or execute `run-scheme'")))
3087
3088           ((or (not quack-switch-to-scheme-method)
3089                (eq quack-switch-to-scheme-method 'cmuscheme))
3090            nil)
3091
3092           ((eq (current-buffer) repl-buf) nil)
3093
3094           ((eq quack-switch-to-scheme-method 'other-window)
3095            (switch-to-buffer-other-window repl-buf))
3096
3097           ;; The following code may be revived if anyone reports problems with
3098           ;; the use of `special-display-popup-frame'.
3099           ;;
3100           ;; ((eq quack-switch-to-scheme-method 'own-frame)
3101           ;;  (let ((pop-up-frames                t)
3102           ;;        (same-window-buffer-names     nil)
3103           ;;        (same-window-regexps          nil)
3104           ;;        (special-display-buffer-names nil)
3105           ;;        (special-display-regexps      nil))
3106           ;;    (switch-to-buffer (pop-to-buffer repl-buf))))
3107
3108           ((eq quack-switch-to-scheme-method 'own-frame)
3109            (quack-force-frame-switch-to-window
3110             (special-display-popup-frame repl-buf)))
3111
3112           (t (error "Invalid quack-switch-to-scheme-method: %S"
3113                     quack-switch-to-scheme-method)))))
3114
3115 ;; Customize:
3116
3117 (defun quack-customize ()
3118   "Customize the Quack package."
3119   (interactive)
3120   (customize-group 'quack))
3121
3122 ;; Auto Modes:
3123
3124 (defun quack-add-auto-mode-alist (alist)
3125   (setq auto-mode-alist
3126         (append alist
3127                 (let ((retained '()))
3128                   (mapcar (function (lambda (pair)
3129                                       (unless (assoc (car pair) alist)
3130                                         (setq retained (cons pair retained)))))
3131                           auto-mode-alist)
3132                   (reverse retained)))))
3133
3134 (quack-add-auto-mode-alist '(("\\.ccl\\'"    . scheme-mode)
3135                              ("\\.rkt\\'"    . scheme-mode)
3136                              ("\\.rktd\\'"   . scheme-mode)
3137                              ("\\.sch\\'"    . scheme-mode)
3138                              ("\\.scm\\'"    . scheme-mode)
3139                              ("\\.ss\\'"     . scheme-mode)
3140                              ("\\.stk\\'"    . scheme-mode)
3141                              ("\\.stklos\\'" . scheme-mode)
3142                              ;;
3143                              ("/\\.mzschemerc\\'" . scheme-mode)
3144                              ;; Non-Scheme:
3145                              ("\\.plt\\'"    . quack-pltfile-mode)))
3146
3147 ;; Syntax Table:
3148
3149 (defmacro quack-str-syntax (str)
3150   `(,(if (and quack-gnuemacs-p (>= emacs-major-version 21))
3151          'string-to-syntax
3152        'quack-kludged-string-to-syntax)
3153     ,str))
3154
3155 (defun quack-kludged-string-to-syntax (str)
3156   (let* ((str-len (length str))
3157          (code    (aref str 0))
3158          (matches (if (> str-len 1) (aref str 1)))
3159          (result  (cond ((= code 32) 0)
3160                         ((= code ?_) 3)
3161                         (t (quack-internal-error))))
3162          (i       2))
3163     (while (< i str-len)
3164       (let ((c (aref str i)))
3165         (setq i (1+ i))
3166         (setq result (logior result
3167                              (lsh 1 (cond ((= c ?1) 16)
3168                                           ((= c ?2) 17)
3169                                           ((= c ?3) 18)
3170                                           ((= c ?4) 19)
3171                                           ((= c ?p) 20)
3172                                           ((= c ?b) 21)
3173                                           ((= c ?n) 21)
3174                                           (t (quack-internal-error))))))))
3175     (cons result (if (= matches 32) nil matches))))
3176
3177 ;; Note: We are assuming that it is better to endeavor to fontify all "#|"
3178 ;;       block comments as nestable rather than as unnestable, regardless of
3179 ;;       whether or not a user's target Scheme dialect supports nested.
3180
3181 (defconst quack-pound-syntax-string (if quack-gnuemacs-p "_ p14bn" "_ p14b"))
3182 ;; (defconst quack-bar-syntax-string   (if quack-gnuemacs-p "  23bn"  "  23b"))
3183 (defconst quack-bar-syntax-string   (if quack-gnuemacs-p "_ 23bn"  "_ 23b"))
3184
3185 (defconst quack-pound-syntax (quack-str-syntax quack-pound-syntax-string))
3186 (defconst quack-bar-syntax   (quack-str-syntax quack-bar-syntax-string))
3187
3188 (modify-syntax-entry ?# quack-pound-syntax-string scheme-mode-syntax-table)
3189 (modify-syntax-entry ?| quack-bar-syntax-string   scheme-mode-syntax-table)
3190
3191 ;; Note: Unclear why, but `scheme.el' in GNU Emacs 21.2 is doing
3192 ;;       `(set-syntax-table scheme-mode-syntax-table)' in whatever buffer is
3193 ;;       active at the time the Elisp package is loaded.
3194
3195 ;; Indent Properties:
3196
3197 (put 'begin0             'scheme-indent-function 1)
3198 (put 'c-declare          'scheme-indent-function 0)
3199 (put 'c-lambda           'scheme-indent-function 2)
3200 (put 'case-lambda        'scheme-indent-function 0)
3201 (put 'catch              'scheme-indent-function 1)
3202 (put 'chicken-setup      'scheme-indent-function 1)
3203 (put 'class              'scheme-indent-function 'defun)
3204 (put 'class*             'scheme-indent-function 'defun)
3205 (put 'compound-unit/sig  'scheme-indent-function 0)
3206 (put 'define:            'scheme-indent-function 3)
3207 (put 'dynamic-wind       'scheme-indent-function 0)
3208 (put 'for/fold           'scheme-indent-function 2)
3209 (put 'instantiate        'scheme-indent-function 2)
3210 (put 'interface          'scheme-indent-function 1)
3211 (put 'lambda/kw          'scheme-indent-function 1)
3212 (put 'let*-values        'scheme-indent-function 1)
3213 (put 'let*:              'scheme-indent-function 'quack-let-colon-indent)
3214 (put 'let+               'scheme-indent-function 1)
3215 (put 'let-values         'scheme-indent-function 1)
3216 (put 'let/ec             'scheme-indent-function 1)
3217 (put 'let:               'scheme-indent-function 'quack-let-colon-indent)
3218 (put 'match              'scheme-indent-function 1)
3219 (put 'mixin              'scheme-indent-function 2)
3220 (put 'module             'scheme-indent-function 'defun)
3221 (put 'module             'scheme-indent-function 2)
3222 (put 'module*            'scheme-indent-function 2)
3223 (put 'module+            'scheme-indent-function 1)
3224 (put 'opt-lambda         'scheme-indent-function 1)
3225 (put 'parameterize       'scheme-indent-function 1)
3226 (put 'parameterize*      'scheme-indent-function 1)
3227 (put 'parameterize-break 'scheme-indent-function 1)
3228 (put 'quasisyntax/loc    'scheme-indent-function 1)
3229 (put 'receive            'scheme-indent-function 2)
3230 (put 'send*              'scheme-indent-function 1)
3231 (put 'sigaction          'scheme-indent-function 1)
3232 (put 'struct             'scheme-indent-function 1)
3233 (put 'sxml-match         'scheme-indent-function 1)
3234 (put 'syntax-case        'scheme-indent-function 2)
3235 (put 'syntax-parse       'scheme-indent-function 1)
3236 (put 'syntax/loc         'scheme-indent-function 1)
3237 (put 'unit               'scheme-indent-function 'defun)
3238 (put 'unit/sig           'scheme-indent-function 2)
3239 (put 'unless             'scheme-indent-function 1)
3240 (put 'when               'scheme-indent-function 1)
3241 (put 'while              'scheme-indent-function 1)
3242 (put 'with-handlers      'scheme-indent-function 1)
3243 (put 'with-method        'scheme-indent-function 1)
3244 (put 'with-syntax        'scheme-indent-function 1)
3245
3246 (defun quack-let-colon-indent (state indent-point normal-indent)
3247   ;; Note: This was adapted from "scheme.el" "scheme-let-indent".
3248   (skip-chars-forward " \t")
3249   (if (looking-at "[-a-zA-Z0-9+*/?!@$%^&_:~]")
3250       (lisp-indent-specform 4 state indent-point normal-indent)
3251     (lisp-indent-specform 1 state indent-point normal-indent)))
3252
3253 ;; Keymaps:
3254
3255 (defvar quack-scheme-mode-keymap nil)
3256
3257 (setq quack-scheme-mode-keymap (make-sparse-keymap))
3258
3259 ;; TODO: Maybe have an option to also map the Ctrl variants of each of these
3260 ;;       keys to their respective bindings.  As Eli pointed out, `C-c C-q C-x'
3261 ;;       is arguably easier to type than `C-c C-q x'.  Actually, though, I
3262 ;;       don't like the `C-c C-q' prefix at all -- it signifies everything that
3263 ;;       is wrong with traditional modifier-happy Emacs keybindings.  Maybe we
3264 ;;       should encourage users to set the prefix to some other key, like an
3265 ;;       unmodified function key.
3266
3267 (define-key quack-scheme-mode-keymap "f" 'quack-find-file)
3268 (define-key quack-scheme-mode-keymap "k" 'quack-view-keyword-docs)
3269 (define-key quack-scheme-mode-keymap "m" 'quack-view-manual)
3270 (define-key quack-scheme-mode-keymap "r" 'run-scheme)
3271 (define-key quack-scheme-mode-keymap "s" 'quack-view-srfi)
3272 (define-key quack-scheme-mode-keymap "l" 'quack-toggle-lambda)
3273 (define-key quack-scheme-mode-keymap "t" 'quack-tidy-buffer)
3274
3275 ;; Menus:
3276
3277 (defmacro quack-bool-menuitem (title var &rest rest)
3278   (unless (stringp title) (quack-internal-error))
3279   (unless (symbolp var)   (quack-internal-error))
3280   `[,title (quack-option-toggle (quote ,var)) :style toggle :selected ,var
3281            ,@rest])
3282
3283 (defmacro quack-radio-menuitems (var alist)
3284   (unless (symbolp var)   (quack-internal-error))
3285   (unless (listp   alist) (quack-internal-error))
3286   `(quote ,(mapcar
3287             (function (lambda (pair)
3288                         (let ((title (car pair))
3289                               (value (cdr pair)))
3290                           (unless (stringp title) (quack-internal-error))
3291                           (unless (symbolp value) (quack-internal-error))
3292                           `[,title
3293                             (quack-option-set (quote ,var) (quote ,value))
3294                             :style    radio
3295                             :selected (eq ,var (quote ,value))])))
3296             alist)))
3297
3298 (defconst quack-browser-radio-alist
3299   '((nil                                . "(Browse-URL Default)")
3300     (browse-url-galeon                  . "Galeon")
3301     (browse-url-mozilla                 . "Mozilla")
3302     (browse-url-kde                     . "KDE Konqueror")
3303     (browse-url-netscape                . "Netscape Navigator")
3304     (browse-url-w3                      . "Emacs W3")
3305     (w3m-browse-url                     . "W3M")
3306     (quack-w3m-browse-url-other-window  . "W3M (in other window)")
3307     (browse-url-lynx-xterm              . "Lynx in Xterm")
3308     (browse-url-lynx-emacs              . "Lynx in Emacs")
3309     (browse-url-default-windows-browser . "MS Windows Default")))
3310
3311 (defconst quack-global-menuspec
3312   `("Quack"
3313     ["About Quack..." quack-about]
3314     ("Options"
3315      ("Startup Options"
3316       "These settings take full effect"
3317       "once Emacs is restarted."
3318       "---"
3319       ,(quack-bool-menuitem "Put Quack on Global Menu Bar" quack-global-menu-p)
3320       ,(quack-bool-menuitem "Remap Find-File Bindings"
3321                             quack-remap-find-file-bindings-p)
3322       "---"
3323       ["Quack Directory..." (customize-option 'quack-dir)]
3324       ["Quack Scheme Mode Keymap Prefix..."
3325        (customize-option 'quack-scheme-mode-keymap-prefix)])
3326      "---"
3327      ("Default Program" :filter quack-defaultprogram-menufilter)
3328      ,(quack-bool-menuitem "Always Prompt for Program"
3329                            quack-run-scheme-always-prompts-p)
3330      ,(quack-bool-menuitem "Program Prompt Defaults to Last"
3331                            quack-run-scheme-prompt-defaults-to-last-p)
3332      ,(quack-bool-menuitem "Remember New Programs"
3333                            quack-remember-new-programs-p)
3334      "---"
3335      ("Newline Behavior"
3336       ,@(quack-radio-menuitems
3337          quack-newline-behavior
3338          (("Newline"               . newline)
3339           ("Newline-Indent"        . newline-indent)
3340           ("Indent-Newline-Indent" . indent-newline-indent))))
3341      ,(quack-bool-menuitem "Smart Open-Paren"
3342                            quack-smart-open-paren-p)
3343      ("Switch-to-Scheme Method"
3344       ,@(quack-radio-menuitems quack-switch-to-scheme-method
3345                                (("Other Window"       . other-window)
3346                                 ("Own Frame"          . own-frame)
3347                                 ("Cmuscheme Behavior" . cmuscheme)))
3348       "---"
3349       ,(quack-bool-menuitem
3350         "Warp Pointer to Frame"
3351         quack-warp-pointer-to-frame-p
3352         :active (eq quack-switch-to-scheme-method 'own-frame)))
3353      ("Fontification"
3354       ,@(quack-radio-menuitems quack-fontify-style
3355                                (("PLT Style"                . plt)
3356                                 ("Extended GNU Emacs Style" . emacs)
3357                                 ("Emacs Default"            . nil)))
3358       "---"
3359       ,(quack-bool-menuitem "Pretty Lambda \(in PLT Style\)"
3360                             quack-pretty-lambda-p
3361                             :active (and quack-pretty-lambda-supported-p
3362                                          (memq quack-fontify-style '(plt))))
3363       ,(quack-bool-menuitem "Fontify Definition Names \(in PLT Style\)"
3364                             quack-pltish-fontify-definition-names-p
3365                             :active (eq quack-fontify-style 'plt))
3366       ,(quack-bool-menuitem "Fontify Syntax Keywords \(in PLT Style\)"
3367                             quack-pltish-fontify-keywords-p
3368                             :active (eq quack-fontify-style 'plt))
3369       ;; TODO: Add menuitem here for "Fontify #: Keywords \(in PLT Style\)"
3370       ,(quack-bool-menuitem "Fontify 3-Semicolon Comments \(in PLT Style\)"
3371                             quack-fontify-threesemi-p
3372                             :active (memq quack-fontify-style '(plt)))
3373       )
3374      ("Web Browser"
3375       ,@(mapcar (function
3376                  (lambda (n)
3377                    (let ((func  (car n))
3378                          (title (cdr n)))
3379                      `[,title
3380                        (quack-option-set 'quack-browse-url-browser-function
3381                                          (quote ,func))
3382                        :style radio
3383                        :selected ,(if (not func)
3384                                       '(not quack-browse-url-browser-function)
3385                                     `(eq quack-browse-url-browser-function
3386                                          (quote ,func)))])))
3387                 quack-browser-radio-alist)
3388       ["(Other)..."
3389        (customize-option 'quack-browse-url-browser-function)
3390        :style    radio
3391        :selected (not (assq quack-browse-url-browser-function
3392                             quack-browser-radio-alist))])
3393      ,(quack-bool-menuitem "Tab Characters are Evil" quack-tabs-are-evil-p)
3394      ("Local Keywords for Remote Manuals"
3395       ,@(quack-radio-menuitems
3396          quack-local-keywords-for-remote-manuals-p
3397          (("Permit" . t)
3398           ("Forbid" . nil)
3399           ("Always" . always))))
3400      ["PLT Collection Directories..."
3401       (customize-option 'quack-pltcollect-dirs)]
3402      "---"
3403      ["Customize..." quack-customize])
3404     "---"
3405     ["Run Scheme"              run-scheme]
3406     ["Switch to Scheme Buffer" switch-to-scheme]
3407     "---"
3408     ("View Manual" :filter quack-view-manual-menufilter)
3409     ("View SRFI"   :filter quack-view-srfi-menufilter)
3410     ["View Keyword Docs..."       quack-view-keyword-docs]
3411     ["Dired on PLT Collection..." quack-dired-pltcollect]))
3412
3413 (defun quack-install-global-menu ()
3414   (when quack-global-menu-p
3415     (quack-when-gnuemacs
3416      (unless (assq 'Quack menu-bar-final-items)
3417        (setq menu-bar-final-items (cons 'Quack menu-bar-final-items)))
3418      (easy-menu-define quack-global-menu global-map ""
3419        quack-global-menuspec))
3420     (quack-when-xemacs
3421      ;; Die! Die! Die!
3422      ;;(mapcar (function (lambda (n)
3423      ;;(delete-menu-item '("Quack") n)
3424      ;;(add-submenu nil quack-global-menuspec "Help" n)))
3425      ;;(list 
3426      ;;;;current-menubar 
3427      ;;default-menubar
3428      ;;))
3429      (delete-menu-item '("Quack") current-menubar)
3430      (add-submenu nil quack-global-menuspec "Help" current-menubar)
3431      (set-menubar-dirty-flag))))
3432
3433 ;; TODO: We should make sure the user's custom settings have been loaded
3434 ;; before we do this.
3435 (quack-install-global-menu)
3436
3437 ;; And die some more!
3438 ;;(quack-when-xemacs (add-hook 'after-init-hook 'quack-install-global-menu))
3439
3440 (defconst quack-scheme-mode-menuspec
3441   `("Scheme"
3442     ("Quack Global" ,@(cdr quack-global-menuspec))
3443     "---"
3444     ["Toggle Lambda Syntax"          quack-toggle-lambda]
3445     ["Tidy Buffer Formatting"        quack-tidy-buffer]
3446     ["Comment-Out Region"            comment-region]
3447     ["Un-Comment-Out Region"         quack-uncomment-region]
3448     "---"
3449     ["Evaluate Last S-expression"    scheme-send-last-sexp]
3450     ["Evaluate Region"               scheme-send-region]
3451     ["Evaluate Region & Go"          scheme-send-region-and-go]
3452     ["Evaluate Last Definition"      scheme-send-definition]
3453     ["Evaluate Last Definition & Go" scheme-send-definition-and-go]
3454     ["Compile Definition"            scheme-compile-definition]
3455     ["Compile Definition & Go"       scheme-compile-definition-and-go]
3456     ["Load Scheme File"              scheme-load-file]
3457     ["Compile Scheme File"           scheme-compile-file]
3458     "---"
3459     ["View Keyword Docs..."          quack-view-keyword-docs]
3460     ["Quack Find File"               quack-find-file]))
3461
3462 (defvar quack-scheme-mode-menu)
3463 (quack-when-gnuemacs
3464  (let ((map (make-sparse-keymap)))
3465    (setq quack-scheme-mode-menu nil)
3466    (easy-menu-define quack-scheme-mode-menu map ""
3467      quack-scheme-mode-menuspec)
3468    (define-key scheme-mode-map [menu-bar scheme]
3469      (cons "Scheme"
3470            (or (lookup-key map [menu-bar Scheme])
3471                (lookup-key map [menu-bar scheme]))))))
3472
3473 (defun quack-view-manual-menufilter (arg)
3474   (quack-menufilter-return "quack-view-manual-menufilter-menu"
3475                            (quack-manuals-menu)))
3476
3477 (defun quack-view-srfi-menufilter (arg)
3478   (quack-menufilter-return
3479    "quack-view-srfi-menufilter-menu"
3480    (condition-case nil
3481        (quack-srfi-menu t)
3482      ;; TODO: Move the generation of this fallback menu down to
3483      ;;       quack-srfi-menu.
3484      (error '(["Update SRFI Index" quack-update-srfi-index]
3485               "---"
3486               ("Draft"     :active nil "")
3487               ("Final"     :active nil "")
3488               ("Withdrawn" :active nil "")
3489               ["Other SRFI..."     quack-view-srfi])))))
3490
3491 (defun quack-defaultprogram-menufilter (arg)
3492   (quack-menufilter-return
3493    "quack-defaultprogram-menufilter-menu"
3494    `(,@(quack-optionmenu-items-setdefaultprogram)
3495        "---"
3496        ["Other Program..." quack-set-other-default-program]
3497        "---"
3498        ("Forget Program"
3499         ,@(mapcar
3500            (function
3501             (lambda (program)
3502               `[,(format "Forget  %s" program)
3503                 (quack-forget-program ,program)]))
3504            quack-programs)))))
3505
3506 (defun quack-optionmenu-items-setdefaultprogram ()
3507   (let* ((programs      (quack-sort-string-list-copy quack-programs))
3508          (add-default-p (and quack-default-program
3509                              (not (member quack-default-program programs)))))
3510     (and add-default-p
3511          (setq programs (cons quack-default-program programs)))
3512     (mapcar
3513      (function
3514       (lambda (program)
3515         (let* ((selected-p (and quack-default-program
3516                                 (equal program quack-default-program))))
3517           `[,(format "%s%s"
3518                      program
3519                      (if (and add-default-p
3520                               (equal program quack-default-program))
3521                          " (temporary)"
3522                        ""))
3523             (quack-option-set 'quack-default-program ,program)
3524             :style radio :selected ,selected-p])))
3525      programs)))
3526
3527 (mapcar (function (lambda (sym) (put sym 'menu-enable 'mark-active)))
3528         '(comment-region
3529           indent-region
3530           quack-uncomment-region
3531           scheme-send-region
3532           scheme-send-region-and-go))
3533
3534 ;; Option Menu Callbacks:
3535
3536 (defun quack-set-other-default-program ()
3537   (interactive)
3538   (let* ((minibuffer-allow-text-properties nil)
3539          (program (quack-without-side-whitespace
3540                    (read-string "Other Default Program: "))))
3541     (if (string= program "")
3542         (message "Default program unchanged.")
3543       (quack-remember-program-maybe program)
3544       (quack-option-set 'quack-default-program
3545                         program))))
3546
3547 (defun quack-forget-program (program)
3548   (setq quack-programs (delete program quack-programs))
3549   (quack-option-set 'quack-programs quack-programs t)
3550   (message "Forgot program %S." program))
3551
3552 (defun quack-custom-set (sym value)
3553   ;; Clean up the value based on the variable symbol.
3554   (cond ((eq sym 'quack-programs)
3555          (setq value (quack-sort-string-list-copy value))))
3556
3557   ;; Set default binding.  Set local binding just for the halibut, although if
3558   ;; there are local bindings, then other things will likely break.  \(We used
3559   ;; to have a check here, but removed it while porting to XEmacs.\)
3560   (set         sym value)
3561   (set-default sym value)
3562
3563   ;; TODO: Probably don't do this during Emacs initialization time, to avoid
3564   ;;       unnecessary behavior like:
3565   ;;
3566   ;;           Loading ~/emacs/my-custom.el (source)...
3567   ;;           Updating Scheme Mode buffers...done
3568   ;;           Updating Scheme Mode buffers...done
3569   ;;           Updating Scheme Mode buffers...done
3570   ;;           Updating Scheme Mode buffers...done
3571   ;;           Updating Scheme Mode buffers...done
3572   ;;           Loading ~/emacs/my-custom.el (source)...done
3573   
3574   ;; Update dependent program state.
3575   (cond ((memq sym '(quack-emacsish-keywords-to-fontify
3576                      quack-fontify-style
3577                      quack-fontify-threesemi-p
3578                      quack-pltish-fontify-definition-names-p
3579                      quack-pltish-fontify-keywords-p
3580                      quack-pltish-keywords-to-fontify
3581                      quack-pretty-lambda-p))
3582          (quack-update-scheme-mode-buffers))
3583
3584         ((eq sym 'quack-local-keywords-for-remote-manuals-p)
3585          (quack-invalidate-manuals-caches))
3586
3587         ((eq sym 'quack-pltcollect-dirs)
3588          (quack-invalidate-pltcollects-caches))))
3589
3590 (defun quack-option-set (sym value &optional silently)
3591   (if quack-options-persist-p
3592       (customize-save-variable sym value)
3593     (quack-custom-set sym value))
3594   (or silently
3595       (message "Set %s%s to: %S"
3596                sym
3597                (if quack-options-persist-p "" " (non-persistently)")
3598                value)))
3599
3600 (defun quack-option-toggle (sym &optional silently)
3601   (quack-option-set sym (not (symbol-value sym)) t)
3602   (or silently
3603       (message "Set %s%s %s."
3604                sym
3605                (if quack-options-persist-p "" " (non-persistently)")
3606                (if (symbol-value sym) "ON" "OFF"))))
3607
3608 (defun quack-update-scheme-mode-buffers ()
3609   (save-excursion
3610     (quack-activity
3611      "Updating Scheme Mode buffers"
3612      (mapcar (function
3613               (lambda (buf)
3614                 (set-buffer buf)
3615                 (when (eq major-mode 'scheme-mode)
3616                   (quack-activity (format "Updating buffer %S" (buffer-name))
3617                                   (scheme-mode)))))
3618              (buffer-list)))))
3619
3620 ;; Pretty Lambda:
3621
3622 (defconst quack-lambda-char (make-char 'greek-iso8859-7 107))
3623
3624 (defconst quack-pretty-lambda-supported-p
3625   (and quack-gnuemacs-p (>= emacs-major-version 21)))
3626
3627 ;; Font Lock:
3628
3629 (defconst quack-emacsish1-font-lock-keywords
3630   `((,(concat "[[(]"
3631               "\\("                     ; #<1
3632               "define\\*?"
3633                                         ; #=2 #=3
3634               (quack-re-alt (quack-re-alt ""
3635                                           "-generic"
3636                                           "-generic-procedure"
3637                                           "-method"
3638                                           "-public"
3639                                           "/kw"
3640                                           "/override"
3641                                           "/private"
3642                                           "/public")
3643                                         ; #=4
3644                             (quack-re-alt "-macro"
3645                                           "-syntax")
3646                             "-class"
3647                             "-module"
3648                             "-signature"
3649                             "-struct")
3650               "\\)"                     ; #>1
3651               "\\>"
3652               "[ \t]*[[(]?"
3653                                         ; #=5
3654               "\\(\\sw+\\)?")
3655      (1 font-lock-keyword-face)
3656      (5 (cond ((match-beginning 3) font-lock-function-name-face)
3657               ((match-beginning 4) font-lock-variable-name-face)
3658               (t                   font-lock-type-face))
3659         nil t))
3660
3661     ;; PLT module definitions.
3662     ("[[(]\\(module\\)\\>[ \t]+\\(\\sw+\\)?"
3663      (1 font-lock-keyword-face)
3664      (2 font-lock-type-face nil t))))
3665
3666 (defconst quack-emacsish2-font-lock-keywords
3667   (append quack-emacsish1-font-lock-keywords
3668           `(
3669             ;; Misc. keywords.
3670             (,(concat
3671                "[[(]\\("
3672                (regexp-opt quack-emacsish-keywords-to-fontify)
3673                "\\)\\>")
3674              . 1)
3675             ;; Class specifiers in SOS, Stklos, Goops.
3676             ("\\<<\\sw+>\\>" . font-lock-type-face)
3677             ;; Colon keywords.
3678             ("\\<:\\sw+\\>" . font-lock-builtin-face))))
3679
3680 (defvar quack-pltish-font-lock-keywords nil)
3681
3682 (defun quack-pltish-num-re (radix digit base16-p)
3683   ;; These regexps started as a transliteration of the R5RS BNF to regular
3684   ;; expressions, adapted for PLTisms, and with a few optimizations.
3685   ;;
3686   ;; PLTisms are that 'e' is not permitted as an exponent marker in base-16
3687   ;; literals, and that "decimal-point" forms are permitted in any radix.
3688   ;;
3689   ;; There's obvious opportunity for further optimization, especially if we
3690   ;; relax the accepted syntax a little.  These regexps have not been tested
3691   ;; much, but, since this is only Emacs syntax fontification, false-positives
3692   ;; and false-negatives will be obvious yet benign.
3693   (let* ((uint    (concat digit "+#*"))
3694          (sign    "[-+]?")
3695          (suffix  (quack-re-optional (if base16-p "[sSfFdDlL]" "[eEsSfFdDlL]")
3696                                      sign
3697                                      "[0-9]+"))
3698          (decimal (quack-re-alt
3699                    (concat uint suffix)
3700                    (concat "\\." digit "+#*" suffix)
3701                    (concat digit
3702                            "+"
3703                            (quack-re-alt (concat "\\." digit "*")
3704                                          "#+\\.")
3705                            "#*")))
3706          (ureal   (quack-re-alt uint
3707                                 (concat uint "/" uint)
3708                                 decimal))
3709          (real    (concat sign ureal))
3710          (complex (quack-re-alt
3711                    (concat real
3712                            (quack-re-alt (concat "@" real)
3713                                          (quack-re-optional
3714                                           "[-+]"
3715                                           (quack-re-optional ureal)
3716                                           "i")
3717                                          ""))
3718                    (concat "[-+]" (quack-re-optional ureal) "i")))
3719          (exact   (quack-re-optional "#[eEiI]"))
3720          (prefix  (quack-re-alt (concat radix exact)
3721                                 (concat exact radix))))
3722     (concat "\\<" prefix complex "\\>")))
3723
3724 (defconst quack-pltish-fls-base
3725   `(
3726     ("\\`\\(MrEd\\|Welcome to MzScheme\\) v[^\n]+" . quack-banner-face)
3727     ("\\`Gambit Version 4\\.0[^\n]*" . quack-banner-face)
3728     ("\\`Welcome to scsh [0-9][^\n]+\nType ,\\? for help[^\n]+"
3729      . quack-banner-face)
3730     ("\\`MIT/GNU Scheme running under [^\n]+" . quack-banner-face)
3731     ;;("\\`; This is the CHICKEN interpreter - Version [^\n]+\n; (c)[^\n]+"
3732     ;; . quack-banner-face)
3733     ;;("\\`Scheme Microcode Version[^\n]+\nMIT Scheme[^\n]+\n\\([^\n]+\n\\)+" .
3734     ;;quack-banner-face)
3735     ;; Unix cookie line.
3736     ("\\`#![^\r\n]*" . quack-pltish-comment-face)
3737     ;; Colon keywords:
3738     ("\\<#:\\sw+\\>" . quack-pltish-colon-keyword-face)
3739     ;; Self-evals:
3740     ("'\\sw+\\>"                . quack-pltish-selfeval-face)
3741     ("'|\\(\\sw\\| \\)+|"       . quack-pltish-selfeval-face)
3742     ;; Note: The first alternative in the following rule will misleadingly
3743     ;; fontify some invalid syntax, such as "#\(x".
3744     ("\\<#\\\\\\([][-`~!@#$%&*()_+=^{}\;:'\"<>,.?/|\\\\]\\|\\sw+\\>\\)"
3745      . quack-pltish-selfeval-face)
3746     ("[][()]"                   . quack-pltish-paren-face)
3747     ("\\<#\\(t\\|f\\)\\>"       . quack-pltish-selfeval-face)
3748     ("\\<+\\(inf.0\\|nan\\)\\>" . quack-pltish-selfeval-face)
3749     ("\\<-inf.0\\>"             . quack-pltish-selfeval-face)
3750     ,@(mapcar (function (lambda (args)
3751                           (cons (apply 'quack-pltish-num-re args)
3752                                 'quack-pltish-selfeval-face)))
3753               '(("#b"        "[01]"        nil)
3754                 ("#o"        "[0-7]"       nil)
3755                 ("\\(#d\\)?" "[0-9]"       nil)
3756                 ("#x"        "[0-9a-fA-F]" t)))))
3757
3758 (defconst quack-pltish-fls-defnames
3759   ;; TODO: Optimize these once they're fairly complete and correct.
3760
3761   ;; TODO: Would be nice to fontify binding names everywhere they are
3762   ;;       introduced, such as in `let' and `lambda' forms.  That may require
3763   ;;       real parsing to do reasonably well -- the kludges get too bad and
3764   ;;       slow, and font-lock gets in the way more than it helps.
3765
3766   `(
3767                                         ;,@quack-pltish-font-lock-keywords
3768
3769     ;; Lots of definition forms that start with "define".
3770     (,(concat "[[(]"
3771               "define\\*?"
3772               ;; TODO: make this into regexp-opt
3773               (quack-re-alt ""
3774                             ":"
3775                             "-class"
3776                             "-class"
3777                             "-const-structure"
3778                             "-constant"
3779                             "-embedded"
3780                             "-entry-point"
3781                             "-external"
3782                             "-for-syntax"
3783                             "-foreign-record"
3784                             "-foreign-type"
3785                             "-foreign-variable"
3786                             "-generic"
3787                             "-generic-procedure"
3788                             "-inline"
3789                             "-location"
3790                             "-macro"
3791                             "-method"
3792                             "-opt"
3793                             "-parameters"
3794                             "-public"
3795                             "-reader-ctor"
3796                             "-record"
3797                             "-record-printer"
3798                             "-record-type"
3799                             "-signature"
3800                             "-structure"
3801                             "-syntax"
3802                             "-values"
3803                             "-values-for-syntax"
3804                             "/contract"
3805                             "/override"
3806                             "/private"
3807                             "/public")
3808               "\\>"
3809               "[ \t]*[[(]?"
3810               "\\(\\sw+\\)")
3811      (2 (let ((name (quack-match-string-no-properties 2)))
3812           (if (= (aref name (1- (length name))) ?%)
3813               quack-pltish-class-defn-face
3814             quack-pltish-defn-face))
3815         nil t))
3816
3817     ;; Racket "struct" and "define-struct" forms:
3818     (,(concat "[[(]"
3819               "\\(?:define-\\)?"
3820               "struct"
3821               "\\>"
3822               "[ \t]*[[(]?"
3823               "\\(\\sw+\\)")
3824      ;; TODO: Use a struct face rather than the class face.
3825      (1 quack-pltish-class-defn-face nil t))
3826
3827     ;; `defmacro' and related SCM forms.
3828     (,(concat "[[(]def"
3829               (quack-re-alt (concat "macro"
3830                                     (quack-re-alt "" "-public"))
3831                             "syntax")
3832               "\\>[ \t]+\\(\\sw+\\)")
3833      3 quack-pltish-defn-face nil t)
3834
3835     ;; `defmac' from SIOD.
3836     ("[[(]defmac[ \t]+[[(][ \t]*\\(\\sw+\\)"
3837      1 quack-pltish-defn-face nil t)
3838
3839     ;; `defvar' and `defun' from SIOD.
3840     (,(concat "[[(]def"
3841               (quack-re-alt "un"
3842                             "var")
3843               "[ \t]+\\(\\sw+\\)")
3844      2 quack-pltish-defn-face nil t)
3845
3846     ;; Guile and Chicken `define-module'.
3847     ("[[(]define-module\\>[ \t]+[[(][ \t]*\\(\\sw+\\([ \t]+\\sw+\\)*\\)"
3848      1 quack-pltish-module-defn-face nil t)
3849
3850     ;; PLT `define-values', `define-syntaxes', and `define-syntax-set'.
3851     (,(concat "[[(]define-"
3852               (quack-re-alt "values" "syntax-set" "syntaxes")
3853               "\\>[ \t]+[[(][ \t]*\\(\\sw+\\([ \t]+\\sw+\\)*\\)")
3854      2 quack-pltish-defn-face nil t)
3855
3856     ;; PLT `module'.
3857     ("[[(]module\\>[ \t]+\\(\\sw+\\)"
3858      1 quack-pltish-module-defn-face nil t)
3859
3860     ;; Named `let'.  (Note: This is disabled because it's too incongruous.)
3861     ;;("[[(]let\\>[ \t]+\\(\\sw+\\)"
3862     ;; 1 quack-pltish-defn-face nil t)
3863     ))
3864
3865 ;; TODO: Adding PLT-style (quasi)quoted list fontifying is obviously not doable
3866 ;;       with just regexps.  Probably requires either cloning
3867 ;;       `font-lock-default-fontify-region' just to get it to call our
3868 ;;       replacement syntactic pass fontification function, *or*
3869 ;;       before-advising `font-lock-fontify-keywords-region' to perform our
3870 ;;       syntactic pass when in scheme-mode, and around-advising
3871 ;;       `font-lock-fontify-syntactically-region' to not do anything for
3872 ;;       scheme-mode (or maybe setting `font-lock-keywords-only' to non-nil,
3873 ;;       unless that breaks something else).  Or just ditch font-lock.  See
3874 ;;       `font-lock-fontify-region-function' variable in font-lock specs.
3875
3876 ;; (defconst quack-pltish-fls-keywords
3877 ;;   `((,(concat
3878 ;;        "[[(]\\("
3879 ;;        (regexp-opt quack-pltish-keywords-to-fontify)
3880 ;;        "\\)\\>")
3881 ;;      (1 quack-pltish-keyword-face))))
3882
3883 (defun quack-install-fontification ()
3884
3885   (when (eq quack-fontify-style 'plt)
3886     (set (make-local-variable 'font-lock-comment-face)
3887          'quack-pltish-comment-face)
3888     (set (make-local-variable 'font-lock-string-face)
3889          'quack-pltish-selfeval-face))
3890
3891   (let* ((sk  `(("\\(#\\)\\(|\\)"
3892                  (1 ,quack-pound-syntax)
3893                  (2 ,quack-bar-syntax))
3894                 ("\\(|\\)\\(#\\)"
3895                  (1 ,quack-bar-syntax)
3896                  (2 ,quack-pound-syntax))))
3897          (pl  (if (and quack-pretty-lambda-supported-p quack-pretty-lambda-p)
3898                   '(("[[(]\\(case-\\|match-\\|opt-\\)?\\(lambda\\)\\>"
3899                      2
3900                      (progn (compose-region (match-beginning 2)
3901                                             (match-end       2)
3902                                             quack-lambda-char)
3903                             nil)))
3904                 '()))
3905          (threesemi
3906           (if quack-fontify-threesemi-p
3907               `(
3908                 (,(concat "^\\(\;\;\;\\)"
3909                           ;; TODO: Make this enforce space or newline after the
3910                           ;; three semicolons.
3911                           "\\("
3912                           "[ \t]*"
3913                           "\\("
3914                           "[^\r\n]*"
3915                           "\\)"
3916                           "\r?\n?\\)")
3917                  (1 quack-threesemi-semi-face prepend)
3918                  (2 quack-threesemi-text-face prepend)
3919                  ;;(4 quack-threesemi-h1-face   prepend)
3920                  ;;(5 quack-threesemi-h2-face   prepend)
3921                  )
3922
3923                 ;; Funcelit:
3924                 ("^\;\;\; @\\(Package\\|section\\|unnumberedsec\\)[ \t]+\\([^\r\n]*\\)"
3925                  (2 quack-threesemi-h1-face prepend))
3926                 ("^\;\;\; @subsection[ \t]+\\([^\r\n]*\\)"
3927                  (1 quack-threesemi-h2-face prepend))
3928
3929                 ;; semiscribble:
3930                 ("^\;\;\; package +\"\\([^\r\n\"]*\\)\" *"
3931                  (1 quack-threesemi-h1-face prepend))
3932                 ("^\;\;\; @section\\(?:\\[[^]]*\\]\\)?{\\([^\r\n]*\\)}"
3933                  (1 quack-threesemi-h1-face prepend))
3934                 ("^\;\;\; @subsection\\(?:\\[[^]]*\\]\\)?{\\([^\r\n]*\\)}"
3935                  (1 quack-threesemi-h2-face prepend))
3936                 
3937                 
3938                 )
3939             '()))
3940          (fld `(,(cond
3941                   ((eq quack-fontify-style 'plt)
3942                    (set (make-local-variable
3943                          'quack-pltish-font-lock-keywords)
3944                         `(,@quack-pltish-fls-base
3945                           ,@(if quack-pltish-fontify-definition-names-p
3946                                 quack-pltish-fls-defnames
3947                               '())
3948                           ,@pl
3949                           ,@(if quack-pltish-fontify-keywords-p
3950                                 ;; quack-pltish-fls-keywords
3951                                 `((,(concat
3952                                      "[[(]\\("
3953                                      (regexp-opt
3954                                       quack-pltish-keywords-to-fontify)
3955                                      "\\)\\>")
3956                                    (1 quack-pltish-keyword-face)))
3957                               '())
3958                           ,@threesemi
3959                           ))
3960                    'quack-pltish-font-lock-keywords)
3961                   ((eq quack-fontify-style 'emacs)
3962                    ;; TODO: Do pretty-lambda here too.  But first get rid of
3963                    ;;       this font-lock style "degrees of general gaudiness"
3964                    ;;       and switch to separate options for each property of
3965                    ;;       fontification.
3966                    '(quack-emacsish1-font-lock-keywords
3967                      quack-emacsish1-font-lock-keywords
3968                      quack-emacsish2-font-lock-keywords))
3969                   (t (quack-internal-error)))
3970                 nil
3971                 t
3972                 ((?! . "w") (?$ . "w") (?% . "w") (?& . "w") (?* . "w")
3973                  (?+ . "w") (?- . "w") (?. . "w") (?/ . "w") (?: . "w")
3974                  (?< . "w") (?= . "w") (?> . "w") (?? . "w") (?@ . "w")
3975                  (?^ . "w") (?_ . "w") (?~ . "w")
3976                  ,@(if (eq quack-fontify-style 'plt)
3977                        '((?# . "w"))
3978                      '()))
3979                 ;; TODO: Using `beginning-of-defun' here could be very slow,
3980                 ;;       say, when you have a large buffer that is wrapped in a
3981                 ;;       `module' form.  Look into whether this is a problem.
3982                 beginning-of-defun
3983                 ,@(if t                 ; quack-gnuemacs-p
3984                       `((font-lock-mark-block-function . mark-defun)
3985                         (font-lock-syntactic-keywords  . ,sk))
3986                     '()))))
3987
3988     ;; TODO: Figure out why `font-lock-syntactic-keywords' just doesn't work in
3989     ;;       XEmacs 21, even though the syntax text properties seem to get set.
3990     ;;       We have already beaten it like an egg-sucking dog.
3991
3992     ;;(if quack-xemacs-p
3993     ;;(put 'scheme-mode 'font-lock-defaults fld)
3994     (set (make-local-variable 'font-lock-defaults) fld)
3995     ;;)
3996
3997     ;;(when quack-xemacs-p
3998     ;;  (set (make-local-variable 'font-lock-syntactic-keywords)
3999     ;;       syntactic-keywords))
4000     ))
4001
4002 ;; Scheme Mode Startup Hook:
4003
4004 (defun quack-locally-steal-key-bindings (old-func new-func)
4005   (mapcar (function (lambda (key)
4006                       (unless (and (vectorp key)
4007                                    (eq (aref key 0) 'menu-bar))
4008                         (local-set-key key new-func))))
4009           (where-is-internal old-func)))
4010
4011 (defun quack-shared-mode-hookfunc-stuff ()
4012
4013   ;; Install the Quack keymap and menu items.
4014   (local-set-key quack-scheme-mode-keymap-prefix quack-scheme-mode-keymap)
4015   (quack-when-xemacs
4016    (when (featurep 'menubar)
4017      ;;(set-buffer-menubar current-menubar)
4018      ;; TODO: For XEmacs, we could have two versions of this menu -- the popup
4019      ;;       one would have the Global submenu, but the menubar one would have
4020      ;;       the Global submenu only if quack-global-menu-p were nil.
4021      (add-submenu nil quack-scheme-mode-menuspec)
4022      (set-menubar-dirty-flag)
4023      (setq mode-popup-menu quack-scheme-mode-menuspec)))
4024
4025   ;; Bind the paren-matching keys.
4026   (local-set-key ")" 'quack-insert-closing-paren)
4027   (local-set-key "]" 'quack-insert-closing-bracket)
4028
4029   (local-set-key "(" 'quack-insert-opening-paren)
4030   (local-set-key "[" 'quack-insert-opening-bracket)
4031
4032   ;; Steal any find-file bindings.
4033   (when quack-remap-find-file-bindings-p
4034     (quack-locally-steal-key-bindings 'find-file     'quack-find-file)
4035     (quack-locally-steal-key-bindings 'ido-find-file 'quack-find-file))
4036
4037   ;; Fight against tabs.
4038   (when quack-tabs-are-evil-p
4039     (setq indent-tabs-mode nil))
4040
4041   ;; Remove character compositions, to get rid of any pretty-lambda.  (Note:
4042   ;; This is bad, if it turns out compositions are used for other purposes in
4043   ;; buffers that are edited with Scheme Mode.)
4044   (when quack-pretty-lambda-supported-p
4045     (eval '(decompose-region (point-min) (point-max))))
4046
4047   ;; Install fontification
4048   (when quack-fontify-style
4049     (when (and (boundp 'font-lock-keywords)
4050                (symbol-value 'font-lock-keywords)
4051                (not (featurep 'noweb-mode)))
4052       ;; This warning is not given if the `noweb-mode' package is installed.
4053       (quack-warning "`font-lock-keywords' already set when hook ran."))
4054     (quack-install-fontification))
4055
4056   ;; Die! Die! Die!
4057   (quack-when-xemacs
4058    (quack-install-global-menu)))
4059
4060 (defun quack-inferior-scheme-mode-hookfunc ()
4061   (quack-shared-mode-hookfunc-stuff))
4062
4063 (defun quack-scheme-mode-hookfunc ()
4064   (quack-shared-mode-hookfunc-stuff)
4065
4066   ;; Bind Return/Enter key.
4067   (local-set-key "\r" 'quack-newline)
4068
4069   ;; Install toolbar.
4070   ;;(unless quack-xemacs-p
4071   ;;(when (display-graphic-p)
4072   ;;(quack-install-tool-bar)))
4073   )
4074
4075 (add-hook 'scheme-mode-hook          'quack-scheme-mode-hookfunc)
4076 (add-hook 'inferior-scheme-mode-hook 'quack-inferior-scheme-mode-hookfunc)
4077
4078 ;; Compilation Mode:
4079
4080 ;; TODO: Add compilation-directory-matcher support for "setup-plt:  in".
4081
4082 (defvar quack-saved-compilation-error-regexp-alist nil)
4083
4084 (defconst quack-compilation-error-regexp-alist-additions
4085   (let ((no-line (if quack-xemacs-p
4086                      (let ((m (make-marker))) (set-marker m 0) m)
4087                    'quack-compile-no-line-number)))
4088   `(
4089
4090     ;; Racket 5.1.1 "raco" compile error (which can have multiple spaces):
4091     ("^raco\\(?:cgc\\)?: +\\([^: ][^:]*\\):\\([0-9]+\\):\\([0-9]+\\):"
4092      1 2 3)
4093
4094     ;; Racket 5.1.1 entries without line number info in "=== context ===":
4095     ("^\\(/[^:]+\\): \\[running body\\]$" 1 nil nil 0)
4096
4097     ;; PLT MzScheme 4.1.4 "=== context ===" traceback when there is only file,
4098     ;; line, and column info, but potentially no following ":" and additional
4099     ;; info like procedure name.
4100     ("^\\([^:\n\" ]+\\):\\([0-9]+\\):\\([0-9]+\\)" 1 2 3)
4101
4102     ;; PLT MzScheme 205 "setup-plt"
4103     ;;   load-handler: expected a `module' declaration for `bar-unit' in
4104     ;;   "/u/collects/bar/bar-unit.ss", but found something else
4105     (,(concat "load-handler: expected a `module' declaration for `[^']+' in "
4106               "\"\\([^:\n\"]+\\)\", but found something else")
4107      1 ,no-line)
4108
4109     ;; PLT MzScheme 205 "setup-plt".
4110     ;;   setup-plt: Error during Compiling .zos for Foo Bar (/u/collects/fb)
4111     ("setup-plt: Error during Compiling .zos for [^\n]+ \(\\([^\n\)]+\\)\)"
4112      1 ,no-line)
4113
4114     ;; PLT MzScheme 4.0.1 "setup-plt".
4115     ("setup-plt: +\\(?:WARNING: +\\)\\([^:\n]+\\)::"
4116      1 ,no-line)
4117
4118     ;; PLT MzScheme 4.0.1 "setup-plt".
4119     ("setup-plt: +\\(?:WARNING: +\\)\\([^:\n ][^:\n]*\\):\\([0-9]+\\):\\([0-9]+\\)"
4120      1 2 3)
4121
4122     ;; PLT MzScheme 4.0.1 "setup-plt":
4123     ("load-handler: expected a `module' declaration for `[^'\n]+' in #<path:\\([^>\n]+\\)>[^\n]+"
4124      1 ,no-line)
4125
4126     ;; PLT Scheme 4.1.2 "default-load-handler" error without useful filename:
4127     ("default-load-handler: cannot open input-file: "
4128      nil ,no-line)
4129
4130     )))
4131
4132 (defun quack-compile-no-line-number (filename column)
4133   (list (point-marker) filename 1 (and column (string-to-number column))))
4134
4135 (defun quack-install-compilation-mode-stuff ()
4136   (unless quack-saved-compilation-error-regexp-alist
4137     (setq quack-saved-compilation-error-regexp-alist 
4138           compilation-error-regexp-alist))
4139   (setq compilation-error-regexp-alist
4140         (append quack-compilation-error-regexp-alist-additions
4141                 quack-saved-compilation-error-regexp-alist)))
4142
4143 (quack-install-compilation-mode-stuff)
4144
4145 ;; Interpreter-mode-alist:
4146
4147 (defvar quack-saved-interpreter-mode-alist nil)
4148
4149 (defvar quack-interpreter-mode-alist-additions
4150   (mapcar (function (lambda (x)
4151                       (cons x 'scheme-mode)))
4152           '("bigloo"
4153             "csi"
4154             "gosh"
4155             "gsi"
4156             "guile"
4157             "kawa"
4158             "mit-scheme"
4159             "mred"
4160             "mred3m"
4161             "mredcgc"
4162             "mzscheme"
4163             "mzscheme3m"
4164             "mzschemecgc"
4165             "r5rs"
4166             "r6rs"
4167             "rs"
4168             "rs"
4169             "scheme"
4170             "scheme48"
4171             "scsh"
4172             "sisc"
4173             "stklos"
4174             "sxi")))
4175
4176 (defun quack-install-interpreter-mode-alist ()
4177   (unless quack-saved-interpreter-mode-alist
4178     (setq quack-saved-interpreter-mode-alist
4179           interpreter-mode-alist))
4180   (setq interpreter-mode-alist
4181         (append quack-interpreter-mode-alist-additions
4182                 quack-saved-interpreter-mode-alist)))
4183
4184 (quack-install-interpreter-mode-alist)
4185
4186 ;; PLT Package Mode:
4187
4188 ;; TODO: Do some simple checking and summarize what directories and files are
4189 ;;       getting modified by this package.
4190
4191 ;; TODO: Maybe don't worry about preserving the decompressed text verbatim in
4192 ;;       the buffer -- set markers and generate headings, and be able to
4193 ;;       construct valid package.
4194
4195 ;; TODO: Command to install package from original file using "setup-plt".
4196
4197 ;; TODO: Fontify Scheme code file contents.
4198
4199 (defvar quack-pltfile-mode-hook nil)
4200
4201 (defvar quack-hiding-ovlcat)
4202 (put 'quack-hiding-ovlcat 'face       'default)
4203 (put 'quack-hiding-ovlcat 'intangible t)
4204 (put 'quack-hiding-ovlcat 'invisible  t)
4205
4206 (defvar quack-pltfile-mode-map (make-sparse-keymap))
4207 (define-key quack-pltfile-mode-map "q" 'quack-pltfile-quit)
4208 (define-key quack-pltfile-mode-map "r" 'quack-pltfile-raw)
4209 (define-key quack-pltfile-mode-map " " 'scroll-up)
4210
4211 ;; TODO: Make a menu map for pltfile-mode.
4212
4213 (defun quack-pltfile-mode ()
4214   (interactive)
4215   "Major mode for viewing PLT Scheme `.plt' package files.
4216
4217 \\{quack-pltfile-mode-map}
4218
4219 Provided by Quack: http://www.neilvandyke.org/quack/"
4220   (kill-all-local-variables)
4221   (put 'quack-pltfile-mode 'mode-class 'special)
4222   (setq major-mode 'quack-pltfile-mode)
4223   (setq mode-name "PLT Package")
4224   (use-local-map quack-pltfile-mode-map)
4225   ;; Note: Currently, the `font-lock' feature is always defined, since we
4226   ;; require it.
4227   (when (featurep 'font-lock)
4228     (setq font-lock-defaults nil))
4229   (buffer-disable-undo)
4230   (let ((saved-bmp (buffer-modified-p)))
4231     (quack-activity "Decoding PLT package" (quack-pltfile-decode-buffer))
4232     (setq buffer-read-only t)
4233     (set-buffer-modified-p saved-bmp))
4234   (quack-when-xemacs
4235    (make-variable-buffer-local 'write-contents-hooks))
4236   (add-hook 'write-contents-hooks 'quack-prevent-pltfile-write)
4237   (run-hooks 'quack-pltfile-mode-hook)
4238   (message "Decoded PLT package.  %s"
4239            (substitute-command-keys
4240             (concat "`\\[quack-pltfile-quit]' to quit"
4241                     ", `\\[quack-pltfile-raw]' for raw format."))))
4242
4243 (defun quack-prevent-pltfile-write ()
4244   (unless (yes-or-no-p
4245            "Write a decoded PLT package buffer?!  Are you *sure*?!")
4246     (error "Aborted write of decoded PLT package buffer.")))
4247
4248 (defun quack-pltfile-raw ()
4249   (interactive)
4250   (let ((auto-mode-alist '()))
4251     (setq buffer-read-only nil)
4252     (widen)
4253     (delete-region (point-min) (point-max))
4254     (fundamental-mode)
4255     (revert-buffer t t)))
4256
4257 (defun quack-pltfile-quit ()
4258   (interactive)
4259   (kill-buffer (current-buffer)))
4260
4261 (defun quack-skip-whitespace-to-nonblank-line-beginning ()
4262   (save-match-data
4263     (while (looking-at "[ \t\r\f]*\n")
4264       (goto-char (match-end 0)))))
4265
4266 (defun quack-pltfile-decode-buffer ()
4267
4268   ;; MIME Base-64 decode.  (Note: an error is signaled if this fails.)
4269   (base64-decode-region (point-min) (point-max))
4270
4271   ;; Gzip decompress.
4272   (let ((coding-system-for-write (if quack-xemacs-p 'binary 'raw-text-unix))
4273         (coding-system-for-read  (if quack-xemacs-p 'binary 'raw-text-unix))
4274         (inhibit-eol-conversion  t)
4275         status)
4276     (unless (= (setq status (call-process-region (point-min) (point-max)
4277                                                  "gzip" t t nil "-d")) 0)
4278       (error "Could not decompress PLT package: gzip process status %s"
4279              status)))
4280
4281   ;; Move past the "PLT" cookie, and the two sexp forms.
4282   (goto-char (point-min))
4283   (unless (looking-at "PLT")
4284     (error "This does not appear to be a PLT package file."))
4285   (goto-char (match-end 0))
4286   (forward-list 2)
4287   (quack-skip-whitespace-to-nonblank-line-beginning)
4288   (quack-make-face-ovlext (point-min) (point) 'quack-pltfile-prologue-face)
4289
4290   ;; Process the buffer contents.
4291   (let ((standard-input (current-buffer)))
4292
4293     (while (not (eobp))
4294       (let ((step-beg (point)))
4295         ;; TODO: This read will fail if we just had whitespace at the end of
4296         ;;       the file, which it shouldn't, but maybe we should check, just
4297         ;;       in case.
4298         (let ((sym (read)))
4299           (unless (symbolp sym)
4300             (error "Expected a symbol, but saw: %S" sym))
4301           (cond
4302
4303            ((eq sym 'dir)
4304             (forward-list)
4305             (quack-skip-whitespace-to-nonblank-line-beginning)
4306             (quack-make-face-ovlext step-beg
4307                                     (point)
4308                                     'quack-pltfile-dir-face))
4309
4310            ((memq sym '(file file-replace))
4311             (forward-list)
4312             (let ((size (read)))
4313               (unless (and (integerp size) (>= size 0))
4314                 (error "Expected a file size, but saw: %S" size))
4315               (unless (looking-at "[ \t\r\n\f]*\\*")
4316                 (error "Expected a `*' after file size."))
4317               (goto-char (match-end 0))
4318
4319               ;; Fontify the file header.
4320               (quack-make-face-ovlext step-beg
4321                                       (1- (point))
4322                                       'quack-pltfile-file-face)
4323
4324               ;; Hide the file contents asterisk.
4325               (quack-make-hiding-ovlext (1- (point)) (point))
4326
4327               ;; Set the coding region for the content.
4328               (let* ((content-beg (point))
4329                      (content-end (+ content-beg size))
4330                      (cs          (detect-coding-region content-beg
4331                                                         content-end)))
4332                 (goto-char content-end)
4333                 (when (listp cs)
4334                   (setq cs (car cs)))
4335                 (unless (eq cs 'undecided)
4336                   (cond ((eq cs 'undecided-dos)  (setq cs 'raw-text-dos))
4337                         ((eq cs 'undecided-mac)  (setq cs 'raw-text-mac))
4338                         ((eq cs 'undecided-unix) (setq cs 'raw-text-unix)))
4339                   (decode-coding-region content-beg content-end cs))
4340                 ;; TODO: XEmacs 21 `decode-coding-region' seems to lose the
4341                 ;;       point position.  This is disconcerting, since the
4342                 ;;       point semantics under coding system changes do not
4343                 ;;       currently seem to be well-specified, so resetting the
4344                 ;;       point here *might* not always be the right thing to
4345                 ;;       do.  Verify.
4346                 (quack-when-xemacs
4347                  (goto-char content-end)))))
4348
4349            (t (error "Expected `dir', `file', or `file-replace', but saw: %S"
4350                      sym)))))))
4351
4352   ;; Return point to top of buffer.
4353   (goto-char (point-min)))
4354
4355 ;; The rest of this file except for the `provide' form is TODO comments.
4356
4357 ;; TODO: Add tool bar support later.
4358 ;;
4359 ;; (defvar quack-toolbarimage-width  24)
4360 ;; (defvar quack-toolbarimage-height 24)
4361 ;;
4362 ;; (defun quack-create-image (&rest args)
4363 ;;   (if (and quack-gnuemacs-p (>= emacs-major-version 21))
4364 ;;       (apply 'create-image args)
4365 ;;     nil))
4366 ;;
4367 ;; (defun quack-make-toolbarimage (&rest lines)
4368 ;;   ;; TODO: We really should make an efficient function to print N spaces
4369 ;;   ;;       or to return a string of N spaces.  Or at least keep 1-2
4370 ;;   ;;       strings for the left and right padding here, which will
4371 ;;   ;;       usually be the same for the duration of this function.
4372 ;;   (quack-create-image
4373 ;;    (let* ((lines-count (length lines))
4374 ;;           (blank-line  (make-string quack-toolbarimage-width 32)))
4375 ;;      (and (> lines-count quack-toolbarimage-height) (quack-internal-error))
4376 ;;      (with-output-to-string
4377 ;;        (princ "/* XPM */\nstatic char *magick[] = {\n")
4378 ;;        ;;(princ "/* columns rows colors chars-per-pixel */\n")
4379 ;;        (princ (format "\"%d %d 5 1\",\n"
4380 ;;                       quack-toolbarimage-width quack-toolbarimage-height))
4381 ;;        (princ "\". c #f0f0f0\",\n")
4382 ;;        (princ "\"@ c #0f0f0f\",\n")
4383 ;;        (princ "\"g c #00b000\",\n")
4384 ;;        (princ "\"r c #d00000\",\n")
4385 ;;        (princ "\"  c None\",\n")
4386 ;;        ;;(princ "/* pixels */\n")
4387 ;;        (let ((line-num 0))
4388 ;;          (mapcar (function
4389 ;;                   (lambda (line)
4390 ;;                     (princ "\"")
4391 ;;                     (if line
4392 ;;                         (let* ((c (length line))
4393 ;;                                (l (/ (- quack-toolbarimage-width c) 2)))
4394 ;;                           (and (> c quack-toolbarimage-width)
4395 ;;                                (quack-internal-error))
4396 ;;                           (princ (make-string l 32))
4397 ;;                           (princ line)
4398 ;;                           (princ (make-string (- quack-toolbarimage-width
4399 ;;                                                  c l)
4400 ;;                                               32)))
4401 ;;                       (princ blank-line))
4402 ;;                     (if (< (setq line-num (1+ line-num))
4403 ;;                            quack-toolbarimage-height)
4404 ;;                         (princ "\",\n")
4405 ;;                       (princ "\"\n"))))
4406 ;;                  (let ((rows-before (/ (- quack-toolbarimage-width
4407 ;;                                           lines-count)
4408 ;;                                        2)))
4409 ;;                    `(,@(make-list rows-before nil)
4410 ;;                        ,@lines
4411 ;;                        ,@(make-list (- quack-toolbarimage-height
4412 ;;                                        lines-count rows-before)
4413 ;;                                     nil)))))
4414 ;;        (princ "};\n")))
4415 ;;    'xpm t))
4416 ;;
4417 ;; (defvar quack-tbi-evalbuf
4418 ;;   (quack-make-toolbarimage
4419 ;;    "@@@@@@@@@@          "
4420 ;;    "@........@@         "
4421 ;;    "@........@.@   ggg  "
4422 ;;    "@........@..@  ggg  "
4423 ;;    "@........@@@@@ ggg  "
4424 ;;    "@............@ ggg  "
4425 ;;    "@..@@........@ ggg  "
4426 ;;    "@...@@.......@ ggg  "
4427 ;;    "@....@@......@ ggg  "
4428 ;;    "@.....@@.....@ ggg  "
4429 ;;    "@....@@@@....@ ggg  "
4430 ;;    "@...@@..@@...@ ggg  "
4431 ;;    "@..@@....@@..@ ggg  "
4432 ;;    "@............@ ggg  "
4433 ;;    "@@@@@@@@@@@@@@ ggg  "
4434 ;;    "               ggg  "
4435 ;;    "             ggggggg"
4436 ;;    "              ggggg "
4437 ;;    "               ggg  "
4438 ;;    "                g   "))
4439 ;;
4440 ;; (defvar quack-tbi-adoc
4441 ;;   (quack-make-toolbarimage
4442 ;;    "@@@@@@@@@@    "
4443 ;;    "@........@@   "
4444 ;;    "@........@.@  "
4445 ;;    "@........@..@ "
4446 ;;    "@........@@@@@"
4447 ;;    "@...@@@......@"
4448 ;;    "@..@@@@@@....@"
4449 ;;    "@..@....@@...@"
4450 ;;    "@...@@@.@@...@"
4451 ;;    "@..@@@@@@@...@"
4452 ;;    "@..@@...@@...@"
4453 ;;    "@..@@..@@@...@"
4454 ;;    "@...@@@@.@@..@"
4455 ;;    "@............@"
4456 ;;    "@@@@@@@@@@@@@@"))
4457 ;;
4458 ;; (defvar quack-tbi-manual
4459 ;;   (quack-make-toolbarimage
4460 ;;    "@@@@@@@@@@    "
4461 ;;    "@........@@   "
4462 ;;    "@........@.@  "
4463 ;;    "@........@..@ "
4464 ;;    "@........@@@@@"
4465 ;;    "@............@"
4466 ;;    "@..@@.@.@@...@"
4467 ;;    "@..@@@@@@@@..@"
4468 ;;    "@..@@.@@.@@..@"
4469 ;;    "@..@@.@@.@@..@"
4470 ;;    "@..@@.@@.@@..@"
4471 ;;    "@..@@.@@.@@..@"
4472 ;;    "@..@@.@@.@@..@"
4473 ;;    "@............@"
4474 ;;    "@@@@@@@@@@@@@@"))
4475 ;;
4476 ;; (defvar quack-tbi-manuallookup
4477 ;;   (quack-make-toolbarimage
4478 ;;    "@@@@@@@@@@          "
4479 ;;    "@........@@         "
4480 ;;    "@........@.@        "
4481 ;;    "@........@..@       "
4482 ;;    "@........@@@@@      "
4483 ;;    "@............@      "
4484 ;;    "@..@@.@@@@@@@@@@    "
4485 ;;    "@...@@@........@@   "
4486 ;;    "@....@@........@.@  "
4487 ;;    "@.....@........@..@ "
4488 ;;    "@....@@........@@@@@"
4489 ;;    "@...@@@............@"
4490 ;;    "@..@@.@..@@.@.@@...@"
4491 ;;    "@.....@..@@@@@@@@..@"
4492 ;;    "@@@@@@@..@@.@@.@@..@"
4493 ;;    "      @..@@.@@.@@..@"
4494 ;;    "      @..@@.@@.@@..@"
4495 ;;    "      @..@@.@@.@@..@"
4496 ;;    "      @..@@.@@.@@..@"
4497 ;;    "      @............@"
4498 ;;    "      @@@@@@@@@@@@@@"))
4499 ;;
4500 ;; (defvar quack-tbi-stop
4501 ;;   (quack-make-toolbarimage
4502 ;;    "    @@@@@    "
4503 ;;    "  @@rrrrr@@  "
4504 ;;    " @rrrrrrrrr@ "
4505 ;;    " @rrrrrrrrr@ "
4506 ;;    "@rr@@rrr@@rr@"
4507 ;;    "@rrr@@r@@rrr@"
4508 ;;    "@rrrr@@@rrrr@"
4509 ;;    "@rrr@@r@@rrr@"
4510 ;;    "@rr@@rrr@@rr@"
4511 ;;    " @rrrrrrrrr@ "
4512 ;;    " @rrrrrrrrr@ "
4513 ;;    "  @@rrrrr@@  "
4514 ;;    "    @@@@@    "))
4515 ;;
4516 ;; (defun quack-install-tool-bar ()
4517 ;;   (require 'tool-bar)
4518 ;;   (let ((map (make-sparse-keymap)))
4519 ;;
4520 ;;     (quack-define-key-after map [quack-load-file]
4521 ;;                             `(menu-item "quack-evalbuffer" scheme-load-file
4522 ;;                                         :image ,quack-tbi-evalbuf
4523 ;;                                         :help  "Load File"))
4524 ;;
4525 ;;     (quack-define-key-after map [quack-alpha]
4526 ;;                             `(menu-item "quack-alpha" quack-alpha
4527 ;;                                         :image ,quack-tbi-adoc
4528 ;;                                         :help  "alpha"))
4529 ;;
4530 ;;     (quack-define-key-after map [quack-manual]
4531 ;;                             `(menu-item "quack-manual" quack-manual
4532 ;;                                         :image ,quack-tbi-manual
4533 ;;                                         :help  "View Manual"))
4534 ;;
4535 ;;     (quack-define-key-after map [quack-view-keyword-docs]
4536 ;;                             `(menu-item "quack-view-keyword-docs"
4537 ;;                                         quack-view-keyword-docs
4538 ;;                                         :image ,quack-tbi-manuallookup
4539 ;;                                         :help  "View Keyword Docs"))
4540 ;;
4541 ;;     (quack-define-key-after map [quack-stop]
4542 ;;                             `(menu-item "quack-stop" quack-stop
4543 ;;                                         :image ,quack-tbi-stop
4544 ;;                                         :help  "Stop"))
4545 ;;
4546 ;;     (set (make-local-variable 'tool-bar-map) map)))
4547
4548 ;; TODO: Extend `scheme-imenu-generic-expression' for PLT-specific definition
4549 ;;       forms and for definitions within modules.
4550
4551 ;; TODO: Clickable URLs
4552 ;;
4553 ;; (defvar quack-url-keymap)
4554 ;; 
4555 ;; (setq quack-url-keymap (make-sparse-keymap))
4556 ;; (define-key quack-url-keymap "\r" 'quack-browse-overlaid-url)
4557 ;; (define-key quack-url-keymap "q" 'quack-browse-overlaid-url)
4558 ;; 
4559 ;; (defun quack-make-url-overlay (beg end &optional url)
4560 ;;   (let ((ovl (make-overlay beg end nil t)))
4561 ;;     (overlay-put ovl 'face      'underline)
4562 ;;     (overlay-put ovl 'local-map 'quack-url-keymap)
4563 ;;     (overlay-put ovl 'help-echo "Press RET to browse this URL.")
4564 ;;     (overlay-put ovl 'quack-url
4565 ;;                      (or url (buffer-substring-no-properties beg end)))
4566 ;;     ovl))
4567 ;; 
4568 ;; (defun quack-insert-url (url)
4569 ;;   (let* ((beg (point)))
4570 ;;     (insert url)
4571 ;;     (quack-make-url-overlay beg (point))))
4572 ;; 
4573 ;; (defun quack-overlaid-url-at-point (&optional pt)
4574 ;;   (let ((overlays (overlays-at (or pt (point))))
4575 ;;         (url      nil))
4576 ;;     (while overlays
4577 ;;       (setq overlays (if (setq url (overlay-get (car overlays) 'quack-url))
4578 ;;                          (cdr overlays)
4579 ;;                        '())))
4580 ;;     url))
4581 ;; 
4582 ;; (defun quack-browse-overlaid-url (pt)
4583 ;;   ;; Dehydration.
4584 ;;   (interactive "d")
4585 ;;   (quack-browse-url (quack-overlaid-url-at-point pt)))
4586
4587 ;; TODO: Possible Future Inferior Process I/O Stuff.  Make encoding with
4588 ;;       inferior process disambiguate REPL values, port output, error info,
4589 ;;       etc.  Start of code commented out below.  This may require rewriting
4590 ;;       chunks of `cmuscheme' and `comint'.
4591 ;;
4592 ;;       Try to use ELI protocol first.  http://www.cliki.net/ELI
4593 ;;
4594 ;; (defface quack-output-face
4595 ;;   '((((class color)) (:foreground "purple4" :background "lavender"))
4596 ;;     (t               (:inverse-video t)))
4597 ;;   "Face used for..."
4598 ;;   :group 'quack)
4599 ;;
4600 ;; (defface quack-value-face
4601 ;;   '((((class color)) (:foreground "blue4" :background "light sky blue"))
4602 ;;     (t               (:inverse-video t)))
4603 ;;   "Face used for..."
4604 ;;   :group 'quack)
4605 ;;
4606 ;; Escape Codes:
4607 ;;     REPL State:
4608 ;;         R  repl read begin
4609 ;;         r  repl read end
4610 ;;         E  repl eval begin
4611 ;;         e  repl eval end
4612 ;;         P  repl print begin
4613 ;;         p  repl print end
4614 ;;     Stream Change:
4615 ;;         O  output stream
4616 ;;         E  error stream
4617 ;;     Error Info?
4618 ;;
4619 ;; (defconst quack-mzscheme-init-string
4620 ;;   (let ((print-length nil)
4621 ;;         (print-level  nil))
4622 ;;     (prin1-to-string
4623 ;;      '(let ((o (current-output-port))
4624 ;;             (i (current-input-port))
4625 ;;             (e (current-eval)))
4626 ;;         ;; TODO: Define custom escaping output and error ports here.
4627 ;;         (current-prompt-read
4628 ;;          (lambda ()
4629 ;;            (display "\eR" o)
4630 ;;            (begin0 (read-syntax "quack-repl" i)
4631 ;;                    (display "\er" o))))
4632 ;;         (current-eval
4633 ;;          (lambda (n)
4634 ;;            (display "\eE" o)
4635 ;;            (begin0 (e n)
4636 ;;                    (display "\ee" o))))
4637 ;;         (current-print
4638 ;;          (lambda (n)
4639 ;;            (display "\eP" o)
4640 ;;            (begin0 (print n o)
4641 ;;                    (display "\ep" o))))))))
4642 ;;
4643 ;; In `quack' function, after call to `run-scheme':
4644 ;;
4645 ;; (add-hook 'comint-preoutput-filter-functions
4646 ;;           'quack-comint-preoutput-filter-func)
4647 ;; (comint-send-string (scheme-proc) quack-mzscheme-init-string)
4648 ;; (comint-send-string (scheme-proc) "\n")
4649
4650 ;; TODO: If we do that, then add pretty-printing of REPL results.
4651
4652 ;; TODO: Maybe provide utilities for converting to/from PLT-style
4653 ;;       square-bracket paren conventions.
4654
4655 ;; TODO: Populate abbrevs table from keywords extracted from manuals, and from
4656 ;;       definitions in current buffer.  Or maybe query running MzScheme
4657 ;;       process for bound symbols.
4658
4659 ;; TODO: Maybe use `compile-zos' to do error-checking for PLT (look up person
4660 ;;       to credit with idea of using that to get more warnings).  Need to know
4661 ;;       more about a particular Scheme implementation than just the command
4662 ;;       line to start its REPL, though.
4663
4664 ;; TODO: Perhaps put some initialization code that depends on user's custom
4665 ;;       settings into after-init-hook.  See if this works in XEmacs.
4666
4667 ;; TODO: Set `interpreter-mode-alist' based on interpreter list.
4668
4669 ;; TODO: "I think it would be good if the quack menu showed up only when emacs
4670 ;;        was in Scheme mode."
4671
4672 ;; TODO: Support this:
4673 ;;
4674 ;;       * Added 'addon-dir for `find-system-path':
4675 ;;       Unix: "~/.plt-scheme"
4676 ;;       Windows: "PLT Scheme" in the user's Application Data folder.
4677 ;;       Mac OS X: "~/Library/PLT Scheme"
4678 ;;       Mac OS Classic: "PLT Scheme" in the preferences folder.
4679 ;;
4680 ;;       The version string for "~/.plt-scheme/<version>/collects/" might be:
4681 ;;       mzscheme -mqe '(begin (display (version)) (exit))'
4682 ;;       Double-check PLT source first.
4683
4684 ;; TODO: Add autoindenting to inferior Scheme buffer when pressing RET on an
4685 ;;       incomplete sexp -- iff we can do this reliably enough.
4686
4687 ;; TODO: When tidying and point is within a series of multiple blank lines that
4688 ;;       are reduced to a single blank line, leave point at the beginning of
4689 ;;       the single blank line.
4690
4691 ;; TODO: Riastradh says: Do you suppose you could add a feature to Quack that
4692 ;;       indents lists beginning with symbols of the form WITH-...  &
4693 ;;       CALL-WITH-... as if their SCHEME-INDENT-FUNCTION property were DEFUN?
4694
4695 ;; TODO: Matt Dickerson asks " Also, the command history appears to be based on
4696 ;;       newlines -- I work with blocks of code in the REPL and would like C-p
4697 ;;       to give me the last block, not the last line of the previous block."
4698
4699 ;; TODO: Maybe get appropriate PLT collection path from the default for
4700 ;;       whatever "mzscheme" executable is picked up.
4701 ;;
4702 ;; mzscheme -emq '(begin (write (current-library-collection-paths)) (exit 0))'
4703 ;; ("/home/neil/collects" "/home/neil/.plt-scheme/208/collects"
4704 ;;  "/usr/lib/plt/collects")
4705
4706 ;; TODO: Bind M-[ to quack-insert-parentheses
4707
4708 ;; TODO: Peter Barabas reports that `quack-global-menu-p' set to nil doesn't
4709 ;; disable the menu.
4710
4711 ;; TODO: Way to get default collects directories.  From Matthew Flatt,
4712 ;; 2006-04-22:
4713 ;; 
4714 ;; env PLTCOLLECTS="" mzscheme -mvqe '(printf "~s\n" (map path->string 
4715 ;; (current-library-collection-paths)))'
4716
4717 ;; TODO: Have key binding to insert "lambda" (for use with pretty-lambda).
4718 ;; Suggested by Olwe Bottorff on 2006-04-20.
4719
4720 ;; TODO: Jerry van Dijk writes: "I would like to try out quack, but I do not
4721 ;; like its menu constantly on the main menu bar (as I use emacs for a lot of
4722 ;; things). Unfortunately sofar quack has bravely defied all my attempts to
4723 ;; remove it. From desecting the customize option to adding (define-key
4724 ;; global-map [menu-bar quack] nil)"
4725
4726 ;; TODO: We could do this:
4727 ;;
4728 ;; mzscheme -m -e "(begin (display #\') (write (map path->string (current-library-collection-paths))) (newline) (exit))"
4729 ;; '("/home/neil/collects"
4730 ;;   "/home/neil/.plt-scheme/360/collects"
4731 ;;   "/usr/lib/plt/collects")
4732
4733 ;; emacs22  -batch -no-site-file -f batch-byte-compile quack.el ; rm quack.elc
4734 ;; emacs21  -batch -no-site-file -f batch-byte-compile quack.el ; rm quack.elc
4735 ;; emacs20  -batch -no-site-file -f batch-byte-compile quack.el ; rm quack.elc
4736 ;; xemacs21 -batch -no-site-file -f batch-byte-compile quack.el ; rm quack.elc
4737
4738 ;; End:
4739
4740 (provide 'quack)
4741
4742 ;; quack.el ends here