-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtex.hs
More file actions
1559 lines (1314 loc) · 58.1 KB
/
tex.hs
File metadata and controls
1559 lines (1314 loc) · 58.1 KB
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
{-
This is the pre-processor which converts the Latex / verbatim of the
Haskell Report into HTML.
This program has evolved in a rather unplanned manner and is now a
jumble of absolutely crappy code, tacked-on features, no documentation,
and other fun stuff. I dislike the other tex -> html translations so
I wrote my own. So there. At least you can tweak the heck out of
this thing to make the html look just right if you want to.
Lots of stuff could be made more automatic. There's still a bunch of
stuff I do by hand to latex code. Especially the images in figures.
The parsing code here is absolutely terrible. I wrote it before the
parser library was part of Hugs. Also everything is way too
stateful. I will cheerfully refund your money if you don't like this
software.
This code runs under Hugs 1.4. Probably under all the other Haskell
compilers too.
To run, just change to the directory containing the .tex / .hs / .verb
files and run main. It always reads `html.config' to setup
parameters.
Configuration file stuff:
aux = file Add definitions in a latex .aux file
htmldir = directory Output directory
files = file1, file2, ... Files to be processed. Cumulative.
index = file Index file to be generated if given. All
section headings are hyperlinked from the index.
refs = file file resolving refs to files. Maps latex tags
onto the html file where they are defined.
morerefs = file For refs to another document for hyperlinks
across docs
style = s1, s2, ... Set document style(s). Styles:
report -- latex document style
article -- latex document style
microsoftsymbols -- Use microsoft symbol font
~mac = value Define macros used in raw html
#comment Only on separate lines.
You can probably make the generated stuff a lot prettier by changing
the html in the page header / footer.
Within the latex file, here's what's special:
%** raw html ~foo expands the definition of foo. ~prev and ~next
are special
%*anchor on/off
Add labels to Haskell source code
%*ignore Define lines to be ignored.
%*endignore
%*section n Set current section number. Gotta do this for appendix.
Some special latex commands (you need to add the definitions to the
latex file).
\newcommand{\anchor}[2]{#2} --
\anchor{url}{text in anchor}
\newcommand{\inputHS}{\input}
\input{foo} include the Haskell source file foo.hs
\newcommand{\outlinec}{\outline} % Centered outlines in html
No expansion of Tex definitions is attempted. You gotta add every
user-defined latex command to the master table. Many primitive latex
commands are supported but not all.
John Peterson
-}
module Main where
import Control.Monad(foldM)
import Control.Exception(catch, IOException)
import System.IO hiding (bracket)
import Data.Char(isSpace, isAlpha, isDigit)
data FontStyle = RM | IT | TT | Bold | Sym | UL
deriving (Eq,Show)
data Font = Font FontStyle Int String -- Has a size and color
deriving (Eq, Show)
ttFont = Font TT 3 ""
mathFont = Font IT 3 ""
romanFont = Font RM 3 ""
instance Show (a -> b) where
showsPrec _ _ = showString "<Function>"
data HaskellDef =
HVars [String] | HTycon String | HInstance String String
deriving Show
data HTML = HProtect [HTML] -- Boundary for local font changes
| HString String -- data characters in text mode
| HISO String -- ISO character name
| HPara -- Paragraph break
| HCmd String -- a raw html command
| HEol -- a soft end of line
| HVerb String -- A string of chars in Verb mode
| HVerbLine String -- as above with a newline
| HAnchor String HTML -- Hyperlinked text
| HDef String -- hyperlink label definition
| HSub HTML -- Subscript
| HSuper HTML -- Superscript
| HQuote HTML -- Quoted text
| HCenter HTML -- Centered text
| HFont FontStyle -- Font selection.
| HColor String -- Color selection.
| HSize Int -- Size selection.
| HLineBreak -- Hard line break (<br>)
| HTable String String [Int] HTML -- Tables.
| HSep -- Column separation in a table
| HHdr Int String HTML -- Heading with anchor
| HList String HTML -- Itemized lists and friends
| HItem HTML -- List bullet
| HSpecial Int -- Special character
| HEmpty
deriving Show
type PC = IO (State, String, [String])
type PCFun = State -> String -> [String] -> PC
emit :: HTML -> PCFun
emit h s = doChar (h +++ s)
h +++ s = s {html = h : html s}
h +++. s = s {html = h : dropWhite (html s)}
dropWhite (HEol : h) = dropWhite h
dropWhite (HPara : h) = dropWhite h
dropWhite h = h
delimiter :: String -> PCFun
delimiter d s l ls = do -- putStr ("Closing: " ++ d ++ "\n")
(head (delims s)) d s l ls
catchd :: (String -> [HTML] -> PCFun) -> State -> String -> [String] ->
PCFun -> PC
catchd f s l ls k = do -- putStr ("open at " ++ l ++ "\n")
k s' l ls where
s' = s {delims = (passHtml f (html s)) : delims s, html = []}
passHtml f h = \d s -> f d (reverse (html s))
(s {html = h, delims = tail (delims s)} )
reqDelim :: String -> ([HTML] -> HTML) -> PCFun -> (String -> [HTML] -> PCFun)
reqDelim d f k = \d' h s l ls -> if d == d' then
k (f h +++ s) l ls
else
do putStr ("Missing " ++ d ++ ", found " ++
d' ++ " instead.\n")
doChar s l ls
reqDelim1 :: String -> ([HTML] -> HTML) -> PCFun -> (String -> [HTML] -> PCFun)
reqDelim1 d f k = \d' h s l ls -> if d == d' then
k (f h +++ s) l ls
else
do putStr ("Missing " ++ d ++ ", found " ++
d' ++ " instead.\n")
return (s,l,ls)
getArg :: (HTML -> PCFun) -> PCFun
getArg k s l ls = getArgf1 '{' '}' k s l ls
getArg2 :: (HTML -> HTML -> PCFun) -> PCFun
getArg2 f = getArg (\h1 -> getArg (\h2 -> f h1 h2))
getArg3 :: (HTML -> HTML -> HTML -> PCFun) -> PCFun
getArg3 f = getArg (\h1 -> getArg (\h2 -> getArg (\h3 -> f h1 h2 h3)))
getArgf1 :: Char -> Char -> (HTML -> PCFun) -> PCFun
getArgf1 open close k s l ls = getArgf2 (trim l) ls where
getArgf2 "" [] = do putStr "EOF where arg expected\n"
delimiter "EOF" s "" []
getArgf2 "" (l:ls) = getArgf2 (trim l) ls
getArgf2 l@(c:cs) ls | c == open =
catchd (reqDelim [close] HProtect (retArg k))
s cs ls doChar
| otherwise = k HEmpty s l ls
retArg :: (HTML -> PCFun) -> PCFun
retArg k s l ls = k (head (html s)) (s {html = tail (html s)}) l ls
-- This program reads in a configuration file as a argument. If no
-- argument is given, the default is "config.html"
main = do configFile <- getConfig
s <- parseConfig configFile
s' <- processFiles s
writeRefFile s'
writeIndexFile s'
getConfig :: IO String
getConfig = return "html.config"
writeRefFile s =
case (refFile s) of
"" -> return ()
f -> do putStr ("Writing reference file " ++ f ++ "\n")
catch (writeFile f (concat (map fmtKV (newRefMap s))))
(\(e :: IOException) -> do
putStr ("Can't write ref file: " ++ f ++ "\n")
return ())
where fmtKV (k,v) = k ++ "=" ++ v ++ "\n"
writeIndexFile s =
case (indexFile s) of
"" -> return ()
f -> do putStr ("Writing index file " ++ f ++ "\n")
let cmd = case (lookup "indexHeader" (macdefs s)) of
Just _ -> macroExpand s "~indexHeader" ++ "\n"
_ -> ""
hdrs = concat (map (\h -> [HItem HEmpty, h, HEol])
(reverse (indexHTML s)))
idx = htmlToString
(HProtect [HCmd cmd, HList "item" (HProtect hdrs)])
catch (writeFile f idx)
(\(e :: IOException) -> do
putStr ("Can't write index file: " ++ f ++ "\n")
return ())
-- parseConfig parses a configuration file to yield an initial state
-- An entry in the config file is a 'tag = value' pair. Tags supported are:
-- aux = file Add definitions in a latex .aux file
-- proganchors = file Anchor the listed productions. One per file line.
-- syntaxanchors = file Anchor the listed functions. One per file line.
-- htmldir = directory Output directory
-- files = file1, file2, ... Files to be processed. Cumulative.
-- index = file index file to be generated if given
-- refs = file file resolving refs to files.
-- style = style Set document style
-- ~mac = value Macro definition
-- #comment Only on separate lines.
parseConfig :: String -> IO IState
parseConfig f = catch
(do c <- readFile f
foldM configLine initState (lines c))
(\(e :: IOException) -> error ("Can't read configuration file " ++ f))
configLine s l | "#" `starts` l = return s
| l == "" = return s
| otherwise =
let (k,v) = parseKV l in
case k of
"aux" -> do putStr ("Reading aux file " ++ v ++ "\n")
a <- readAuxFile v
return (s {auxInfo = auxInfo s ++ a})
"proganchors" -> do a <- readAnchorFile v
return (s {panchors = panchors s ++ a})
"files" -> return (s {sourceFiles = sourceFiles s ++ parseCommas v})
"htmldir" -> return (s {htmlDir = v})
"index" -> return (s {indexFile = v})
"refs" -> do refs <- readRefFile v
return (s {refFile = v, refMap = refs})
-- Has to come after refs
"morerefs" -> do morerefs <- readRefFile v
return (s {refMap = refMap s ++ morerefs})
"style" -> return (s {style = parseCommas v})
'~':m -> return (s {macdefs = (m,v) : macdefs s})
_ -> badline where
badline = error ("Bad line in config:\n" ++ l ++ "\n")
readRefFile :: String -> IO [(String, String)]
readRefFile f = catch (do l <- readFile f
return (map parseKV (lines l)))
(\(e :: IOException) -> do
putStr ("Can't read ref file: " ++ f ++ "\n")
return [])
readAuxFile :: String -> IO [(String,String)]
readAuxFile f = catch (do l <- readFile f
return (processAuxLines (lines l)))
(\(e :: IOException) -> do
putStr ("Can't read aux file: " ++ f ++ "\n")
return [])
readAnchorFile :: String -> IO [String]
readAnchorFile f = catch (do l <- readFile f
return (lines l))
(\(e :: IOException) -> do
putStr ("Can't read anchor file: " ++ f ++ "\n")
return [])
-- Look for \newlabel{label}{value} in aux files. Ignore all else.
processAuxLines :: [String] -> [(String,String)]
processAuxLines [] = []
processAuxLines (l:ls) | "\\newlabel" `starts` l = f 10 3 ""
| "\\bibcite" `starts` l = f 9 2 "$"
| otherwise = rest
where
rest = processAuxLines ls
f x1 x2 prefix = (prefix++name,val) : rest where
dropNewLabel = drop x1 l -- kills \newlabel{ or \bibcite{
(name,r) = break (== '}') dropNewLabel
r' = drop x2 r
val = takeWhile (/= '}') r'
parseKV l = let (k,l1) = span (/= '=') l
val = case l1 of
('=':v) -> trim v
_ -> ""
in (trimr k,val)
parseCommas :: String -> [String]
parseCommas "" = []
parseCommas l = let (tok,l') = break (== ',') l in
filter (/= ' ') tok :
(case l' of "" -> []
(_:l'') -> parseCommas l'')
-- Data Defintions
-- Current mode in Latex source
data IState = IState { sourceFiles :: [String],
auxInfo :: [(String,String)],
panchors :: [String],
sanchors :: [String],
anchorMode :: Bool,
htmlDir :: String,
sourceFile :: String,
indexFile :: String,
indexHTML :: [HTML],
verbMode :: Bool,
section :: [String],
avoidSectionBump :: Bool,
inMath :: Bool,
inQuotes :: Bool,
refFile :: String,
refMap :: [(String,String)],
newRefMap :: [(String,String)],
style :: [String],
macdefs :: [(String,String)]}
deriving Show
initState = IState { sourceFiles = [], auxInfo = [], panchors = [],
sanchors = [], anchorMode = False,
htmlDir = "", sourceFile = "", indexFile = "",
indexHTML = [],
verbMode = False, section = [],
avoidSectionBump = False, inQuotes = False,
inMath = False, refFile = "", refMap = [], newRefMap = [],
style = ["article"], macdefs=[]}
-- This is the `changable' part of the state. Save updates by pushing
-- global stuff into the `gs' field.
data State = State {html :: [HTML],
delims :: [String -> PCFun],
gs :: IState}
deriving Show
-- This is the initial state at the start of the file
initLS :: IState -> State
initLS s = State {gs = s, delims = [], html = []}
-- These control the formatting of syntax
processFiles :: IState -> IO IState
processFiles s = do --putStr (show s ++ "\n")
doFile (sourceFiles s) s "" where
doFile [] s _ = return s
doFile (file:fs) s p = do s' <- processFile (addp s p fs) file
doFile fs s' file
addp s p fs = s {macdefs = ("prev",fname p) :
("next",case fs of (f:_) -> fname f; _ -> "") :
macdefs s}
fname f = let (file,_) = parseFileName f in file
processFile :: IState -> String -> IO IState
processFile s f = let (file,ext) = parseFileName f
s' = s {sourceFile = file, verbMode = ext == ".verb"}
outFile = htmlDir s ++ file ++ ".html" in
do
catch
(do putStr ("Reading " ++ f ++ "\n")
l <- readFile f
(html,s'') <- texToHtml s' (lines l)
putStr ("Writing " ++ outFile ++ "\n")
catch (do writeFile outFile (htmlToString html)
return s'')
(\(e :: IOException) -> do
putStr ("Write to " ++ outFile ++ " failed.\n")
return s'))
(\(e :: IOException) -> do
putStr ("File " ++ outFile ++ " error " ++ (show e) ++ "\n")
return s')
parseFileName f = let (re,rf) = span (/= '.') (reverse f) in
case (re,rf) of
(_,'.':f') -> (reverse f','.':(reverse re))
_ -> (f,"")
-- This sets up the parts of the state that need to be reset at the start of
-- each file.
texToHtml :: IState -> [String] -> IO (HTML, IState)
texToHtml s ls = do (s',_,_) <- catchd
(reqDelim1 "EOF" HProtect
(\s l ls -> return (s,l,ls)))
(initLS s) "" ls doChar
-- print (html s')
return (HProtect (html s'),gs s')
-- This is the main loop for scanning each line of the input file.
scanLines :: State -> [String] -> PC
scanLines s [] = delimiter "EOF" s "" []
scanLines s (l:ls) | htmlLine l = handleCommand s l ls
-- | l == "@" && verbMode (gs s) = doCodeLines s ls
| l == "@@@" && verbMode (gs s) = doSyntaxLines s ls
| texComment l = scanLines s ls
| l == "" = scanLines (HPara +++. s) (dropWhile (== "") ls)
| otherwise = doChar s l ls
where
-- Lines starting %* are commands to this preprocessor.
htmlLine l = case l of
('%':'*':_) -> True
_ -> False
texComment l = case l of ('%':_) -> True
_ -> False
-- This handles commands to this preprocessor endcoded as %* lines in the
-- source.
handleCommand s l ls | "*" `starts` c =
scanLines (HCmd (macroExpand (gs s) (tail c) ++ "\n")
+++ s) ls
| l == "%*ignore" = case
dropWhile (/= "%*endignore") ls of
[] -> error "Missing %*endignore"
(l:ls) -> scanLines s ls
| otherwise = do s' <- docmd htmlCommands
scanLines s' ls
where
c = drop 2 l
(cmd,args') = span isAlpha c
args = trim args'
docmd :: [(String,State -> String -> IO State)] ->
IO State
docmd [] = do putStr ("Bad preprocessor cmd: " ++ cmd ++ "\n")
putStr ("Args: " ++ args ++ "\n")
return s
docmd ((c,fn):cs) | c == cmd = fn s args
| otherwise = docmd cs
-- Worlds stupidest macro expansion
macroExpand s str = exp1 str where
exp1 "" = ""
exp1 ('~':str) = let (n,r) = span isAlpha str
d = lookup n (macdefs s) in
case d of
Just v -> exp1 (v++r)
Nothing -> "Missing var " ++ n ++ "\n" ++ exp1 r
exp1 (c:str) = c : exp1 str
-- These are handlers for the special commands to this preprocessor (%*).
htmlCommands :: [(String, State -> String -> IO State)]
htmlCommands = [("anchor",doAddAnchors),
("section",doSetSection),
("dump", doDump)]
-- These are the handlers for the commands. They return a new state and
-- some html
-- %*anchor on adds designated anchors to syntax and source code
-- %*anchor off
doAddAnchors :: State -> String -> IO State
doAddAnchors s a = return (s {gs = (gs s) {anchorMode = a == "on"}})
-- %*section n sets current section to n (can't set subsections)
-- care is needed to avoid bumping the section
-- on the next \section.
doSetSection :: State -> String -> IO State
doSetSection s a = return
(s {gs = (gs s) {section = s1,
avoidSectionBump = not (null s1)}})
where s1 = if null a then [] else [a]
-- For debugging
doDump :: State -> String -> IO State
doDump s a = do putStr ("Syntax anchors: \n" ++
concat (map (++ " ") (sanchors (gs s))))
putStr ("Code Anchors:\n" ++
concat (map (++ " ") (panchors (gs s))))
putStr ("Refs:\n" ++
concat (map (\a -> show a ++ " ") (refMap (gs s))))
return s
-- This handles lines in verbatim mode as initiated by a single @ on a line.
-- Don't mix line-by-line verbatim and within a line verbatim!
-- This is where Haskell definitions are anchored
doCodeLines s (l:ls) | l == "@" = scanLines s ls
| otherwise = do s' <- emitCodeLine s l
doCodeLines s ls
emitCodeLine s l | anchorMode (gs s) =
case maybeAnchor l of
Nothing -> return (HVerbLine l +++ s)
Just anc ->
let labs = entityToLabels anc
a = HProtect (map HDef labs ++ [HVerbLine l]) in
do s' <- registerAnchors labs s
return (a +++ s')
| otherwise = return (HVerbLine l +++ s)
emitCodeLines s [] = return s
emitCodeLines s (l:ls) = do s' <- emitCodeLine s l
emitCodeLines s' ls
maybeAnchor :: String -> Maybe HaskellDef
maybeAnchor l | "data " `starts` l = Just (HTycon (dataName (drop 5 l)))
| "newtype " `starts` l = Just (HTycon (dataName (drop 8 l)))
| "type " `starts` l = Just (HTycon (dataName (drop 5 l)))
| "class " `starts` l = Just (HTycon (dataName (drop 6 l)))
| "instance " `starts` l = Just (anchorInstance (drop 9 l))
| not (null l) && (not (isSpace (head l))) =
maybeAnchorSignature l
| otherwise = Nothing
dropContext l = trim (dc1 l l) where
dc1 ('=' : '>' : l') l = l'
dc1 [] l = l
dc1 (_:l1) l = dc1 l1 l
dataName s = getTok (trim (dropContext s))
-- Totally Bogus!
anchorInstance s = let s' = trim (dropContext s)
(c,s'') = break isSpace s'
s1 = trim s''
t = case (getTok s1) of
"(IO" -> "IO"
"(a->b)" -> "a->b"
"[]" -> "[a]"
x -> x in
HInstance c t
maybeAnchorSignature s = case parseCL s of
([],_) -> Nothing
(names,r) ->
case (trim r) of
(':' : ':' : c : _) ->
if isSpace c then
Just (HVars names)
else Nothing
_ -> Nothing
_ -> Nothing
parseCL ('(':s) = parseOp s
parseCL s@(c:_) | isAlpha c = let (var,s') = span (\c -> isAlpha c ||
c == '_' ||
isDigit c ||
c == '\'') s
(v,r) = parseCL1 (trim s') in
(var:v,r)
| otherwise = ([],"")
parseOp s = let (op,s') = break (== ')') s in
case s' of
(')':s) -> let (v,r) = parseCL1 s in (op:v,r)
_ -> ([],"")
parseCL1 (',':s) = parseCL (trim s)
parseCL1 s = ([],s)
-- This handles lines of syntax definition
syntaxCols :: [Int]
syntaxCols = [100,20,250]
doSyntaxLines :: State -> [String] -> PC
doSyntaxLines s ls = do (hs, gs', ls') <- doSyntaxLine (initLS (gs s)) ls
let h' = HTable "cellspacing=0 cellspacing=0"
"" syntaxCols (HProtect hs)
scanLines (s {gs = gs' {inMath = inMath (gs s)},
html = h' : html s}) ls'
doSyntaxLine s [] = error "Eof in syntax mode!"
doSyntaxLine s (l:ls) | l == "@@@" = return (html s, gs s, ls)
| emptyLine l = doSyntaxLine (HLineBreak +++ s)
(dropWhile emptyLine ls)
| definitionLine l = defLine s l ls
| otherwise = continuedLine s l ls
emptyLine "" = True
emptyLine ('%':_) = True
emptyLine _ = False
definitionLine l = case (trim l) of
('|':cs) -> False
_ -> True
-- This handles lines defining Haskell syntax (@@@). These lines either
-- start with a non-terminal or a |. This determines which:
continuedLine s l ls = do (hs,gs) <- texToHtml ((gs s) {inMath = True})
["& @|@ &" ++ l']
let h' = unProtect hs ++ [HLineBreak]
doSyntaxLine (s {gs = gs, html = html s ++ h'}) ls
where
l' = tail (trim l) -- trim the leading |
defLine s l ls = do (hs,gs) <- texToHtml ((gs s) {inMath = True})
[tok ++ tok' ++
" & " ++ arrow ++ l']
let gs' = if doAnchor then
removeSyntaxAnchor tok gs else
gs
h' = a ++ unProtect hs ++ [HLineBreak]
doSyntaxLine (s {gs = gs', html = html s ++ h'}) ls
where
doAnchor = anchorMode (gs s) && tok `elem` sanchors (gs s)
(tok,rest) = span isAN l
(tok',r') = break isSpace rest
(_,r'') = span isSpace r'
(l',hasArrow) = case r'' of ('-':'>':cs) -> (cs, True)
cs -> (cs, False)
arrow | hasArrow = " {\\tt \\rightarrow} &"
| otherwise = ""
a = if doAnchor then [HAnchor ("syntax-" ++ tok) HEmpty] else []
removeSyntaxAnchor tok gs = gs -- Needs to be fixed!
unProtect (HProtect x) = unProtect' x
unProtect x = [x]
unProtect' [HProtect x] = unProtect' x
unProtect' x = x
-- This is the main character dispatcher
doChar :: PCFun
doChar s "" ls = scanLines (HEol +++ s) ls -- end of line
doChar s (c:cs) ls =
case c of
'@' | verbMode (gs s)
-> case cs of
('@':cs') -> put "@" cs'
_ -> do (s',l',ls') <- doVerb s cs ls
doChar s' l' ls'
'%' -> scanLines s ls -- Tex comment
'\\' -> doTexCommand s cs ls
'$' -> doChar (setMath s (not mathMode)) cs ls
'"' | verbMode (gs s)
-> if inQuotes (gs s) then
delimiter "\"" (s {gs = (gs s) {inQuotes = False}}) cs ls
else
catchd (reqDelim "\"" (\h -> HProtect (HFont IT:h))
(\s -> doChar (setMath s mathMode)))
(s {gs = (gs s) {inMath = True, inQuotes = True}})
cs ls doChar
'~' -> put " " cs
'_' -> if mathMode then subsuper HSub else put "_" cs
'^' -> if mathMode then subsuper HSuper else put "^" cs
'\'' -> case cs of
('\'':cs') -> put "\"" cs'
_ -> put "'" cs
'`' -> case cs of
('`':cs') -> put "\"" cs'
_ -> put "`" cs
'{' -> catchd (reqDelim "}" HProtect doChar) s cs ls doChar
'&' -> emit HSep s cs ls
'}' -> delimiter "}" s cs ls
_ -> let (l',l'') = break (`elem` "@%\\$\"~_^'`{&}") cs in
put (c:l') l''
where
mathMode = inMath (gs s)
put str r = emit (HString str) s r ls
put' h r = emit h s r ls
subsuper fn = getArg (doSuper fn) s (addBraces cs) ls
doSuper fn h s l ls = emit (fn h) s l ls
addBraces "" = ""
addBraces (s@('{':cs)) = s
addBraces (c:cs) = '{':c:'}':cs -- Won't catch x^\foo
popMath s = doChar (setMath s False)
setMath s b = s {gs = (gs s) {inMath = b}}
doTexCommand s l ls =
let (cmd,args) = parseTexCommand l
doISO = emit (HISO (drop 3 cmd)) s args ls
badCmd = do putStr ("Tex command " ++ cmd ++ " not recognized\n")
doChar s args ls
in
if "ISO" `starts` cmd then doISO else
case lookup cmd texCommands of
Just hndlr -> hndlr s (trim args) ls
Nothing -> badCmd
parseTexCommand "" = ("","")
parseTexCommand cs | isAlpha (head cs) =
let (t,a) = span (\c -> isAlpha c || isDigit c ||
c == '*') cs in
(t, a)
| otherwise =
([head cs],tail cs)
-- This handles verbatim mode. This should not be handling code mode
-- which starts with a single @ on a line.
doVerb s "" [] = error "End of file in verb mode"
doVerb s "" (l:ls) = doVerb (HVerb "\n" +++ s) l ls
doVerb s ('@':'@':l) ls = doVerb (HVerb "@" +++ s) l ls
doVerb s ('@':l) ls = return (s, l, ls) -- Exit verb mode
doVerb s l ls = doVerb (HVerb l' +++ s) l'' ls
where
(l',l'') = span (/= '@') l
--- Indexing stuff
maybeIndex :: State -> String -> HTML -> IO (String, State)
maybeIndex s sect title =
let tag = "sect" ++ sect in
case (indexFile (gs s)) of
"" -> return (tag,s)
_ -> let h = HAnchor (sourceFile (gs s) ++ ".html#" ++ tag) title in
return (tag, s {gs = (gs s) {indexHTML = h : indexHTML (gs s)}})
{-
inTable s = case tableStuff s of
Nothing -> False
_ -> True
--
let Just (a,i,m) = tableStuff s
s' = setTableStuff (Just (a,i+1,m)) s in
("</td><td " ++ encodeAlign (a !! (i+1)) ++ ">")
++. doChar s' cs ls
| inTable s && c == '\\' && "\\" `starts` cs =
let Just (a,_,m) = tableStuff s
s' = setTableStuff (Just (a,0,m)) s in
("</td></tr><tr><td" ++ encodeAlign (a !! 0) ++ ">") ++.
doChar s' (skipBracket (tail cs)) ls
| mathMode s = doMChar
case c of
'$' -> exitMath
-}
-- This strips off latex command args. Not robust at all! Should do a
-- deeper parse. Missing arguments are ignored.
ignore1 :: Char -> Char -> Int -> String -> [String] -> (String,[String])
ignore1 opn cls k l ls = ignore2 k l ls 0
where
ignore2 0 l ls lev = (l,ls)
ignore2 k "" [] lev = ("",[])
ignore2 k "" (l:ls) lev = ignore2 k l ls lev
ignore2 k (c:cs) l lev | c == opn = ignore2 k cs l (lev+1)
| c == cls && lev == 0 = (cs,l) -- Error!
| c == cls && lev == 1 = ignore2 (k-1) cs l 0
| c == cls = ignore2 k cs l (lev-1)
| isSpace c = ignore2 k cs l lev
| lev == 0 = (c:cs,l)
| otherwise = ignore2 k cs l lev
-- This is a really poor parser for simple string args to commands.
-- Assume (for now) that no line breaks are in the argument
getSArg :: String -> [String] -> (String,String,[String])
getSArg l ls = getSArg2 '{' '}' l ls
getBArg :: String -> [String] -> (String,String,[String])
getBArg l ls = getSArg2 '[' ']' l ls
getSArg2 open close s ls = (s1, s2, ls) where
(s1,s2) = case trim s of
(c:cs) -> if c == open then b cs 0 else ("",c:cs)
str -> ("",str)
b "" i = ("","")
b (c:cs) i | c == open = cons1 open (b cs (i+1))
b (c:cs) 0 | c == close = ("",cs)
b (c:cs) i | c == close = cons1 close (b cs (i-1))
b (c:cs) i = cons1 c (b cs i)
cons1 c (cs,x) = (c:cs,x)
starts [] _ = True
starts _ [] = False
starts (a:as) (b:bs) | a == b = starts as bs
| otherwise = False
alternate :: [a] -> a -> [a]
alternate [] _ = []
alternate [l] _ = [l]
alternate (l:ls) a = l : a : alternate ls a
trim s = dropWhile isSpace s
trimr s = reverse (dropWhile isSpace (reverse s))
getTok s = takeWhile (\c -> not (isSpace c)) s
isReport s = "report" `elem` style (gs s)
isArticle s = "article" `elem` style (gs s)
useMSSymbols s = "microsoftsymbols" `elem` style (gs s)
sectStyle s | isReport s = 1
| isArticle s = 0
| otherwise = error "Bad style"
(.|.) :: PCFun -> PCFun -> PCFun
f1 .|. f2 = \s -> if useMSSymbols s then f1 s else f2 s
--- Handlers for Tex commands
texCommands :: [(String,PCFun)]
texCommands = [("\\",doEol),
("newline",doEol),
("",ignore 0),
("-",ignore 0),
("markboth",ignore 2),
("begin",doBegin),
("end",doEnd),
("item",doItem),
("bibitem",doBibItem),
("Large",emit (HSize 4)),
("bf",emit (HFont Bold)),
("tt",emit (HFont TT)),
("vspace",ignore 1),
("em",emit (HFont IT)),
("cite",doCite),
("noindent",ignore 0),
("Haskell",use "Haskell "),
("chapter",doSection 1), -- only in report
("chapter*",embed (HHdr 1 "")), -- only in report
("section",\s -> doSection (1+sectStyle s) s),
("section*",\s -> embed (HHdr (2+sectStyle s) "") s),
("subsection",\s -> doSection (2+sectStyle s) s),
("subsection*",\s -> embed (HHdr (3+sectStyle s) "") s),
("subsubsection",\s -> doSection (3+sectStyle s) s),
("subsubsection*",\s -> embed (HHdr (3+sectStyle s) "") s),
("paragraph",embed (HHdr 3 "")),
("paragraph*",embed (HHdr 3 "")),
("label",doLabel),
("ref",doRef),
("sref",\s -> doRef (HString "Section " +++ s)), -- mpj
("bi",doBeginItemize),
("ei",delimiter "itemize"),
("bto",doBeginTabularB), -- has a border
("eto",delimiter "tabular"),
(">",emit HSep),
("=",emit HSep),
("kill",ignore 0),
("underline",embed (\h -> HProtect [HFont IT, h])),
("`",ignore 0),
("'",ignore 0),
("#",use "#"),
("%",use "%"),
("frac", doFrac),
("ignorehtml",ignore 1),
("bprog",emit (HVerb "\n")),
("bprogNoSkip",ignore 0),
("eprog", emit (HVerb "\n")),
("eprogNoSkip",ignore 0),
("footnote",bracket " (" ")"),
("bkqA",use "`"),
("bkqB",use "`"),
("bkq",use "`"),
("protect",ignore 0),
("qquad",emit (HVerb " ")),
("mbox",ignore 0),
("anchor",doAnchor),
("outline",embed boxed),
("outlinec",embed (HCenter . boxed)),
("ecaption",embed (\a -> (HCenter (HHdr 3 "" a)))),
("nopagebreak",ignoreB),
("rm",embed (inFont RM)),
("it",emit (HFont IT)),
("em",emit (HFont IT)),
("bf",emit (HFont Bold)),
("input",doInput),
("[",doEqn),
("]",delimiter "\\]"),
(" ",use " "),
("verb",doVerbc),
("ba",doBa "ea"),
("bt",doBa "et"),
("ea",delimiter "ea"),
("et",delimiter "et"),
("rangle",use ">"),
("langle",use "<"),
("tr",embed (inFont RM)),
("{",use "{"),
("}",use "}"),
("index",ignore 1),
("indexclass",ignore 1),
("indexdi",ignore 1),
("indexsyn",ignore 1),
("indextt",ignore 1),
("indexmodule",ignore 1),
("indextycon",ignore 1),
("indexsynonym",ignore 1),
("arity",expandS (\a -> "{\\rm arity(}" ++ a ++ "{\\rm )}")),
("infix",expandS (\a -> "{\\rm infix(}" ++ a ++ "{\\rm )}")),
("nopagebreak",ignoreB),
("struthack",ignore 1),
("hline",ignore 0),
("centerline",ignore 0),
("hspace*",ignore 1),
("pageref",ignore 1),
("/",ignore 0),
(",",use " "),
("kappa",emitSym "k"),
("overline",embed (\h -> HProtect [HFont UL, h])),
("multicolumn",ignore 2),
("pi",emitSym "p"),
("epsilon",emitSym "e"),
("prime",use "'"),
("clearpage",ignore 0),
("medskip",ignore 0),
("syn",bracket "[" "]"),
("S",use "report section "),
("newpage",ignore 0),
("_",use "_"),
("epsbox",ignore 1),
("caption",ignore 1),
("hspace",ignore 1),
("cleardoublepage",ignore 0),
("bprogB",ignore 0),
("eprogB",ignore 0),
("startnewsection",ignore 0),
("inputHS",doInputHS),
("pagenumbering",ignore 1),
("pagestyle",ignore 1),
("setcounter",ignore 2),
("LaTeX",use "LaTeX"),
("copyright", emit (HISO "copy")),
("newblock", ignore 0),
("figcaption", doFigCaption),
-- For the tutorial:
("see",doSee),
-- For mpj:
("ts",ignore 0),
("la",use "<"),
("ra",use ">"),
("prei",ignore 0),
("nextitem",doItem),
("smon",ignore 0),
("smoff",ignore 0),
("metaArg",embed (\h -> HProtect [HFont RM, h])),
("inbox",embed boxed),
("clarg",getArg3 (\h1 h2 h3 -> emit (
boxed (HProtect [
inFont IT h2,
HString " ",
inFont RM h1])))),
("cls",ignore 2),
("cldone",ignore 0),
("helponly",ignore 1),
("htmlonly",ignore 1),
("latexonly",ignore 1),
("latexignore",ignore 1),
("helprefn",getArg2 (\h1 h2 -> emit h1)),
("parag",embed (HHdr 3 "")),
("showURL",getArg2 (\h1 h2 ->
emit (HProtect [HProtect [HFont TT,h1],h2]))),