Debian Codegraph @

ext/toc.c

raw symbols SCIP
1 /*
2 * toc -- spit out a table of contents based on header blocks
3 *
4 * Copyright (C) 2008 Jjgod Jiang, David L Parsons
5 * portions Copyright (C) 2011 Stefano D'Angelo
6 * The redistribution terms are provided in the COPYRIGHT file that must
7 * be distributed with this source code.
8 */
9 #include "config.h"
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <ctype.h>
13
14 #include "cstring.h"
15 #include "markdown.h"
16 #include "amalloc.h"
17
18 static int Csputc_mkd_sta_function_t(const int n, const void* iot) {
19 Csputc(n, iot);
20 }
21
22
23 /* write an header index
24 */
25 int
26 mkd_toc(Document *p, char **doc)
27 {
28 Paragraph *tp, *srcp;
29 int last_hnumber = 0;
30 Cstring res;
31 int size;
32 int first = 1;
33 extern void Csreparse(Cstring *, char *, int, mkd_flag_t);
34
35
36 if ( !(doc && p && p->ctx) ) return -1;
37
38 *doc = 0;
39
40 if ( ! is_flag_set(p->ctx->flags, MKD_TOC) ) return 0;
41
42 CREATE(res);
43 RESERVE(res, 100);
44
45 for ( tp = p->code; tp ; tp = tp->next ) {
46 if ( tp->typ == SOURCE ) {
47 for ( srcp = tp->down; srcp; srcp = srcp->next ) {
48 if ( (srcp->typ == HDR) && srcp->text ) {
49
50 while ( last_hnumber > srcp->hnumber ) {
51 if ( (last_hnumber - srcp->hnumber) > 1 )
52 Csprintf(&res, "\n");
53 Csprintf(&res, "</li>\n%*s</ul>\n%*s",
54 last_hnumber-1, "", last_hnumber-1, "");
55 --last_hnumber;
56 }
57
58 if ( last_hnumber == srcp->hnumber )
59 Csprintf(&res, "</li>\n");
60 else if ( (srcp->hnumber > last_hnumber) && !first )
61 Csprintf(&res, "\n");
62
63 while ( srcp->hnumber > last_hnumber ) {
64 Csprintf(&res, "%*s<ul>\n", last_hnumber, "");
65 if ( (srcp->hnumber - last_hnumber) > 1 )
66 Csprintf(&res, "%*s<li>\n", last_hnumber+1, "");
67 ++last_hnumber;
68 }
69 Csprintf(&res, "%*s<li><a href=\"#", srcp->hnumber, "");
70 mkd_string_to_anchor(T(srcp->text->text),
71 S(srcp->text->text),
72 Csputc_mkd_sta_function_t,
73 &res,1,p->ctx);
74 Csprintf(&res, "\">");
75 Csreparse(&res, T(srcp->text->text),
76 S(srcp->text->text), IS_LABEL);
77 Csprintf(&res, "</a>");
78
79 first = 0;
80 }
81 }
82 }
83 }
84
85 while ( last_hnumber > 0 ) {
86 --last_hnumber;
87 Csprintf(&res, "</li>\n%*s</ul>\n%*s",
88 last_hnumber, "", last_hnumber, "");
89 }
90
91 if ( (size = S(res)) > 0 ) {
92 /* null-terminate & strdup into a free()able memory chunk
93 */
94 EXPAND(res) = 0;
95 *doc = strdup(T(res));
96 }
97 DELETE(res);
98 return size;
99 }
100
101
102 /* write an header index
103 */
104 int
105 mkd_generatetoc(Document *p, FILE *out)
106 {
107 char *buf = 0;
108 int sz = mkd_toc(p, &buf);
109 int ret = EOF;
110
111 if ( sz > 0 )
112 ret = fwrite(buf, 1, sz, out);
113
114 if ( buf ) free(buf);
115
116 return (ret == sz) ? ret : EOF;
117 }