Initial Commit
[packages] / xemacs-packages / edebug / cl-read.el
1 ;; Customizable, Common Lisp like reader for Emacs Lisp.
2 ;; 
3 ;; Copyright (C) 1993 by Guido Bosch <Guido.Bosch@loria.fr>
4
5 ;; This file is part of XEmacs
6
7 ;; XEmacs is free software; you can redistribute it and/or modify it
8 ;; under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation; either version 2, or (at your option)
10 ;; any later version.
11
12 ;; XEmacs is distributed in the hope that it will be useful, but
13 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 ;; General Public License for more details.
16
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
19 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
20 ;; 02111-1307, USA.
21
22 ;;; Synched up with: Not in FSF
23
24 ;;; Commentary:
25
26 ;; Please send bugs and comments to the author.
27 ;;
28 ;; <DISCLAIMER>
29 ;; This program is still under development.  Neither the author nor
30 ;; his employer accepts responsibility to anyone for the consequences of
31 ;; using it or for whether it serves any particular purpose or works
32 ;; at all.
33
34 \f
35 ;; Introduction
36 ;; ------------
37 ;;
38 ;; This package replaces the standard Emacs Lisp reader (implemented
39 ;; as a set of built-in Lisp function in C) by a flexible and
40 ;; customizable Common Lisp like one (implemented entirely in Emacs
41 ;; Lisp). During reading of Emacs Lisp source files, it is about 40%
42 ;; slower than the built-in reader, but there is no difference in
43 ;; loading byte compiled files - they dont contain any syntactic sugar
44 ;; and are loaded with the built in subroutine `load'.
45 ;;
46 ;; The user level functions for defining read tables, character and
47 ;; dispatch macros are implemented according to the Commom Lisp
48 ;; specification by Steel's (2nd edition), but the read macro functions
49 ;; themselves are implemented in a slightly different way, because the
50 ;; basic character reading is done in an Emacs buffer, and not by
51 ;; using the primitive functions `read-char' and `unread-char', as real
52 ;; CL does.  To get 100% compatibility with CL, the above functions
53 ;; (or their equivalents) must be implemented as subroutines.
54 ;;
55 ;; Another difference with real CL reading is that basic tokens (symbols
56 ;; numbers, strings, and a few more) are still read by the original
57 ;; built-in reader. This is necessary to get reasonable performance.
58 ;; As a consquence, the read syntax of basic tokens can't be
59 ;; customized.
60
61 ;; Most of the built-in reader syntax has been replaced by lisp
62 ;; character macros: parentheses and brackets, simple and double
63 ;; quotes, semicolon comments and the dot. In addition to that, the
64 ;; following new syntax features are provided:
65
66 ;; Backquote-Comma-Atsign Macro: `(,el ,@list) 
67 ;;
68 ;; (the clumsy Emacs Lisp syntax (` ((, el) (,@ list))) is also
69 ;; supported, but with one restriction: the blank behind the quote
70 ;; characters is mandatory when using the old syntax. The cl reader
71 ;; needs it as a landmark to distinguish between old and new syntax.
72 ;; An example:
73 ;;
74 ;; With blanks, both readers read the same:
75 ;; (` (, (head)) (,@ (tail))) -std-read->  (` (, (head)) (,@ (tail)))
76 ;; (` (, (head)) (,@ (tail))) -cl-read->   (` (, (head)) (,@ (tail)))
77 ;;
78 ;; Without blanks, the form is interpreted differently by the two readers:
79 ;; (`(,(head)) (,@(tail))) -std-read-> (` (, (head)) (,@ (tail)))
80 ;; (`(,(head)) (,@(tail))) -cl-read->  ((` ((, ((head)))) ((,@ ((tail)))))
81 ;;
82 ;; 
83 ;; Dispatch Character Macro" `#'
84 ;;
85 ;; #'<function>                 function quoting
86 ;; #\<character>                character syntax
87 ;; #.<form>                     read time evaluation
88 ;; #p<path>, #P<path>           paths
89 ;; #+<feature>, #-<feature>     conditional reading
90 ;; #<n>=, #<n>#                 tags for shared structure reading
91 ;;
92 ;; Other read macros can be added easily (see the definition of the
93 ;; above ones in this file, using the functions `set-macro-character'
94 ;; and `set-dispatch-macro-character')
95 ;;
96 ;; The Cl reader is mostly downward compatile, (exception: backquote
97 ;; comma macro, see above). E.g., this file, which is written entirely
98 ;; in the standard Emacs Lisp syntax, can be read and compiled with the
99 ;; cl-reader activated (see Examples below). 
100
101 ;; This also works with package.el for Common Lisp packages.
102
103 \f
104 ;; Requirements
105 ;; ------------
106 ;; The package runs on Emacs 18 and Emacs 19 (FSF and Lucid) It is
107 ;; built on top of Dave Gillespie's cl.el package (version 2.02 or
108 ;; later).  The old one (from Ceazar Quiroz, still shiped with some
109 ;; Emacs 19 disributions) will not do.
110 \f
111 ;; Usage
112 ;; -----
113 ;; The package is implemented as a kind of minor mode to the
114 ;; emacs-lisp-mode. As most of the Emacs Lisp files are still written
115 ;; in the standard Emacs Lisp syntax, the cl reader is only activated
116 ;; on elisp files whose property lines contain the following entry:
117 ;;
118 ;; -*- Read-Syntax: Common-Lisp -*-
119 ;;
120 ;; Note that both property name ("Read-Syntax") and value
121 ;; ("Common-Lisp") are not case sensitive. There can also be other
122 ;; properties in this line: 
123 ;;
124 ;; -*- Mode: Emacs-Lisp; Read-Syntax: Common-Lisp -*-
125 \f
126 ;; Installation
127 ;; ------------
128 ;; Save this file in a directory where Emacs will find it, then
129 ;; byte compile it (M-x byte-compile-file).
130 ;;
131 ;; A permanent installation of the package can be done in two ways:
132 ;;
133 ;; 1.) If you want to have the package always loaded, put this in your
134 ;;     .emacs, or in just the files that require it:
135 ;;
136 ;; (require 'cl-read) 
137 ;;
138 ;; 2.) To load the cl-read package automatically when visiting an elisp
139 ;;     file that needs it, it has to be installed using the
140 ;;     emacs-lisp-mode-hook. In this case, put the following function
141 ;;     definition and add-hook form in your .emacs:
142 ;;
143 ;; (defun cl-reader-autoinstall-function () 
144 ;;   "Activates the Common Lisp style reader for emacs-lisp-mode buffers,
145 ;; if the property line has a local variable setting like this: 
146 ;; \;\; -*- Read-Syntax: Common-Lisp -*-"
147 ;;
148 ;;   (or (boundp 'local-variable-hack-done)
149 ;;       (let (local-variable-hack-done
150 ;;             (case-fold-search t))
151 ;;         (hack-local-variables-prop-line 't)
152 ;;         (cond 
153 ;;          ((and (boundp 'read-syntax)
154 ;;                read-syntax
155 ;;                (string-match "^common-lisp$" (symbol-name read-syntax)))
156 ;;           (require 'cl-read)
157 ;;           (make-local-variable 'cl-read-active)
158 ;;           (setq cl-read-active 't))))))
159 ;;
160 ;; (add-hook 'emacs-lisp-mode-hook 'cl-reader-autoinstall-function)
161 ;;
162 ;; The `cl-reader-autoinstall-function' function tests for the
163 ;; presence of the correct Read-Syntax property in the first line of
164 ;; the file and loads the cl-read package if necessary. cl-read
165 ;; replaces the following standard elisp functions:
166 ;;
167 ;;      - read
168 ;;      - read-from-string
169 ;;      - eval-current-buffer
170 ;;      - eval-buffer
171 ;;      - eval-region
172 ;;      - eval-expression (to call reader explicitly)
173 ;;
174 ;; There may be other built-in functions that need to be replaced
175 ;; (e.g. load).  The behavior of the new reader function depends on
176 ;; the value of the buffer local variable `cl-read-active': if it is
177 ;; nil, they just call the original functions, otherwise they call the
178 ;; cl reader. If the cl reader is active in a buffer, this is
179 ;; indicated in the modeline by the string "CL" (minor mode like). 
180 ;;
181 \f
182 ;; Examples:
183 ;; ---------
184 ;; After having installed the package as described above, the
185 ;; following forms can be evaluated (M-C-x) with the cl reader being
186 ;; active. (make sure that the mode line displays "(Emacs-Lisp CL)")
187 ;;
188 ;; (setq whitespaces '(#\space #\newline #\tab))
189 ;; (setq more-whitespaces `(#\page ,@whitespaces #\linefeed))
190 ;; (setq whitespace-strings (mapcar #'char-to-string more-whitespaces))
191 ;; 
192 ;; (setq shared-struct '(#1=[hello world] #1# #1#))
193 ;; (progn (setq cirlist '#1=(a b . #1#)) 't)
194 ;;
195 ;; This file, though written in standard Emacs Lisp syntax, can also be
196 ;; compiled with the cl reader active: Type M-x byte-compile-file
197 \f
198 ;; TO DO List: 
199 ;; -----------
200 ;; - Provide a replacement for load so that uncompiled cl syntax
201 ;;   source file can be loaded, too.  For now prohibit loading un-bytecompiled.
202 ;; - Do we really need the (require 'cl) dependency?   Yes.
203 ;; - More read macros: #S for structs, #A for array, #X for hex, #nR for radix
204 ;; - Refine the error signaling mechanism.
205 ;;     - invalid-cl-read-syntax is now defined. what else?
206
207 \f
208 ; Change History
209
210 ; $Log: cl-read.el,v $
211 ; Revision 1.2  2000-10-06 08:47:07  youngs
212 ; Martin's Monster Mega typo patch
213 ;
214 ; Revision 1.1.1.1  1998/01/14 06:31:38  steve
215 ; Created
216 ;
217 ; Revision 1.19  94/03/21  19:59:24  liberte
218 ; Add invalid-cl-read-syntax error symbol.
219 ; Add reader::read-sexp and reader::read-sexp-func to allow customization
220 ; based on the results of reading.
221 ; Remove more dependencies on cl-package.
222 ; Remove reader::eval-current-buffer, eval-buffer, and eval-region,
223 ; and use elisp-eval-region package instead.
224
225 ; Revision 1.18  94/03/04  23:42:24  liberte
226 ; Fix typos in comments.
227
228 ; Revision 1.17  93/11/24  12:04:09  bosch
229 ; cl-packages dependency removed. `reader::read-constituent' and
230 ; corresponding variables moved to cl-packages.el.
231 ; Multi-line comment #| ... |# dispatch character read macro added.
232
233 ; Revision 1.16  1993/11/23  10:21:02  bosch
234 ; Patches from Daniel LaLiberte integrated.
235 ;
236 ; Revision 1.15  1993/11/18  21:21:10  bosch
237 ; `reader::symbol-regexp1' modified.
238 ;
239 ; Revision 1.14  1993/11/17  19:06:32  bosch
240 ; More characters added to `reader::symbol-characters'.
241 ; `reader::read-constituent' modified.
242 ; defpackage form added.
243 ;
244 ; Revision 1.13  1993/11/16  13:06:41  bosch
245 ; - Symbol reading for CL package convention implemented.
246 ;   Variables `reader::symbol-characters', `reader::symbol-regexp1' and
247 ;   `reader::symbol-regexp2' and functions `reader::lookup-symbol' and
248 ;   `reader::read-constituent' added.
249 ; - Prefix for internal symbols is now "reader::" (Common Lisp
250 ;   compatible).
251 ; - Dispatch character macro #: for reading uninterned symbols added.
252 ;
253 ; Revision 1.12  1993/11/07  19:29:07  bosch
254 ; Minor bug fix.
255 ;
256 ; Revision 1.11  1993/11/07  19:23:59  bosch
257 ; Comment added. Character read macro #\<char> rewritten. Now reads 
258 ; e.g. #\meta-control-x. Needs to be checked. 
259 ; fix in `reader::restore-shared-structure'. `cl-reader-autoinstall-function' improved.
260 ;
261 ; Revision 1.10  1993/11/06  18:35:35  bosch
262 ; Included Daniel LaLiberte's Patches.
263 ; Efficiency of `reader::restore-shared-structure' improved.
264 ; Implementation notes for shared structure reading added.
265 ;
266 ; Revision 1.9  1993/09/08  07:44:54  bosch
267 ; Comment modified.
268 ;
269 ; Revision 1.8  1993/08/10  13:43:34  bosch
270 ; Hook function `cl-reader-autoinstall-function' for automatic installation added.
271 ; Buffer local variable `cl-read-active' added: together with the above
272 ; hook it allows the file specific activation of the cl reader.
273 ;
274 ; Revision 1.7  1993/08/10  10:35:21  bosch
275 ; Functions `read*' and `read-from-string*' renamed into `reader::read'
276 ; and `reader::read-from-string'. Whitespace character skipping after
277 ; recursive reader calls removed (Emacs 19 should not need this).
278 ; Functions `cl-reader-install'  and `cl-reader-uninstall' updated.
279 ; Introduction text and  function comments added.
280 ;
281 ; Revision 1.6 1993/08/09 15:36:05 bosch Function `read*' now nearly
282 ; elisp compatible (no functions as streams, yet -- I don't think I
283 ; will ever implement this, it would be far too slow).  Elisp
284 ; compatible function `read-from-string*' added.  Replacements for
285 ; `eval-current-buffer', `eval-buffer' and `eval-region' added.
286 ; Renamed feature `cl-dg' in `cl', as Dave Gillespie's cl.el package
287 ; is rather stable now.  Function `cl-reader-install' and
288 ; `cl-reader-uninstall' modified.
289 ;
290 ; Revision 1.5  1993/08/09  10:23:35  bosch
291 ; Functions `copy-readtable' and `set-syntax-from-character' added.
292 ; Variable `reader::internal-standard-readtable' added.  Standard
293 ; readtable initialization modified. Whitespace skipping placed back
294 ; inside the read loop.
295 ;
296 ; Revision 1.4  1993/05/14  13:00:48  bosch
297 ; Included patches from Daniel LaLiberte.
298 ;
299 ; Revision 1.3  1993/05/11  09:57:39  bosch
300 ; `read*' renamed in `reader::read-from-buffer'. `read*' now can read
301 ; from strings.
302 ;
303 ; Revision 1.2  1993/05/09  16:30:50  bosch
304 ; (require 'cl-read) added.
305 ; Calling of `{before,after}-read-hook' modified.
306 ;
307 ; Revision 1.1  1993/03/29  19:37:21  bosch
308 ; Initial revision
309 ;
310 ;
311 \f
312 ;;; Code:
313
314 (require 'cl)
315 ;; Thou shalt evaluate a defadvice only once, or thou shalt surely lose. -sb
316 (require 'advise-eval-region)
317
318 ;; load before compiling
319 ;; This is ugly, but apparently the only way to do it :-(  -sb
320 (provide 'cl-read)
321 (require 'cl-read)
322
323 ;; bootstrapping with cl-packages
324 ;; defpackage and in-package are ignored until cl-read is installed.
325 '(defpackage reader
326   (:nicknames "rd")
327   (:use el)
328   (:export
329    cl-read-active
330    copy-readtable
331    set-macro-character
332    get-macro-character
333    set-syntax-from-character
334    make-dispatch-macro-character
335    set-dispatch-macro-character
336    get-dispatch-macro-character
337    before-read-hook
338    after-read-hook
339    cl-reader-install
340    cl-reader-uninstall
341    read-syntax
342    cl-reader-autoinstall-function))
343
344 '(in-package reader)
345 \f
346
347 (autoload 'compiled-function-p "bytecomp")
348
349 ;; This makes cl-read behave as a kind of minor mode: 
350
351 (make-variable-buffer-local 'cl-read-active)
352 (defvar cl-read-active nil
353   "Buffer local variable that enables Common Lisp style syntax reading.")
354 (setq-default cl-read-active nil)
355
356 (or (assq 'cl-read-active minor-mode-alist)
357     (setq minor-mode-alist
358           (cons '(cl-read-active " CL") minor-mode-alist)))
359
360 ;; Define a new error symbol: invalid-cl-read-syntax
361 ;; XEmacs change
362 (define-error 'invalid-cl-read-syntax "Invalid CL read syntax"
363   'invalid-read-syntax)
364
365 (defun reader::error (msg &rest args)
366   (signal 'invalid-cl-read-syntax (list (apply 'format msg args))))
367
368 \f
369 ;; The readtable
370
371 (defvar reader::readtable-size 256
372   "The size of a readtable."
373   ;; Actually, the readtable is a vector of size (1+
374   ;; reader::readtable-size), because the last element contains the
375   ;; symbol `readtable', used for defining `readtablep.
376   )
377
378 ;; An entry of the readtable must have one of the following forms:
379 ;;
380 ;; 1. A symbol, one of {illegal, constituent, whitespace}.  It means 
381 ;;    the character's reader class.
382 ;;
383 ;; 2. A function (i.e., a symbol with a function definition, a byte
384 ;;    compiled function or an uncompiled lambda expression).  It means the
385 ;;    character is a macro character.
386 ;;
387 ;; 3. A vector of length `reader::readtable-size'. Elements of this vector
388 ;;    may be `nil' or a function (see 2.). It means the character is a
389 ;;    dispatch character, and the vector its dispatch function table.
390
391 (defvar *readtable*)
392 (defvar reader::internal-standard-readtable)
393
394 (defun* copy-readtable 
395     (&optional (from-readtable *readtable*) 
396                (to-readtable 
397                 (make-vector (1+ reader::readtable-size) 'illegal)))
398   "Return a copy of FROM-READTABLE \(default: *readtable*\). If the
399 FROM-READTABLE argument is provided as `nil', make a copy of a
400 standard \(CL-like\) readtable. If TO-READTABLE is provided, modify and
401 return it, otherwise create a new readtable object."
402
403   (if (null from-readtable)
404       (setq from-readtable reader::internal-standard-readtable))
405
406   (loop for i to reader::readtable-size
407         as from-syntax = (aref from-readtable i)
408         do (setf (aref to-readtable i)
409                  (if (vectorp from-syntax)
410                      (copy-sequence from-syntax)
411                    from-syntax))
412         finally return to-readtable))
413
414
415 (defmacro reader::get-readtable-entry (char readtable)
416   (` (aref (, readtable) (, char))))
417    
418 (defun set-macro-character 
419   (char function &optional readtable)
420     "Makes CHAR to be a macro character with FUNCTION as handler.
421 When CHAR is seen by reader::read-from-buffer, it calls FUNCTION.
422 Returns always t. Optional argument READTABLE is the readtable to set
423 the macro character in (default: *readtable*)."
424   (or readtable (setq readtable *readtable*))
425   (or (reader::functionp function) 
426       (reader::error "Not valid character macro function: %s" function)) 
427   (setf (reader::get-readtable-entry char readtable) function)
428   t)
429
430
431 (put 'set-macro-character 'edebug-form-spec 
432      '(&define sexp function-form &optional sexp))
433 (put 'set-macro-character 'lisp-indent-function 1)
434
435 (defun get-macro-character (char &optional readtable)
436    "Return the function associated with the character CHAR.
437 Optional READTABLE defaults to *readtable*. If char isn't a macro
438 character in READTABLE, return nil."
439    (or readtable (setq readtable *readtable*))
440    (let ((entry (reader::get-readtable-entry char readtable)))
441      (if (reader::functionp entry) 
442          entry)))
443
444 (defun set-syntax-from-character 
445   (to-char from-char &optional to-readtable from-readtable)   
446   "Make the syntax of TO-CHAR be the same as the syntax of FROM-CHAR.
447 Optional TO-READTABLE and FROM-READTABLE are the corresponding tables
448 to use. TO-READTABLE defaults to the current readtable
449 \(*readtable*\), and FROM-READTABLE to nil, meaning to use the
450 syntaxes from the standard Lisp Readtable."
451   (or to-readtable (setq to-readtable *readtable*))
452   (or from-readtable 
453       (setq from-readtable reader::internal-standard-readtable))
454   (let ((from-syntax
455          (reader::get-readtable-entry from-char from-readtable)))
456     (if (vectorp from-syntax)
457         ;; dispatch macro character table
458         (setq from-syntax (copy-sequence from-syntax)))
459     (setf (reader::get-readtable-entry to-char to-readtable)
460           from-syntax))
461   t)
462
463
464 ;; Dispatch macro character
465 (defun make-dispatch-macro-character (char &optional readtable)
466   "Let CHAR be a dispatch macro character in READTABLE (default: *readtable*)."
467   (or readtable (setq readtable *readtable*))
468   (setf (reader::get-readtable-entry char readtable)
469         ;; create a dispatch character table 
470         (make-vector reader::readtable-size nil)))
471
472
473 (defun set-dispatch-macro-character 
474   (disp-char sub-char function &optional readtable)
475   "Make reading CHAR1 followed by CHAR2 be handled by FUNCTION.
476 Optional argument READTABLE (default: *readtable*).  CHAR1 must first be 
477 made a dispatch char with `make-dispatch-macro-character'."
478   (or readtable (setq readtable *readtable*))
479   (let ((disp-table (reader::get-readtable-entry disp-char readtable)))
480     ;; check whether disp-char is a valid dispatch character
481     (or (vectorp disp-table)
482         (reader::error "`%c' not a dispatch macro character." disp-char))
483     ;; check whether function is a valid function 
484     (or (reader::functionp function) 
485         (reader::error "Not valid dispatch character macro function: %s" 
486                        function))
487     (setf (aref disp-table sub-char) function)))
488
489 (put 'set-dispatch-macro-character 'edebug-form-spec
490      '(&define sexp sexp function-form &optional sexp))
491 (put 'set-dispatch-macro-character 'lisp-indent-function 2)
492
493
494 (defun get-dispatch-macro-character 
495   (disp-char sub-char &optional readtable)
496   "Return the macro character function for SUB-CHAR unser DISP-CHAR.
497 Optional READTABLE defaults to *readtable*.
498 Returns nil if there is no such function."
499   (or readtable (setq readtable *readtable*))
500   (let ((disp-table (reader::get-readtable-entry disp-char readtable)))
501     (and (vectorp disp-table)
502          (reader::functionp (aref disp-table sub-char))
503          (aref disp-table sub-char))))
504
505
506 (defun reader::functionp (function)
507   ;; Check whether FUNCTION is a valid function object to be used 
508   ;; as (dispatch) macro character function.
509   (or (and (symbolp function) (fboundp function))
510       (compiled-function-p function)
511       (and (consp function) (eq (first function) 'lambda))))
512            
513 \f
514 ;; The basic reader loop 
515
516 ;; shared and circular structure reading
517 (defvar reader::shared-structure-references nil)
518 (defvar reader::shared-structure-labels nil)
519
520 (defun reader::read-sexp-func (point func)
521   ;; This function is called to read a sexp at POINT by calling FUNC.
522   ;; reader::read-sexp-func is here to be advised, e.g. by Edebug,
523   ;; to do something before or after reading.
524   (funcall func))
525
526 (defmacro reader::read-sexp (point &rest body)
527   ;; Called to return a sexp starting at POINT.  BODY creates the sexp result
528   ;; and should leave point after the sexp.  The body is wrapped in
529   ;; a lambda expression and passed to reader::read-sexp-func.
530   (` (reader::read-sexp-func (, point) (function (lambda () (,@ body))))))
531
532 (put 'reader::read-sexp 'edebug-form-spec '(form body))
533 (put 'reader::read-sexp 'lisp-indent-function 2)
534 (put 'reader::read-sexp 'lisp-indent-hook 1)  ;; Emacs 18
535
536
537 (defconst before-read-hook nil)
538 (defconst after-read-hook nil)
539
540 ;; Set the hooks to `read-char' in order to step through the reader. e.g.
541 ;; (add-hook 'before-read-hook '(lambda () (message "before") (read-char)))
542 ;; (add-hook 'after-read-hook '(lambda () (message "after") (read-char)))
543
544 (defmacro reader::encapsulate-recursive-call (reader-call)
545   ;; Encapsulate READER-CALL, a form that contains a recursive call to
546   ;; the reader, for usage inside the main reader loop.  The macro
547   ;; wraps two hooks around READER-CALL: `before-read-hook' and
548   ;; `after-read-hook'.
549   ;;
550   ;; If READER-CALL returns normally, the macro exits immediately from
551   ;; the surrounding loop with the value of READER-CALL as result.  If
552   ;; it exits non-locally (with tag `reader-ignore'), it just returns
553   ;; the value of READER-CALL, in which case the surrounding reader
554   ;; loop continues its execution.
555   ;;
556   ;; In both cases, `before-read-hook' and `after-read-hook' are
557   ;; called before and after executing READER-CALL.
558   ;; Are there any other uses for these hooks?  Edebug doesn't need them.
559   (` (prog2
560          (run-hooks 'before-read-hook)
561          ;; this catch allows to ignore the return, in the case that
562          ;; reader::read-from-buffer should continue looping (e.g.
563          ;; skipping over comments)
564          (catch 'reader-ignore
565            ;; this only works inside a block (e.g., in a loop): 
566            ;; go outside 
567            (return 
568             (prog1 
569                 (, reader-call)
570               ;; this occurrence of the after hook fires if the 
571               ;; reader-call returns normally ...
572               (run-hooks 'after-read-hook))))
573        ;; ... and that one if  it was thrown to the tag 'reader-ignore
574        (run-hooks 'after-read-hook))))
575
576 (put 'reader::encapsulate-recursive-call 'edebug-form-spec '(form))
577 (put 'reader::encapsulate-recursive-call 'lisp-indent-function 0)
578
579 (defun reader::read-from-buffer (&optional stream reader::recursive-p)
580   (or (bufferp stream)
581       (reader::error "Sorry, can only read on buffers"))
582   (if (not reader::recursive-p)
583       ;; set up environment for shared structure reading
584       (let (reader::shared-structure-references
585             reader::shared-structure-labels
586             tmp-sexp)
587         ;; the reader returns an unshared sexpr, possibly containing
588         ;; symbolic references
589         (setq tmp-sexp (reader::read-from-buffer stream 't))
590         (if ;; sexpr actually contained shared structures
591             reader::shared-structure-references
592             (reader::restore-shared-structure tmp-sexp)
593           ;; it did not, so don't bother about restoring
594           tmp-sexp))
595
596     (loop for char = (following-char)
597           for entry = (reader::get-readtable-entry  char *readtable*)
598           if (eobp) do (reader::error "End of file during reading")
599           do 
600           (cond 
601
602            ((eq entry 'illegal)
603             (reader::error "`%c' has illegal character syntax" char))
604
605            ;; skipping whitespace characters must be done inside this
606            ;; loop as character macro subroutines may return without
607            ;; leaving the loop using (throw 'reader-ignore ...)
608            ((eq entry 'whitespace)
609             (forward-char 1)  
610             ;; skip all whitespace
611             (while (eq 'whitespace 
612                        (reader::get-readtable-entry  
613                         (following-char) *readtable*))
614               (forward-char 1)))
615
616            ;; for every token starting with a constituent character
617            ;; call the built-in reader (symbols, numbers, strings,
618            ;; characters with ?<char> syntax)
619            ((eq entry 'constituent)    
620             (reader::encapsulate-recursive-call
621              (reader::read-constituent stream)))
622
623            ((vectorp entry)
624             ;; Dispatch macro character. The dispatch macro character
625             ;; function is contained in the vector `entry', at the
626             ;; place indicated by <sub-char>, the first non-digit
627             ;; character following the <disp-char>:
628             ;;  <disp-char><digit>*<sub-char>
629             (reader::encapsulate-recursive-call
630               (loop initially do (forward-char 1)
631                     for sub-char = (prog1 (following-char) 
632                                      (forward-char 1))
633                     while (memq sub-char 
634                                 '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9))
635                     collect sub-char into digit-args
636                     finally 
637                     (return 
638                      (funcall 
639                       ;; no test is done here whether a non-nil
640                       ;; contents is a correct dispatch character
641                       ;; function to apply.
642                       (or (aref entry sub-char)
643                           (reader::error
644                            "Undefined subsequent dispatch character `%c'" 
645                            sub-char))
646                       stream
647                       sub-char 
648                       (string-to-int
649                        (apply 'concat 
650                               (mapcar 
651                                'char-to-string digit-args))))))))
652             
653            (t
654             ;; must be a macro character. In this case, `entry' is
655             ;; the function to be called
656             (reader::encapsulate-recursive-call
657               (progn 
658                 (forward-char 1)
659                 (funcall entry stream char))))))))
660
661
662 ;; Constituent reader fix for Emacs 18
663 (if (string-match "^19" emacs-version)
664     (defun reader::read-constituent (stream)
665       (reader::read-sexp (point)
666         (reader::original-read stream)))
667
668   (defun reader::read-constituent (stream)
669     (reader::read-sexp (point)
670       (prog1 (reader::original-read stream)
671         ;; For Emacs 18, backing up is necessary because the `read' function 
672         ;; reads one character too far after reading a symbol or number.
673         ;; This doesnt apply to reading chars (e.g. ?n).
674         ;; This still loses for escaped chars.
675         (if (not (eq (reader::get-readtable-entry
676                       (preceding-char) *readtable*) 'constituent))
677             (forward-char -1))))))
678
679 \f
680 ;; Make the default current CL readtable
681
682 (defconst *readtable*
683   (loop with raw-readtable = 
684         (make-vector (1+ reader::readtable-size) 'illegal)
685         initially do (setf (aref raw-readtable reader::readtable-size)
686                            'readtable)
687         for entry in 
688         '((constituent ?! ?@ ?$ ?% ?& ?* ?_ ?- ?+ ?= ?/ ?\\ ?0 ?1 ?2
689                        ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?: ?~ ?> ?< ?a ?b
690                        ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m ?n ?o ?p
691                        ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z ?A ?B ?C ?D
692                        ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O ?P ?Q ?R
693                        ?S ?T ?U ?V ?W ?X ?Y ?Z)
694           (whitespace ?  ?\t ?\n ?\r ?\f)
695
696           ;; The following CL character classes are only useful for
697           ;; token parsing.  We don't need them, as token parsing is
698           ;; left to the built-in reader.
699           ;; (single-escape ?\\)
700           ;; (multiple-escape ?|)
701           )
702         do 
703         (loop for char in (rest entry)
704               do (setf (reader::get-readtable-entry  char raw-readtable)
705                        (first entry)))
706         finally return raw-readtable)
707   "The current readtable.")
708
709
710 ;; Variables used non-locally in the standard readmacros
711 (defvar reader::context)
712 (defvar reader::stack)
713 (defvar reader::recursive-p)
714
715 \f
716 ;;;; Read macro character definitions
717
718 ;;; Hint for modifying, testing and debugging new read macros: All the
719 ;;; read macros and dispatch character macros below are defined in
720 ;;; the `*readtable*'.  Modifications or
721 ;;; instrumenting with edebug are effective immediately without having to
722 ;;; copy the internal readtable to the standard *readtable*.  However,
723 ;;; if you wish to modify reader::internal-standard-readtable, then
724 ;;; you must recopy *readtable*.
725
726 ;; Chars and strings
727
728 ;; This is defined to distinguish chars from constituents 
729 ;; since chars are read by the standard reader without reading too far.
730 (set-macro-character ?\?
731   (function
732    (lambda (stream char)
733      (forward-char -1)
734      (reader::read-sexp (point)
735        (reader::original-read stream)))))
736
737 ;; ?\M-\C-a
738
739 ;; This is defined to distinguish strings from constituents
740 ;; since backing up after reading a string is simpler.
741 (set-macro-character ?\"
742   (function
743    (lambda (stream char)
744      (forward-char -1)
745      (reader::read-sexp (point)
746        (prog1 (reader::original-read stream)
747          ;; This is not needed with Emacs 19, but it is OK.  See above.
748          (if (/= (preceding-char) ?\")
749              (forward-char -1)))))))
750
751 ;; Lists and dotted pairs
752 (set-macro-character ?\( 
753   (function 
754    (lambda (stream char)
755      (reader::read-sexp (1- (point))
756        (catch 'read-list
757          (let ((reader::context 'list) reader::stack )
758            ;; read list elements up to a `.'
759            (catch 'dotted-pair
760              (while t
761                (setq reader::stack (cons (reader::read-from-buffer stream 't) 
762                                          reader::stack))))
763            ;; In dotted pair. Read one more element
764            (setq reader::stack (cons (reader::read-from-buffer stream 't) 
765                                      reader::stack)
766                  ;; signal it to the closing paren
767                  reader::context 'dotted-pair)
768            ;; Next char *must* be the closing paren that throws read-list
769            (reader::read-from-buffer stream 't)
770            ;; otherwise an error is signalled
771            (reader::error "Illegal dotted pair read syntax")))))))
772
773 (set-macro-character ?\) 
774   (function 
775    (lambda (stream char)
776      (cond ((eq reader::context 'list)
777             (throw 'read-list (nreverse reader::stack)))
778            ((eq reader::context 'dotted-pair)
779             (throw 'read-list (nconc (nreverse (cdr reader::stack)) 
780                                      (car reader::stack))))
781            (t 
782             (reader::error "`)' doesn't end a list"))))))
783         
784 (set-macro-character ?\.
785   (function 
786    (lambda (stream char)
787      (and (eq reader::context 'dotted-pair) 
788           (reader::error "No more than one `.' allowed in list"))
789      (throw 'dotted-pair nil))))
790
791 ;; '(#\a . #\b)
792 ;; '(a . (b . c))
793
794 ;; Vectors: [a b]
795 (set-macro-character ?\[
796   (function
797    (lambda (stream char)
798      (reader::read-sexp (1- (point))
799        (let ((reader::context 'vector))
800          (catch 'read-vector
801            (let ((reader::context 'vector)
802                  reader::stack)
803              (while t (push (reader::read-from-buffer stream 't)
804                             reader::stack)))))))))
805
806 (set-macro-character ?\] 
807   (function 
808    (lambda (stream char)
809      (if (eq reader::context 'vector)
810          (throw 'read-vector (apply 'vector (nreverse reader::stack)))
811        (reader::error "`]' doesn't end a vector"))))) 
812
813 ;; Quote and backquote/comma macro
814 (set-macro-character ?\'
815   (function
816    (lambda (stream char)
817      (reader::read-sexp (1- (point))
818        (list (reader::read-sexp (point) 'quote)
819              (reader::read-from-buffer stream 't))))))
820
821 (set-macro-character ?\`
822   (function
823    (lambda (stream char)
824      (if (= (following-char) ?\ )
825          ;; old backquote syntax. This is ambiguous, because 
826          ;; (`(sexp)) is a valid form in both syntaxes, but 
827          ;; unfortunately not the same. 
828          ;; old syntax: read -> (` (sexp))
829          ;; new syntax: read -> ((` (sexp)))
830          (reader::read-sexp (1- (point)) '\`)
831        (reader::read-sexp (1- (point))
832          (list (reader::read-sexp (point) '\`)
833                (reader::read-from-buffer stream 't)))))))
834
835 (set-macro-character ?\,
836   (function
837    (lambda (stream char)
838      (cond ((eq (following-char) ?\ )
839             ;; old syntax
840             (reader::read-sexp (point) '\,))
841            ((eq (following-char) ?\@)
842             (forward-char 1)
843             (cond ((eq (following-char) ?\ )
844                    (reader::read-sexp (point) '\,\@))
845                   (t
846                    (reader::read-sexp (- (point) 2)
847                      (list 
848                       (reader::read-sexp (point) '\,\@)
849                       (reader::read-from-buffer stream 't))))))
850            (t
851             (reader::read-sexp (1- (point))
852               (list
853                (reader::read-sexp (1- (point)) '\,)
854                (reader::read-from-buffer stream 't))))))))
855
856 ;; 'a
857 ;; '(a b c)
858 ;; (let ((a 10) (b '(20 30))) `(,a ,@b c))
859 ;; the old syntax is also supported:
860 ;; (let ((a 10) (b '(20 30))) (` ((, a) (,@ b) c)))
861
862 ;; Single line character comment:  ; 
863 (set-macro-character ?\;
864   (function
865    (lambda (stream char)
866      (skip-chars-forward "^\n\r")
867      (throw 'reader-ignore nil))))
868
869
870 \f
871 ;; Dispatch character character #
872 (make-dispatch-macro-character ?\#)
873
874 (defsubst reader::check-0-infix (n)
875   (or (= n 0) 
876       (reader::error "Numeric infix argument not allowed: %d" n)))
877
878
879 (defalias 'search-forward-regexp 're-search-forward)
880
881 ;; nested multi-line comments #| ... |#
882 (set-dispatch-macro-character ?\# ?\|
883   (function 
884    (lambda (stream char n)
885      (reader::check-0-infix n)
886      (let ((counter 0))
887        (while (search-forward-regexp "#|\\||#" nil t)
888          (if (string-equal
889               (buffer-substring
890                (match-beginning 0) (match-end 0))
891               "|#")
892              (cond ((> counter 0)
893                     (decf counter))
894                    ((= counter 0)
895                     ;; stop here
896                     (goto-char (match-end 0))
897                     (throw 'reader-ignore nil))
898                    ('t
899                     (reader::error "Unmatching closing multicomment")))
900            (incf counter)))
901        (reader::error "Unmatching opening multicomment")))))
902
903 ;; From cl-packages.el
904 (defconst reader::symbol-characters "[A-Za-z0-9-_!@$%^&*+=|~{}<>/]")
905 (defconst reader::symbol-regexp2
906   (format "\\(%s+\\)" reader::symbol-characters))
907
908 (set-dispatch-macro-character ?\# ?\:
909   (function
910    (lambda (stream char n)
911      (reader::check-0-infix n)
912      (or (looking-at reader::symbol-regexp2)
913          (reader::error "Invalid symbol read syntax"))
914      (goto-char (match-end 0))
915      (make-symbol 
916       (buffer-substring (match-beginning 0) (match-end 0))))))
917
918 ;; Function quoting: #'<function>
919 (set-dispatch-macro-character ?\# ?\'
920   (function
921    (lambda (stream char n)
922      (reader::check-0-infix n)
923      ;; Probably should test if cl is required by current buffer.
924      ;; Currently, cl will always be a feature because cl-read requires it.
925      (reader::read-sexp (- (point) 2)
926        (list 
927         (reader::read-sexp (point) (if (featurep 'cl)  'function* 'function))
928         (reader::read-from-buffer stream 't))))))
929
930 ;; Character syntax: #\<char> 
931 ;; Not yet implemented: #\Control-a #\M-C-a etc. 
932 ;; This definition is not used - the next one is more general.
933 '(set-dispatch-macro-character ?# ?\\
934   (function 
935    (lambda (stream char n)
936      (reader::check-0-infix n)
937      (let ((next (following-char))
938            name)
939        (if (not (and (<= ?a next) (<= next ?z)))
940            (progn (forward-char 1) next)
941          (setq next (reader::read-from-buffer stream t))
942          (cond ((symbolp next) (setq name (symbol-name next)))
943                ((integerp next) (setq name (int-to-string next))))
944          (if (= 1 (length name))
945              (string-to-char name)
946            (case next
947              (linefeed  ?\n)
948              (newline   ?\r)
949              (space     ?\ )
950              (rubout    ?\b)
951              (page      ?\f)
952              (tab       ?\t)
953              (return    ?\C-m)
954              (t
955               (reader::error "Unknown character specification `%s'"
956                              next))))))))
957   )
958
959 (defvar reader::special-character-name-table
960   '(("linefeed" . ?\n)
961     ("newline"  . ?\r)
962     ("space"    . ?\ )
963     ("rubout"   . ?\b)
964     ("page"     . ?\f)
965     ("tab"        . ?\t)
966     ("return"   . ?\C-m)))
967
968 (set-dispatch-macro-character ?# ?\\
969   (function 
970    (lambda (stream char n)
971      (reader::check-0-infix n)
972      (forward-char -1)
973      ;; We should read in a special package to avoid creating symbols.
974      (let ((symbol (reader::read-from-buffer stream t))
975            (case-fold-search t)
976            name modifier character char-base)
977        (setq name (symbol-name symbol))
978        (if (string-match "^\\(meta-\\|m-\\|control-\\|c-\\)+" name)
979            (setq modifier (substring name
980                                      (match-beginning 1)
981                                      (match-end 1))
982                  character (substring name (match-end 1)))
983          (setq character name))
984        (setq char-base 
985              (cond ((= (length character) 1)
986                     (string-to-char character))
987                    ('t 
988                     (cdr (assoc character 
989                                 reader::special-character-name-table)))))
990        (or char-base 
991            (reader::error
992             "Unknown character specification `%s'" character))
993         
994        (and modifier
995             (progn 
996               (and (string-match "control-\\|c-" modifier)
997                    (decf char-base 32))
998               (and (string-match "meta-\\|m-" modifier)
999                    (incf char-base 128))))
1000        char-base))))
1001
1002 ;; '(#\meta-space #\tab #\# #\> #\< #\a #\A  #\return #\space)
1003 ;; (eq #\m-tab ?\M-\t)
1004 ;; (eq #\c-m-x #\m-c-x)
1005 ;; (eq #\Meta-Control-return #\M-C-return)
1006 ;; (eq #\m-m-c-c-x #\m-c-x)
1007 ;; #\C-space #\C-@ ?\C-@
1008
1009
1010
1011 ;; Read and load time evaluation:  #.<form>
1012 ;; Not yet implemented: #,<form>
1013 (set-dispatch-macro-character ?\# ?\.
1014   (function 
1015    (lambda (reader::stream reader::char reader::n)
1016      (reader::check-0-infix reader::n)
1017      ;; This eval will see all internal vars of reader, 
1018      ;; e.g. stream, reader::recursive-p.  Anything that might be bound.
1019      ;; We must use `read' here rather than read-from-buffer with 'recursive-p
1020      ;; because the expression must not have unresolved #n#s in it anyway.
1021      ;; Otherwise the top-level expression must be completely read before
1022      ;; any embedded evaluation(s) occur(s).  CLtL2 does not specify this.
1023      ;; Also, call `read' so that it may be customized, by e.g. Edebug
1024      (eval (read reader::stream)))))
1025 ;; '(#.(current-buffer) #.(get-buffer "*scratch*"))
1026
1027 ;; Path names (kind of):  #p<string>, #P<string>,
1028 (set-dispatch-macro-character ?\# ?\P
1029   (function 
1030    (lambda (stream char n)
1031      (reader::check-0-infix n)
1032      (let ((string (reader::read-from-buffer stream 't)))
1033        (or (stringp string) 
1034            (reader::error "Pathname must be a string: %s" string))
1035        (expand-file-name string)))))
1036
1037 (set-dispatch-macro-character ?\# ?\p
1038   (get-dispatch-macro-character ?\# ?\P))
1039
1040 ;; #P"~/.emacs"
1041 ;; #p"~root/home" 
1042
1043 ;; Feature reading:  #+<feature>,  #-<feature>
1044 ;; Not yet implemented: #+<boolean expression>, #-<boolean expression>
1045
1046
1047 (defsubst reader::read-feature (stream char n flag)
1048   (reader::check-0-infix n)
1049   (let (;; Use the original reader to only read the feature.
1050         ;; This is not exactly correct without *read-suppress*.
1051         ;; Also Emacs 18 read goes one too far,
1052         ;; so we assume there is a space after the feature.
1053         (feature (reader::original-read stream))
1054         (object (reader::read-from-buffer stream 't)))
1055     (if (eq (featurep feature) flag)
1056         object
1057       ;; Ignore it.
1058       (throw 'reader-ignore nil))))
1059
1060 (set-dispatch-macro-character ?\# ?\+
1061   (function 
1062    (lambda (stream char n)
1063      (reader::read-feature stream char n t))))
1064
1065 (set-dispatch-macro-character ?\# ?\-
1066   (function 
1067    (lambda (stream char n)
1068      (reader::read-feature stream char n nil))))
1069
1070 ;; (#+cl loop #+cl do #-cl while #-cl t (body))
1071
1072
1073
1074 \f
1075 ;; Shared structure reading: #<n>=, #<n>#
1076
1077 ;; Reading of sexpression with shared and circular structure read
1078 ;; syntax  is done in two steps:
1079 ;; 
1080 ;; 1. Create an sexpr with unshared structures, just as the ordinary
1081 ;;    read macros do, with two exceptions: 
1082 ;;    - each label (#<n>=) creates, as a side effect, a symbolic
1083 ;;      reference for the sexpr that follows it
1084 ;;    - each reference (#<n>#) is replaced by the corresponding
1085 ;;      symbolic reference. 
1086 ;;
1087 ;; 2. This non-cyclic and unshared lisp structure is given to the
1088 ;;    function `reader::restore-shared-structure' (see
1089 ;;    `reader::read-from-buffer'), which simply replaces
1090 ;;    destructively all symbolic references by the lisp structures the
1091 ;;    references point at. 
1092 ;;
1093 ;; A symbolic reference is an uninterned symbol whose name is obtained
1094 ;; from the label/reference number using the function `int-to-string': 
1095 ;;
1096 ;; There are two non-locally used variables (bound in
1097 ;; `reader::read-from-buffer') which control shared structure reading: 
1098 ;; `reader::shared-structure-labels': 
1099 ;;      A list of integers that correspond to the label numbers <n> in
1100 ;;      the string currently read. This is used to avoid multiple
1101 ;;      definitions of the same label.
1102 ;; `reader::shared-structure-references': 
1103 ;;      The list of symbolic references that will be used as temporary
1104 ;;      placeholders for the shared objects introduced by a reference
1105 ;;      with the same number identification.
1106
1107 (set-dispatch-macro-character ?\# ?\=
1108   (function 
1109    (lambda (stream char n)
1110      (and (= n 0) (reader::error "0 not allowed as label"))
1111      ;; check for multiple definition of the same label
1112      (if (memq n reader::shared-structure-labels)
1113          (reader::error "Label defined twice")
1114        (push n reader::shared-structure-labels))
1115      ;; create an uninterned symbol as symbolic reference for the label
1116      (let* ((string (int-to-string n))
1117             (ref (or (find string reader::shared-structure-references
1118                            :test 'string=)
1119                      (first 
1120                       (push (make-symbol string) 
1121                             reader::shared-structure-references)))))
1122        ;; the link between the symbolic reference and the lisp
1123        ;; structure it points at is done using the symbol value cell
1124        ;; of the reference symbol.
1125        (setf (symbol-value ref) 
1126              ;; this is also the return value 
1127              (reader::read-from-buffer stream 't))))))
1128
1129
1130 (set-dispatch-macro-character ?\# ?\#
1131   (function
1132    (lambda (stream char n)
1133      (and (= n 0) (reader::error "0 not allowed as label"))
1134      ;; use the non-local variable `reader::recursive-p' (from the reader
1135      ;; main loop) to detect labels at the top level of an sexpr.
1136      (if (not reader::recursive-p)
1137          (reader::error "References at top level not allowed"))
1138      (let* ((string (int-to-string n))
1139             (ref (or (find string reader::shared-structure-references
1140                            :test 'string=)
1141                      (first
1142                       (push (make-symbol string) 
1143                             reader::shared-structure-references)))))
1144        ;; the value of reading a #n# form is a reference symbol
1145        ;; whose symbol value is or will be the shared structure. 
1146        ;; `reader::restore-shared-structure' then replaces the symbol by
1147        ;; its value.
1148        ref))))
1149
1150 (defun reader::restore-shared-structure (obj)
1151   ;; traverses recursively OBJ and replaces all symbolic references by
1152   ;; the objects they point at. Remember that a symbolic reference is
1153   ;; an uninterned symbol whose value is the object it points at. 
1154   (cond 
1155    ((consp obj)
1156     (loop for rest on obj
1157           as lastcdr = rest
1158           do
1159           (if;; substructure is a symbolic reference
1160               (memq (car rest) reader::shared-structure-references)
1161               ;; replace it by its symbol value, i.e. the associated object
1162               (setf (car rest) (symbol-value (car rest)))
1163             (reader::restore-shared-structure (car rest)))
1164           finally 
1165           (if (memq (cdr lastcdr) reader::shared-structure-references)
1166               (setf (cdr lastcdr) (symbol-value (cdr lastcdr)))
1167             (reader::restore-shared-structure (cdr lastcdr)))))
1168    ((vectorp obj)
1169     (loop for i below (length obj)
1170           do
1171           (if;; substructure  is a symbolic reference
1172               (memq (aref obj i) reader::shared-structure-references)
1173               ;; replace it by its symbol value, i.e. the associated object
1174               (setf (aref obj i) (symbol-value (aref obj i)))
1175             (reader::restore-shared-structure (aref obj i))))))
1176   obj)
1177
1178
1179 ;; #1=(a b #3=[#2=c])
1180 ;; (#1=[#\return #\a] #1# #1#)
1181 ;; (#1=[a b c] #1# #1#)
1182 ;; #1=(a b . #1#)
1183
1184 ;; Creation and initialization of an internal standard readtable. 
1185 ;; Do this after all the macros and dispatch chars above have been defined.
1186
1187 (defconst reader::internal-standard-readtable (copy-readtable)
1188   "The original (CL-like) standard readtable. If you ever modify this
1189 readtable, you won't be able to recover a standard readtable using
1190 \(copy-readtable nil\)")
1191
1192 \f
1193 ;; Replace built-in functions that call the built-in reader
1194 ;; 
1195 ;; The following functions are replaced here: 
1196 ;;
1197 ;; read                 by      reader::read
1198 ;; read-from-string     by      reader::read-from-string
1199 ;;
1200 ;; eval-expression      by      reader::eval-expression
1201 ;; Why replace eval-expression? Not needed for Lucid Emacs since the
1202 ;; reader for arguments is also written in Lisp, and so may be overridden.
1203 ;;
1204 ;; eval-current-buffer  by      reader::eval-current-buffer
1205 ;; eval-buffer          by      reader::eval-buffer
1206 ;; original-eval-region by      reader::original-eval-region
1207
1208
1209 ;; Temporary read buffer used for reading from strings
1210 (defconst reader::tmp-buffer
1211   (get-buffer-create " *CL Read*"))
1212
1213 ;; Save a pointer to the original read function
1214 (or (fboundp 'reader::original-read)
1215     (fset 'reader::original-read  (symbol-function 'read)))
1216
1217 (defun reader::read (&optional stream reader::recursive-p)
1218   "Read one Lisp expression as text from STREAM, return as Lisp object.
1219 If STREAM is nil, use the value of `standard-input' \(which see\).
1220 STREAM or the value of `standard-input' may be:
1221  a buffer \(read from point and advance it\)
1222  a marker \(read from where it points and advance it\)
1223  a string \(takes text from string, starting at the beginning\)
1224  t \(read text line using minibuffer and use it\).
1225
1226 This is the cl-read replacement of the standard elisp function
1227 `read'. The only incompatibility is that functions as stream arguments
1228 are not supported."
1229   (if (not cl-read-active)
1230       (reader::original-read stream)
1231     (if (null stream)                   ; read from standard-input
1232         (setq stream standard-input))
1233
1234     (if (eq stream 't)                  ; read from minibuffer
1235         (setq stream (read-from-minibuffer "Common Lisp Expression: ")))
1236
1237     (cond 
1238
1239      ((bufferp stream)                  ; read from buffer
1240       (reader::read-from-buffer stream reader::recursive-p))
1241
1242      ((markerp stream)                  ; read from marker
1243       (save-excursion 
1244         (set-buffer (marker-buffer stream))
1245         (goto-char (marker-position stream))
1246         (reader::read-from-buffer (current-buffer) reader::recursive-p)))
1247
1248      ((stringp stream)                  ; read from string
1249       (save-excursion
1250         (set-buffer reader::tmp-buffer)
1251         (auto-save-mode -1)
1252         (erase-buffer)
1253         (insert stream)
1254         (goto-char (point-min))
1255         (reader::read-from-buffer reader::tmp-buffer reader::recursive-p)))
1256      (t 
1257       (reader::error "Not a valid stream: %s" stream)))))
1258
1259 ;; read-from-string
1260 ;; save a pointer to the original `read-from-string' function
1261 (or (fboundp 'reader::original-read-from-string)
1262     (fset 'reader::original-read-from-string
1263           (symbol-function 'read-from-string)))
1264
1265 (defun reader::read-from-string (string &optional start end)
1266   "Read one Lisp expression which is represented as text by STRING.
1267 Returns a cons: (OBJECT-READ . FINAL-STRING-INDEX).
1268 START and END optionally delimit a substring of STRING from which to read;
1269 they default to 0 and (length STRING) respectively.
1270
1271 This is the cl-read replacement of the standard elisp function
1272 `read-from-string'.  It uses the reader macros in *readtable* if
1273 `cl-read-active' is non-nil in the current buffer."
1274
1275   ;; Does it really make sense to have read-from-string depend on
1276   ;; what the current buffer happens to be?   Yes, so code that
1277   ;; has nothing to do with cl-read uses original reader.
1278   (if (not cl-read-active)
1279       (reader::original-read-from-string string start end)
1280     (or start (setq start 0))
1281     (or end (setq end (length string)))
1282     (save-excursion
1283       (set-buffer reader::tmp-buffer)
1284       (auto-save-mode -1)
1285       (erase-buffer)
1286       (insert (substring string 0 end))
1287       (goto-char (1+ start))
1288       (cons 
1289        (reader::read-from-buffer reader::tmp-buffer nil)
1290        (1- (point))))))
1291
1292 ;; (read-from-string "abc (car 'a) bc" 4)
1293 ;; (reader::read-from-string "abc (car 'a) bc" 4)
1294 ;; (read-from-string "abc (car 'a) bc" 2 11)
1295 ;; (reader::read-from-string "abc (car 'a) bc" 2 11)
1296 ;; (reader::read-from-string "`(car ,first ,@rest)")
1297 ;; (read-from-string ";`(car ,first ,@rest)")
1298 ;; (reader::read-from-string ";`(car ,first ,@rest)")
1299
1300 ;; We should replace eval-expression, too, so that it reads (and
1301 ;; evals) in the current buffer.  Alternatively, this could be fixed
1302 ;; in C.  In Lemacs 19.6 and later, this function is already written
1303 ;; in lisp, and based on more primitive read functions we already
1304 ;; replaced. The reading happens during the interactive parameter
1305 ;; retrieval, which is written in lisp, too.  So this replacement of
1306 ;; eval-expression is only required for (FSF) Emacs 18 (and 19?).
1307
1308 (or (fboundp 'reader::original-eval-expression)
1309     (fset 'reader::original-eval-expression 
1310           (symbol-function 'eval-expression)))
1311
1312 (defun reader::eval-expression (reader::expression)
1313   "Evaluate EXPRESSION and print value in minibuffer.
1314 Value is also consed on to front of variable `values'."
1315   (interactive 
1316    (list
1317     (car (read-from-string
1318           (read-from-minibuffer 
1319            "Eval: " nil 
1320            ;;read-expression-map ;; not for emacs 18
1321            nil ;; use default map
1322            nil ;; don't do read with minibuffer current.
1323            ;; 'edebug-expression-history ;; not for emacs 18
1324            )))))
1325   (setq values (cons (eval reader::expression) values))
1326   (prin1 (car values) t))
1327
1328 (require 'eval-reg "eval-reg")
1329 ; (require 'advice)
1330
1331 \f
1332 ;; installing/uninstalling the cl reader
1333 ;; These two should always be used in pairs, or just install once and
1334 ;; never uninstall. 
1335 (defun cl-reader-install ()
1336   (interactive)
1337   (fset 'read                   'reader::read)
1338   (fset 'read-from-string       'reader::read-from-string)
1339   (fset 'eval-expression        'reader::eval-expression)
1340   (elisp-eval-region-install))
1341
1342 (defun cl-reader-uninstall ()
1343   (interactive)
1344   (fset 'read                  
1345         (symbol-function 'reader::original-read))
1346   (fset 'read-from-string       
1347         (symbol-function 'reader::original-read-from-string))
1348   (fset 'eval-expression
1349         (symbol-function 'reader::original-eval-expression))
1350   (elisp-eval-region-uninstall))
1351
1352 ;; Globally installing the cl-read replacement functions is safe, even
1353 ;; for buffers without cl read syntax. The buffer local variable
1354 ;; `cl-read-active' controls whether the replacement functions of this
1355 ;; package or the original ones are actually called.
1356 (cl-reader-install)
1357 (cl-reader-uninstall)
1358
1359 (add-hook 'emacs-lisp-mode-hook 'cl-reader-autoinstall-function)
1360
1361 '(defvar read-syntax)
1362
1363 '(defun cl-reader-autoinstall-function () 
1364   "Activates the Common Lisp style reader for emacs-lisp-mode buffers,
1365 if the property line has a local variable setting like this: 
1366 \;\; -*- Read-Syntax: Common-Lisp -*-"
1367   ;; this is a hack to avoid recursion in the case that the prop line 
1368   ;; containes "Mode: emacs-lisp" entry
1369   (or (boundp 'local-variable-hack-done)
1370       (let (local-variable-hack-done
1371             (case-fold-search t))
1372         ;; Usually `hack-local-variables-prop-line' is called only after
1373         ;; installation of the major mode. But we need to know about the
1374         ;; local variables before that, so we call the local variable hack
1375         ;; explicitly here:
1376         (hack-local-variables-prop-line 't)
1377         ;; But hack-local-variables-prop-line not defined in emacs 18.
1378         (cond 
1379          ((and (boundp 'read-syntax)
1380                read-syntax
1381                (string-match "^common-lisp$" (symbol-name read-syntax)))
1382           (require 'cl-read)
1383           (make-local-variable 'cl-read-active)
1384           (setq cl-read-active 't))))))
1385
1386 ;; Emacs 18 doesnt have hack-local-variables-prop-line.  So use this instead.
1387 (defun cl-reader-autoinstall-function ()
1388   (save-excursion
1389     (goto-char (point-min))
1390     (let ((case-fold-search t))
1391       (cond ((re-search-forward 
1392               "read-syntax: *common-lisp" 
1393               (save-excursion 
1394                 (end-of-line)
1395                 (point))
1396               t)
1397              (require 'cl-read)
1398              (make-local-variable 'cl-read-active)
1399              (setq cl-read-active t))))))
1400
1401 \f
1402 (run-hooks 'cl-read-load-hooks)
1403
1404 ;; cl-read.el ends here