-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathdocgen.c
More file actions
1987 lines (1890 loc) · 67.1 KB
/
docgen.c
File metadata and controls
1987 lines (1890 loc) · 67.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
// Copyright 2021 Mitchell Kember. Subject to the MIT License.
#include <assert.h>
#include <ctype.h>
#include <libgen.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
// Enable this to print Pandoc's Markdown input instead of passing it to Pandoc.
// You must Ctrl-C out after since docgen will hang waiting for Pandoc's output.
#define DEBUG_PANDOC_INPUT 0
// Enable this to print Pandoc's HTML output instead of postprocessing it and
// writing it to disk. This has the side effect of writing an empty output file.
#define DEBUG_PANDOC_OUTPUT 0
// Returns true if s starts with the given prefix.
static bool startswith(const char *s, const char *prefix) {
return strncmp(s, prefix, strlen(prefix)) == 0;
}
// Returns true if s ends with the given suffix.
static bool endswith(const char *s, const char *suffix) {
int n = strlen(s);
int m = strlen(suffix);
return n >= m && strncmp(s + (n - m), suffix, m) == 0;
}
// Concatenates two strings into a newly allocated string.
static char *concat(const char *s1, const char *s2) {
int n1 = strlen(s1);
int n2 = strlen(s2);
char *dest = malloc(n1 + n2 + 1);
memcpy(dest, s1, n1);
memcpy(dest + n1, s2, n2);
dest[n1 + n2] = '\0';
return dest;
}
// A pointer-and-length string. Not necessarily null terminated.
struct Span {
char *data;
int len;
};
// An absent span. Distinct from SPAN("").
#define NULL_SPAN ((struct Span){NULL, 0})
// Creates a span from a string literal or array.
#define SPAN(s) ((struct Span){s, sizeof s - 1})
// Converts s to lowercase using the given buffer.
static struct Span tolower_s(struct Span s, char *buf, int cap) {
assert(cap >= s.len);
for (int i = 0; i < s.len; i++) {
buf[i] = tolower(s.data[i]);
}
return (struct Span){buf, s.len};
}
// Name of the pandoc executable.
static const char PANDOC[] = "pandoc";
// Pandoc options that differ between invocations.
struct PandocOpts {
// Path to the input file.
const char *input;
// Path to the output file.
const char *output;
// Destination path. Usually output is "/dev/stdout" so that docgen can do
// further post-processing, while dest is the actual HTML path. It is only
// used for construct the -M id=... parameter; the file is not opened.
const char *dest;
// Contents of <title>...</title>.
const char *title;
// Links to up/prev/next page. If any are set, up must be set.
const char *up;
const char *prev;
const char *next;
};
// Invokes pandoc, printing the command to stderr before executing it. Normally
// does not return since it replaces the current process. If exec fails, returns
// false (most likely because Pandoc is not installed or not in $PATH).
static bool pandoc(const struct PandocOpts opts) {
const int LEN = 1 // pandoc
+ 3 // -o output -dconfig
+ 4 // -M id -M title
+ 6 // -M prev -M up -M next
+ 1 // input
+ 1; // NULL
const char *argv[LEN];
int i = 0;
argv[i++] = PANDOC;
argv[i++] = "-o";
argv[i++] = opts.output;
argv[i++] = "-dpandoc/config.yml";
// Note: We don't need to free memory allocated by concat because it will
// all disappear when execvp replaces the process image.
argv[i++] = "-M";
const char *id_arg = concat("id=", strchr(opts.dest, '/') + 1);
*strrchr(id_arg, '.') = '\0';
argv[i++] = id_arg;
argv[i++] = "-M";
const int title_idx = i;
argv[i++] = concat("title=", opts.title);
if (opts.up) {
argv[i++] = "-M";
argv[i++] = concat("up=", opts.up);
if (opts.prev) {
argv[i++] = "-M";
argv[i++] = concat("prev=", opts.prev);
}
if (opts.next) {
argv[i++] = "-M";
argv[i++] = concat("next=", opts.next);
}
}
argv[i++] = opts.input;
argv[i++] = NULL;
assert(i <= LEN);
for (int j = 0; j < i - 1; j++) {
// Quote the title argument since it has spaces.
const char *quote = j == title_idx ? "'" : "";
const char *space = j == i - 2 ? "" : " ";
fprintf(stderr, "%s%s%s%s", quote, argv[j], quote, space);
}
putc('\n', stderr);
// It is safe to cast to (char **) because execvp will not modify argv
// except as a consequence of replacing the process image.
execvp(PANDOC, (char **)argv);
perror(PANDOC);
return false;
}
// PID of the Pandoc process, stored so that signal_handler can kill it.
static volatile pid_t global_pandoc_pid = 0;
// Flag indicating that global_pandoc_pid is set. We need this because pid_t is
// not guaranteed to be written in a single instruction.
static volatile sig_atomic_t global_pandoc_pid_set = 0;
// Kills global_pandoc_pid (if set).
static void kill_pandoc(void) {
if (global_pandoc_pid_set) {
kill(global_pandoc_pid, SIGTERM);
}
}
// Kills global_pandoc_pid (if set) and then runs the default signal handler.
static void signal_handler(int signum) {
kill_pandoc();
signal(signum, SIG_DFL);
raise(signum);
}
// Termination signals that we want to handle.
static const int SIGNUMS[] = {SIGHUP, SIGINT, SIGQUIT, SIGTERM};
static const int N_SIGNUMS = sizeof SIGNUMS / sizeof SIGNUMS[0];
// Ensures that global_pandoc_pid (if set) is killed when this process
// terminates normally (returning from main or calling exit) or receives one of
// the signals in SIGNUMS. It is still possible for the pandoc process to be
// orphaned, for example if this process receives SIGKILL.
static bool kill_pandoc_on_termination(void) {
if (atexit(kill_pandoc) == -1) {
perror("atexit");
return false;
}
struct sigaction action;
action.sa_handler = signal_handler;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
for (int i = 0; i < N_SIGNUMS; i++) {
struct sigaction old;
if (sigaction(SIGNUMS[i], NULL, &old) == -1) {
perror("sigaction");
return false;
}
if (old.sa_handler == SIG_IGN) continue;
if (sigaction(SIGNUMS[i], &action, NULL) == -1) {
perror("sigaction");
return false;
}
}
return true;
}
// Represents a child process executing pandoc.
struct PandocProc {
// PID of the child process.
pid_t pid;
// Stream for writing to the child's stdin.
FILE *in;
// Stream for reading from the child's stdout.
FILE *out;
};
// Helper that closes both ends of a pipe.
#define CLOSE2(p) \
do { \
close(p[0]); \
close(p[1]); \
} while (0)
// Runs pandoc with opts in a child process, storing its information in proc.
// Also registers handlers to kill the child process if the parent terminates
// (this is useful if the Lua filter has an infinite loop bug, for example).
// Returns true on success. To take advantage of proc->in and proc->out, set
// opts.input to "/dev/stdin" and opts.output to "/dev/stdout", respectively.
// The caller should invoke wait_pandoc or finish_pandoc later.
static bool fork_pandoc(struct PandocProc *proc, struct PandocOpts opts) {
if (!kill_pandoc_on_termination()) {
return false;
}
enum { READ, WRITE, RW_N };
int in[RW_N], out[RW_N];
if (pipe(in) == -1) {
perror("pipe");
return false;
}
if (pipe(out) == -1) {
perror("pipe");
CLOSE2(in);
return false;
}
if ((proc->pid = fork()) == -1) {
perror("fork");
CLOSE2(in);
CLOSE2(out);
return false;
}
if (proc->pid == 0) {
// Move the input read-side to file descriptor 0 (stdin).
close(in[WRITE]);
dup2(in[READ], 0);
close(in[READ]);
// Move the output write-side to file descriptor 1 (stdout).
close(out[READ]);
#if !DEBUG_PANDOC_OUTPUT
dup2(out[WRITE], 1);
#endif
close(out[WRITE]);
// Replace this process with pandoc.
return pandoc(opts);
}
global_pandoc_pid = proc->pid;
global_pandoc_pid_set = 1;
close(in[READ]);
close(out[WRITE]);
proc->in = fdopen(in[WRITE], "w");
if (!proc->in) {
perror("fdopen");
close(in[WRITE]);
close(out[READ]);
return false;
}
proc->out = fdopen(out[READ], "r");
if (!proc->out) {
perror("fdopen");
fclose(proc->in);
close(out[READ]);
return false;
}
#if DEBUG_PANDOC_INPUT
proc->in = stderr;
#endif
return true;
}
// Closes streams and blocks until proc finishes. Then cleans up globals set by
// fork_pandoc for signal handlers, and resets all of proc's fields to their
// default values. Returns true on success.
static bool wait_pandoc(struct PandocProc *proc) {
if (proc->in) {
fclose(proc->in);
proc->in = NULL;
}
if (proc->out) {
fclose(proc->out);
proc->out = NULL;
}
bool success;
assert(proc->pid != 0);
int proc_status;
if (waitpid(proc->pid, &proc_status, 0) == -1) {
perror("waitpid");
success = false;
} else {
success = WIFEXITED(proc_status) && WEXITSTATUS(proc_status) == 0;
}
global_pandoc_pid_set = 0;
global_pandoc_pid = 0;
proc->pid = 0;
proc->in = NULL;
proc->out = NULL;
return success;
}
// Like strstr, but searches for n needles in parallel, favoring the one that
// occurs earliest. Returns a pointer into haystack and stores the needle
// address in found. Returns NULL if none was found.
static char *multi_strstr(const char *haystack, const char **found, int n,
...) {
va_list args;
va_start(args, n);
char *h = NULL;
const char *f = NULL;
for (int i = 0; i < n; i++) {
const char *fi = va_arg(args, const char *);
char *hi = strstr(haystack, fi);
if (hi && (!h || hi < h)) {
h = hi;
f = fi;
}
}
va_end(args);
*found = f;
return h;
}
// Post-processes HTML, mainly to adjust spacing.
static void postprocess_html(FILE *in, FILE *out) {
char *line = NULL;
size_t cap = 0;
ssize_t len;
while ((len = getline(&line, &cap, in)) > 0) {
const char *p = line;
const char *n;
const char *close_code = "</code>";
const char *close_em = "</em>";
const char *spaced_en_dash = " – ";
const char *quote_period = "”.";
const char *quote_comma = "”,";
const char *found;
while ((n = multi_strstr(p, &found, 5, close_code, close_em,
spaced_en_dash, quote_period, quote_comma))) {
fwrite(p, n - p, 1, out);
p = n + strlen(found);
if (found == close_code) {
fputs(close_code, out);
// For words partially made up of code, like `cons`ing.
if (isalpha(*p)) {
fputs(" ", out);
}
} else if (found == close_em) {
fputs(close_em, out);
if ((*p == ':' || *p == ';')
&& (n[-1] == 'd' || n[-1] == 'r' || n[-1] == 't')) {
fputs(" ", out);
}
} else if (found == spaced_en_dash) {
// Replace an open-set en dash with a closed-set em dash.
fputs("—", out);
} else if (found == quote_period) {
fputs(".<span class=\"tuck\">”</span>", out);
} else if (found == quote_comma) {
fputs(",<span class=\"tuck\">”</span>", out);
} else {
assert(false);
}
}
assert(p <= line + len);
fwrite(p, line + len - p, 1, out);
}
}
// Post-processes the HTML from proc.out and writes it to the given file. Then
// calls wait_pandoc. Returns true on success.
static bool finish_pandoc(struct PandocProc *proc, const char *output) {
fclose(proc->in);
proc->in = NULL;
FILE *out = fopen(output, "w");
if (!out) {
perror("fopen");
return false;
}
postprocess_html(proc->out, out);
fclose(out);
return wait_pandoc(proc);
}
// A parsed heading from Markdown or Scheme.
struct Heading {
// Markdown: The "1A" in "# 1A: Foo bar", or NULL_SPAN if there is none.
// Scheme: The "1.2" in (Section :1.2 "Foo") or (Exercise ?1.2).
struct Span label;
// Markdown: The "Foo bar" in "# 1A: Foo bar" or "# Foo bar".
// Scheme: The "Foo" in (Section :1.2 "Foo"). NULL_SPAN for exercises.
struct Span title;
};
// Creates a heading with title only, from a string literal.
#define TITLE_HEADING(t) \
((struct Heading){.label = NULL_SPAN, .title = SPAN(t)})
// Parses a heading from a line of Markdown.
static struct Heading parse_md_heading(struct Span s) {
char *const p = s.data;
const int n = s.len;
assert(n >= 2 && p[0] == '#' && p[n - 1] == '\n');
int i = 1;
while (i < n && p[i] == '#') i++;
assert(p[i++] == ' ' && i < n);
if (p[i] >= '1' && p[i] <= '9') {
int j = i;
while (j < n && p[j] != ':') j++;
if (j + 2 < n && p[j + 1] == ' ') {
return (struct Heading){
.label = {p + i, j - i},
.title = {p + j + 2, n - j - 3},
};
}
}
return (struct Heading){
.label = NULL_SPAN,
.title = {p + i, n - i - 1},
};
}
// Parses a heading from a line of Scheme.
static struct Heading parse_ss_heading(struct Span s) {
char *const p = s.data;
const int n = s.len;
assert(p[0] == '(');
for (int i = 0; i < n; i++) {
if (p[i] == '?') {
int j = ++i;
while (j < n && p[j] != ')' && p[j] != '\n') j++;
return (struct Heading){
.label = {p + i, j - i},
.title = NULL_SPAN,
};
} else if (p[i] == ':') {
int j = ++i;
while (j < n && p[j] != ' ') j++;
int k = j;
while (k < n && p[k] != '"') k++;
int l = ++k;
while (l < n && p[l] != '"') l++;
return (struct Heading){
.label = {p + i, j - i},
.title = {p + k, l - k},
};
}
}
assert(false);
}
// A document sector is an integer s where
//
// (s >> 0*DS_BITS) & DS_MASK gives the h1 index (chapter),
// (s >> 1*DS_BITS) & DS_MASK gives the h2 index (section),
// (s >> 2*DS_BITS) & DS_MASK gives the h3 index (subsection),
// (s >> 3*DS_BITS) & DS_MASK gives the h4 index (subsubsection),
// (s >> 4*DS_BITS) & DS_MASK gives the exercise index.
//
// An index of 0 means that heading has not been encountered yet. Exercises are
// always nested directly under chapters (they are not really an h5 index).
//
// Example (Markdown):
//
// Some text. s=0x0000
// s=0x0000
// # First s=0x0001
// s=0x0001
// ## A s=0x0101
// ## B s=0x0201
// # Second s=0x0002
//
// Example (Scheme):
//
// ; ... s=0x0000000000
// (Chapter :1) s=0x0000000001
// ; ... s=0x0000000001
// (Section :1.2) s=0x0000000201
// (Section :1.2.3) s=0x0000030201
// (Section :1.2.3.4) s=0x0004030201
// (Exercise ?3.5) s=0x0500000003
//
typedef uint64_t Sector;
#define DS_MASK UINT64_C(0xff)
#define DS_BITS UINT64_C(8)
#define DS_INDEX(s, h) ((int)(((s) >> (h - 1) * DS_BITS) & DS_MASK))
#define DS_MASK_UPTO(h) ((UINT64_C(1) << h * DS_BITS) - 1)
#define DS_INCREMENT(h) (UINT64_C(1) << (h - 1) * DS_BITS)
#define DS_NEXT(s, h) ((s & DS_MASK_UPTO(h)) + DS_INCREMENT(h))
#define DS_VALUE(h, i) ((Sector)(i) << (Sector)(h - 1) * DS_BITS)
#define DS_EXERCISE_LEVEL 5
// Writes a dotted string representation of sector in buf. Writes no more than
// size characters (including the null terminator). For example, the sector
// 0x030201 becomes "1.2.3".
static void write_dotted_section(char *buf, int size, Sector sector) {
assert(size >= 2);
assert(sector != 0);
int i = 0;
i += snprintf(buf + i, size - i, "%d", (int)(sector & DS_MASK));
sector >>= DS_BITS;
while (sector && i < size) {
i += snprintf(buf + i, size - i, ".%d", (int)(sector & DS_MASK));
sector >>= DS_BITS;
}
}
// Markdown line scanner.
struct MarkdownScanner {
// The Markdown file.
FILE *file;
// Current line and its capacity.
struct Span line;
size_t cap;
// True if we are inside a fenced code block.
bool code;
// Current sector within the document.
Sector sector;
// If this line is a heading, 1/2/... for h1/h2/..., otherwise 0.
int level;
};
// Initializes a Markdown line scanner. Returns true on success.
static bool init_md(struct MarkdownScanner *scan, const char *path) {
FILE *file = fopen(path, "r");
if (!file) {
perror(path);
return false;
}
scan->file = file;
scan->line = NULL_SPAN;
scan->code = false;
scan->sector = 0;
scan->level = 0;
return true;
}
// Closes the Markdown line scanner's file and frees memory for the line.
static void close_md(struct MarkdownScanner *scan) {
free(scan->line.data);
scan->line = NULL_SPAN;
if (scan->file) {
fclose(scan->file);
scan->file = NULL;
}
}
// Advances a Markdown line scanner to the next line. Returns true on successs,
// and false on failure or EOF.
static bool scan_md(struct MarkdownScanner *scan) {
if (!scan->file) {
return false;
}
const bool prev_blank = scan->line.len <= 1;
scan->line.len = getline(&scan->line.data, &scan->cap, scan->file);
scan->level = 0;
if (scan->line.len == -1) {
return false;
}
if (startswith(scan->line.data, "```")) {
scan->code = !scan->code;
return true;
}
if (!scan->code && prev_blank) {
int h = 0;
while (h < scan->line.len && scan->line.data[h] == '#') h++;
if (h > 0 && h < scan->line.len && scan->line.data[h] == ' ') {
scan->sector = DS_NEXT(scan->sector, h);
scan->level = h;
}
}
return true;
}
// Copies the current line in the scanner to out.
static void copy_md(struct MarkdownScanner *scan, FILE *out) {
fwrite(scan->line.data, scan->line.len, 1, out);
}
// Buffer sizes for rendering various things.
#define SZ_HREF 256
#define SZ_RELATIVE 32
#define SZ_HEADING 64
#define SZ_LABEL 8
// A Markdown line scanner that picks out "::: highlight" divs.
struct HighlightScanner {
// The underlying Markdown scanner.
struct MarkdownScanner md;
// Current state: START for "::: highlight", END for ":::", INSIDE between
// the two, and NONE otherwise. START is divided into 1ST (the first
// highlight block for the current saved heading) and NTH (not the first).
enum { HL_NONE, HL_START_1ST, HL_START_NTH, HL_INSIDE, HL_END } state;
// A saved heading and its sector, used for organizing highlights.
struct Heading heading;
Sector sector;
// Storage for the heading spans.
char line_buf[SZ_HEADING];
// The sector of the last emitted highlight.
Sector highlight_sector;
};
// Initializes a highlight scanner. Returns true on success. See also init_md.
static bool init_hl(struct HighlightScanner *scan, const char *path) {
if (!init_md(&scan->md, path)) {
return false;
}
scan->state = HL_NONE;
scan->sector = 0;
scan->highlight_sector = 0;
return true;
}
// Closes the highlight scanner's file and frees memory for the line.
static void close_hl(struct HighlightScanner *scan) { close_md(&scan->md); }
// Advances a highlight scanner to the next line. See also scan_md.
static bool scan_hl(struct HighlightScanner *scan) {
if (!scan_md(&scan->md)) {
return false;
}
const struct Span line = scan->md.line;
switch (scan->state) {
case HL_NONE:
case HL_END:
if (strncmp(line.data, "::: highlight\n", line.len) == 0) {
assert(scan->sector != 0);
scan->state = HL_START_NTH;
if (scan->highlight_sector != scan->sector) {
scan->highlight_sector = scan->sector;
scan->state = HL_START_1ST;
}
} else {
scan->state = HL_NONE;
}
break;
case HL_START_1ST:
case HL_START_NTH:
case HL_INSIDE:
if (strncmp(line.data, ":::\n", line.len) == 0) {
scan->state = HL_END;
} else {
scan->state = HL_INSIDE;
}
break;
}
return true;
}
// Saves the heading in the current line. This creates the difference between
// the HL_START_1ST and HL_START_NTH states.
static void save_heading_hl(struct HighlightScanner *scan) {
strncpy(scan->line_buf, scan->md.line.data, scan->md.line.len);
struct Span line = scan->md.line;
line.data = scan->line_buf;
scan->heading = parse_md_heading(line);
scan->sector = scan->md.sector;
}
// A Scheme code line scanner.
struct SchemeScanner {
// The Scheme file.
FILE *file;
// Current line and its capacity.
struct Span line;
size_t cap;
// Current sector within the file.
Sector sector;
// If this line is a heading, 1 for :A, 2 for :A.B, 3 for :A.B.C, 4 for
// :A.B.C.D, and DS_EXERCISE_LEVEL for ?A.B (exercises).
int level;
// True if this line is in the "use" block following the heading line.
bool use;
};
// Line at the end of chapter-*.ss files closing the SICP macro.
const char END_SICP_LINE[] = ") ; end of SICP\n";
// Initializes a Scheme line scanner. Returns true on success.
static bool init_ss(struct SchemeScanner *scan, const char *path) {
FILE *file = fopen(path, "r");
if (!file) {
perror(path);
return false;
}
scan->file = file;
scan->line = NULL_SPAN;
scan->sector = 0;
scan->level = 0;
scan->use = false;
return true;
}
// Closes the Scheme line scanner's file and frees memory for the line.
static void close_ss(struct SchemeScanner *scan) {
free(scan->line.data);
scan->line = NULL_SPAN;
if (scan->file) {
fclose(scan->file);
scan->file = NULL;
}
}
// Advances a Scheme line scanner to the next line. Returns true on successs,
// and false on failure, EOF, or END_SICP_LINE.
static bool scan_ss(struct SchemeScanner *scan) {
if (!scan->file) {
return false;
}
const bool prev_blank = scan->line.len <= 1;
scan->line.len = getline(&scan->line.data, &scan->cap, scan->file);
const bool current_blank = scan->line.len <= 1;
if (scan->line.len == -1 || strcmp(scan->line.data, END_SICP_LINE) == 0) {
return false;
}
if (scan->level == 0 && prev_blank) {
if (startswith(scan->line.data, "(Chapter :")) {
scan->level = 1;
scan->sector = DS_VALUE(1, scan->line.data[10] - '0');
} else if (startswith(scan->line.data, "(Section :")) {
int level = 0;
Sector sector = 0;
for (int i = 10; i < scan->line.len; i++) {
level++;
sector |= DS_VALUE(level, scan->line.data[i] - '0');
if (scan->line.data[++i] != '.') break;
}
scan->level = level;
scan->sector = sector;
} else if (startswith(scan->line.data, "(Exercise ?")) {
scan->level = DS_EXERCISE_LEVEL;
int i = 11;
Sector chapter = scan->line.data[i++] - '0';
assert(scan->line.data[i++] == '.');
const char *endptr;
Sector ex = strtol(scan->line.data + i, (char **)&endptr, 10);
assert(ex > 0 && endptr);
scan->sector =
DS_VALUE(1, chapter) | DS_VALUE(DS_EXERCISE_LEVEL, ex);
}
} else if (scan->level != 0) {
scan->level = 0;
scan->use = true;
}
if (scan->use && current_blank) {
scan->use = false;
}
return true;
}
// Saved state for a Scheme line scanner.
struct SchemeSave {
// The old scanner, with line set to NULL_SPAN.
struct SchemeScanner scan;
// The position in the file as reported by ftell.
long offset;
};
// Saves a checkpoint in the Scheme file, to be restored later with restore_ss.
static struct SchemeSave save_ss(struct SchemeScanner *scan) {
struct SchemeSave save = {.scan = *scan};
save.scan.line = NULL_SPAN;
save.offset = ftell(scan->file);
return save;
}
// Restores a checkpoint saved by save_ss. Everything will be as it was at that
// point, except the line will be NULL_SPAN until the next scan.
static void restore_ss(struct SchemeScanner *scan, struct SchemeSave save) {
*scan = save.scan;
fseek(scan->file, save.offset, SEEK_SET);
}
// Renders a heading to out. The level determines h1/h2/etc. If id is present,
// uses it and renders a "#" link. If heading.label is present, renders a
// .number span. If href_fmt is present, renders heading.title as a link using
// href_fmt and the printf-style arguments that follow.
static void render_heading(FILE *out, int level, struct Span id,
struct Heading heading, const char *href_fmt, ...) {
if (id.data) {
fprintf(out,
"<h%d id=\"%.*s\" class=\"anchor\">"
"<a class=\"anchor__link link\" href=\"#%.*s\""
" aria-hidden=\"true\">#</a> ",
level, id.len, id.data, id.len, id.data);
} else {
fprintf(out, "<h%d>", level);
}
if (heading.label.data) {
// Make chapter numbers big.
const char *big = "";
if (level == 1 && heading.label.len == 1) {
big = " number--big";
}
fprintf(out, "<span class=\"number%s\">%.*s</span> ", big,
heading.label.len, heading.label.data);
}
if (href_fmt) {
char href[SZ_HREF];
va_list args;
va_start(args, href_fmt);
vsnprintf(href, sizeof href, href_fmt, args);
va_end(args);
fprintf(
out,
// Both the .nowrap class and the ⁠ entity (U+2060) are
// required to prevent the external icon from wrapping.
"<a class=\"link\" href=\"%s\">%.*s<span class=\"nowrap\">⁠"
"<svg class=\"external\" width=\"24\" height=\"24\""
" aria-hidden=\"true\"><use xlink:href=\"#external\"/>"
"</svg></span></a>",
href, heading.title.len, heading.title.data);
} else {
fwrite(heading.title.data, heading.title.len, 1, out);
}
fprintf(out, "</h%d>\n", level);
}
// Renders the start of a highlighted blockquote in highlight.html. Most of the
// work is offloaded to the Lua script. Constructs the id from label and the
// one-based index of this highlight in all the highlights under that label.
static void render_highlight_start(FILE *out, struct Span label, int index) {
fprintf(out, "<div id=\"%.*s-q%d\" class=\"highlight\">\n", label.len,
label.data, index);
}
// Renders the end of a highlighted blockquote.
static void render_highlight_end(FILE *out) { fputs("</div>\n", out); }
// State to keep track of while rendering a table of contents.
struct TocRenderer {
// Nesting depth of <ul> tags.
int depth;
};
// Creates a new table-of-contents renderer.
static struct TocRenderer new_toc_renderer(void) {
return (struct TocRenderer){.depth = 0};
}
// Renders the start of a table of contents to out.
static void render_toc_start(struct TocRenderer *tr, FILE *out) {
assert(tr->depth == 0);
render_heading(out, 2, SPAN("contents"), TITLE_HEADING("Contents"), NULL);
fputs("<nav aria-labelledby=\"contents\">", out);
}
// Renders the end of a table of contents to out.
static void render_toc_end(struct TocRenderer *tr, FILE *out) {
for (; tr->depth > 1; tr->depth--) {
fputs("</ul></li>", out);
}
if (tr->depth > 0) {
assert(--tr->depth == 0);
}
fputs("</ul></nav>\n", out);
}
// Renders an item in a table of contents to out. The depth can be at most one
// greater than the previous item. The link's href is given in printf style.
static void render_toc_item(struct TocRenderer *tr, FILE *out, int depth,
struct Heading heading, const char *href_fmt, ...) {
char href[SZ_RELATIVE];
va_list args;
va_start(args, href_fmt);
vsnprintf(href, sizeof href, href_fmt, args);
va_end(args);
switch (depth - tr->depth) {
case 0:
fputs("</li>", out);
break;
case 1:
tr->depth++;
fputs("<ul class=\"toc\">", out);
break;
default:
assert(tr->depth > depth);
for (; tr->depth > depth; tr->depth--) {
fputs("</ul></li>", out);
}
break;
}
assert(tr->depth == depth);
fprintf(out,
"<li class=\"toc__item\">"
"<span class=\"toc__label\">%.*s</span>"
// Put a space between <span> and <a> so that they don't run
// together in alternative stylesheets like Safari Reader.
" "
"<a href=\"%s\">%.*s</a>",
heading.label.len, heading.label.data, href, heading.title.len,
heading.title.data);
}
// Renderer for literate code.
struct LiterateRenderer {
// State for the current line.
enum LiterateState { LR_NONE, LR_PROSE, LR_CODE } state;
// True if there is a pending blank line we haven't rendered yet.
bool pending_blank;
// An indent if we are in a list like (a), (b), etc., otherwise empty.
const char *list_indent;
};
// Creates a new table-of-contents renderer.
static struct LiterateRenderer new_literate_renderer(void) {
return (struct LiterateRenderer){
.state = LR_NONE,
.pending_blank = false,
.list_indent = "",
};
}
// Ends a section of literate output.
static void end_literate_section(struct LiterateRenderer *lr, FILE *out) {
if (lr->state == LR_CODE) {
fprintf(out, "%s```\n", lr->list_indent);
}
putc('\n', out);
lr->state = LR_NONE;
lr->pending_blank = false;
lr->list_indent = "";
}
// Renders a line of prose or code.
static void render_literate(struct LiterateRenderer *lr, FILE *out,
struct Span line) {
if (line.len <= 1 || strcmp(line.data, ";;\n") == 0) {
lr->pending_blank = true;
return;
}
enum LiterateState prev_state = lr->state;
lr->state = startswith(line.data, ";; ") ? LR_PROSE : LR_CODE;
if (lr->state == prev_state && lr->pending_blank) {
putc('\n', out);
}
switch (lr->state) {
case LR_NONE:
assert(false);
break;
case LR_PROSE:
if (prev_state == LR_CODE) {
fprintf(out, "%s```\n\n", lr->list_indent);
}
fwrite(line.data + 3, line.len - 3, 1, out);
if (prev_state != LR_PROSE || lr->pending_blank) {
bool new_item = line.len >= 6 && line.data[3] == '('
&& isalpha(line.data[4]) && line.data[5] == ')';
bool continued_item = lr->list_indent && line.len >= 8
&& startswith(line.data, ";; ")
&& isgraph(line.data[7]);
lr->list_indent = new_item || continued_item ? " " : "";
}
break;
case LR_CODE:
if (prev_state != LR_CODE) {
fprintf(out, "\n%s```\n", lr->list_indent);
}
fputs(lr->list_indent, out);
fwrite(line.data, line.len, 1, out);
break;
}
lr->pending_blank = false;
}
// State for rendering (use (id name ...) ...) blocks as nested lists.
struct ImportRenderer {
// Number of unclosed parens in the use-block.
int depth;
};
// Creates a new import renderer.
static struct ImportRenderer new_import_renderer(void) {
return (struct ImportRenderer){
.depth = 0,
};
}
// Renders imports from the given line.
static void render_import(struct ImportRenderer *ir, FILE *out,
struct Span line) {
int start = -1;
bool first = true;
for (int i = 0; i < line.len; i++) {
char c = line.data[i];
switch (c) {
case '(':
ir->depth++;
first = true;
if (ir->depth == 1) {
fputs(
"<aside class=\"imports\"><h4>Imports:</h4>"