/
format.lisp
2665 lines (2411 loc) · 110 KB
/
format.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
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
605
606
607
608
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; -*- Mode: Lisp; Package: CCL -*-
;;;
;;; Copyright 1994-2009 Clozure Associates
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
;;; Functions to implement FORMAT.
;;;
(in-package "CCL")
;;; Special variables local to FORMAT
;;; why do these have top-level bindings ????? - seems wrong or at least unnecessary
(defvar *format-control-string* ""
"The current FORMAT control string")
(defvar *format-index* 0
"The current index into *format-control-string*")
(defvar *format-length* 0
"The length of the current FORMAT control string")
(defvar *format-arguments* ()
"Arguments to the current call of FORMAT")
(defvar *format-original-arguments* ()
"Saved arglist from top-level FORMAT call for ~* and ~@*")
(defvar *format-arguments-variance* nil
"Non-NIL only during compile-time scanning of a format string, in which case it is the
number of additional elements at the front of *format-arguments* that may be already used
up at runtime. I.e. the actual *format-arguments* may be anything between *format-arguments*
and (nthcdr *format-arguments-variance* *format-arguments*)")
(def-standard-initial-binding *format-stream-stack* nil "A stack of string streams for collecting FORMAT output")
(defvar *format-pprint* nil
"Has a pprint format directive (~W ~I ~_ ~:T) or logical-block directive been seen?")
(defvar *format-justification-semi* nil
"Has a ~<...~:;...~> been seen?")
(defvar *format-colon-rest* nil
)
;;; prevent circle checking rest args. Really EVIL when dynamic-extent
(def-standard-initial-binding *format-top-level* nil)
;;; ERRORS
;;; Since errors may occur while an indirect control string is being
;;; processed, i.e. by ~? or ~{~:}, some sort of backtrace is necessary
;;; in order to indicate the location in the control string where the
;;; error was detected. To this end, errors detected by format are
;;; signalled by throwing a list of the form ((control-string args))
;;; to the tag FORMAT-ERROR. This throw will be caught at each level
;;; of indirection, and the list of error messages re-thrown with an
;;; additional message indicating that indirection was present CONSed
;;; onto it. Ultimately, the last throw will be caught by the top level
;;; FORMAT function, which will then signal an error to the Slisp error
;;; system in such a way that all the errror messages will be displayed
;;; in reverse order.
(defun format-error (complaint &rest args)
(throw 'format-error
(list (list "~1{~:}~%~S~%~V@T^" complaint args
*format-control-string* (1+ *format-index*)))))
;;; MACROS
;;; This macro establishes the correct environment for processing
;;; an indirect control string. CONTROL-STRING is the string to
;;; process, and FORMS are the forms to do the processing. They
;;; invariably will involve a call to SUB-FORMAT. CONTROL-STRING
;;; is guaranteed to be evaluated exactly once.
(eval-when (compile eval #-bccl load)
; does this need to exist?????
#|| ; put it out of its misery
(defmacro format-with-control-string (control-string &rest forms)
`(let ((string (if (simple-string-p ,control-string)
,control-string
(coerce ,control-string 'simple-base-string))))
(declare (simple-string string))
(let ((error (catch 'format-error
(let ((*format-control-string* string)
(*format-length* (length string))
(*format-index* 0))
,@forms
nil))))
(when error
(throw 'format-error
(cons (list "While processing indirect control string~%~S~%~V@T^"
*format-control-string*
(1+ *format-index*))
error))))))
||#
(defmacro format-indirect-error (error)
`(throw 'format-error
(cons (list "While processing indirect control string~%~S~%~V@T^"
*format-control-string*
(1+ *format-index*))
,error)))
(defmacro get-a-format-string-stream ()
'(or (pop *format-stream-stack*) (make-string-output-stream :element-type 'base-char))) ; ??
;;; This macro rebinds collects output to the standard output stream
;;; in a string. For efficiency, we avoid consing a new stream on
;;; every call. A stack of string streams is maintained in order to
;;; guarantee re-entrancy.
(defmacro with-format-string-output (stream-sym &rest forms)
`(let ((,stream-sym nil))
(unwind-protect
(progn
(setq ,stream-sym (get-a-format-string-stream))
,@forms
(prog1
(get-output-stream-string ,stream-sym)
(push ,stream-sym *format-stream-stack*)))
(when ,stream-sym (file-position ,stream-sym 0)))))
;;; This macro decomposes the argument list returned by PARSE-FORMAT-OPERATION.
;;; PARMVAR is the list of parameters. PARMDEFS is a list of lists of the form
;;; (<var> <default>). The FORMS are evaluated in an environment where each
;;; <var> is bound to either the value of the parameter supplied in the
;;; parameter list, or to its <default> value if the parameter was omitted or
;;; explicitly defaulted.
(defmacro with-format-parameters (parmvar parmdefs &body body &environment env)
(do ((parmdefs parmdefs (cdr parmdefs))
(bindings () (cons `(,(caar parmdefs) (or (if ,parmvar (pop ,parmvar))
,(cadar parmdefs)))
bindings)))
((null parmdefs)
(multiple-value-bind (forms decls) (parse-body body env)
`(let ,(nreverse bindings)
,@decls
(when ,parmvar
(format-error "Too many parameters"))
,@forms)))))
;;; Returns the index of the first occurrence of the specified character
;;; between indices START (inclusive) and END (exclusive) in the control
;;; string.
(defmacro format-find-char (char start end)
`(%str-member ,char *format-control-string*
,start ,end))
) ;end of eval-when for macros
;;; CONTROL STRING PARSING
;;; The current control string is kept in *format-control-string*.
;;; The variable *format-index* is the position of the last character
;;; processed, indexing from zero. The variable *format-length* is the
;;; length of the control string, which is one greater than the maximum
;;; value of *format-index*.
;;; Gets the next character from the current control string. It is an
;;; error if there is none. Leave *format-index* pointing to the
;;; character returned.
(defun format-nextchar ()
(let ((index (%i+ 1 *format-index*)))
(if (%i< (setq *format-index* index) *format-length*)
(schar *format-control-string* index)
(format-error "Syntax error"))))
;;; Returns the current character, i.e. the one pointed to by *format-index*.
(defmacro format-peek ()
`(schar *format-control-string* *format-index*))
;;; Attempts to parse a parameter, starting at the current index.
;;; Returns the value of the parameter, or NIL if none is found.
;;; On exit, *format-index* points to the first character which is
;;; not a part of the recognized parameter.
(defun format-get-parameter (ch)
(case ch
(#\# (format-nextchar)
(let ((n (or *format-arguments-variance* 0))
(len (length *format-arguments*)))
(declare (fixnum n len))
(if (eql n 0)
len
`(the (integer ,(- len n) ,len) (length *format-arguments*)))))
((#\V #\v)
(prog1 (pop-format-arg) (format-nextchar)))
(#\' (prog1 (format-nextchar) (format-nextchar)))
(t (cond ((or (eq ch #\-) (eq ch #\+) (digit-char-p ch))
(let ((neg-parm (eq ch #\-)))
(unless (setq ch (digit-char-p ch))
(unless (setq ch (digit-char-p (format-nextchar)))
(format-error "Illegal parameter")))
(do ((number ch (+ ch (* number 10))))
((not (setq ch (digit-char-p (format-nextchar))))
(if neg-parm (- number) number)))))
(t nil)))))
(defun format-skip-parameter (ch) ; only caller is parse-format-operation
"Might someday want to add proper format error checking for negative
parameters"
(let ()
(case ch
((#\V #\v #\#)
(format-nextchar))
(#\' (format-nextchar) (format-nextchar))
(#\,)
(t (when (or (eq ch #\-) (eq ch #\+)) (format-nextchar))
(while (digit-char-p (format-nextchar)))))))
(defun format-no-semi (char &optional colon atsign)
(when *format-justification-semi*
(format-error "~~~:[~;:~]~:[~;@~]~c illegal in this context" colon atsign char))
(setq *format-pprint* t))
;;; Parses a format directive, including flags and parameters. On entry,
;;; *format-index* should point to the "~" preceding the command. On
;;; exit, *format-index* points to the command character itself.
;;; Returns the list of parameters, the ":" flag, the "@" flag, and the
;;; command character as multiple values. Explicitly defaulted parameters
;;; appear in the list of parameters as NIL. Omitted parameters are simply
;;; not included in the list at all.
(defun parse-format-operation (&optional get-params) ; only caller is format-find-command
(let ((ch (format-nextchar)) parms colon atsign)
(when (or (digit-char-p ch)
;(%str-member ch ",#Vv'"))
(memq ch '(#\- #\, #\# #\V #\v #\')))
(cond (get-params
(setq parms (list (format-get-parameter ch)))
(until (neq (setq ch (format-peek)) #\,)
(setq ch (format-nextchar))
(push (format-get-parameter ch) parms)))
(t (setq parms t) ; tell caller there were some so we get correct error msgs
(format-skip-parameter ch)
(until (neq (setq ch (format-peek)) #\,)
(setq ch (format-nextchar))
(format-skip-parameter ch)))))
; allow either order
(case ch
(#\: (setq colon t ch (format-nextchar))
(when (eq ch #\@)
(setq atsign t ch (format-nextchar))))
(#\@ (setq atsign t ch (format-nextchar))
(when (eq ch #\:)
(setq colon t ch (format-nextchar)))))
(values (if (consp parms) (nreverse parms) parms)
colon
atsign
ch)))
;;; Starting at the current value of *format-index*, finds the first
;;; occurrence of one of the specified directives. Embedded constructs,
;;; i.e. those inside ~(~), ~[~], ~{~}, or ~<~>, are ignored. And error is
;;; signalled if no satisfactory command is found. Otherwise, the
;;; following are returned as multiple values:
;;;
;;; The value of *format-index* at the start of the search
;;; The index of the "~" character preceding the command
;;; The parameter list of the command
;;; The ":" flag
;;; The "@" flag
;;; The command character
;;;
;;; Implementation note: The present implementation is not particulary
;;; careful with storage allocation. It would be a good idea to have
;;; a separate function for skipping embedded constructs which did not
;;; bother to cons parameter lists and then throw them away. This issue has been addressed. (akh)
;;;
;;; We go to some trouble here to use POSITION for most of the searching.
;;; God only knows why!!!!
;; and interesting note - the only caller who wants parameters is format-get-segments for
;; ~< .... ~n:; ...~>
(defun format-find-command (command-list &optional get-params evil-commands)
(let* ((start *format-index*)
(length *format-length*)
tilde)
(loop
(setq tilde (format-find-char #\~ *format-index* length))
(if (not tilde) (format-error "Expecting one of ~S" command-list))
(setq *format-index* tilde)
(multiple-value-bind (parms colon atsign command)
(parse-format-operation get-params)
(when (memq command command-list)
(return (values start tilde parms colon atsign command)))
(when (and evil-commands
(or (memq command '(#\w #\_ #\i #\W #\I))
(and colon (memq command '(#\t #\T)))))
(format-error "Illegal in this context"))
(case command
(#\{ (format-nextchar) (format-find-command '(#\})))
(#\( (format-nextchar) (format-find-command '(#\))))
(#\[ (format-nextchar) (format-find-command '(#\])))
(#\< (format-nextchar)
(multiple-value-bind (prev tilde parms colon atsign cmd)
(format-find-command '(#\>))
(declare (ignore prev tilde parms atsign cmd))
(if (and evil-commands colon)
(format-error "Logical-block directive not allowed inside justification directive"))))
(#\~ (format-nextchar))
((#\} #\> #\) #\])
(format-error "No matching bracket")))))))
(defun format-find-command-no-params (command-list &key (colon t) (atsign t))
(multiple-value-bind (prev tilde parms colon-flag atsign-flag command)
(format-find-command command-list)
(with-format-parameters parms ()
(format-no-flags (and (not colon) colon-flag) (and (not atsign) atsign-flag)))
(values prev tilde command colon-flag atsign-flag)))
;;; This is the FORMAT top-level function.
(defun format (stream control-string &rest format-arguments)
(declare (dynamic-extent format-arguments))
(if (null stream)
(with-output-to-string (s)
(apply #'format s control-string format-arguments))
(if (stringp stream)
(with-output-to-string (s stream)
(apply #'format s control-string format-arguments))
(let ((*format-top-level* t))
(when (xp-structure-p stream)(setq stream (xp-stream-stream stream))) ; for xp tests only! They call format on a structure
(setq stream (if (eq stream t)
*standard-output*
(require-type stream 'stream)))
(if (functionp control-string)
(apply control-string stream format-arguments)
(let* ((control-string (ensure-simple-string control-string))
(*format-control-string* control-string)
(*format-pprint* nil)
(*format-justification-semi* nil))
(declare (type simple-string control-string))
(cond
;; Try to avoid pprint overhead in this case.
((not (position #\~ control-string))
(write-string control-string stream))
((and (or *print-pretty* *print-circle*)
(not (typep stream 'xp-stream)))
(maybe-initiate-xp-printing
#'(lambda (s o)
(do-sub-format-1 s o))
stream format-arguments))
(t
(let ((*format-original-arguments* format-arguments)
(*format-arguments* format-arguments)
(*format-colon-rest* 'error)) ; what should this be??
(do-sub-format stream))))))
nil))))
(defun format-to-string (string control-string &rest format-arguments)
(declare (dynamic-extent format-arguments))
(if string
(with-output-to-string (stream string)
(apply #'format stream control-string format-arguments))
(with-output-to-string (stream)
(apply #'format stream control-string format-arguments))))
(defun do-sub-format (stream)
(let (errorp)
(setq errorp
(catch 'format-error
(catch 'format-escape
(sub-format stream 0 (length *format-control-string*)))
nil))
(when errorp
(error "~%~:{~@?~%~}" (nreverse errorp)))))
;;; This function does the real work of format. The segment of the control
;;; string between indiced START (inclusive) and END (exclusive) is processed
;;; as follows: Text not part of a directive is output without further
;;; processing. Directives are parsed along with their parameters and flags,
;;; and the appropriate handlers invoked with the arguments COLON, ATSIGN, and
;;; PARMS.
;;;
;;; POP-FORMAT-ARG also defined in l1-format
; in l1-format
(def-standard-initial-binding *logical-block-xp* nil)
(without-duplicate-definition-warnings
(defun pop-format-arg (&aux (args *format-arguments*) (xp *logical-block-xp*) (av *format-arguments-variance*))
(when (and (null args) (null xp))
(format-error "Missing argument"))
(when xp
(if (null av)
(when (pprint-pop-check+ args xp) ; gets us level and length stuff in logical block
(throw 'logical-block nil))
;; Could record that might exit here, but nobody cares.
#+no (note-format-scan-option *logical-block-options*)))
(if (or (null av) (eql av 0))
(progn
(setq *format-arguments* (cdr args))
(%car args))
(let ((types (loop for x in args as i from 0 below av
collect (nx-form-type x))))
(when (eql av (length args))
(setq *format-arguments-variance* (1- av)))
(setq *format-arguments* (cdr args))
`(the (or ,@types) (car *format-arguments*))))))
; SUB-FORMAT is now defined in L1-format.lisp
; DEFFORMAT is also defined there.
;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; pretty-printing stuff
;;;
(defformat #\W format-write (stream colon atsign)
(format-no-semi #\W)
(let ((arg (pop-format-arg)))
(cond (atsign
(let ((*print-level* nil)
(*print-length* nil))
(if colon
(let ((*print-pretty* t))
(write-1 arg stream))
(write-1 arg stream))))
(t (if colon
(let ((*print-pretty* t))
(write-1 arg stream))
(write-1 arg stream))))))
(defformat #\I format-indent (stream colon atsign &rest parms)
(declare (dynamic-extent parms))
(declare (ignore atsign))
(format-no-semi #\I)
(with-format-parameters parms ((n 0))
(pprint-indent (if colon :current :block) n stream)))
(defformat #\_ format-conditional-newline (stream colon atsign)
(format-no-semi #\_)
(let ((option
(cond (atsign
(cond (colon :mandatory)
(t :miser)))
(colon :fill)
(t :linear))))
(pprint-newline option stream)))
;;; Tabulation ~T
(defformat #\T format-tab (stream colon atsign &rest parms)
(declare (dynamic-extent parms))
(when colon
(format-no-semi #\T t))
(with-format-parameters parms ((colnum 1) (colinc 1))
(cond ((or (typep stream 'xp-stream) (xp-structure-p stream))
(let ((kind (if colon
(if atsign :section-relative :section)
(if atsign :line-relative :line))))
(cond ((xp-structure-p stream)
(pprint-tab+ kind colnum colinc stream))
((typep stream 'xp-stream)
(pprint-tab+ kind colnum colinc
(slot-value stream 'xp-structure))))))
((not colon)
(pprint-tab-not-pretty stream colnum colinc atsign)))))
(defun pprint-tab-not-pretty (stream colnum colinc &optional atsign)
(let* ((position (column stream))
(count (if atsign
(if position
(if (zerop colinc)
colnum (+ colnum (mod (- (+ position colnum)) colinc)))
colnum)
(if position
(if (<= colnum position)
(if (zerop colinc)
0 (- colinc (mod (- position colnum) colinc)))
(- colnum position))
2))))
(while (> count 0)
(write-string " "
stream :start
0 :end (min count 80))
(setq count (- count 80)))))
;;; ~/ call function
(defformat #\/ format-call-function (stream colon atsign &rest parms)
(let* ((string *format-control-string*)
(ipos (1+ *format-index*))
(epos (format-find-char #\/ ipos *format-length*)))
; the spec is DUMB here - it requires that : and :: be treated the same
(when (not epos) (format-error "Unmatched ~~/"))
(let ((cpos (format-find-char #\: ipos epos))
package)
(cond (cpos
(setq package (or (find-package (string-upcase (%substr string ipos cpos)))
(format-error "Unknown package")))
(when (eql #\: (schar string (%i+ 1 cpos)))
(setq cpos (%i+ cpos 1)))
(setq ipos (%i+ cpos 1)))
(t (setq package (find-package "CL-USER"))))
(let ((thing (intern (string-upcase (%substr string ipos epos)) package)))
(setq *format-index* epos) ; or 1+ epos?
(apply thing stream (pop-format-arg) colon atsign parms)))))
;;; Conditional case conversion ~( ... ~)
#| coral's old version
(defformat #\( format-capitalization (stream colon atsign)
(format-nextchar)
(multiple-value-bind (prev tilde) (format-find-command-no-params '(#\)))
(let* (finished
(string (with-format-string-output stream
(setq finished (catch 'format-escape (sub-format stream prev tilde) t)))))
(write-string
(cond ((and atsign colon)
(nstring-upcase string))
(colon
(nstring-capitalize string))
(atsign
(let ((strlen (length string)))
;; Capitalize the first word only
(nstring-downcase string)
(do ((i 0 (1+ i)))
((or (<= strlen i) (alpha-char-p (char string i)))
(setf (char string i) (char-upcase (char string i)))
string))))
(t (nstring-downcase string)))
stream :start
0 :end (length string))
(unless finished (throw 'format-escape nil)))))
|#
(defformat #\( format-capitalization (stream colon atsign)
(format-nextchar)
(multiple-value-bind (prev tilde) (format-find-command-no-params '(#\)))
(let (catchp)
(cond ((typep stream 'xp-stream)
(let ((xp (slot-value stream 'xp-structure)))
(push-char-mode xp (cond ((and colon atsign) :UP)
(colon :CAP1)
(atsign :CAP0)
(T :DOWN)))
(setq catchp
(catch 'format-escape
(sub-format stream prev tilde)
nil))
(pop-char-mode xp)))
(t
(let* ((string (with-format-string-output stream
(setq catchp (catch 'format-escape
(sub-format stream prev tilde)
nil)))))
(write-string
(cond ((and atsign colon)
(nstring-upcase string))
(colon
(nstring-capitalize string))
(atsign
;; Capitalize the first word only
(nstring-downcase string)
(dotimes (i (length string) string)
(let ((ch (char string i)))
(when (alpha-char-p ch)
(setf (char string i) (char-upcase ch))
(return string)))))
(t (nstring-downcase string)))
stream :start
0 :end (length string)))))
(when catchp
(throw 'format-escape catchp))
)))
;;; Up and Out (Escape) ~^
(defformat #\^ format-escape (stream colon atsign &optional p1 p2 p3)
(declare (ignore stream))
(when atsign
(format-error "FORMAT command ~~~:[~;:~]@^ is undefined" colon))
(when (cond (p3 (etypecase p2
(real
(<= p1 p2 p3))
(character
(char< p1 p2 p3))))
(p2 (equal p1 p2))
(p1 (eql p1 0))
(t (null (if colon *format-colon-rest* *format-arguments*))))
(throw 'format-escape (if colon 'format-colon-escape t))))
;;; Conditional expression ~[ ... ]
;;; ~[ - Maybe these guys should deal with ~^ too - i.e. catch format-escape etc.
;;; but I cant think of a case where just throwing to the { catcher fails
(defun format-untagged-condition (stream)
(let ((test (pop-format-arg)))
(unless (integerp test)
(format-error "Argument to ~~[ must be integer - ~S" test))
(do ((count 0 (1+ count)))
((= count test)
(multiple-value-bind (prev tilde cmd colon atsign)
(format-find-command-no-params '(#\; #\]) :atsign nil)
(declare (ignore colon atsign))
(sub-format stream prev tilde)
(unless (eq cmd #\])
(format-find-command '(#\])))))
(multiple-value-bind (prev tilde cmd colon atsign)
(format-find-command-no-params '(#\; #\]) :atsign nil)
(declare (ignore prev tilde atsign))
(when (eq cmd #\]) (return))
(format-nextchar)
(when colon
(multiple-value-bind (prev tilde cmd colon atsign)
(format-find-command-no-params '(#\; #\]))
(declare (ignore colon atsign))
(sub-format stream prev tilde)
(unless (eq cmd #\])
(format-find-command-no-params '(#\]))))
(return))))))
;;; ~@[
(defun format-funny-condition (stream)
(multiple-value-bind (prev tilde) (format-find-command-no-params '(#\]))
(if *format-arguments*
(if (car *format-arguments*)
(sub-format stream prev tilde)
(pop *format-arguments*))
(format-error "Missing argument"))))
;;; ~:[
(defun format-boolean-condition (stream)
(multiple-value-bind (prev tilde command) (format-find-command-no-params '(#\; #\]))
(when (eq command #\])
(format-error "Two clauses separated by ~~; are required for ~~:["))
(format-nextchar)
(if (pop-format-arg)
(multiple-value-bind (prev tilde)
(format-find-command-no-params '(#\]) :colon nil :atsign nil)
(sub-format stream prev tilde))
(progn
(sub-format stream prev tilde)
(format-find-command-no-params '(#\]))))))
(defformat #\[ format-condition (stream colon atsign &optional p)
(when p (push p *format-arguments*))
(format-nextchar)
(cond (colon
(when atsign
(format-error "~~:@[ undefined"))
(format-boolean-condition stream))
(atsign
(format-funny-condition stream))
(t (format-untagged-condition stream))))
;;; Iteration ~{ ... ~}
(defformat #\{ format-iteration (stream colon atsign &rest parms)
(declare (dynamic-extent parms))
(with-format-parameters parms ((max-iter -1))
(format-nextchar)
(multiple-value-bind (prev tilde end-cmd end-colon end-atsign)
(format-find-command-no-params '(#\}) :atsign nil)
(declare (ignore end-cmd end-atsign))
(if (= prev tilde)
;; Use an argument as the control string if ~{~} is empty
(let ((string (pop-format-arg)))
(cond ((stringp string)
(when (not (simple-string-p string)) ; fix here too
(setq string (coerce string 'simple-string))))
((not (functionp string))
(format-error "Control string is not a string or function")))
(let ((error
(catch 'format-error
(cond
((stringp string)
(let* ((length (length (the simple-string string)))
(*format-control-string* string)
(*format-length* length)
(*format-index* 0))
(format-do-iteration stream 0 length
max-iter colon atsign end-colon)))
(t ;(functionp string)
(format-do-iteration stream string nil
max-iter colon atsign end-colon)))
nil)))
(when error (format-indirect-error error))))
(format-do-iteration stream prev tilde
max-iter colon atsign end-colon)))))
;;; The two catch tags FORMAT-ESCAPE and FORMAT-COLON-ESCAPE are needed here
;;; to correctly implement ~^ and ~:^. The former aborts only the current
;;; iteration, but the latter aborts the entire iteration process.
;;; ~{ arg is a list ~:{ arg is list of sublists, ~@{ arg is spread ~:@{ spread lists
;;; We have nuked two catch tags. Instead throw two different values:
;;; T if ~^ and 'format-colon-escape if ~:^
(defun format-do-iteration (stream start end max-iter colon atsign at-least-once-p)
(flet ((do-iteration-1 (stream start end colon at-least-once-p)
(let (catchp)
(do* ((count 0 (1+ count)))
((or (= count max-iter)
(and (null *format-arguments*)
(if (= count 0) (not at-least-once-p) t))))
(setq catchp
(catch 'format-escape
(if colon
(let* ((args (unless (and at-least-once-p (null *format-arguments*))
(pop-format-arg)))
(*format-top-level* nil)
(*format-colon-rest* *format-arguments*)
(*format-arguments* args)
(*format-original-arguments* args))
(unless (listp *format-arguments*)
(report-bad-arg *format-arguments* 'list))
(if (functionp start)
(apply start stream args)
(sub-format stream start end)))
(let ((*format-original-arguments* *format-arguments*))
(if (functionp start)
(setq *format-arguments* (apply start stream *format-arguments*))
(sub-format stream start end))))
nil))
(when (or (eq catchp 'format-colon-escape)
(and catchp (null colon)))
(return-from do-iteration-1 nil))))))
(if atsign
(do-iteration-1 stream start end colon at-least-once-p)
; no atsign - munch on first arg
(let* ((*format-arguments* (pop-format-arg))
(*format-top-level* nil)
(*format-original-arguments* *format-arguments*))
(unless (listp *format-arguments*)
(report-bad-arg *format-arguments* 'list))
(do-iteration-1 stream start end colon at-least-once-p)))))
;;; Justification ~< ... ~>
;;; Parses a list of clauses delimited by ~; and terminated by ~>.
;;; Recursively invoke SUB-FORMAT to process them, and return a list
;;; of the results, the length of this list, and the total number of
;;; characters in the strings composing the list.
(defun format-get-trailing-segments ()
(format-nextchar)
(multiple-value-bind (prev tilde parms colon atsign cmd)
(format-find-command '(#\; #\>) nil T)
(with-format-parameters parms ()
(when colon
(format-error "~~:; allowed only after first segment in ~~<"))
(format-no-flags nil atsign))
(let ((str (catch 'format-escape
(with-format-string-output stream
(sub-format stream prev tilde)))))
(if (stringp str)
(if (eq cmd #\;)
(multiple-value-bind
(segments numsegs numchars)
(format-get-trailing-segments)
(values (cons str segments)
(1+ numsegs)
(+ numchars
(length str))))
(values (list str)
1
(length str)))
(progn
(unless (eq cmd #\>) (format-find-command '(#\>) nil T))
(values () 0 0))))))
;;; Gets the first segment, which is treated specially. Call
;;; FORMAT-GET-TRAILING-SEGMENTS to get the rest.
(defun format-get-segments ()
(let (ignore)
(declare (ignore-if-unused ignore)) ; why??
(multiple-value-bind (prev tilde parms colon atsign cmd)
(format-find-command '(#\; #\>) nil T) ; skipping
(when atsign
(format-error "Atsign flag not allowed"))
;(setq *format-arguments* blech)
(let ((first-seg (catch 'format-escape
(with-format-string-output stream
(sub-format stream prev tilde)))))
(if (stringp first-seg)
(if (eq cmd #\;)
(progn
(when parms
(setq *format-index* tilde)
; now get the parameters if any - do this way cause of the V thingies
; maybe only necessary in the : case
(multiple-value-setq (ignore ignore parms)
(format-find-command '(#\; #\>) t T)))
(multiple-value-bind
(segments numsegs numchars)
(format-get-trailing-segments)
(if colon
(values first-seg parms segments numsegs numchars)
(values nil nil (cons first-seg segments)
(1+ numsegs)
(+ (length first-seg) numchars)))))
(values nil nil (list first-seg) 1 (length first-seg)))
(progn
(unless (eq cmd #\>) (format-find-command '(#\>) nil T))
(values nil nil () 0 0)))))))
#|
;;; Given the total number of SPACES needed for padding, and the number
;;; of padding segments needed (PADDINGS), returns a list of such segments.
;;; We try to allocate the spaces equally to each segment. When this is
;;; not possible, we allocate the left-over spaces randomly, to improve the
;;; appearance of many successive lines of justified text.
;;;
;;; Query: Is this right? Perhaps consistency might be better for the kind
;;; of applications ~<~> is used for.
(defun make-pad-segs (spaces paddings)
(do* ((extra-space () (and (plusp extra-spaces)
(< (random (float 1)) (/ segs extra-spaces))))
(result () (cons (if extra-space (1+ min-space) min-space) result))
(min-space (truncate spaces paddings))
(extra-spaces (- spaces (* paddings min-space))
(if extra-space (1- extra-spaces) extra-spaces))
(segs paddings (1- segs)))
((zerop segs) result)))
|#
(defun make-pad-segs (spaces segments)
(multiple-value-bind (min-space extra-spaces) (truncate spaces segments)
(declare (fixnum min-space extra-spaces))
(let* ((result (make-list segments :initial-element min-space))
(res result))
(setq min-space (1+ min-space))
(dotimes (i extra-spaces)
(rplaca res min-space)
(setq res (%cdr res)))
result)))
;;; Determine the actual width to be used for a field requiring WIDTH
;;; characters according to the following rule: If WIDTH is less than or
;;; equal to MINCOL, use WIDTH as the actual width. Otherwise, round up
;;; to MINCOL + k * COLINC for the smallest possible positive integer k.
(defun format-round-columns (width mincol colinc)
(if (< width mincol)
(+ width (* colinc (ceiling (- mincol width) colinc)))
width))
(defun format-justification-round-columns (width mincol colinc)
(if (< width mincol)
mincol
(+ mincol (* colinc (ceiling (- width mincol) colinc)))))
(defformat #\< format-justification (stream colon atsign &rest parms)
(declare (dynamic-extent parms))
(multiple-value-bind (start tilde ecmd ecolon eatsign)
(format-find-command-no-params '(#\>)) ; bumps format-index
(declare (ignore tilde ecmd))
(cond
(ecolon
(format-logical-block stream colon atsign eatsign start *format-index* parms))
(t (setq *format-index* start)
(with-format-parameters parms ((mincol 0) (colinc 1) (minpad 0) (padchar #\space))
(unless (integerp mincol)
(format-error "Mincol must be an integer - ~S" mincol))
(unless (and (integerp colinc) (plusp colinc))
(format-error "Colinc must be a positive integer - ~S" colinc))
(unless (integerp minpad)
(format-error "Minpad must be an integer - ~S" minpad))
(unless (characterp padchar)
(if (typep padchar `(integer 0 #.char-code-limit))
(setq padchar (code-char padchar))
(format-error "Padchar must be a character or integer from 0 to ~a - ~S"
char-code-limit padchar)))
(format-nextchar)
(multiple-value-bind (special-arg special-parms segments numsegs numchars)
(format-get-segments)
(when (= numsegs 1) (setq minpad 0))
(when segments
(let* ((padsegs (+ (if (or colon (= numsegs 1)) 1 0)
(1- numsegs)
(if atsign 1 0)))
(width (format-justification-round-columns (+ numchars (* minpad padsegs))
mincol colinc))
(spaces (if (and atsign (not colon) (= numsegs 1)) ;dirty but works
(list 0 (- width numchars))
(append (if (or colon (= numsegs 1)) () '(0))
(make-pad-segs (- width numchars) padsegs)
(if atsign () '(0))))))
(when special-arg
(if *format-pprint*
(format-error "Justification illegal in this context"))
(setq *format-justification-semi* t)
(with-format-parameters special-parms ((spare 0)
(linel (stream-line-length stream)))
(let ((pos (column stream)))
(when (> (+ pos width spare) linel)
(stream-write-entire-string stream special-arg)))))
(do ((segs segments (cdr segs))
(spcs spaces (cdr spcs)))
((null segs) (dotimes (i (car spcs)) (write-char padchar stream)))
(dotimes (i (car spcs)) (write-char padchar stream))
(stream-write-entire-string stream (car segs)))))))))))
(defun format-logical-block (stream colon atsign end-atsign start end &rest parms)
(declare (ignore parms))
(flet ((format-check-simple (str)
(when (and str (or (%str-member #\~ str) (%str-member #\newline str)))
(format-error "Suffix and prefix must be simple")))
(first-block-p (start)
(let* ((*format-index* 0))
(loop
(parse-format-operation)
(when (eq (format-peek) #\<)
(cond ((eq *format-index* start)
(return t))
(t (return nil))))))))
(format-no-semi #\<)
(let ((format-string *format-control-string*)
(prefix (if colon "(" ""))
(suffix (if colon ")" ""))
body-string start1 tilde ignore colon1 atsign1 per-line-p)
(declare (ignore-if-unused ignore colon1))
(setq *format-index* start)
(multiple-value-setq (start1 tilde ignore colon1 atsign1)
(format-find-command '(#\; #\>)))
(setq body-string (%substr format-string (1+ start) tilde))
(when (not (eql *format-index* end)) ; > 1 segment
(setq prefix body-string)
(if atsign1 (setq per-line-p t))
(multiple-value-setq (start1 tilde)
(format-find-command '(#\; #\>)))
(setq body-string (%substr format-string (1+ start1) tilde))
(when (neq *format-index* end)
(multiple-value-setq (start1 tilde)(format-find-command '(#\; #\>)))
(setq suffix (%substr format-string (1+ start1) tilde))
(when (neq *format-index* end)
(format-error "Too many chunks"))))
(when end-atsign (setq body-string (format-fill-transform body-string)))
(format-check-simple prefix)
(format-check-simple suffix)
(unless *format-arguments*
(setq *format-index* start)
(format-error "Missing argument"))
(let ((args (if (not atsign)
; This piece of garbage is needed to avoid double length counting from (formatter ...) things
; but also to allow (flet . t) not to barf.
; Was formerly simply (if *format-arguments* (pop-format-arg))
; Actually wanna not count the arg iff the ~< is at the top level
; in a format string i.e. "is this the first ~< in THIS string?"
(when *format-arguments*
(if (and (listp *format-arguments*)
(first-block-p start))
(pop *format-arguments*) ; dont count
(pop-format-arg))) ; unless not listp or not first
(prog1 *format-arguments*
(setq *format-arguments* nil))))
(*format-control-string* body-string)
(*format-top-level* (and atsign *format-top-level*)))