format.lisp 63.4 KB
Newer Older
1
;;; -*- Package: FORMAT -*-
ram's avatar
ram committed
2
3
;;;
;;; **********************************************************************
4
5
6
7
8
9
;;; This code was written as part of the CMU Common Lisp project at
;;; Carnegie Mellon University, and has been placed in the public domain.
;;; If you want to use this code or any part of CMU Common Lisp, please contact
;;; Scott Fahlman or slisp-group@cs.cmu.edu.
;;;
(ext:file-comment
10
  "$Header: /Volumes/share2/src/cmucl/cvs2git/cvsroot/src/code/format.lisp,v 1.18 1991/12/02 23:58:27 wlott Exp $")
11
;;;
ram's avatar
ram committed
12
13
;;; **********************************************************************
;;;
14
;;; Functions to implement FORMAT and FORMATTER for CMU Common Lisp.
ram's avatar
ram committed
15
;;;
16
17
18
;;; Written by William Lott, with lots of stuff stolen from the previous
;;; version by David Adam and later rewritten by Bill Maddox.
;;; 
ram's avatar
ram committed
19

20
21
(in-package "FORMAT")
(use-package "EXT")
22
(import 'kernel:index)
ram's avatar
ram committed
23

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
(in-package "LISP")
(export '(format formatter))

(in-package "FORMAT")

(defstruct (format-directive
	    (:print-function %print-format-directive))
  (string (required-argument) :type simple-string)
  (start (required-argument) :type (and unsigned-byte fixnum))
  (end (required-argument) :type (and unsigned-byte fixnum))
  (character (required-argument) :type base-character)
  (colonp nil :type (member t nil))
  (atsignp nil :type (member t nil))
  (params nil :type list))

(defun %print-format-directive (struct stream depth)
  (declare (ignore depth))
  (format stream "#<~A>"
	  (subseq (format-directive-string struct)
		  (format-directive-start struct)
		  (format-directive-end struct))))

(defvar *format-directive-expanders*
  (make-array char-code-limit :initial-element nil))
48
49
(defvar *format-directive-interpreters*
  (make-array char-code-limit :initial-element nil))
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

(defun %print-format-error (condition stream)
  (format stream
	  "~:[~;Error in format: ~]~
	   ~?~@[~%  ~A~%  ~V@T^~]"
	  (format-error-print-banner condition)
	  (format-error-complaint condition)
	  (format-error-arguments condition)
	  (format-error-control-string condition)
	  (format-error-offset condition)))

(defvar *default-format-error-control-string* nil)
(defvar *default-format-error-offset* nil)

(define-condition format-error (error)
  ((complaint (required-argument))
   (arguments nil)
   (control-string *default-format-error-control-string*)
   (offset *default-format-error-offset*)
   (print-banner t))
  (:report %print-format-error))
ram's avatar
ram committed
71
72


73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

;;;; TOKENIZE-CONTROL-STRING

(defun tokenize-control-string (string)
  (declare (simple-string string))
  (let ((index 0)
	(end (length string))
	(result nil))
    (loop
      (let ((next-directive (or (position #\~ string :start index) end)))
	(when (> next-directive index)
	  (push (subseq string index next-directive) result))
	(when (= next-directive end)
	  (return))
	(let ((directive (parse-directive string next-directive)))
	  (push directive result)
	  (setf index (format-directive-end directive)))))
    (nreverse result)))

(defun parse-directive (string start)
  (let ((posn (1+ start)) (params nil) (colonp nil) (atsignp nil)
	(end (length string)))
    (flet ((get-char ()
	     (if (= posn end)
		 (error 'format-error
			:complaint "String ended before directive was found."
			:control-string string
			:offset start)
		 (schar string posn))))
      (loop
	(let ((char (get-char)))
	  (cond ((or (char<= #\0 char #\9) (char= char #\+) (char= char #\-))
		 (multiple-value-bind
		     (param new-posn)
		     (parse-integer string :start posn :junk-allowed t)
108
		   (push (cons posn param) params)
109
110
111
112
113
114
115
116
		   (setf posn new-posn)
		   (case (get-char)
		     (#\,)
		     ((#\: #\@)
		      (decf posn))
		     (t
		      (return)))))
		((or (char= char #\v) (char= char #\V))
117
		 (push (cons posn :arg) params)
118
119
120
121
122
123
124
125
		 (incf posn)
		 (case (get-char)
		   (#\,)
		   ((#\: #\@)
		    (decf posn))
		   (t
		    (return))))
		((char= char #\#)
126
		 (push (cons posn :remaining) params)
127
128
129
130
131
132
133
134
135
		 (incf posn)
		 (case (get-char)
		   (#\,)
		   ((#\: #\@)
		    (decf posn))
		   (t
		    (return))))
		((char= char #\')
		 (incf posn)
136
		 (push (cons posn (get-char)) params))
137
		((char= char #\,)
138
		 (push (cons (1- posn) nil) params))
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
		((char= char #\:)
		 (if colonp
		     (error 'format-error
			    :complaint "Too many colons supplied."
			    :control-string string
			    :offset posn)
		     (setf colonp t)))
		((char= char #\@)
		 (if atsignp
		     (error 'format-error
			    :complaint "Too many at-signs supplied."
			    :control-string string
			    :offset posn)
		     (setf atsignp t)))
		(t
		 (when (char= (schar string (1- posn)) #\,)
155
		   (push (cons (1- posn) nil) params))
156
157
158
159
160
161
162
163
164
165
166
167
		 (return))))
	(incf posn))
      (let ((char (get-char)))
	(when (char= char #\/)
	  (let ((closing-slash (position #\/ string :start (1+ posn))))
	    (if closing-slash
		(setf posn closing-slash)
		(error 'format-error
		       :complaint "No matching closing slash."
		       :control-string string
		       :offset posn))))
	(make-format-directive
168
169
	    :string string :start start :end (1+ posn)
	    :character (char-upcase char)
170
171
	    :colonp colonp :atsignp atsignp
	    :params (nreverse params))))))
ram's avatar
ram committed
172
173
174
175




176
177
;;;; FORMAT

178
(defun format (destination control-string &rest format-arguments)
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
  "Provides various facilities for formatting output.
  CONTROL-STRING contains a string to be output, possibly with embedded
  directives, which are flagged with the escape character \"~\".  Directives
  generally expand into additional text to be output, usually consuming one
  or more of the FORMAT-ARGUMENTS in the process.  A few useful directives
  are:
        ~A or ~nA     Prints one argument as if by PRINC
        ~S or ~nS     Prints one argument as if by PRIN1
        ~D or ~nD     Prints one argument as a decimal integer
        ~%            Does a TERPRI
        ~&            Does a FRESH-LINE

         where n is the width of the field in which the object is printed.
  
  DESTINATION controls where the result will go.  If DESTINATION is T, then
  the output is sent to the standard output stream.  If it is NIL, then the
  output is returned in a string as the value of the call.  Otherwise,
  DESTINATION must be a stream to which the output will be sent.

  Example:   (FORMAT NIL \"The answer is ~D.\" 10) => \"The answer is 10.\"

  FORMAT has many additional capabilities not described here.  Consult the
  manual for details."
  (etypecase destination
203
204
    (null
     (with-output-to-string (stream)
205
       (%format stream control-string format-arguments)))
206
    (string
207
208
     (with-output-to-string (stream destination)
       (%format stream control-string format-arguments)))
209
    ((member t)
210
     (%format *standard-output* control-string format-arguments)
211
212
     nil)
    (stream
213
     (%format destination control-string format-arguments)
214
215
216
217
218
     nil)))

(defun %format (stream string-or-fun orig-args &optional (args orig-args))
  (if (functionp string-or-fun)
      (apply string-or-fun stream args)
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
      (catch 'up-and-out
	(let* ((string (etypecase string-or-fun
			 (simple-string
			  string-or-fun)
			 (string
			  (coerce string-or-fun 'simple-string))))
	       (*default-format-error-control-string* string))
	  (interpret-directive-list stream (tokenize-control-string string)
				    orig-args args)))))

(defun interpret-directive-list (stream directives orig-args args)
  (if directives
      (let ((directive (car directives)))
	(etypecase directive
	  (simple-string
	   (write-string directive stream)
	   (interpret-directive-list stream (cdr directives) orig-args args))
	  (format-directive
	   (multiple-value-bind
	       (new-directives new-args)
	       (let ((function
		      (svref *format-directive-interpreters*
			     (char-code (format-directive-character
					 directive))))
		     (*default-format-error-offset*
		      (1- (format-directive-end directive))))
		 (unless function
		   (error 'format-error
			  :complaint "Unknown format directive."))
		 (multiple-value-bind
		     (new-directives new-args)
		     (funcall function stream directive
			      (cdr directives) orig-args args)
		   (values new-directives new-args)))
	     (interpret-directive-list stream new-directives
				       orig-args new-args)))))
      args))
ram's avatar
ram committed
256
257


258
;;;; FORMATTER
ram's avatar
ram committed
259

260
261
(defmacro formatter (control-string)
  `#',(%formatter control-string))
ram's avatar
ram committed
262

263
264
265
266
267
(defun %formatter (control-string)
  `(lambda (stream &rest orig-args)
     (let ((args orig-args))
       ,(expand-control-string control-string)
       args)))
ram's avatar
ram committed
268

269
270
(eval-when (compile load eval)
  (defvar *current-directive-offset* nil))
ram's avatar
ram committed
271

272
273
274
(defun expand-control-string (string)
  (let* ((string (etypecase string
		   (simple-string
ram's avatar
ram committed
275
		    string)
276
277
278
279
280
281
		   (string
		    (coerce string 'simple-string))))
	 (*default-format-error-control-string* string)
	 (directives (tokenize-control-string string)))
    `(let ((*default-format-error-control-string* ',string))
       (block nil
282
	 ,@(expand-directive-list directives)))))
283
284
285
286
287
288
289

(defun expand-directive-list (directives)
  (let ((results nil)
	(remaining-directives directives))
    (loop
      (unless remaining-directives
	(return))
ram's avatar
ram committed
290
      (multiple-value-bind
291
292
293
294
295
296
297
298
299
300
301
302
303
304
	  (form new-directives)
	  (expand-directive (car remaining-directives)
			    (cdr remaining-directives))
	(push form results)
	(setf remaining-directives new-directives)))
    (reverse results)))

(defun expand-directive (directive more-directives)
  (etypecase directive
    (format-directive
     (let ((expander
	    (aref *format-directive-expanders*
		  (char-code (format-directive-character directive)))))
       (if expander
305
306
	   (let* ((offset (1- (format-directive-end directive)))
		  (*default-format-error-offset* offset))
ram's avatar
ram committed
307
	     (multiple-value-bind
308
309
		 (form directives)
		 (funcall expander directive more-directives)
310
311
	       (values `(compiler-let
			    ((*current-directive-offset* ',offset))
312
313
314
315
316
317
318
319
320
			  ,form)
		       directives)))
	   (error 'format-error
		  :complaint "Unknown directive."
		  :control-string (format-directive-string directive)
		  :offset (1- (format-directive-end directive))))))
    (simple-string
     (values `(write-string ,directive stream)
	     more-directives))))
321

ram's avatar
ram committed
322

323
324
325
326
;;;; Format directive definition macros and runtime support.

(eval-when (compile eval)

327
328
329
330
331
332
333
334
(defmacro next-arg (&optional offset)
  `(if args
       (pop args)
       (error 'format-error
	      :complaint "No more arguments."
	      ,@(when (or offset *current-directive-offset*)
		  `(:offset ,(or offset *current-directive-offset*))))))

335
336
337
338
339
340
341
342
(defmacro def-complex-format-directive (char lambda-list &body body)
  (let ((defun-name (intern (format nil "~:@(~:C~)-FORMAT-DIRECTIVE-EXPANDER"
				    char)))
	(directive (gensym))
	(directives (if lambda-list (car (last lambda-list)) (gensym))))
    `(progn
       (defun ,defun-name (,directive ,directives)
	 ,@(if lambda-list
343
344
345
346
347
348
349
350
351
352
353
354
	       `((let ,(mapcar #'(lambda (var)
				   `(,var
				     (,(intern (concatenate
						'string
						"FORMAT-DIRECTIVE-"
						(symbol-name var))
					       (symbol-package 'foo))
				      ,directive)))
			       (butlast lambda-list))
		   ,@body))
	       `((declare (ignore ,directive ,directives))
		 ,@body)))
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
       (%set-format-directive-expander ,char #',defun-name))))

(defmacro def-format-directive (char lambda-list &body body)
  (let ((directives (gensym))
	(declarations nil)
	(body-without-decls body))
    (loop
      (let ((form (car body-without-decls)))
	(unless (and (consp form) (eq (car form) 'declare))
	  (return))
	(push (pop body-without-decls) declarations)))
    (setf declarations (reverse declarations))
    `(def-complex-format-directive ,char (,@lambda-list ,directives)
       ,@declarations
       (values (progn ,@body-without-decls)
	       ,directives))))

372
(defmacro expand-bind-defaults (specs params &body body)
373
374
375
376
377
378
379
380
381
  (once-only ((params params))
    (collect ((expander-bindings) (runtime-bindings))
      (dolist (spec specs)
	(destructuring-bind (var default) spec
	  (let ((symbol (gensym)))
	    (expander-bindings
	     `(,var ',symbol))
	    (runtime-bindings
	     `(list ',symbol
382
383
384
		    (let* ((param-and-offset (pop ,params))
			   (offset (car param-and-offset))
			   (param (cdr param-and-offset)))
385
		      (case param
386
			(:arg `(or (next-arg ,offset) ,,default))
387
388
389
390
391
392
393
394
395
			(:remaining '(length args))
			((nil) ,default)
			(t param))))))))
      `(let ,(expander-bindings)
	 `(let ,(list ,@(runtime-bindings))
	    ,@(if ,params
		  (error 'format-error
			 :complaint
			 "Too many parameters, expected no more than ~D"
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
			 :arguments (list ,(length specs))
			 :offset (caar ,params)))
	    ,,@body)))))

(defmacro def-complex-format-interpreter (char lambda-list &body body)
  (let ((defun-name
	    (intern (format nil "~:@(~:C~)-FORMAT-DIRECTIVE-INTERPRETER"
			    char)))
	(directive (gensym))
	(directives (if lambda-list (car (last lambda-list)) (gensym))))
    `(progn
       (defun ,defun-name (stream ,directive ,directives orig-args args)
	 (declare (ignorable stream orig-args args))
	 ,@(if lambda-list
	       `((let ,(mapcar #'(lambda (var)
				   `(,var
				     (,(intern (concatenate
						'string
						"FORMAT-DIRECTIVE-"
						(symbol-name var))
					       (symbol-package 'foo))
				      ,directive)))
			       (butlast lambda-list))
		   (values (progn ,@body) args)))
	       `((declare (ignore ,directive ,directives))
		 ,@body)))
       (%set-format-directive-interpreter ,char #',defun-name))))

(defmacro def-format-interpreter (char lambda-list &body body)
  (let ((directives (gensym)))
    `(def-complex-format-interpreter ,char (,@lambda-list ,directives)
       ,@body
       ,directives)))

(defmacro interpret-bind-defaults (specs params &body body)
  (once-only ((params params))
    (collect ((bindings))
      (dolist (spec specs)
	(destructuring-bind (var default) spec
	  (bindings `(,var (let* ((param-and-offset (pop ,params))
				  (offset (car param-and-offset))
				  (param (cdr param-and-offset)))
			     (case param
			       (:arg (next-arg offset))
			       (:remaining (length args))
			       ((nil) ,default)
			       (t param)))))))
      `(let* ,(bindings)
	 (when ,params
	   (error 'format-error
		  :complaint
		  "Too many parameters, expected no more than ~D"
		  :arguments (list ,(length specs))
		  :offset (caar ,params)))
	 ,@body))))
451
452
453
454
455
456
457

); eval-when

(defun %set-format-directive-expander (char fn)
  (setf (aref *format-directive-expanders* (char-code (char-upcase char))) fn)
  char)

458
459
460
461
462
463
(defun %set-format-directive-interpreter (char fn)
  (setf (aref *format-directive-interpreters*
	      (char-code (char-upcase char)))
	fn)
  char)

464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
(defun find-directive (directives kind stop-at-semi)
  (if directives
      (let ((next (car directives)))
	(if (format-directive-p next)
	    (let ((char (format-directive-character next)))
	      (if (or (char= kind char)
		      (and stop-at-semi (char= char #\;)))
		  (car directives)
		  (find-directive
		   (cdr (flet ((after (char)
				 (member (find-directive (cdr directives)
							 char
							 nil)
					 directives)))
			  (case char
			    (#\( (after #\)))
			    (#\< (after #\>))
			    (#\[ (after #\]))
			    (#\{ (after #\}))
			    (t directives))))
		   kind stop-at-semi)))
	    (find-directive (cdr directives) kind stop-at-semi)))))

ram's avatar
ram committed
487

488
;;;; Simple outputting noise.
489
490
491
492
493
494
495
496
497
498
499
500

(defun format-write-field (stream string mincol colinc minpad padchar padleft)
  (unless padleft
    (write-string string stream))
  (dotimes (i minpad)
    (write-char padchar stream))
  (do ((chars (+ (length string) minpad) (+ chars colinc)))
      ((>= chars mincol))
    (dotimes (i colinc)
      (write-char padchar stream)))
  (when padleft
    (write-string string stream)))
ram's avatar
ram committed
501

502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
(defun format-princ (stream arg colonp atsignp mincol colinc minpad padchar)
  (format-write-field stream
		      (if (or arg (not colonp))
			  (princ-to-string arg)
			  "()")
		      mincol colinc minpad padchar atsignp))

(def-format-directive #\A (colonp atsignp params)
  (if params
      (expand-bind-defaults ((mincol 0) (colinc 1) (minpad 0) (padchar #\space))
		     params
	`(format-princ stream (next-arg) ',colonp ',atsignp
		       ,mincol ,colinc ,minpad ,padchar))
      `(princ ,(if colonp '(or (next-arg) "()") '(next-arg)) stream)))

(def-format-interpreter #\A (colonp atsignp params)
  (if params
      (interpret-bind-defaults ((mincol 0) (colinc 1) (minpad 0) (padchar #\space))
		     params
	(format-princ stream (next-arg) colonp atsignp
		      mincol colinc minpad padchar))
      (princ (if colonp (or (next-arg) "()") (next-arg)) stream)))

(defun format-prin1 (stream arg colonp atsignp mincol colinc minpad padchar)
  (format-write-field stream
		      (if (or arg (not colonp))
			  (prin1-to-string arg)
			  "()")
		      mincol colinc minpad padchar atsignp))

(def-format-directive #\S (colonp atsignp params)
  (cond (params
	 (expand-bind-defaults ((mincol 0) (colinc 1) (minpad 0) (padchar #\space))
			params
	   `(format-prin1 stream (next-arg) ,colonp ,atsignp
			  ,mincol ,colinc ,minpad ,padchar)))
	(colonp
	 `(let ((arg (next-arg)))
	    (if arg
		(prin1 arg stream)
		(princ "()" stream))))
	(t
	 '(prin1 (next-arg) stream))))

(def-format-interpreter #\S (colonp atsignp params)
  (cond (params
	 (interpret-bind-defaults ((mincol 0) (colinc 1) (minpad 0) (padchar #\space))
			params
	   (format-prin1 stream (next-arg) colonp atsignp
			 mincol colinc minpad padchar)))
	(colonp
	 (let ((arg (next-arg)))
	   (if arg
	       (prin1 arg stream)
	       (princ "()" stream))))
	(t
	 (prin1 (next-arg) stream))))

(def-format-directive #\C (colonp atsignp params)
  (expand-bind-defaults () params
    (if colonp
	'(format-print-named-character (next-arg) stream)
	(if atsignp
	    '(prin1 (next-arg) stream)
	    '(write-char (next-arg) stream)))))

(def-format-interpreter #\C (colonp atsignp params)
  (interpret-bind-defaults () params
    (if colonp
	(format-print-named-character (next-arg) stream)
	(if atsignp
	    (prin1 (next-arg) stream)
	    (write-char (next-arg) stream)))))

(defun format-print-named-character (char stream)
  (let* ((name (char-name char)))
    (cond (name
	   (write-string (string-capitalize name) stream))
	  ((<= 0 (char-code char) 31)
	   ;; Print control characters as "^"<char>
	   (write-char #\^ stream)
	   (write-char (code-char (+ 64 (char-code char))) stream))
	  (t
	   (write-char char stream)))))

(def-format-directive #\W (colonp atsignp params)
  (expand-bind-defaults () params
    `(write (next-arg) :stream stream
	    ,@(when colonp
		'(:pretty t))
	    ,@(when atsignp
		'(:level nil :length nil)))))

(def-format-interpreter #\W (colonp atsignp params)
  (interpret-bind-defaults () params
    (let ((*print-pretty* (or colonp *print-pretty*))
	  (*print-level* (and atsignp *print-level*))
	  (*print-length* (and atsignp *print-length*)))
      (write (next-arg) :stream stream))))


;;;; Integer outputting.

605
;;; FORMAT-PRINT-NUMBER does most of the work for the numeric printing
ram's avatar
ram committed
606
;;; directives.  The parameters are interpreted as defined for ~D.
607
;;;
wlott's avatar
wlott committed
608
(defun format-print-integer (stream number print-commas-p print-sign-p
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
			     radix mincol padchar commachar commainterval)
  (let ((*print-base* radix)
	(*print-radix* nil))
    (if (integerp number)
	(let* ((text (princ-to-string (abs number)))
	       (commaed (if print-commas-p
			    (format-add-commas text commachar commainterval)
			    text))
	       (signed (cond ((minusp number)
			      (concatenate 'string "-" commaed))
			     (print-sign-p
			      (concatenate 'string "+" commaed))
			     (t commaed))))
	  ;; colinc = 1, minpad = 0, padleft = t
	  (format-write-field stream signed mincol 1 0 padchar t))
	(princ number))))

(defun format-add-commas (string commachar commainterval)
  (let ((length (length string)))
    (multiple-value-bind (commas extra)
			 (truncate (1- length) commainterval)
      (let ((new-string (make-string (+ length commas)))
	    (first-comma (1+ extra)))
	(replace new-string string :end1 first-comma :end2 first-comma)
	(do ((src first-comma (+ src commainterval))
	     (dst first-comma (+ dst commainterval 1)))
	    ((= src length))
	  (setf (schar new-string dst) commachar)
	  (replace new-string string :start1 (1+ dst)
		   :start2 src :end2 (+ src commainterval)))
	new-string))))
ram's avatar
ram committed
640

641
642
(defun expand-format-integer (base colonp atsignp params)
  (if (or colonp atsignp params)
643
      (expand-bind-defaults
644
645
646
647
648
	  ((mincol 0) (padchar #\space) (commachar #\,) (commainterval 3))
	  params
	`(format-print-integer stream (next-arg) ,colonp ,atsignp ,base ,mincol
			       ,padchar ,commachar ,commainterval))
      `(write (next-arg) :stream stream :base ,base :radix nil :escape nil)))
649
650
651
652
653
654
655
656
657

(defmacro interpret-format-integer (base)
  `(if (or colonp atsignp params)
       (interpret-bind-defaults
	   ((mincol 0) (padchar #\space) (commachar #\,) (commainterval 3))
	   params
	 (format-print-integer stream (next-arg) colonp atsignp ,base mincol
			       padchar commachar commainterval))
       (write (next-arg) :stream stream :base ,base :radix nil :escape nil)))
ram's avatar
ram committed
658

659
660
661
(def-format-directive #\D (colonp atsignp params)
  (expand-format-integer 10 colonp atsignp params))

662
663
664
(def-format-interpreter #\D (colonp atsignp params)
  (interpret-format-integer 10))

665
666
667
(def-format-directive #\B (colonp atsignp params)
  (expand-format-integer 2 colonp atsignp params))

668
669
670
(def-format-interpreter #\B (colonp atsignp params)
  (interpret-format-integer 2))

671
672
673
(def-format-directive #\O (colonp atsignp params)
  (expand-format-integer 8 colonp atsignp params))

674
675
676
(def-format-interpreter #\O (colonp atsignp params)
  (interpret-format-integer 8))

677
678
679
(def-format-directive #\X (colonp atsignp params)
  (expand-format-integer 16 colonp atsignp params))

680
681
682
(def-format-interpreter #\X (colonp atsignp params)
  (interpret-format-integer 16))

683
684
(def-format-directive #\R (colonp atsignp params)
  (if params
685
      (expand-bind-defaults
686
687
688
689
690
691
692
693
694
695
696
697
698
	  ((base 10) (mincol 0) (padchar #\space) (commachar #\,)
	   (commainterval 3))
	  params
	`(format-print-integer stream (next-arg) ,colonp ,atsignp ,base ,mincol
			       ,padchar ,commachar ,commainterval))
      (if atsignp
	  (if colonp
	      '(format-print-old-roman stream (next-arg))
	      '(format-print-roman stream (next-arg)))
	  (if colonp
	      '(format-print-ordinal stream (next-arg))
	      '(format-print-cardinal stream (next-arg))))))

699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
(def-format-interpreter #\R (colonp atsignp params)
  (if params
      (interpret-bind-defaults
	  ((base 10) (mincol 0) (padchar #\space) (commachar #\,)
	   (commainterval 3))
	  params
	(format-print-integer stream (next-arg) colonp atsignp base mincol
			      padchar commachar commainterval))
      (if atsignp
	  (if colonp
	      (format-print-old-roman stream (next-arg))
	      (format-print-roman stream (next-arg)))
	  (if colonp
	      (format-print-ordinal stream (next-arg))
	      (format-print-cardinal stream (next-arg))))))


(defconstant cardinal-ones
  #(nil "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"))

(defconstant cardinal-tens
  #(nil nil "twenty" "thirty" "forty"
	"fifty" "sixty" "seventy" "eighty" "ninety"))

(defconstant cardinal-teens
  #("ten" "eleven" "twelve" "thirteen" "fourteen"  ;;; RAD
    "fifteen" "sixteen" "seventeen" "eighteen" "nineteen"))

(defconstant cardinal-periods
  #("" " thousand" " million" " billion" " trillion" " quadrillion"
    " quintillion" " sextillion" " septillion" " octillion" " nonillion"
    " decillion"))

(defconstant ordinal-ones
  #(nil "first" "second" "third" "fourth"
	"fifth" "sixth" "seventh" "eighth" "ninth")
  "Table of ordinal ones-place digits in English")

(defconstant ordinal-tens 
  #(nil "tenth" "twentieth" "thirtieth" "fortieth"
	"fiftieth" "sixtieth" "seventieth" "eightieth" "ninetieth")
  "Table of ordinal tens-place digits in English")

(defun format-print-small-cardinal (stream n)
  (multiple-value-bind 
      (hundreds rem) (truncate n 100)
    (when (plusp hundreds)
      (write-string (svref cardinal-ones hundreds) stream)
      (write-string " hundred" stream)
      (when (plusp rem)
	(write-char #\space stream)))
    (when (plusp rem)
      (multiple-value-bind (tens ones)
			   (truncate rem 10)
       (cond ((< 1 tens)
	      (write-string (svref cardinal-tens tens) stream)
	      (when (plusp ones)
		(write-char #\- stream)
		(write-string (svref cardinal-ones ones) stream)))
	     ((= tens 1)
	      (write-string (svref cardinal-teens ones) stream))
	     ((plusp ones)
	      (write-string (svref cardinal-ones ones) stream)))))))

(defun format-print-cardinal (stream n)
  (cond ((minusp n)
	 (write-string "negative " stream)
	 (format-print-cardinal-aux stream (- n) 0 n))
	((zerop n)
	 (write-string "zero" stream))
	(t
	 (format-print-cardinal-aux stream n 0 n))))

(defun format-print-cardinal-aux (stream n period err)
  (multiple-value-bind (beyond here) (truncate n 1000)
    (unless (<= period 10)
      (error "Number too large to print in English: ~:D" err))
    (unless (zerop beyond)
      (format-print-cardinal-aux stream beyond (1+ period) err))
    (unless (zerop here)
      (unless (zerop beyond)
	(write-char #\space stream))
      (format-print-small-cardinal stream here)
      (write-string (svref cardinal-periods period) stream))))

(defun format-print-ordinal (stream n)
  (when (minusp n)
    (write-string "negative " stream))
  (let ((number (abs n)))
    (multiple-value-bind
	(top bot) (truncate number 100)
      (unless (zerop top)
	(format-print-cardinal stream (- number bot)))
      (when (and (plusp top) (plusp bot))
	(write-char #\space stream))
      (multiple-value-bind
	  (tens ones) (truncate bot 10)
	(cond ((= bot 12) (write-string "twelfth" stream))
	      ((= tens 1)
	       (write-string (svref cardinal-teens ones) stream);;;RAD
	       (write-string "th" stream))
	      ((and (zerop tens) (plusp ones))
	       (write-string (svref ordinal-ones ones) stream))
	      ((and (zerop ones)(plusp tens))
	       (write-string (svref ordinal-tens tens) stream))
	      ((plusp bot)
	       (write-string (svref cardinal-tens tens) stream)
	       (write-char #\- stream)
	       (write-string (svref ordinal-ones ones) stream))
	      ((plusp number)
	       (write-string "th" stream))
	      (t
	       (write-string "zeroeth" stream)))))))

;;; Print Roman numerals

(defun format-print-old-roman (stream n)
  (unless (< 0 n 5000)
    (error "Number too large to print in old Roman numerals: ~:D" n))
  (do ((char-list '(#\D #\C #\L #\X #\V #\I) (cdr char-list))
       (val-list '(500 100 50 10 5 1) (cdr val-list))
       (cur-char #\M (car char-list))
       (cur-val 1000 (car val-list))
       (start n (do ((i start (progn
				(write-char cur-char stream)
				(- i cur-val))))
		    ((< i cur-val) i))))
      ((zerop start))))

(defun format-print-roman (stream n)
  (unless (< 0 n 4000)
    (error "Number too large to print in Roman numerals: ~:D" n))
  (do ((char-list '(#\D #\C #\L #\X #\V #\I) (cdr char-list))
       (val-list '(500 100 50 10 5 1) (cdr val-list))
       (sub-chars '(#\C #\X #\X #\I #\I) (cdr sub-chars))
       (sub-val '(100 10 10 1 1 0) (cdr sub-val))
       (cur-char #\M (car char-list))
       (cur-val 1000 (car val-list))
       (cur-sub-char #\C (car sub-chars))
       (cur-sub-val 100 (car sub-val))
       (start n (do ((i start (progn
				(write-char cur-char stream)
				(- i cur-val))))
		    ((< i cur-val)
		     (cond ((<= (- cur-val cur-sub-val) i)
			    (write-char cur-sub-char stream)
			    (write-char cur-char stream)
			    (- i (- cur-val cur-sub-val)))
			   (t i))))))
	  ((zerop start))))


;;;; Plural.

(def-format-directive #\P (colonp atsignp params end)
  (expand-bind-defaults () params
855
    (let ((arg (if colonp
856
		   `(if (eq orig-args args)
857
			(error 'format-error
858
859
			       :complaint "No previous argument."
			       :offset ,(1- end))
860
861
862
863
864
865
866
867
			(do ((arg-ptr orig-args (cdr arg-ptr)))
			    ((eq (cdr arg-ptr) args)
			     (car arg-ptr))))
		   '(next-arg))))
      (if atsignp
	  `(write-string (if (eql ,arg 1) "y" "ies") stream)
	  `(unless (eql ,arg 1) (write-char #\s stream))))))

868
869
870
871
872
873
874
875
876
877
878
879
880
(def-format-interpreter #\P (colonp atsignp params)
  (interpret-bind-defaults () params
    (let ((arg (if colonp
		   (if (eq orig-args args)
		       (error 'format-error
			      :complaint "No previous argument.")
		       (do ((arg-ptr orig-args (cdr arg-ptr)))
			   ((eq (cdr arg-ptr) args)
			    (car arg-ptr))))
		   (next-arg))))
      (if atsignp
	  (write-string (if (eql arg 1) "y" "ies") stream)
	  (unless (eql arg 1) (write-char #\s stream))))))
881

882
883

;;;; Floating point noise.
884
885
886
887
888
889

(def-format-directive #\F (colonp atsignp params)
  (when colonp
    (error 'format-error
	   :complaint
	   "Cannot specify the colon modifier with this directive."))
890
  (expand-bind-defaults ((w nil) (d nil) (k nil) (ovf nil) (pad #\space)) params
891
892
    `(format-fixed stream (next-arg) ,w ,d ,k ,ovf ,pad ,atsignp)))

893
894
895
896
897
898
899
900
(def-format-interpreter #\F (colonp atsignp params)
  (when colonp
    (error 'format-error
	   :complaint
	   "Cannot specify the colon modifier with this directive."))
  (interpret-bind-defaults ((w nil) (d nil) (k nil) (ovf nil) (pad #\space)) params
    (format-fixed stream (next-arg) w d k ovf pad atsignp)))

901
902
903
904
905
906
907
908
909
910
911
(defun format-fixed (stream number w d k ovf pad atsign)
  (if (floatp number)
      (format-fixed-aux stream number w d k ovf pad atsign)
      (if (rationalp number)
	  (format-fixed-aux stream
			    (coerce number 'single-float)
			    w d k ovf pad atsign)
	  (let ((*print-base* 10))
	    (format-write-field stream
				(princ-to-string number)
				w 1 0 #\space t)))))
ram's avatar
ram committed
912

913
914
915
;;; We return true if we overflowed, so that ~G can output the overflow char
;;; instead of spaces.
;;;
916
(defun format-fixed-aux (stream number w d k ovf pad atsign)
917
918
  (cond
   ((not (or w d))
919
    (prin1 number stream)
920
921
922
923
924
925
    nil)
   (t
    (let ((spaceleft w))
      (when (and w (or atsign (minusp number))) (decf spaceleft))
      (multiple-value-bind 
	  (str len lpoint tpoint)
926
	  (lisp::flonum-to-string (abs number) spaceleft d k)
927
928
929
930
931
932
933
934
935
936
	;;if caller specifically requested no fraction digits, suppress the
	;;optional trailing zero
	(when (and d (zerop d)) (setq tpoint nil))
	(when w 
	  (decf spaceleft len)
	  ;;optional leading zero
	  (when lpoint
	    (if (or (> spaceleft 0) tpoint) ;force at least one digit
		(decf spaceleft)
		(setq lpoint nil)))
ram's avatar
ram committed
937
	  ;;optional trailing zero
938
939
940
941
942
943
	  (when tpoint
	    (if (> spaceleft 0)
		(decf spaceleft)
		(setq tpoint nil))))
	(cond ((and w (< spaceleft 0) ovf)
	       ;;field width overflow
944
	       (dotimes (i w) (write-char ovf stream))
945
946
	       t)
	      (t
947
	       (when w (dotimes (i spaceleft) (write-char pad stream)))
948
	       (if (minusp number)
949
950
951
952
953
		   (write-char #\- stream)
		   (if atsign (write-char #\+ stream)))
	       (when lpoint (write-char #\0 stream))
	       (write-string str stream)
	       (when tpoint (write-char #\0 stream))
954
	       nil)))))))
ram's avatar
ram committed
955

956
957
958
959
960
(def-format-directive #\E (colonp atsignp params)
  (when colonp
    (error 'format-error
	   :complaint
	   "Cannot specify the colon modifier with this directive."))
961
962
963
964
965
966
967
968
969
970
971
972
  (expand-bind-defaults
      ((w nil) (d nil) (e nil) (k 1) (ovf nil) (pad #\space) (mark nil))
      params
    `(format-exponential stream (next-arg) ,w ,d ,e ,k ,ovf ,pad ,mark
			 ,atsignp)))

(def-format-interpreter #\E (colonp atsignp params)
  (when colonp
    (error 'format-error
	   :complaint
	   "Cannot specify the colon modifier with this directive."))
  (interpret-bind-defaults
973
974
      ((w nil) (d nil) (e nil) (k 1) (ovf nil) (pad #\space) (mark nil))
      params
975
    (format-exponential stream (next-arg) w d e k ovf pad mark atsignp)))
976
977
978
979
980
981
982
983
984
985
986
987

(defun format-exponential (stream number w d e k ovf pad marker atsign)
  (if (floatp number)
      (format-exp-aux stream number w d e k ovf pad marker atsign)
      (if (rationalp number)
	  (format-exp-aux stream
			  (coerce number 'single-float)
			  w d e k ovf pad marker atsign)
	  (let ((*print-base* 10))
	    (format-write-field stream
				(princ-to-string number)
				w 1 0 #\space t)))))
ram's avatar
ram committed
988
989
990

(defun format-exponent-marker (number)
  (if (typep number *read-default-float-format*)
991
      #\e
ram's avatar
ram committed
992
      (typecase number
993
994
995
	(single-float #\f)
	(double-float #\d)
	(short-float #\s)
996
	(long-float #\l))))
ram's avatar
ram committed
997
998
999
1000

;;;Here we prevent the scale factor from shifting all significance out of
;;;a number to the right.  We allow insignificant zeroes to be shifted in
;;;to the left right, athough it is an error to specify k and d such that this
For faster browsing, not all history is shown. View entire blame