-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathDoc.hs
1207 lines (1058 loc) · 39.6 KB
/
Doc.hs
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
{- |
Module : ./Common/Doc.hs
Description : document data type Doc for (pretty) printing in various formats
Copyright : (c) Christian Maeder and Uni Bremen 2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : portable
This module contains a document data type 'Doc' for displaying
(heterogenous) CASL specifications at least as plain text and latex
(and maybe html as well)
Inspired by John Hughes's and Simon Peyton Jones's Pretty Printer
Combinators in Text.PrettyPrint.HughesPJ, Thomas Hallgren's
PrettyDoc within programatica,
Daan Leijen's PPrint: A prettier printer 2001, and Olaf Chiti's Pretty
printing with lazy Dequeues 2003
The main combinators are those of HughesPJ except
nest, hang and $$. Instead of $$ '$+$' must be used that always forces a
line break. Indentation must be constructed using '<>' or '<+>', i.e.
'text' \"spec\" '<+>' MultilineBlock.
Also char, ptext, int, integer, float, double and rational do not
exist. These can all be simulated using 'text' (and 'show'). There's
an instance for 'Int' in "Common.DocUtils".
Furthermore, documents can no longer be tested with isEmpty. 'empty'
documents are silently ignored (as by HughesPJ) and
often it is more natural (or even necessary anyway) to test the
original data structure for emptiness.
Putting a document into braces should be done using 'specBraces' (but
a function braces is also exported), ensuring that opening and closing
braces are in the same column if the whole document does not fit on a
single line.
Rendering of documents is achieved by translations to the old
"Common.Lib.Pretty". For plain text simply 'show' can be
used. Any document can be translated to LaTeX via 'toLatex' and then
processed further by "Common.PrintLaTeX". If you like the output is a
different question, but the result should be legal LaTeX in
conjunction with the hetcasl.sty file.
For nicer looking LaTeX the predefined symbol constants should be
used! There is a difference between 'bullet' and 'dot' that is not
visible in plain text.
There are also three kinds of keywords, a plain 'keyword', a
'topSigKey' having the width of \"preds\", and a 'topKey' having the
width of \"view\". In plain text only inserted spaces are visible.
Strings in small caps are created by 'structId' and
'indexed'. The latter puts the string also into a LaTeX index.
In order to avoid considering display annotations and precedences,
documents can be constructed using 'annoDoc', 'idDoc', and 'idApplDoc'.
Currently only a few annotations (i.e. labels and %implied) are
printed 'flushRight'. This function is problematic as it does not
prevent something to be appended using '<>' or '<+>'. Furthermore
flushed parts are currently only visible in plain text, if they don't
fit on the same line (as nest is used for indenting).
Further functions are documented in "Common.DocUtils".
Examples can be produced using: hets -v2 -o pp.dol,pp.tex
-}
module Common.Doc
( -- * the document type
Doc
, Label (..)
, StripComment (..)
, renderHtml
, renderExtHtml
, renderText
, renderExtText
-- * primitive documents
, empty
, space
, semi
, comma
, colon
, quMarkD
, equals
, lparen
, rparen
, lbrack
, rbrack
, lbrace
, rbrace
-- * converting strings into documents
, plainText
, text
, codeToken
, commentText
, keyword
, topSigKey
, topKey
, indexed
, structId
-- * wrapping documents in delimiters
, parens
, brackets
, braces
, specBraces
, quotes
, doubleQuotes
-- * combining documents
-- , (<>) -- exported via instance Semigroup Doc
, (<+>)
, hcat
, hsep
, ($+$)
, ($++$)
, vcat
, vsep
, sep
, cat
, fsep
, fcat
, punctuate
, sepByCommas
, sepBySemis
-- * symbols possibly rendered differently for Text or LaTeX
, dot
, bullet
, defn
, less
, greater
, lambda
, mapsto
, funArrow
, pfun
, cfun
, pcfun
, exequal
, forallDoc
, exists
, unique
, cross
, bar
, notDoc
, inDoc
, andDoc
, orDoc
, implies
, equiv
, prefix_proc
, sequential
, interleave
, synchronous
, genpar_open
, genpar_close
, alpar_open
, alpar_sep
, alpar_close
, external_choice
, internal_choice
, hiding_proc
, ren_proc_open
, ren_proc_close
, dagger
, vdash
, dashv
, breve
-- * for Hybrid casl
, prettyAt
, prettyHere
, prettyBind
, prettyUniv
, prettyExist
-- * docifying annotations and ids
, annoDoc
, idDoc
, idLabelDoc
, predIdApplDoc
, idApplDoc
-- * transforming to existing formats
, toLatex
, toLatexAux
-- * manipulating documents
, flushRight
, changeGlobalAnnos
, rmTopKey
, showRaw
) where
import Common.AS_Annotation
import Common.ConvertLiteral
import Common.GlobalAnnotations
import Common.Id
import Common.IRI
import Common.Keywords
import Common.LaTeX_funs
import Common.Prec
import qualified Common.Lib.Pretty as Pretty
import Data.Char
import Data.List
import Data.Maybe
import qualified Data.Map as Map
import qualified Data.Set as Set
infixr 6 <+>
infixl 5 $+$
infixl 5 $++$
-- * the data type
data LabelKind = IdDecl | IdAppl deriving (Show, Eq)
data TextKind =
IdKind | IdSymb | Symbol | Comment | Keyword | TopKey Int
| Indexed | StructId | Native | HetsLabel
| IdLabel LabelKind TextKind Id deriving Show
data Format = Small | FlushRight deriving Show
data ComposeKind
= Vert -- ($+$) (no support for $$!)
| Horiz -- (<>)
| HorizOrVert -- either Horiz or Vert
| Fill
deriving (Eq, Show)
-- | an abstract data type
data Doc
= Empty -- creates an empty line if composed vertically
| AnnoDoc Annotation -- we know how to print annotations
| IdDoc LabelKind Id -- for plain ids outside applications
| IdApplDoc Bool Id [Doc] -- for mixfix applications and literal terms
| Text TextKind String -- non-empty and no white spaces inside
| Cat ComposeKind [Doc]
| Attr Format Doc -- for annotations
| ChangeGlobalAnnos (GlobalAnnos -> GlobalAnnos) Doc
showRawList :: [Doc] -> String
showRawList l = "[" ++ intercalate ", " (map showRaw l) ++ "]"
showRaw :: Doc -> String
showRaw gd =
case gd of
Empty -> "Empty"
AnnoDoc an -> "AnnoDoc(" ++ show an ++ ")"
IdDoc lk n -> "IdDoc" ++ show (lk, n)
IdApplDoc b n l ->
"IdApplDoc(" ++ show b ++ ", " ++ show n ++ ", " ++ showRawList l ++ ")"
Text tk s -> "Text(" ++ show tk ++ ", " ++ s ++ ")"
Cat ck l ->
"Cat(" ++ show ck ++ ", " ++ showRawList l ++ ")"
Attr fm d -> "Attr(" ++ show fm ++ ", " ++ showRaw d ++ ")"
ChangeGlobalAnnos _ d -> "ChangeGlobalAnnos(" ++ showRaw d ++ ")"
textStyle :: Pretty.Style
textStyle = Pretty.style
{ Pretty.ribbonsPerLine = 1.19
, Pretty.lineLength = 80 }
renderText :: GlobalAnnos -> Doc -> String
renderText = renderExtText $ StripComment False
renderExtText :: StripComment -> GlobalAnnos -> Doc -> String
renderExtText stripCs ga =
id . Pretty.renderStyle textStyle . toText stripCs ga
instance Show Doc where
show = renderText emptyGlobalAnnos
renderHtml :: GlobalAnnos -> Doc -> String
renderHtml = renderExtHtml (StripComment False) $ MkLabel False
renderExtHtml :: StripComment -> Label -> GlobalAnnos -> Doc -> String
renderExtHtml stripCs lbl ga = replSpacesForHtml 0
. Pretty.renderStyle textStyle . toHtml stripCs lbl ga
replSpacesForHtml :: Int -> String -> String
replSpacesForHtml n s = case s of
"" -> ""
c : r -> case c of
'\n' -> c : "<br />" ++ replSpacesForHtml 0 r
' ' -> replSpacesForHtml (n + 1) r
_ -> (case n of
0 -> (c :)
1 -> ([' ', c] ++)
_ -> ((' ' : concat (replicate n " ") ++ [c]) ++))
$ replSpacesForHtml 0 r
isEmpty :: Doc -> Bool
isEmpty d = case d of
Empty -> True
Cat _ [] -> True
_ -> False
-- * the visible interface
empty :: Doc -- ^ An empty document
empty = Empty
plainText :: String -> Doc
plainText = Text IdKind
text :: String -> Doc
text s = case lines s of
[] -> Text IdKind ""
[x] -> Text IdKind x
l -> vcat $ map (Text IdKind) l
semi :: Doc -- ^ A ';' character
semi = text ";"
comma :: Doc -- ^ A ',' character
comma = text ","
colon :: Doc -- ^ A ':' character
colon = symbol colonS
-- the only legal white space within Text
space :: Doc -- ^ A horizontal space (omitted at end of line)
space = text " "
equals :: Doc -- ^ A '=' character
equals = symbol equalS
-- use symbol for signs that need to be put in mathmode for latex
symbol :: String -> Doc
symbol = Text Symbol
-- for text within comments
commentText :: String -> Doc
commentText = Text Comment
-- put this string into math mode for latex and don't escape it
native :: String -> Doc
native = Text Native
lparen, rparen, lbrack, rbrack, lbrace, rbrace, quote, doubleQuote :: Doc
lparen = text "("
rparen = text ")"
lbrack = text "["
rbrack = text "]"
lbrace = symbol "{" -- to allow for latex translations
rbrace = symbol "}"
quote = symbol "\'"
doubleQuote = symbol "\""
parens :: Doc -> Doc -- ^ Wrap document in @(...)@
parens d = hcat [lparen, d, rparen]
brackets :: Doc -> Doc -- ^ Wrap document in @[...]@
brackets d = hcat [lbrack, d, rbrack]
braces :: Doc -> Doc -- ^ Wrap document in @{...}@
braces d = hcat [lbrace, d, rbrace]
specBraces :: Doc -> Doc -- ^ Wrap document in @{...}@
specBraces d = cat [addLBrace d, rbrace]
-- | move the opening brace inwards
addLBrace :: Doc -> Doc
addLBrace d = case d of
Cat k (e : r) -> Cat k $ addLBrace e : r
ChangeGlobalAnnos f e -> ChangeGlobalAnnos f $ addLBrace e
_ -> lbrace <> d
quotes :: Doc -> Doc -- ^ Wrap document in @\'...\'@
quotes d = hcat [quote, d, quote]
doubleQuotes :: Doc -> Doc -- ^ Wrap document in @\"...\"@
doubleQuotes d = hcat [doubleQuote, d, doubleQuote]
instance Semigroup Doc where
a <> b = hcat [a, b]
rmEmpties :: [Doc] -> [Doc]
rmEmpties = filter (not . isEmpty)
hcat :: [Doc] -> Doc -- ^List version of '<>'
hcat = Cat Horiz . rmEmpties
(<+>) :: Doc -> Doc -> Doc -- ^Beside, separated by space
a <+> b = hsep [a, b]
punctuate :: Doc -> [Doc] -> [Doc]
punctuate d l = case l of
x : r@(_ : _) -> (x <> d) : punctuate d r
_ -> l
hsep :: [Doc] -> Doc -- ^List version of '<+>'
hsep = Cat Horiz . punctuate space . rmEmpties
($+$) :: Doc -> Doc -> Doc -- ^Above, without dovetailing.
a $+$ b = vcat [a, b]
-- | vertical composition with a specified number of blank lines
aboveWithNLs :: Int -> Doc -> Doc -> Doc
aboveWithNLs n d1 d2
| isEmpty d2 = d1
| isEmpty d1 = d2
| otherwise = d1 $+$ foldr ($+$) d2 (replicate n $ text "")
-- | vertical composition with one blank line
($++$) :: Doc -> Doc -> Doc
($++$) = aboveWithNLs 1
-- | list version of '($++$)'
vsep :: [Doc] -> Doc
vsep = foldr ($++$) empty
vcat :: [Doc] -> Doc -- ^List version of '$+$'
vcat = Cat Vert . rmEmpties
cat :: [Doc] -> Doc -- ^ Either hcat or vcat
cat = Cat HorizOrVert . rmEmpties
sep :: [Doc] -> Doc -- ^ Either hsep or vcat
sep = Cat HorizOrVert . punctuate space . rmEmpties
fcat :: [Doc] -> Doc -- ^ \"Paragraph fill\" version of cat
fcat = Cat Fill . rmEmpties
fsep :: [Doc] -> Doc -- ^ \"Paragraph fill\" version of sep
fsep = Cat Fill . punctuate space . rmEmpties
keyword, topSigKey, topKey, indexed, structId :: String -> Doc
keyword = Text Keyword
indexed = Text Indexed
structId = Text StructId
topKey = Text (TopKey 4)
topSigKey = Text (TopKey 5)
lambdaSymb, daggerS, vdashS, dashvS, breveS :: String
lambdaSymb = "\\"
daggerS = "!"
vdashS = "|-"
dashvS = "-|"
breveS = "~"
-- docs possibly rendered differently for Text or LaTeX
quMarkD, dot, bullet, defn, less, greater, lambda, mapsto, funArrow, pfun,
cfun, pcfun, exequal, forallDoc, exists, unique, cross, bar, notDoc,
inDoc, andDoc, orDoc, implies, equiv, prefix_proc, sequential,
interleave, synchronous, genpar_open, genpar_close, alpar_open,
alpar_sep, alpar_close, external_choice, internal_choice, hiding_proc,
ren_proc_open, ren_proc_close, dagger, vdash, dashv, breve, prettyAt,
prettyHere, prettyBind, prettyUniv, prettyExist :: Doc
quMarkD = text quMark
dot = text dotS
bullet = symbol dotS
defn = symbol defnS
less = symbol lessS
greater = symbol greaterS
lambda = symbol lambdaSymb
mapsto = symbol mapsTo
funArrow = symbol funS
pfun = symbol pFun
cfun = symbol contFun
pcfun = symbol pContFun
exequal = symbol exEqual
forallDoc = symbol forallS
exists = symbol existsS
unique = symbol existsUnique
cross = symbol prodS
bar = symbol barS
notDoc = symbol notS
inDoc = symbol inS
andDoc = symbol lAnd
orDoc = symbol lOr
implies = symbol implS
equiv = symbol equivS
prefix_proc = symbol prefix_procS
sequential = text sequentialS
interleave = symbol interleavingS
synchronous = symbol synchronousS
genpar_open = symbol genpar_openS
genpar_close = symbol genpar_closeS
alpar_open = symbol alpar_openS
-- note that alpar_sepS and synchronousS are equal
alpar_sep = symbol alpar_sepS
alpar_close = symbol alpar_closeS
external_choice = symbol external_choiceS
internal_choice = symbol internal_choiceS
hiding_proc = text hiding_procS -- otherwise it clashes with lambda
ren_proc_open = symbol ren_proc_openS
ren_proc_close = symbol ren_proc_closeS
dagger = symbol daggerS
vdash = symbol vdashS
dashv = symbol dashvS
breve = symbol breveS
-- * for hybrid casl
prettyAt = symbol asP
prettyHere = symbol "Here"
prettyBind = symbol "Bind"
prettyUniv = symbol "Univ"
prettyExist = symbol "Exist"
-- | we know how to print annotations
annoDoc :: Annotation -> Doc
annoDoc = AnnoDoc
-- | for plain ids outside of terms
idDoc :: Id -> Doc
idDoc = IdDoc IdAppl
-- | for newly declared ids
idLabelDoc :: Id -> Doc
idLabelDoc = IdDoc IdDecl
-- | for mixfix applications and literal terms (may print \"\" for empty)
idApplDoc :: Id -> [Doc] -> Doc
idApplDoc = IdApplDoc False
-- | for mixfix applications of predicate identifiers
predIdApplDoc :: Id -> [Doc] -> Doc
predIdApplDoc = IdApplDoc True
-- | put document as far to the right as fits (for annotations)
flushRight :: Doc -> Doc
flushRight = Attr FlushRight
small :: Doc -> Doc
small = Attr Small
-- * folding stuff
data DocRecord a = DocRecord
{ foldEmpty :: Doc -> a
, foldAnnoDoc :: Doc -> Annotation -> a
, foldIdDoc :: Doc -> LabelKind -> Id -> a
, foldIdApplDoc :: Doc -> Bool -> Id -> [a] -> a
, foldText :: Doc -> TextKind -> String -> a
, foldCat :: Doc -> ComposeKind -> [a] -> a
, foldAttr :: Doc -> Format -> a -> a
, foldChangeGlobalAnnos :: Doc -> (GlobalAnnos -> GlobalAnnos) -> a -> a
}
foldDoc :: DocRecord a -> Doc -> a
foldDoc r d = case d of
Empty -> foldEmpty r d
AnnoDoc a -> foldAnnoDoc r d a
IdDoc l i -> foldIdDoc r d l i
IdApplDoc b i l -> foldIdApplDoc r d b i $ map (foldDoc r) l
Text k s -> foldText r d k s
Cat k l -> foldCat r d k $ map (foldDoc r) l
Attr a e -> foldAttr r d a $ foldDoc r e
ChangeGlobalAnnos f e -> foldChangeGlobalAnnos r d f $ foldDoc r e
idRecord :: DocRecord Doc
idRecord = DocRecord
{ foldEmpty = const Empty
, foldAnnoDoc = const AnnoDoc
, foldIdDoc = const IdDoc
, foldIdApplDoc = const IdApplDoc
, foldText = const Text
, foldCat = const Cat
, foldAttr = const Attr
, foldChangeGlobalAnnos = const ChangeGlobalAnnos
}
anyRecord :: DocRecord a
anyRecord = DocRecord
{ foldEmpty = error "anyRecord.Empty"
, foldAnnoDoc = error "anyRecord.AnnoDoc"
, foldIdDoc = error "anyRecord.IdDoc"
, foldIdApplDoc = error "anyRecord.IdApplDoc"
, foldText = error "anyRecord.Text"
, foldCat = error "anyRecord.Cat"
, foldAttr = error "anyRecord.Attr"
, foldChangeGlobalAnnos = error "anyRecord.ChangeGlobalAnnos"
}
newtype Label = MkLabel Bool
newtype StripComment = StripComment Bool
-- * conversion to plain text
-- | simple conversion to a standard text document
toText :: StripComment -> GlobalAnnos -> Doc -> Pretty.Doc
toText stripCs ga = toTextAux . codeOut stripCs ga
(mkPrecIntMap $ prec_annos ga) Nothing Map.empty
toTextAux :: Doc -> Pretty.Doc
toTextAux = foldDoc anyRecord
{ foldEmpty = const Pretty.empty
, foldText = \ _ k s -> case k of
TopKey n -> Pretty.text $ s ++ replicate (n - length s) ' '
_ -> Pretty.text s
, foldCat = \ d c l -> case d of
Cat _ ds@(_ : _) -> if all hasSpace $ init ds then
(case c of
Vert -> Pretty.vcat
Horiz -> Pretty.hsep
HorizOrVert -> Pretty.sep
Fill -> Pretty.fsep) $ map (toTextAux . rmSpace) ds
else (case c of
Vert -> Pretty.vcat
Horiz -> Pretty.hcat
HorizOrVert -> Pretty.cat
Fill -> Pretty.fcat) l
_ -> Pretty.empty
, foldAttr = \ _ k d -> case k of
FlushRight -> let l = length $ show d in
if l < 66 then Pretty.nest (66 - l) d else d
_ -> d
, foldChangeGlobalAnnos = \ _ _ d -> d
}
-- * conversion to html
-- | conversion to html
toHtml :: StripComment -> Label -> GlobalAnnos -> Doc -> Pretty.Doc
toHtml stripCs lbl ga d = let
dm = Map.map (Map.! DF_HTML)
. Map.filter (Map.member DF_HTML) $ display_annos ga
dis = getDeclIds d
in foldDoc (toHtmlRecord lbl dis) $ codeOut stripCs ga
(mkPrecIntMap $ prec_annos ga) (Just DF_HTML) dm d
toHtmlRecord :: Label -> Set.Set Id -> DocRecord Pretty.Doc
toHtmlRecord lbl dis = anyRecord
{ foldEmpty = const Pretty.empty
, foldText = const $ textToHtml lbl dis
, foldCat = \ d c l -> case d of
Cat _ ds@(_ : _) -> if all hasSpace $ init ds then
(case c of
Vert -> Pretty.vcat
Horiz -> Pretty.hsep
HorizOrVert -> Pretty.sep
Fill -> Pretty.fsep)
$ map (foldDoc (toHtmlRecord lbl dis) . rmSpace) ds
else (case c of
Vert -> Pretty.vcat
Horiz -> Pretty.hcat
HorizOrVert -> Pretty.cat
Fill -> Pretty.fcat) l
_ -> Pretty.empty
, foldAttr = \ a k d -> case k of
FlushRight ->
let Attr _ o = a
l = length $ show $ toTextAux o
in if l < 66 then Pretty.nest (66 - l) d else d
_ -> d
, foldChangeGlobalAnnos = \ _ _ d -> d
}
textToHtml :: Label -> Set.Set Id -> TextKind -> String -> Pretty.Doc
textToHtml lbl@(MkLabel mkLbl) dis k s = let
e = escapeHtml s ""
h = Pretty.text e
zeroText = Pretty.sizedText 0
tagB t = '<' : t ++ ">"
tagE t = tagB $ '/' : t
tag t d = Pretty.hcat [zeroText (tagB t), d, zeroText (tagE t) ]
tagBold = tag "strong"
hi = tag "em" h
in case k of
Native -> Pretty.text s
Keyword -> tagBold h
TopKey n -> let l = n - length s in
tagBold $ h Pretty.<> Pretty.text (replicate l ' ')
Comment -> tag "small" h
Indexed -> hi
StructId -> hi
HetsLabel -> tag "small" hi
IdLabel appl tk i -> let
d = textToHtml lbl dis tk s
si = escapeHtml (showId i "") ""
in if mkLbl && Set.member i dis then Pretty.hcat
[zeroText $ "<a " ++ (if appl == IdAppl then "href=\"#" else "name=\"")
++ si ++ "\">", d, zeroText "</a>"]
else d
_ -> h
escChar :: Char -> ShowS
escChar c = case c of
'\'' -> showString "'"
'<' -> showString "<"
'>' -> showString ">"
'&' -> showString "&"
'"' -> showString """
_ -> showChar c
escapeHtml :: String -> ShowS
escapeHtml cs rs = foldr escChar rs cs
-- * conversion to latex
toLatex :: GlobalAnnos -> Doc -> Pretty.Doc
toLatex = toLatexAux (StripComment False) $ MkLabel False
toLatexAux :: StripComment -> Label -> GlobalAnnos -> Doc -> Pretty.Doc
toLatexAux stripCs lbl ga d = let
dm = Map.map (Map.! DF_LATEX) .
Map.filter (Map.member DF_LATEX) $ display_annos ga
dis = getDeclIds d
in foldDoc (toLatexRecord lbl dis False)
. makeSmallMath False False $ codeOut stripCs ga
(mkPrecIntMap $ prec_annos ga) (Just DF_LATEX) dm d
-- avoid too many tabs
toLatexRecord :: Label -> Set.Set Id -> Bool -> DocRecord Pretty.Doc
toLatexRecord lbl dis tab = anyRecord
{ foldEmpty = const Pretty.empty
, foldText = const $ textToLatex lbl dis False
, foldCat = \ o _ _ -> case o of
Cat c os@(d : r)
| any isNative os -> Pretty.hcat $
latex_macro "{\\Ax{"
: map (foldDoc (toLatexRecord lbl dis False)
{ foldText = \ _ k s ->
case k of
Native -> Pretty.sizedText (axiom_width s) s
IdLabel _ Native _ ->
Pretty.sizedText (axiom_width s) s
IdKind | s == " " ->
Pretty.sizedText (axiom_width s) "\\,"
_ -> textToLatex lbl dis False k s
}) os
++ [latex_macro "}}"]
| null r -> foldDoc (toLatexRecord lbl dis tab) d
| otherwise -> (if tab && c /= Horiz then
(latex_macro setTab Pretty.<>)
. (latex_macro startTab Pretty.<>)
. (Pretty.<> latex_macro endTab)
else id)
$ (case c of
Vert -> Pretty.vcat
Horiz -> Pretty.hcat
HorizOrVert -> Pretty.cat
Fill -> Pretty.fcat)
$ case c of
Vert ->
map (foldDoc $ toLatexRecord lbl dis False) os
_ -> foldDoc (toLatexRecord lbl dis False) d :
map (foldDoc $ toLatexRecord lbl dis True) r
_ -> Pretty.empty
, foldAttr = \ o k d -> case k of
FlushRight -> flushright d
Small -> case o of
Attr Small (Text j s) -> textToLatex lbl dis True j s
_ -> makeSmallLatex True d
, foldChangeGlobalAnnos = \ _ _ d -> d
}
-- | move a small attribute inwards but not into mathmode bits
makeSmallMath :: Bool -> Bool -> Doc -> Doc
makeSmallMath smll math =
foldDoc idRecord
{ foldAttr = \ o _ _ -> case o of
Attr Small d -> makeSmallMath True math d
Attr k d -> Attr k $ makeSmallMath smll math d
_ -> error "makeSmallMath.foldAttr"
, foldCat = \ o _ _ -> case o of
Cat c l
| any isNative l ->
(if smll then Attr Small else id)
-- flatten math mode bits
$ Cat Horiz $ map
(makeSmallMath False True . rmSpace) l
| math -> Cat Horiz
$ map (makeSmallMath False True) l
| smll && allHoriz o ->
-- produce fewer small blocks with wrong size though
Attr Small $ Cat Horiz $
map (makeSmallMath False math) l
| otherwise -> Cat c $ map (makeSmallMath smll math) l
_ -> error "makeSmallMath.foldCat"
, foldText = \ d _ _ -> if smll then Attr Small d else d
}
-- | check for unbalanced braces
needsMathMode :: Int -> String -> Bool
needsMathMode i s = case s of
[] -> i > 0
'{' : r -> needsMathMode (i + 1) r
'}' : r -> i == 0 || needsMathMode (i - 1) r
_ : r -> needsMathMode i r
isMathLatex :: Doc -> Bool
isMathLatex d = case d of
Text Native s -> needsMathMode 0 s
Text (IdLabel _ Native _) s -> needsMathMode 0 s
Attr Small f -> isMathLatex f
_ -> False
isNative :: Doc -> Bool
isNative d = case d of
Cat Horiz [t, _] -> isMathLatex t
_ -> isMathLatex d
-- | remove the spaces inserted by punctuate
rmSpace :: Doc -> Doc
rmSpace = snd . anaSpace
hasSpace :: Doc -> Bool
hasSpace = fst . anaSpace
anaSpace :: Doc -> (Bool, Doc)
anaSpace d = case d of
Cat Horiz [t, Text IdKind s] | s == " " -> (True, t)
_ -> (False, d)
allHoriz :: Doc -> Bool
allHoriz d = case d of
Text _ _ -> True
Cat Horiz l -> all allHoriz l
Attr _ f -> allHoriz f
Empty -> True
_ -> False
makeSmallLatex :: Bool -> Pretty.Doc -> Pretty.Doc
makeSmallLatex b d = if b then
Pretty.hcat [latex_macro startAnno, d, latex_macro endAnno] else d
symbolToLatex :: String -> Pretty.Doc
symbolToLatex s =
Map.findWithDefault (hc_sty_axiom $ escapeSpecial s) s latexSymbols
getDeclIds :: Doc -> Set.Set Id
getDeclIds = foldDoc anyRecord
{ foldEmpty = const Set.empty
, foldText = \ _ _ _ -> Set.empty
, foldCat = \ _ _ -> Set.unions
, foldAttr = \ _ _ d -> d
, foldChangeGlobalAnnos = \ _ _ d -> d
, foldIdDoc = \ _ lk i ->
if lk == IdDecl then Set.singleton i else Set.empty
, foldIdApplDoc = \ _ _ _ _ -> Set.empty
, foldAnnoDoc = \ _ _ -> Set.empty
}
textToLatex :: Label -> Set.Set Id -> Bool -> TextKind -> String -> Pretty.Doc
textToLatex lbl@(MkLabel mkLbl) dis b k s = case s of
"" -> Pretty.text ""
h : _ -> let e = escapeLatex s in case k of
IdKind -> makeSmallLatex b $ if elem s $ map (: []) ",;[]() "
then casl_normal_latex s
else hc_sty_id e
IdSymb -> makeSmallLatex b $ if s == "__" then symbolToLatex s
else if isAlpha h || elem h "._'" then hc_sty_id e
else hc_sty_axiom (escapeSpecial s)
Symbol -> makeSmallLatex b $ symbolToLatex s
Comment -> makeSmallLatex b $ casl_comment_latex e
-- multiple spaces should be replaced by \hspace
Keyword -> (if b then makeSmallLatex b . hc_sty_small_keyword
else hc_sty_plain_keyword) s
TopKey _ -> hc_sty_casl_keyword s
Indexed -> hc_sty_structid_indexed s
StructId -> hc_sty_structid s
Native -> hc_sty_axiom s
HetsLabel -> let d = textToLatex lbl dis b Comment s in
if mkLbl then Pretty.hcat [ latex_macro "\\HetsLabel{", d
, latex_macro $ "}{" ++ escapeLabel s ++ "}" ]
else d
-- HetsLabel may be avoided by the Label case
IdLabel appl tk i -> let
d = textToLatex lbl dis b tk s
si = showId i ""
in if b || not mkLbl || appl == IdAppl && not (Set.member i dis)
|| not (isLegalLabel si)
-- make this case True to avoid labels
then d else Pretty.hcat
[ latex_macro $ '\\' : shows appl "Label{"
, d
, latex_macro $ "}{" ++ escapeLabel si ++ "}" ]
escapeLabel :: String -> String
escapeLabel = map ( \ c -> if c == '_' then ':' else c)
latexSymbols :: Map.Map String Pretty.Doc
latexSymbols = Map.union (Map.fromList
[ ("{", casl_normal_latex "\\{")
, ("}", casl_normal_latex "\\}")
, (barS, casl_normal_latex "\\AltBar{}")
, (percentS, hc_sty_small_keyword "%")
, (percents, hc_sty_small_keyword "%%")
, (exEqual, Pretty.sizedText (axiom_width "=") "\\Ax{\\stackrel{e}{=}}") ])
$ Map.map hc_sty_axiom $ Map.fromList
[ (dotS, "\\bullet")
, (diamondS, "\\Diamond")
, ("__", "\\_\\_")
, (lambdaSymb, "\\lambda")
, (mapsTo, "\\mapsto")
, (funS, "\\rightarrow")
, (pFun, "\\rightarrow?")
, (contFun, "\\stackrel{c}{\\rightarrow}")
, (pContFun, "\\stackrel{c}{\\rightarrow}?")
, (forallS, "\\forall")
, (existsS, "\\exists")
, (existsUnique, "\\exists!")
, (prodS, "\\times")
, (notS, "\\neg")
, (inS, "\\in")
, (lAnd, "\\wedge")
, (lOr, "\\vee")
, (daggerS, "\\dag")
, (vdashS, "\\vdash")
, (dashvS, "\\dashv")
, (breveS, "\\breve{~}")
, (implS, "\\Rightarrow")
, (equivS, "\\Leftrightarrow")
, (interleavingS, "{|}\\mkern-2mu{|}\\mkern-2mu{|}")
, (synchronousS, "\\parallel")
, (external_choiceS, "\\Box")
, (internal_choiceS, "\\sqcap")
, (ren_proc_openS, "[\\mkern-2mu{[}")
, (ren_proc_closeS, "]\\mkern-2mu{]}")
]
-- * coding out stuff
{- | transform document according to a specific display map and other
global annotations like precedences, associativities, and literal
annotations. -}
codeOut :: StripComment -> GlobalAnnos -> PrecMap -> Maybe Display_format
-> Map.Map Id [Token] -> Doc -> Doc
codeOut stripCs ga precs d m = foldDoc idRecord
{ foldAnnoDoc = \ _ -> small . codeOutAnno stripCs m
, foldIdDoc = \ _ lk -> codeOutId lk m
, foldIdApplDoc = \ o _ _ -> codeOutAppl stripCs ga precs d m o
, foldChangeGlobalAnnos = \ o _ _ ->
let ChangeGlobalAnnos fg e = o
ng = fg ga
in codeOut stripCs ng (mkPrecIntMap $ prec_annos ng) d
(maybe m (\ f -> Map.map (Map.! f) .
Map.filter (Map.member f) $ display_annos ng) d) e
}
codeToken :: String -> Doc
codeToken = Text IdSymb
codeOrigId :: LabelKind -> Map.Map Id [Token] -> Id -> [Doc]
codeOrigId lk m i@(Id ts cs _) = let
(toks, places) = splitMixToken ts
conv = reverse . snd . foldl ( \ (b, l) t ->
let s = tokStr t
in if isPlace t then (b, symbol s : l)
else (True, (if b then codeToken s else makeLabel lk IdSymb s i)
: l)) (False, [])
in if null cs then conv ts
else conv toks ++ codeCompIds m cs : conv places
cCommaT :: Map.Map Id [Token] -> [Id] -> [Doc]
cCommaT m = punctuate comma . map (codeOutId IdAppl m)
codeCompIds :: Map.Map Id [Token] -> [Id] -> Doc
codeCompIds m = brackets . fcat . cCommaT m
codeOutId :: LabelKind -> Map.Map Id [Token] -> Id -> Doc
codeOutId lk m i = fcat $ case Map.lookup i m of
Nothing -> codeOrigId lk m i
Just ts -> reverse $ snd $ foldl ( \ (b, l) t ->
let s = tokStr t
in if isPlace t then (b, symbol s : l) else
(True, (if b then native s else
makeLabel lk Native s i) : l)) (False, []) ts
makeLabel :: LabelKind -> TextKind -> String -> Id -> Doc
makeLabel l k s i = Text (IdLabel l k i) s
annoLine :: String -> Doc
annoLine w = percent <> keyword w
annoLparen :: String -> Doc
annoLparen w = percent <> keyword w <> lparen
wrapLines :: TextKind -> Doc -> [String] -> Doc -> Doc
wrapLines k a l b = let p = (null (head l), null (last l)) in
case map (Text k) l of
[] -> a <> b
[x] -> hcat [a, x, b]
[x, y] -> case p of
(True, c) -> a $+$ if c then b else y <> b
(False, True) -> a <> x $+$ b
_ -> a <> (x $+$ y <> b)
x : r -> let
m = init r
y = last r
xm = x : m
am = a : m
yb = [y <> b]
in case p of
(True, c) -> vcat $ am ++ if c then [b] else yb
(False, True) -> a <> vcat xm $+$ b
_ -> a <> vcat (xm ++ yb)
wrapAnnoLines :: Doc -> [String] -> Doc -> Doc
wrapAnnoLines = wrapLines Comment
percent :: Doc
percent = symbol percentS
annoRparen :: Doc
annoRparen = rparen <> percent