Source file bracetax_latex_printer.ml
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
(** The LaTeX output format, implements {!type:Signatures.printer}
functions. *)
(**/**)
module Commands = Bracetax_commands
module Error = Bracetax_error
module Signatures = Bracetax_signatures
module Escape = Bracetax_escape
type t = {
stack: Commands.Stack.t;
mutable write: string -> unit;
write_mem: (string -> unit) Stack.t;
mutable inside_header:bool;
mutable current_table: Commands.Table.table option;
error: Error.error_fun;
mutable loc: Error.location;
opt_href_footnote: bool;
url_hook: string -> string;
img_hook: string -> string;
opt_table_caption_after: bool;
separate_header: (string * string * string) ref option;
}
module CS = Commands.Stack
let (~%) = Printf.sprintf
let p = print_string
let create
~writer ?(=false) ? ?(img_hook=fun s -> s)
?(url_hook=fun s -> s) ?(table_caption_after=true) () =
let module S = Signatures in
let write = writer.S.w_write in
{
stack = CS.empty ();
write = write;
write_mem = Stack.create ();
inside_header = false;
current_table = None;
error = writer.S.w_error;
loc = {Error.l_line = -1; l_char = -1;l_file = "NO FILE";};
opt_href_footnote = href_is_footnote;
url_hook = url_hook;
img_hook = img_hook;
opt_table_caption_after = table_caption_after;
separate_header = separate_header;
}
let strstat s = (~% "[%d:%d]" s.Error.l_line s.Error.l_char)
let debugstr t s msg =
if false then
(~% "%%%%DEBUG:[%s] Loc:[%d;%d]\n"
msg s.Error.l_line s.Error.l_char)
else
""
let line = line
let sanitize_text line =
let patterns = [
('$' , "{\\char`$}" );
('-' , "-{}" );
('&' , "\\&\\linebreak[0]" );
('%' , "\\%{}" );
('#' , "\\#{}" );
('{' , "{\\{}" );
('}' , "{\\}}" );
('/' , "\\slash{}\\linebreak[0]" );
('_' , "{\\char`_}" );
('\\', "{\\char`\\\\}" );
('^' , "{\\char`^}" );
('~' , "{\\char`~}" );
('`' , "{\\char``}" );
] in
Escape.replace_chars ~src:line ~patterns
let sanitize_nontext line =
let patterns = [
('$' , "" );
('&' , "" );
('%' , "" );
('#' , "" );
('{' , "" );
('}' , "" );
('_' , "" );
('\\', "" );
('^' , "" );
('~' , "" );
] in
Escape.replace_chars ~src:line ~patterns
let sanitize_url line =
let patterns = [
('$' , "" );
('{' , "" );
('}' , "" );
('\\', "" );
('^' , "" );
('%' , "\\%" );
('#' , "\\#" );
] in
Escape.replace_chars ~src:line ~patterns
let section_start n l =
let section =
match n with
| 4 -> "paragraph"
| 3 -> "subsubsection"
| 2 -> "subsection"
| 1 | _ -> "section"
in
~% "\n\\%s{" section
let section_stop n l =
let lsan =
match l with | "" -> "" | s -> ~% "\\label{%s}" (sanitize_nontext s) in
~% "}\n%s\n" lsan
let link_start t args =
let link, new_write = Commands.Link.start ~url_hook:t.url_hook args in
Stack.push t.write t.write_mem;
t.write <- new_write;
link
let link_stop t l =
t.write <- Stack.pop t.write_mem;
let kind, target, text = Commands.Link.stop l in
let target_str =
(match target with Some s -> s | None -> "notarget") in
t.write (
match kind with
| `local ->
let target = sanitize_nontext target_str in
(match text with
| Some s -> ~% "%s (\\ref{%s})" s target
| None -> ~% "\\ref{%s}" target)
| _ ->
let san_urltxt url =
let patterns = [
('?',"?\\linebreak[0]");
('.',".\\linebreak[0]");
('=',"=\\linebreak[0]"); ] in
let src = sanitize_text url in
Escape.replace_chars ~src ~patterns in
if not t.opt_href_footnote then
(~% "\\href{%s}{%s}"
(sanitize_url target_str)
(match text with
Some s -> s | None -> san_urltxt target_str))
else
let san_text =
(match text with
Some s -> s | None -> san_urltxt target_str) in
(~% "%s\\footnote{ \\href{%s}{%s}}"
san_text (sanitize_url target_str)
(san_urltxt target_str))
);
()
let quotation_open_close t a =
let default = ("``", "''") in
try
match List.hd a with
| "'" -> ("`", "'")
| "en" -> ("``", "''")
| "fr" -> ("«~", "~»")
| "de" -> ("\\unichar{8222}", "\\unichar{8220}")
| "es" -> ("\\unichar{171}", "\\unichar{187}")
| s ->
t.error (Error.mk t.loc `warning (`unknown_quotation_style s));
default
with
| e -> default
let t =
t.inside_header <- true;
begin match t.separate_header with
| None ->
t.write (~% "%% HEADER:\n\\date{}");
| Some r ->
Stack.push t.write t.write_mem;
t.write <- (fun str ->
begin match CS.head t.stack with
| Some `title -> let t,a,s = !r in r := (t ^ str, a, s);
| Some `authors -> let t,a,s = !r in r := (t, a ^ str, s);
| Some `subtitle -> let t,a,s = !r in r := (t, a, s ^ str);
| _ -> ()
end;
);
end
let t =
t.inside_header <- false;
begin match t.separate_header with
| None ->
t.write "\\maketitle\n\n\n";
| Some r ->
t.write <- Stack.pop t.write_mem;
end
let title_start t = t.write "\\title{"
let title_stop t = t.write "}\n"
let authors_start t = t.write "\\author{"
let authors_stop t = t.write "}\n"
let subtitle_start t = t.write "\\date{"
let subtitle_stop t = t.write "}\n"
let image_start t args =
let error_msg m = t.error (Error.mk t.loc `error m) in
let src, opts, lbl =
Commands.Names.image_params ~img_hook:t.img_hook error_msg args in
let opts_str =
match opts with
| `wpx w -> (~% "[width=%dpt]" w)
| `wpercent w -> (~% "[width=%f\\columnwidth]" ((float w) /. 100.))
| `none -> ""
in
let sansrc = match src with "" -> "IMAGEWITHNOSOURCE" | s -> s in
let sanlbl =
match sanitize_nontext lbl with
| "" -> "" | s -> ~% "\\label{%s}" s in
t.write (~% "\n\
\\begin{figure}[htcb]\n\
\ \\centering\n\
\ \\includegraphics%s{%s}\n\
\ \\caption{%s"
opts_str sansrc sanlbl
);
`image (src, opts, lbl)
let image_stop = "}\n\\end{figure}\n"
let table_start t args =
let table, to_stack, new_write = Commands.Table.start args in
t.current_table <- Some table;
Stack.push t.write t.write_mem;
t.write <- new_write;
to_stack
let print_table t table =
let module CT = Commands.Table in
let write = t.write in
let lbl_str =
match table.CT.label with
| None -> ""
| Some s -> (~% "\\label{%s}" (sanitize_nontext s))
in
let table_format =
let rec make acc = function
| 0 -> acc
| n -> make ("c" :: acc) (n - 1)
in
"|" ^ (String.concat "|" (make [] table.CT.col_nb)) ^ "|"
in
let caption_str =
(~% "\\caption{%s%s}\n" (Buffer.contents table.CT.caption) lbl_str) in
write (~% "\n\
\\begin{table}[htcb]\n\
\ %s\
\ \\begin{center}\n\
\ \\begin{tabular}{%s}\n\
\ \\hline " (if not t.opt_table_caption_after then caption_str else "") table_format
);
let nb_rows, nb_cols, matrix =
CT.Util.cells_to_matrix ~loc:t.loc ~error:t.error table in
let string_of_cell c =
let text = (Buffer.contents c.CT.cell_text) in
let text_with_type =
if c.CT.is_head then ~% "\\textbf{%s}" text else text in
let text_with_type_and_rows =
if c.CT.rows_used <> 1 then
~% "\\multirow{%d}{*}{%s}" c.CT.rows_used text_with_type
else
text_with_type in
let alignment =
match c.CT.align with
| `right -> "r"
| `center -> "c"
| `left -> "l"
in
let multicol =
(~% "\\multicolumn{%d}{|%s|}{%s}"
c.CT.cols_used alignment text_with_type_and_rows)
in
multicol
in
let empty_multicol cols = (~% "\\multicolumn{%d}{|c|}{}" cols) in
let separator cur_col cols_used nb_cols =
if cur_col + cols_used - 1 <> nb_cols - 1 then " & " else " \\\\\n" in
let str_matrix = Array.make_matrix nb_rows nb_cols "" in
let lines_matrix = Array.make_matrix nb_rows nb_cols false in
for row = 0 to nb_rows - 1 do
for col = 0 to nb_cols - 1 do
begin match matrix.(row).(col) with
| `none -> ()
| `cell c ->
let the_cell =
(string_of_cell c) ^ (separator col c.CT.cols_used nb_cols) in
begin
try
str_matrix.(row).(col) <- the_cell;
for i = row + 1 to row + c.CT.rows_used - 1 do
Printf.eprintf "\n[]bouh\n%!";
str_matrix.(i).(col) <-
(empty_multicol c.CT.cols_used)
^ (separator col c.CT.cols_used nb_cols);
done;
for i = col to col + c.CT.cols_used - 1 do
lines_matrix.(row + c.CT.rows_used - 1).(i) <- true;
done;
with
Invalid_argument("index out of bounds") ->
()
end
| `filled (r, c) -> ()
end;
done;
done;
for row = 0 to nb_rows - 1 do
let buf_separ = Buffer.create 42 in
let buf_row = Buffer.create 42 in
for col = 0 to nb_cols - 1 do
Buffer.add_string buf_row str_matrix.(row).(col);
if (lines_matrix.(row).(col)) then (
Buffer.add_string buf_separ
(~% " \\cline{%d-%d}" (col + 1) (col + 1));
);
done;
write (Buffer.contents buf_row);
write (Buffer.contents buf_separ);
write "\n";
done;
write (~% "\n\
\ \\end{tabular}\n\
\ \\end{center}\n\
\ %s\
\\end{table}\n"
(if t.opt_table_caption_after then caption_str else ""));
()
let table_stop t =
begin match t.current_table with
| None -> failwith "Why am I here ??? no table to end."
| Some tab ->
t.write <- Stack.pop t.write_mem;
t.current_table <- None;
print_table t tab;
end
let cell_start t args =
match t.current_table with
| None ->
t.error (Error.mk t.loc `error `cell_out_of_table);
`cell (false, 1, `center)
| Some tab -> Commands.Table.cell_start ~loc:t.loc ~error:t.error tab args
let cell_stop t env =
match t.current_table with
| None ->
()
| Some tab -> Commands.Table.cell_stop ~loc:t.loc ~error:t.error tab
let list_start = function
| `itemize -> "\n\\begin{itemize}\n"
| `numbered -> "\n\\begin{enumerate}\n"
let list_item = "\n \\item{} "
let list_stop = function
| `itemize -> "\n\\end{itemize}\n"
| `numbered -> "\n\\end{enumerate}\n"
let start_subsup t supsub =
let discriminating_char =
match supsub with `superscript -> '^' | `subscript -> '_' | _ -> '%' in
let inside_italic, inside_bold =
let it, bf = ref false, ref false in
List.iter (function
| `italic -> it := true;
| `bold -> bf := true;
| _ -> ()) (CS.to_list t.stack);
!it, !bf
in
t.write (~% "$%c{\\textnormal{\\footnotesize{}%s%s"
discriminating_char
(if inside_italic then "\\itshape{}" else "")
(if inside_bold then "\\bfseries{}" else "")
);
supsub
let stop_subsup t = t.write "}}$"
let handle_text t location line =
t.loc <- location;
if ((not t.inside_header)) ||
(t.inside_header && (CS.head t.stack <> Some `header)) then (
let data = sanitize_text line in
t.write (~% "%s" data);
) else (
if
CS.head t.stack = Some `header
&& (not (Escape.is_white_space line))
then (
t.write (~% "%%%%IGNORED TEXT: %s\n" (sanitize_comments line));
);
)
let handle_comment_line t location line =
t.loc <- location;
t.write (~% "%%%s %s\n"
(debugstr t location "Comment") (sanitize_comments line));
()
let terminate t location =
t.loc <- location;
if (CS.to_list t.stack) <> [] then (
let l = List.map Commands.env_to_string (CS.to_list t.stack) in
t.error (Error.mk t.loc `error (`terminating_with_open_environments l));
);
()
let start_environment ?(is_begin=false) t location name args =
let module C = Commands.Names in
t.loc <- location;
let cmd name args =
match name with
| s when C.is_quotation s ->
let op, clo = quotation_open_close t args in
t.write op;
`quotation (op, clo)
| s when C.is_italic s -> t.write "{\\itshape{}" ; `italic
| s when C.is_bold s -> t.write "{\\bfseries{}" ; `bold
| s when C.is_mono_space s -> t.write "\\texttt{" ; `mono_space
| s when C.is_superscript s -> start_subsup t `superscript
| s when C.is_subscript s -> start_subsup t `subscript
| s when (C.is_end s) -> `cmd_end
| s when C.is_list s ->
let style, other_args, waiting =
let error_msg m = t.error (Error.mk t.loc `error m) in
match args with
| [] -> (`itemize, [], ref true)
| h :: t -> (C.list_style error_msg h, t, ref true) in
t.write (list_start style);
`list (style, other_args, waiting)
| s when C.is_item s -> `item
| s when C.is_section s ->
let level, label = C.section_params args in
t.write (section_start level label);
`section (level, label)
| s when C.is_link s -> (link_start t args)
| s when C.is_image s -> image_start t args
| s when C.is_header s -> header_start t; `header
| s when C.is_title s -> title_start t; `title
| s when C.is_subtitle s -> subtitle_start t; `subtitle
| s when C.is_authors s -> authors_start t; `authors
| s when C.is_table s -> table_start t args
| s when C.is_cell s -> cell_start t args
| s when C.is_note s -> t.write "\\footnote{" ; `note
| s when C.is_quote s -> t.write "\\begin{quote}\n" ; `quote
| s ->
t.error (Error.mk t.loc `error (`unknown_command s));
`unknown (s, args)
in
let the_cmd =
if C.is_begin name then (
match args with
| [] ->
t.error (Error.mk t.loc `error `begin_without_arg);
(`cmd_begin ("", []))
| h :: t -> (`cmd_begin (h, t))
) else (
cmd name args
)
in
if is_begin then (
CS.push t.stack (`cmd_inside the_cmd);
) else (
CS.push t.stack the_cmd;
)
let start_command t location name args =
t.loc <- location;
match Commands.non_env_cmd_of_name name args with
| `unknown (name, args) -> start_environment t location name args
| cmd -> CS.push t.stack cmd
let stop_command t location =
t.loc <- location;
let rec out_of_env env =
match env with
| `cmd_end ->
begin match CS.pop t.stack with
| Some (`cmd_inside benv) ->
out_of_env benv
| Some c ->
t.error (Error.mk t.loc `error `non_matching_end);
CS.push t.stack c;
| None ->
t.error (Error.mk t.loc `error `non_matching_end);
end
| `cmd_begin (nam, args) ->
start_environment ~is_begin:true t location nam args;
| `paragraph -> t.write "\\par{}\n"
| `new_line -> t.write "\\\\{}\n"
| `non_break_space -> t.write "~"
| `horizontal_ellipsis -> t.write "\\ldots{}"
| `en_dash -> t.write "--"
| `em_dash -> t.write "---"
| `open_brace -> t.write "\\{"
| `close_brace -> t.write "\\}"
| `sharp -> t.write "\\#{}"
| (`utf8_char i) -> t.write (~% "\\unichar{%d}" i)
| (`quotation (op, clo)) -> t.write clo
| `italic -> t.write "}"
| `bold -> t.write "}"
| `mono_space -> t.write "}"
| `superscript -> stop_subsup t
| `subscript -> stop_subsup t
| `list (style, _, r) -> t.write (list_stop style)
| `item ->
begin match CS.head t.stack with
| Some (`list (style, _, _))
| Some (`cmd_inside (`list (style, _, _))) ->
t.write list_item;
| Some c ->
t.error (Error.mk t.loc `error `item_out_of_list);
CS.push t.stack c;
| None ->
t.error (Error.mk t.loc `error `item_out_of_list)
end
| `section (level, label) -> t.write (section_stop level label);
| `link l -> link_stop t l;
| `image _ -> t.write image_stop;
| `header -> header_stop t;
| `title -> title_stop t;
| `subtitle -> subtitle_stop t;
| `authors -> authors_stop t;
| `table _ -> table_stop t
| `cell _ as c -> cell_stop t c
| `note -> t.write "}"
| `quote -> t.write "\n\\end{quote}"
| `cmd_inside c ->
t.error (Error.mk t.loc `error `closing_brace_matching_begin);
| `unknown c -> ()
| c ->
t.error (Error.mk t.loc `fatal_error
(`transformer_lost (Commands.env_to_string c)));
in
begin match CS.pop t.stack with
| Some env -> out_of_env env
| None ->
t.error (Error.mk t.loc `error `nothing_to_end_with_brace);
end
let start_raw_mode t location kind_str args =
t.loc <- location;
let kind = Commands.Raw.raw_cmd_of_str kind_str in
begin match kind with
| `code ->
CS.push t.stack (`code args);
begin match args with
| _ :: q :: _ ->
t.write (~% "%%\n%%verbatimbegin:%s\n\\begin{verbatim}" q)
| _ -> t.write "%\n\\begin{verbatim}";
end;
| `bypass | `text | `ignore as env_kind ->
CS.push t.stack env_kind;
end
let handle_raw_text t location text =
t.loc <- location;
begin match CS.head t.stack with
| Some (`code _) | Some `bypass ->
t.write text;
| Some `text ->
t.write (sanitize_text text);
| Some `ignore -> ()
| _ ->
failwith "handle_raw_text: Shouldn't be there, Parser's fault ?";
end
let stop_raw_mode t location =
t.loc <- location;
begin match CS.pop t.stack with
| Some (`code args) ->
t.write "\\end{verbatim}";
begin match args with
| _ :: q :: _ -> t.write (~% "\n%%verbatimend:%s\n" q)
| _ -> ()
end;
| Some `bypass | Some `text | Some `ignore -> ()
| _ ->
failwith "Shouldn't be there, Parser's fault ?";
end
(**/**)
(** Build a [printer] to feed {!val:Parser.do_transformation}, the
optional arguments have the same meaning than for
{!val:Transform.brtx_to_latex}. *)
let build
?(=false) ? ?table_caption_after
?img_hook ?url_hook ? ~writer () =
let t =
create ~writer ?href_is_footnote
?separate_header ?img_hook ?url_hook ?table_caption_after () in
let printer = {
Signatures.
print_comment =
if print_comments then
(handle_comment_line t)
else
(fun a b -> ());
print_text = handle_text t;
enter_cmd = start_command t;
leave_cmd = stop_command t;
terminate = terminate t;
is_raw = Commands.Raw.is_raw_cmd;
default_raw_end = Commands.Raw.default_raw_end;
enter_raw = start_raw_mode t;
print_raw = handle_raw_text t;
leave_raw = stop_raw_mode t;
error = writer.Signatures.w_error; } in
printer
(** Build a LaTeX header. *)
let ?(title="") ?(="") ?stylesheet_link () =
let package_str =
match stylesheet_link with
| None -> ""
| Some f -> ~% "\\usepackage{%s}" f
in
~% "\
\\documentclass[a4paper,10pt]{article}\n\
\n\
\\clubpenalty=10000\n\
\\widowpenalty=10000\n\
\n\
\\usepackage[T1]{fontenc}\n\
\\usepackage[english]{babel}\n\
\\usepackage{multirow}\n\
\\usepackage{tipa}\n\
\\usepackage{ucs}\n\
\\usepackage[utf8x,utf8]{inputenc}\n\
\\usepackage[ \n\
bookmarks = true, \n\
bookmarksnumbered = true, \n\
colorlinks = true, \n\
]{hyperref} \n\
\\usepackage{color}\n\
\\definecolor{webred}{rgb}{0.3,0,0}\n\
\\definecolor{blurl}{rgb}{0,0,0.3}\n\
\\hypersetup{\n\
linkcolor = webred, %%black\n\
citecolor = webred, %%black\n\
urlcolor = blurl , %%black\n\
linkbordercolor = {1 1 1},\n\
citebordercolor = {1 1 1},\n\
urlbordercolor = {1 1 1},\n\
pdfauthor = {},\n\
pdftitle = {%s},\n\
pdfsubject = {},\n\
pdfkeywords = {},\n\
pdfcreator = {Bracetax and PDFLaTeX},\n\
pdfproducer = {Bracetax and PDFLaTeX}}\n\
\n\
\\usepackage[pdftex]{graphicx}\n\
\\frenchspacing\n\
\\DeclareGraphicsExtensions{.jpg,.mps,.pdf,.png}\n\
\n\
%%%s\n\
%s\n\
\n\
\\begin{document}\n\
\n\
" title (sanitize_comments comment) package_str
(** Close a LaTeX document. *)
let () = "\n\\end{document}\n"