-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonospace.spad.pamphlet
1298 lines (1196 loc) · 54.8 KB
/
monospace.spad.pamphlet
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
\documentclass{article}
\usepackage{axiom}
\begin{document}
\title{\$SPAD/src/algebra monospace.spad}
\author{Martin J Baker}
\maketitle
\begin{abstract}
MonospaceFormat is a package to output text from OutputForm.
\end{abstract}
\eject
\tableofcontents
\eject
\section{Preface}
This is a formatter for outputing text to a monospaced,
two-dimensional output device, typically the command line
console.
The existing mathprint and mathprintWithNumber in 'i-output.boot'
(sometimes known in the documentaion as algebraFormat)
is written in boot code and this is intended to have the same
functionality using SPAD code.
\section{Overview}
I am currently testing by compiling with the same name as an
existing formatter: 'htmlFormat'.
So the output can then be enabled by typing:
\begin{verbatim}
)set output html on
\end{verbatim}
\section{Installing}
If you don't want to replace the html formatter but want to add it as
an additional formatter then the following files need to be modified:
\begin{verbatim}
src/interp/setvars.boot.pamphlet
src/algebra/Makefile.pamphlet
src/algebra/exposed.lsp.pamphlet
src/doc/axiom.bib.pamphlet
interp/i-output.boot.pamphlet
\end{verbatim}
\section{Using the formatter}
We can cause the command line interpreter to output by typing
the following:
\begin{verbatim}
)set output monospace on
\end{verbatim}
After this the command line will output (in addition to other formats
that are enabled).
\section{Matrix Formatting}
There are many other possibilities, for instance we can generate a matrix
with bars either side to indicate a determinant. All we have to do is
change the css for the site, page or individual element.
\section{Programmers Guide}
This package converts from OutputForm, which is a hierarchical tree structure,
to an array of Character.
This is created by traversing OutputForm while building up an array of
Character which represents a rectangular area of screen.
The second stage is to output this Character rectangle.
To explain how this works I need to use diagrams, is hard to put diagrams
in a pamphlet so I have put a fuller description on this web page:
\url{http://www.euclideanspace.com/maths/standards/program/mycode/output/monospace/}
\subsection{CharRectangle}
<<domain CRECT CharRectangle>>=
)abbrev domain CRECT CharRectangle
++ Author: Martin Baker
++ Date Created: March 2014
++ Date Last Updated: March 2014
++ Related Domains: MonospaceFormatter
++ Description:
++ This is really only intended as a helper to MonospaceFormatter
++ I guess it could be used by other domains but I can't think of
++ a reason why it would.
++ For this reason, and to avoid infinite loops, I have not
++ included a coecion to OutputForm.
++
++ This domain represent a rectangular area of the output device,
++ typically a command line console, which is using a fixed
++ width font.
++ This means that we can represent the restangle by a 2D array
++ of Character.
++ All functions assume all rows are the same length (no trim)
++ that is, padded out if necessary with trailing spaces.
++ Anyone writing code must ensure that rows are not accidently
++ given different lengths. It is faster if we can assume this
++ and dont have to check it each time.
CharRectangle : Exports == Implementation where
NNI==> NonNegativeInteger
Exports == with
charRectangle:(a:String) -> %
++ constructor to create rectangle
charRectangle:(a:List List Character) -> %
++ constructor to avoid pretend
empty:() -> %
++ contruct an empty rectangle with no rows or columns
paddedRectangle:(height:NNI,width:NNI) -> %
++ constructor to create rectangle with an array of empty spaces.
getHeight:(a:%) -> NNI
++ heights are measured in numbers of lines, this is designed for
++ something like a command line console where we can't offset
++ by fractions of a like.
getWidth:(a:%) -> NNI
++ widths are measured in number of characters, This is designed for
++ monospaced (fixed width) fonts so every character is the same
++ width and offsets of fractions of a character width are not
++ possible
vpad:(a:%,height:NNI) -> %
++ pad with spaces to make rectangle a given height
++ try to pad equally at the top and bottom so that the content
++ remains in the middle. if this can't be done evenly then put
++ extra line at the top.
hpad:(a:%,width:NNI) -> %
++ pad with spaces to make rectangle a given width
++ try to pad equally on the left and right so that the content
++ remains in the middle. if this can't be done evenly then put
++ extra line on the right.
vconcat:(a:List %) -> %
++ vertical concatination of rectangles produces a new rectangle
++ consisting of all the supplied rectangles, one above the other.
++ The order of the list is assumed to be top to bottom.
++ Concatinated rectangles don't have to match in either width or
++ height. The values will all be increased to the value of the
++ biggest and padded so that they are centred.
hconcat:(a:List %) -> %
++ horizontal concatination of rectangles produces a new rectangle
++ consisting of all the suppled rectangles, side by side.
++ The order of the list is assumed to be left to right.
++ Concatinated rectangles don't have to match in either width or
++ height. The values will all be increased to the value of the
++ biggest and padded so that they are centred.
aconcat:(a:List List %,mode : Symbol) -> %
++ array concatination
++ building an array of rectangles can't always be done by doing
++ vconcat first and then hconcat, or the other way round,
++ because they will be alligned vertically but not horizontally
++ or alligned horizontally but not vertically. So we need this
++ when we want to allign in both dimensions simultaneously.
++ The valid modes are:
++ "PLAIN"::Symbol no boundary
++ "MATRIX"::Symbol boundary of 1 and left+right brackets
seteltChar:(a:%,c:Character,offsetx:NNI,offsety:NNI)->%
setSubRectangle:(a:%,b:%,offsetx:NNI,offsety:NNI) -> %
++ embed b into a offset by the given coordinates
++ replacing whatever is there.
++ immutable (does not alter a).
stringise:(a:%) -> List String
++ generates a string for each line. Trailing spaces are stripped
++ off the end of each line.
Implementation ==> add
-- We store as a two dimentianal array of characters, rather than
-- a one dimentional array of strings, because this makes it
-- easier to concatinate in the vertical and horizontal directions.
-- I have used List List Character instead of PrimitiveArray Character
-- because PrimitiveArray looks like a wrapper for a lisp type and
-- I wanted to get rid of all lisp and accociated pretends
Rep := List List Character
-- constructor to create rectangle
charRectangle(a:String):% ==
[entries(a)]
-- constructor to avoid pretend
charRectangle(a:List List Character):% == a
-- contruct an empty rectangle with no rows or columns
empty():% == (empty()$List(List(Character)))::%
-- constructor to create rectangle with an array of empty spaces.
paddedRectangle(height:NNI,width:NNI):% ==
res:List List Character := empty()$List(List(Character))
row:List Character := empty()$List(Character)
for w in 1..width repeat
row:=concat(row,char(" "))$List(Character)
for h in 1..height repeat
res:=concat(res,row)$List(List(Character))
res
-- heights are measured in numbers of lines, this is designed for
-- something like a command line console where we can't offset
-- by fractions of a like.
getHeight(a:%):NNI ==
#(a pretend List(List(Character)))
-- widths are measured in number of characters, This is designed for
-- monospaced (fixed width) fonts so every character is the same
-- width and offsets of fractions of a character width are not
-- possible
getWidth(a:%):NNI ==
maxWidth:NNI := 0
for x in a repeat
if #x > maxWidth then maxWidth := #x
maxWidth
-- pad with spaces to make rectangle a given height
-- try to pad equally at the top and bottom so that the content
-- remains in the middle. if this can't be done evenly then put
-- extra line at the top.
vpad(a:%,requiredHeight:NNI):% ==
-- if requiredHeight is already equal or greater than that
-- required then return without changing
(getHeight(a) >= requiredHeight) => a
-- work out ammount to padded
deltaU:Union(NNI,"failed") := subtractIfCan(requiredHeight,getHeight(a))
if deltaU case "failed" then return a
delta:NNI := deltaU::NNI
dR:Record(quotient:NNI,remainder:NNI) := divide(delta::NNI,2::NNI)$NNI
topPadCount:NNI := dR.quotient
if dR.remainder > 0 then topPadCount := topPadCount + 1
bottomPadCount:NNI := dR.quotient
paddedLine:List Character := [char(" ")]
for x in 1..(getWidth(a)) repeat
if x=1 then paddedLine := [char(" ")]
else paddedLine := concat(paddedLine,char(" "))$List(Character)
-- can I replace above 'for' loop with list comprehension?
-- paddedLine:List Character := [char(" ") for x in [1..(getWidth(a)::NNI)]]
newRectangle:List List Character := [paddedLine]
for i in 1..topPadCount repeat
if i=1 then newRectangle:= [paddedLine]
else newRectangle := concat(newRectangle,paddedLine)$List(List(Character))
for b in a repeat
newRectangle := concat(newRectangle,b)$List(List(Character))
for i in 1..bottomPadCount repeat
newRectangle := concat(newRectangle,paddedLine)$List(List(Character))
newRectangle::%
-- pad with spaces to make rectangle a given width
-- try to pad equally on the left and right so that the content
-- remains in the middle. if this can't be done evenly then put
-- extra line on the right.
hpad(a:%,requiredWidth:NNI):% ==
-- if requiredWidth is already equal or greater than that
-- required then return without changing
(getWidth(a) >= requiredWidth) => a
-- work out ammount to padded
deltaU:Union(NNI,"failed") := subtractIfCan(requiredWidth,getWidth(a))
if deltaU case "failed" then return a
delta:NNI := deltaU::NNI
dR:Record(quotient:NNI,remainder:NNI) := divide(delta::NNI,2::NNI)$NNI
rightPadCount:NNI := dR.quotient
if dR.remainder > 0 then rightPadCount := rightPadCount + 1
leftPadCount:NNI := dR.quotient
oldRectangle:List List Character := a pretend List List Character
newRectangle:List List Character := a pretend List List Character
padLeft:List Character := [char(" ")]
for x in 1..leftPadCount repeat
if x=1 then padLeft := [char(" ")]
else padLeft := concat(padLeft,char(" "))$List(Character)
padRight:List Character := [char(" ")]
for x in 1..rightPadCount repeat
if x=1 then padRight := [char(" ")]
else padRight := concat(padRight,char(" "))$List(Character)
firstRowFlag:Boolean := true
for thisRow in oldRectangle repeat
newRow:List Character := concat([padLeft,thisRow,padRight])$List(Character)
if firstRowFlag then newRectangle := [newRow]
else newRectangle := concat(newRectangle,newRow)$List(List(Character))
firstRowFlag := false
newRectangle::%
-- vertical concatination of rectangles produces a new rectangle
-- consisting of all the supplied rectangles, one above the other.
-- The order of the list is assumed to be top to bottom.
-- Concatinated rectangles don't have to match in either width or
-- height. The values will all be increased to the value of the
-- biggest and padded so that they are centred.
vconcat(a:List %):% ==
-- first we calculate the maximum width and height of all then
-- rectangles to be concatinated.
maxWidth:NNI := 0
maxHeight:NNI := 0
for x in a repeat
w := getWidth(x)
h := getHeight(x)
if w > maxWidth then maxWidth:= w
if h > maxHeight then maxHeight:= h
res:List List Character := empty()$List(List(Character))
-- go through each input rectangle and pad them out to
-- the same width
-- put all the rows on after the other.
for x in a repeat
paddedIn:% := hpad(x,maxWidth)
for y in paddedIn repeat -- 'y' is a row
-- so 'res' contains the rows in all the inputs
res := concat(res,y)$List(List(Character))
res::%
-- horizontal concatination of rectangles produces a new rectangle
-- consisting of all the suppled rectangles, side by side.
-- The order of the list is assumed to be left to right.
-- Concatinated rectangles don't have to match in either width or
-- height. The values will all be increased to the value of the
-- biggest and padded so that they are centred.
hconcat(a:List %):% ==
-- first we calculate the maximum width and height of all then
-- rectangles to be concatinated.
maxWidth:NNI := 0
maxHeight:NNI := 0
for x in a repeat
w := getWidth(x)
h := getHeight(x)
if w > maxWidth then maxWidth:= w
if h > maxHeight then maxHeight:= h
-- sayTeX$Lisp concat(["maxWidth=",(mathObject2String$Lisp maxWidth)," ",_
-- " maxHeight=",(mathObject2String$Lisp maxHeight)])$String
-- initialise return value
res:List List Character := empty()$List(List(Character))
for j in 1..maxHeight repeat
res := concat(res,empty()$List(Character))$List(List(Character))
-- go through each input rectangle and pad them out to
-- the same height
-- put all the columns on after the other.
for x in a repeat
paddedIn:% := vpad(x,maxHeight)
for y in paddedIn for i in 1..(#paddedIn) repeat
-- sayTeX$Lisp concat(["i=",(mathObject2String$Lisp i)," ",_
-- " x=",(mathObject2String$Lisp x),_
-- " paddedIn=",(mathObject2String$Lisp paddedIn),_
-- " res=",(mathObject2String$Lisp res)," y=",_
-- (mathObject2String$Lisp y)@String])$String
res.i := concat(res.i,y)$List(Character)
res::%
-- array concatination
-- building an array of rectangles can't always be done by doing
-- vconcat first and then hconcat, or the other way round,
-- because they will be alligned vertically but not horizontally
-- or alligned horizontally but not vertically. So we need this
-- when we want to allign in both dimensions simultaneously.
-- The valid modes are:
-- "PLAIN"::Symbol no boundary
-- "MATRIX"::Symbol boundary of 1 and left+right brackets
aconcat(a:List List %,mode : Symbol):% ==
maxHeights: List NNI := empty()$List(NNI)
for y in a repeat -- traverse the outer rows
maxHeight:NNI := 0
for x in y repeat -- traverse the outer columns
h := getHeight(x)
if h > maxHeight then maxHeight:= h
if mode="MATRIX"::Symbol then maxHeight := maxHeight + 1
maxHeights:=concat(maxHeights,maxHeight)$List(NNI)
if #maxHeights < 1 then return empty()
maxWidths: List NNI := empty()$List(NNI)
for u in a repeat
maxWidths:=concat(maxWidths,0::NNI)$List(NNI)
for y in a for i in 1..(#a) repeat -- traverse the outer rows
for x in y for j in 1..(#y) repeat -- traverse the outer columns
w := getWidth(x)
-- sayTeX$Lisp concat([" w=",(mathObject2String$Lisp w)])$String
if w > maxWidths.j then maxWidths.j:= w
-- sayTeX$Lisp concat([" maxWidths.",(mathObject2String$Lisp j),"=",_
-- (mathObject2String$Lisp maxWidths.j)])$String
if #maxWidths < 1 then return empty()
-- sayTeX$Lisp concat(["maxHeights=",(mathObject2String$Lisp maxHeights)," ",_
-- " maxWidths=",(mathObject2String$Lisp maxWidths)])$String
totalWidth:NNI := 0
totalHeight:NNI := 0
if mode="MATRIX"::Symbol then
for k in 1..(#maxWidths) repeat maxWidths.k := maxWidths.k + 1
totalWidth := 1
for w in maxWidths repeat totalWidth := totalWidth + w
for h in maxHeights repeat totalHeight := totalHeight + h
if mode="MATRIX"::Symbol then
totalHeight := subtractIfCan(totalHeight,1::NNI)::NNI
-- sayTeX$Lisp concat(["totalHeight=",(mathObject2String$Lisp totalHeight)," ",_
-- " totalWidth=",(mathObject2String$Lisp totalWidth)])$String
-- initialise return value
res:% := paddedRectangle(totalHeight,totalWidth)
offsety:NNI := 0
for outerRow in a for rowNum in 1..(#a) repeat
offsetx:NNI := 0
if mode="MATRIX"::Symbol then offsetx:NNI := 1
for thisRect in outerRow for colNum in 1..(#outerRow) repeat
res := setSubRectangle(res,thisRect,offsetx,offsety)
--sayTeX$Lisp concat(["offsetx=",(mathObject2String$Lisp offsetx)," ",_
-- " offsety=",(mathObject2String$Lisp offsety),_
-- " thisRect=",(mathObject2String$Lisp thisRect)])$String
offsetx := offsetx + maxWidths.colNum
offsety := offsety + maxHeights.rowNum
-- if matrix then add brackets
if mode="MATRIX"::Symbol then
for bigrow in res for u in 0..(#res-1) repeat
for v in 0..(#bigrow-1) repeat
if v=0 or v=#bigrow-1 then
if u=0 or u=#res-1 then res := seteltChar(res,char("+"),v,u)
else res := seteltChar(res,char("|"),v,u)
--sayTeX$Lisp concat(["aconcat res=",(mathObject2String$Lisp res)])$String
res
-- overwrite a character in a given position.
-- does not change a
seteltChar(a:%,c:Character,offsetx:NNI,offsety:NNI):% ==
--sayTeX$Lisp concat(["setelt a=",(mathObject2String$Lisp a),_
-- " offsetx=",(mathObject2String$Lisp offsetx),_
-- " offsety=",(mathObject2String$Lisp offsety),_
-- " c=",(mathObject2String$Lisp c)])$String
r:List List Character := a pretend List(List(Character))
r2:List List Character := empty()$List(List(Character))
for y in r for j in 0..(#r-1) repeat
row:List Character := empty()$List(Character)
for x in y for i in 0..(#y-1) repeat
if j=offsety and i=offsetx then row:=concat(row,c)$List(Character)
else row:=concat(row,x)$List(Character)
--sayTeX$Lisp concat(["setelt i=",(mathObject2String$Lisp i),_
--" j=",(mathObject2String$Lisp j),_
--" offsetx=",(mathObject2String$Lisp offsetx),_
--" offsety=",(mathObject2String$Lisp offsety),_
--" row=",(mathObject2String$Lisp row)])$String
r2 := concat(r2,row)$List(List(Character))
--sayTeX$Lisp concat(["setelt r2=",(mathObject2String$Lisp r2)])$String
r2
-- embed b into a offset by the given coordinates
-- replacing whatever is there.
-- immutable (does not alter a).
setSubRectangle(a:%,b:%,offsetx:NNI,offsety:NNI):% ==
r:List List Character := a pretend List(List(Character))
q:List List Character := b pretend List(List(Character))
r2:List List Character := empty()$List(List(Character))
for y in r for j in 1..(#r) repeat
row:List Character := empty()$List(Character)
for x in y for i in 1..(#y) repeat
row:=concat(row,x)$List(Character)
r2 := concat(r2,row)$List(List(Character))
for y in q for j in 1..(#q) repeat
for x in y for i in 1..(#y) repeat
thisOffsetx:NNI := (offsetx-1+i)::NNI
thisOffsety:NNI := (offsety-1+j)::NNI
r3:% := seteltChar(charRectangle(r2),x,_
thisOffsetx,thisOffsety)
r2 := r3 pretend List(List(Character))
--sayTeX$Lisp concat(["setSubRectangle r2=",(mathObject2String$Lisp r2)])$String
r2
-- generates a string for each line. Trailing spaces are stripped
-- off the end of each line.
stringise(a:%):List String ==
if #a < 1 then return [""]
[rightTrim(construct(b),char(" ")) for b in a]
@
\subsection{MonospaceFormat}
<<package MONOFORM MonospaceFormat>>=
)abbrev domain MONOFORM MonospaceFormat
++ Author: Martin J Baker
++ Date: March 2014
++ Description:
++ \spadtype{MonospaceFormat} provides a coercion from \spadtype{OutputForm}
++ to monospaced text.
MonospaceFormat() : public == private where
E ==> OutputForm
I ==> Integer
NNI ==> NonNegativeInteger
L ==> List
S ==> String
public == SetCategory with
coerce : E -> S
++ coerce(o) changes o in the standard output format to monospace
++ format.
coerceS : E -> S
++ coerceS(o) changes o in the standard output format to monospace
++ format and displays formatted result.
coerceL : E -> S
++ coerceL(o) changes o in the standard output format to monospace
++ format and displays result as one long string.
exprex : E -> S
++ exprex(o) coverts \spadtype{OutputForm} to \spadtype{String}
display : S -> Void
++ display(o) prints the string returned by coerce.
private == add
import OutputForm
import Character
import Integer
import List OutputForm
import List String
-- other formatters have specialisd formatters such as sayHtml$Lisp
-- is that needed here?
sayMono ==> sayTeX$Lisp
expr : E
prec, opPrec : I
str : S
blank : S := " \ "
maxPrec : I := 1000000
minPrec : I := 0
unaryOps : L S := ["-"]$(L S)
unaryPrecs : L I := [700]$(L I)
-- the precedence of / in the following is relatively low because
-- the bar obviates the need for parentheses.
binaryOps : L S := ["+->","|","^","/","<",">","=","OVER"]$(L S)
binaryPrecs : L I := [0, 0, 900, 700, 400, 400, 400, 700]$(L I)
naryOps : L S := ["-","+","*",blank,",",";"," ","ROW","",
" \cr ","&","/\","\/"]$(L S)
naryPrecs : L I := [700, 700, 800, 800, 110, 110, 0, 0, 0, 0, 0, 600, 600]$(L I)
naryNGOps : L S := ["ROW","&"]$(L S)
plexOps : L S := ["SIGMA","SIGMA2","PI","PI2","INTSIGN",_
"INDEFINTEGRAL"]$(L S)
plexPrecs : L I := [700, 800, 700, 800, 700, 700]$(L I)
specialOps : L S := ["MATRIX","BRACKET","BRACE","CONCATB","VCONCAT",_
"AGGLST","CONCAT","OVERBAR","ROOT","SUB","TAG",_
"SUPERSUB","ZAG","AGGSET","SC","PAREN",_
"SEGMENT","QUOTE","theMap", "SLASH"]
-- the next two lists provide translations for some strings for
-- which monospace has some special character codes.
specialStrings : L S :=
["cos", "cot", "csc", "log", "sec", "sin", "tan", _
"cosh", "coth", "csch", "sech", "sinh", "tanh", _
"acos","asin","atan","erf","...","$","infinity","Gamma", _
"%pi","%e","%i"]
specialStringsInMono : L S :=
["cos","cot","csc","log","sec","sin","tan", _
"cosh","coth","csch","sech","sinh","tanh", _
"arccos","arcsin","arctan","erf","...","$","infinity",_
"Gamma","%pi","%e","%i"]
debug := false
atomize : E -> L E
formatBinary : (S, L E, I) -> CharRectangle
formatFunction : (CharRectangle, L E, I) -> CharRectangle
formatMatrix : L E -> CharRectangle
formatNary : (S, L E, I) -> CharRectangle
formatNaryNoGroup : (S, L E, I) -> CharRectangle
formatNullary : S -> CharRectangle
formatPlex : (S, L E, I) -> CharRectangle
formatSpecial : (S, L E, I) -> CharRectangle
formatUnary : (S, E, I) -> CharRectangle
formatMonomode : (E, I) -> CharRectangle
precondition : E -> E
-- this function is applied to the OutputForm expression before
-- doing anything else.
outputTree : Tree S -> Void
-- This function traverses the tree and linierises it into a string.
-- To get the formatting we use a nested set of tables. It also checks
-- for +- and removes the +. it may also need to remove the outer
-- set of brackets.
outputRectangle : CharRectangle -> Void
-- This function traverses the tree and linierises it into a string.
-- To get the formatting we use a nested set of tables. It also checks
-- for +- and removes the +. it may also need to remove the outer
-- set of brackets.
stringify : E -> S
coerce(expr : E) : S ==
outputRectangle formatMonomode(precondition expr, minPrec)
" "
coerceS(expr : E) : S ==
outputRectangle formatMonomode(precondition expr, minPrec)
" "
coerceL(expr : E) : S ==
outputRectangle formatMonomode(precondition expr, minPrec)
" "
display(mono : S) : Void ==
sayMono mono
void()$Void
-- this retuns a string representation of OutputForm arguments
-- it is used when debug is true to trace the calling of functions
-- in this package
argsToString(args : L E) : S ==
sop : S := exprex first args
args := rest args
s : S := concat ["{",sop]
for a in args repeat
s1 : S := exprex a
s := concat [s, s1]
s := concat [s,"}"]
exprex(expr : E) : S ==
-- This breaks down an expression into atoms and returns it as
-- a string. It's for developmental purposes to help understand
-- the expressions.
a : E
expr := precondition expr
(ATOM(expr)$Lisp@Boolean) or (stringify expr = "NOTHING") =>
concat ["{",stringify expr,"}"]
le : L E := (expr pretend L E)
op := first le
sop : S := exprex op
args : L E := rest le
nargs : I := #args
s : S := concat ["{",sop]
if nargs > 0 then
for a in args repeat
s1 : S := exprex a
s := concat [s, s1]
s := concat [s,"}"]
atomize(expr : E) : L E ==
-- This breaks down an expression into a flat list of atomic
-- expressions.
-- expr should be preconditioned.
le : L E := nil()
a : E
letmp : L E
(ATOM(expr)$Lisp@Boolean) or (stringify expr = "NOTHING") =>
le := append(le, list(expr))
letmp := expr pretend L E
for a in letmp repeat
le := append(le, atomize a)
le
-- output mono test using tables and
-- remove unnecessary '+' at end of first string
-- when second string starts with '-'
outputRectangle(c:CharRectangle):Void ==
s:List String := stringise(c)
for ln in s repeat
sayMono ln
void()$Void
stringify expr == (mathObject2String$Lisp expr)@S
precondition expr ==
outputTran$Lisp expr
-- I dont know what SC is so put it in a table for now
formatSC(args : L E, prec : I) : CharRectangle ==
if debug then sayMono "formatSC: "concat[" args=",_
argsToString(args)," prec=",string(prec)$S]
null args => charRectangle("")
cells : L CharRectangle := [formatMonomode(a, prec) for a in args]
--newNode("td id='sc' style='border-bottom-style:solid'",_
--formatMonomode(a, prec)) for a in args]
row:CharRectangle := hconcat(cells)
--newNode("table border='0' id='sc'",row)
row
-- draw a line over the content
-- used for square root
buildOverbar(content : CharRectangle) : CharRectangle ==
if debug then sayMono "buildOverbar"
w:NNI := getWidth(content)
s:String := ""
for i in 1..w repeat
if i=1 or i=w then s := concat(s,"+")$String
else s := concat(s,"-")$String
hconcat([charRectangle(s),content])
-- to build an square root we put it in a double column,
-- single row table and set the top border of the second column to
-- solid
buildRoot(content : CharRectangle) : CharRectangle ==
if debug then sayMono "buildRoot"
w:NNI := getWidth(content)
s:String := ""
for i in 1..w repeat
if i=1 or i=w then s := concat(s,"+")$String
else s := concat(s,"-")$String
e11:CharRectangle := charRectangle(" ")
e12:CharRectangle := charRectangle(s)
e21:CharRectangle := charRectangle("\|")
aconcat([[e11,e12],[e21,content]],"PLAIN"::Symbol)
-- to build an 'n'th root we put it in a double column,
-- single row table and set the top border of the second column to
-- solid
buildNRoot(content : CharRectangle, nth : CharRectangle) : CharRectangle ==
if debug then sayMono "buildNRoot"
w:NNI := getWidth(content)
s:String := ""
for i in 1..w repeat
if i=1 or i=w then s := concat(s,"+")$String
else s := concat(s,"-")$String
e12:CharRectangle := charRectangle(s)
e21:CharRectangle := charRectangle("\|")
aconcat([[nth,e12],[e21,content]],"PLAIN"::Symbol)
-- formatSpecial handles "theMap","AGGLST","AGGSET","TAG","SLASH",
-- "VCONCAT", "CONCATB","CONCAT","QUOTE","BRACKET","BRACE","PAREN",
-- "OVERBAR","ROOT", "SEGMENT","SC","MATRIX","ZAG"
-- note "SUB" and "SUPERSUB" are handled directly by formatMonomode
formatSpecial(op : S, args : L E, prec : I) : CharRectangle ==
if debug then sayMono _
"formatSpecial: "concat["op=",op," args=",argsToString(args),_
" prec=",string(prec)$S]
arg : E
prescript : Boolean := false
op = "theMap" => charRectangle("theMap(...)")
op = "AGGLST" =>
-- sayMono "calling formatNary with ,"
formatNary(",",args,prec)
op = "AGGSET" =>
formatNary(";",args,prec)
op = "TAG" =>
if debug then sayMono "TAG - not yet handled"
hconcat([formatMonomode(first args,prec),charRectangle("→"),_
formatMonomode(second args, prec)])
--RightArrow
op = "SLASH" =>
if debug then sayMono "SLASH - not yet handled"
formatMonomode(second args, prec) -- temp
hconcat([formatMonomode(first args, prec),charRectangle("/"),_
formatMonomode(second args, prec)])
op = "VCONCAT" =>
if debug then sayMono "VCONCAT - not yet handled"
vconcat([formatMonomode(u, minPrec) for u in args])
op = "CONCATB" =>
formatNary(" ",args,prec)
op = "CONCAT" =>
formatNary("",args,minPrec)
op = "QUOTE" =>
hconcat([charRectangle("'"),formatMonomode(first args, minPrec)])
op = "BRACKET" =>
hconcat([charRectangle("["),formatMonomode(first args, minPrec),charRectangle("]")])
op = "BRACE" =>
hconcat([charRectangle("{"),formatMonomode(first args, minPrec),charRectangle("}")])
op = "PAREN" =>
hconcat([charRectangle("("),formatMonomode(first args, minPrec),charRectangle(")")])
op = "OVERBAR" =>
null args => charRectangle("")
buildOverbar(formatMonomode(first args, minPrec))
op = "ROOT" and #args < 1 => charRectangle("")
op = "ROOT" and #args = 1 => _
buildRoot(formatMonomode(first args, minPrec))
op = "ROOT" and #args > 1 => _
buildNRoot(formatMonomode(first args, minPrec), _
formatMonomode(second args, minPrec))
op = "SEGMENT" =>
-- '..' indicates a range in a list for example
tmp : CharRectangle := hconcat([formatMonomode(first args, minPrec),_
charRectangle("..")])
null rest args => tmp
hconcat([tmp,formatMonomode(first rest args, minPrec)])
op = "SC" => formatSC(args,minPrec)
op = "MATRIX" => formatMatrix rest args
op = "ZAG" =>
-- {{+}{3}{{ZAG}{1}{7}}{{ZAG}{1}{15}}{{ZAG}{1}{1}}{{ZAG}{1}{25}}_
-- {{ZAG}{1}{1}}{{ZAG}{1}{7}}{{ZAG}{1}{4}}}
-- to format continued fraction traditionally need to intercept
-- it at the formatNary of the "+"
hconcat([charRectangle(" \zag{"),formatMonomode(first args, minPrec),
charRectangle("}{"),
formatMonomode(first rest args,minPrec),charRectangle("}")])
charRectangle("formatSpecial not implemented:"op)
formatSuperSub(expr : E, args : L E, opPrec : I) : CharRectangle ==
-- This one produces ordinary derivatives with differential notation,
-- it needs a little more work yet.
-- first have to divine the semantics, add cases as needed
if debug then sayMono _
"formatSuperSub: "concat["expr=",stringify expr," args=",_
argsToString(args)," prec=",string(opPrec)$S]
atomE : L E := atomize(expr)
op : S := stringify first atomE
op ~= "SUPERSUB" => charRectangle("Mistake in formatSuperSub: no SUPERSUB")
#args ~= 1 => charRectangle("Mistake in SuperSub: #args <> 1")
var : E := first args
-- should be looking at something like {{SUPERSUB}{var}{ }{, ,..., }}
-- for example here's the second derivative of y w.r.t. x
-- {{{SUPERSUB}{y}{ }{, ,}}{x}}, expr is the first {} and args is the
-- {x}
funcS : S := stringify first rest atomE
bvarS : S := stringify first args
-- count the number of commas
commaS : S := stringify first rest rest rest atomE
commaTest : S := ","
ndiffs : I := 0
while position(commaTest, commaS, 1) > 0 repeat
ndiffs := ndiffs+1
commaTest := commaTest","
res:CharRectangle := hconcat(_
[charRectangle("ⅆ"string(ndiffs)""funcS"ⅆ"),_
formatMonomode(first args,minPrec),charRectangle(""string(ndiffs)"⁡"),_
formatMonomode(first args,minPrec),charRectangle(")")])
res
formatPrime(expr : E, args : L E, opPrec : I) : CharRectangle ==
-- This one produces ordinary derivatives with differential notation,
-- it needs a little more work yet.
-- first have to divine the semantics, add cases as needed
if debug then sayMono _
"formatPrime: "concat["expr=",stringify expr," args=",_
argsToString(args)," prec=",string(opPrec)$S]
atomE : L E := atomize(expr)
op : S := stringify first atomE
op ~= "PRIME" => charRectangle("Mistake in formatPrime: no PRIME")
#args < 1 => charRectangle("Mistake in SuperSub: #args < 1")
var : E := first args
#atomE < 2 => hconcat([charRectangle("'"),formatMonomode(var,opPrec)])
hconcat([formatMonomode(atomE.2,opPrec),charRectangle("'"),_
charRectangle("("),_
formatMonomode(var,opPrec),charRectangle(")")])
-- build structure such as integral as a table
buildPlex3(main : CharRectangle, supsc : CharRectangle, op : CharRectangle, subsc : CharRectangle) : CharRectangle ==
if debug then sayMono "buildPlex3"
m:CharRectangle := main
ssup:CharRectangle := supsc
sop:CharRectangle := op
ssub:CharRectangle := subsc
aconcat([[ssub,sop],[ssup,m]],"PLAIN"::Symbol)
-- build structure such as integral as a table
buildPlex2(main : CharRectangle, supsc : CharRectangle, op : CharRectangle) : CharRectangle ==
m:CharRectangle := main
ssup:CharRectangle := supsc
sop:CharRectangle := op
ssub:CharRectangle := charRectangle(" ")
aconcat([[sop,ssub],[ssup,m]],"PLAIN"::Symbol)
-- draw integral symbol as:
-- ++
-- |
-- ++
integralSymbol() : CharRectangle ==
vconcat([charRectangle(" ++"),charRectangle(" | "),charRectangle("++ ")])
-- format an integral
-- args.1 = "NOTHING"
-- args.2 = bound variable
-- args.3 = body, thing being integrated
--
-- FriCAS replaces the bound variable with somthing like
-- %A and puts the original variable used
-- in the input command as a superscript on the integral sign.
formatIntSign(args : L E, opPrec : I) : CharRectangle ==
-- the original OutputForm expression looks something like this:
-- {{INTSIGN}{NOTHING or lower limit?}
-- {bvar or upper limit?}{{*}{integrand}{{CONCAT}{d}{axiom var}}}}
-- the args list passed here consists of the rest of this list, i.e.
-- starting at the NOTHING or ...
if debug then sayMono "formatIntSign: "concat[" args=",_
argsToString(args)," prec=",string(opPrec)$S]
(stringify first args) = "NOTHING" =>
buildPlex2(formatMonomode(args.3,opPrec),integralSymbol(),_
formatMonomode(args.2, opPrec))
buildPlex3(formatMonomode(first args, opPrec), formatMonomode(args.3, opPrec), _
integralSymbol(),formatMonomode(args.2,opPrec))
-- plex ops are "SIGMA","SIGMA2","PI","PI2","INTSIGN","INDEFINTEGRAL"
-- expects 2 or 3 args
formatPlex(op : S, args : L E, prec : I) : CharRectangle ==
if debug then sayMono "formatPlex: "concat["op=",op," args=",_
argsToString(args)," prec=",string(prec)$S]
checkarg : Boolean := false
hold : S
p : I := position(op, plexOps)
p < 1 => error "unknown plex op"
op = "INTSIGN" => formatIntSign(args,minPrec)
opPrec := plexPrecs.p
n : I := #args
(n ~= 2) and (n ~= 3) => error "wrong number of arguments for plex"
s : CharRectangle :=
op = "SIGMA" =>
checkarg := true
charRectangle("∑")
-- Sum
op = "SIGMA2" =>
checkarg := true
charRectangle("∑")
-- Sum
op = "PI" =>
checkarg := true
charRectangle("∏")
-- Product
op = "PI2" =>
checkarg := true
charRectangle("∏")
-- Product
op = "INTSIGN" => charRectangle("∫")
-- Integral, int
op = "INDEFINTEGRAL" => charRectangle("∫")
-- Integral, int
charRectangle("formatPlex: unexpected op:"op)
-- if opPrec < prec then perhaps we should parenthesize?
-- but we need to be careful we don't get loads of unnecessary
-- brackets
if n = 2 then return buildPlex2(formatMonomode(first args, minPrec), _
formatMonomode(args.2, minPrec), s)
buildPlex3(formatMonomode(first args, minPrec), formatMonomode(args.2, minPrec), _
s, formatMonomode(args.3, minPrec))
-- an example is: op=ROW arg={{ROW}{1}{2}}
formatMatrixRow(op : S, arg : E, prec : I, y : I, h : I) : L CharRectangle ==
if debug then sayMono "formatMatrixRow: "concat["op=",op,_
" args=",stringify arg," prec=",string(prec)$S]
ATOM(arg)$Lisp@Boolean => [_
charRectangle("formatMatrixRow does not contain row")]
l : L E := (arg pretend L E)
op : S := stringify first l
args : L E := rest l
--sayMono "formatMatrixRow op="op" args="argsToString(args)
w : I := #args
cells : (List CharRectangle) := empty()
for x in 1..w repeat
--sayMono "formatMatrixRow: x="string(x)$S" width="string(w)$S
cells := append(cells,[formatMonomode(args.(x), prec)])
cells
-- an example is: op=MATRIX args={{ROW}{1}{2}}{{ROW}{3}{4}}
formatMatrixContent(op : S, args : L E, prec : I) : L L CharRectangle ==
if debug then sayMono "formatMatrixContent: "concat["op=",op,_
" args=",argsToString(args)," prec=",string(prec)$S]
y : I := 0
rows:(List List CharRectangle) := empty()$List(List(CharRectangle))
for e in args repeat
rows := concat(rows,formatMatrixRow("ROW", e, prec, y := y + 1, #args))$List(List(CharRectangle))
rows
formatMatrix(args : L E) : CharRectangle ==
-- format for args is [[ROW ...], [ROW ...], [ROW ...]]
-- generate string for formatting columns (centered)
if debug then sayMono "formatMatrix: "concat["args=",_
argsToString(args)]
aconcat(formatMatrixContent("MATRIX",args,minPrec),"MATRIX"::Symbol)
-- output arguments in column table
buildColumnTable(elements : List CharRectangle) : CharRectangle ==
if debug then sayMono "buildColumnTable"
vconcat(elements)
-- build superscript structure as either sup tag or
-- if it contains anything that won't go into a
-- sup tag then build it as a table
buildSuperscript(main : CharRectangle, super : CharRectangle) : CharRectangle ==
if debug then sayMono "buildSuperscript"
e11:CharRectangle := charRectangle(" ")
e22:CharRectangle := charRectangle(" ")
aconcat([[e11,super],[main,e22]],"PLAIN"::Symbol)
-- build subscript structure as either sub tag or
-- if it contains anything that won't go into a
-- sub tag then build it as a table
buildSubscript(main : CharRectangle, subsc : CharRectangle) : CharRectangle ==
if debug then sayMono "buildSubscript"
e11:CharRectangle := charRectangle(" ")
e22:CharRectangle := charRectangle(" ")
aconcat([[main,e11],[e22,subsc]],"PLAIN"::Symbol)
formatSub(expr : E, args : L E, opPrec : I) : CharRectangle ==
-- format subscript
-- this function expects expr to start with SUB
-- it expects first args to be the operator or value that
-- the subscript is applied to
-- and the rest args to be the subscript
if debug then sayMono "formatSub: "concat["expr=",_
stringify expr," args=",argsToString(args)," prec=",_
string(opPrec)$S]
atomE : L E := atomize(expr)
if empty?(atomE) then
if debug then sayMono "formatSub: expr = empty"
return charRectangle("formatSub: expr = empty")
op : S := stringify first atomE
op ~= "SUB" =>
if debug then sayMono "formatSub: expr~=SUB"
charRectangle("formatSub: expr~=SUB")
-- assume args.1 is the expression and args.2 is its subscript
if debug then sayMono concat("formatSub: num args=",_
string(#args)$String)$String
if #args < 2 then
return charRectangle(concat("formatSub: num args=",_
string(#args)$String)$String)
if #args > 2 then
return buildSubscript(formatMonomode(first args, opPrec), _
hconcat([formatMonomode(e,opPrec) for e in rest args]))
-- if we get here then there are 2 args
if #atomE > 2 then
left:L CharRectangle := [formatMonomode(atomE.x, opPrec) for x in 2..#atomE]