aboutsummaryrefslogtreecommitdiff
path: root/md.c
blob: 5cb0340fea70c05b16bdab42979c94a4ac115419 (plain)
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
// Copyright 2021 Jeremias Stotter
//
// This file is part of ´JBlog´.
//
// ´JBlog´ is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ´JBlog´ is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ´JBlog´.  If not, see <http://www.gnu.org/licenses/>.

#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

#include <time.h>

#include "jblog.h"

#define LINE_MAX 4096

// Some not so nice things about this:
//   HTML escapes like &#42; are not handled by this although they might be handled by the client anyways
//   No setext headings because why not just use the hash symbol?

size_t append(char* in_dest, char* in_src);
size_t prepend(char* in_dest, char* in_src);
char* get_link_components(char* start, char** out_text, char** out_loc, size_t* out_len);

enum html_type {
	t_root = 0,
	t_inner,
	t_h, // Contains a pointer to an int as its value, this pointer indicates title strength (1-6)
	t_p,
	t_br,
	t_str, // t_str contains an int pointer as its level
	t_img,
	t_a,
	t_ol,
	t_ul,
	t_li
};

// The file will be structured as a tree that, in the end will be converted to valid html
struct tree_element {
	struct tree_element* parent;
	int type;
	int children_n;
	struct tree_element** children;
	// Is this element allowed to have inner html
	bool allow_inner;
	// Can be anythign additional, like src for img or text in the case of inner
	void* value;
};

struct tree_element* new_element() {
	return calloc(1, sizeof(struct tree_element));
}

void free_tree(struct tree_element* root) {
	if(root->value)
		free(root->value);
	if(root->children) {
		for(int i = 0; i < root->children_n; i++) {
			free_tree(root->children[i]);
		}
		free(root->children);
	}
	free(root);
}

struct tree_element* new_child(struct tree_element* parent) {
	parent->children_n++;
	parent->children = realloc(parent->children, sizeof(struct tree_element*)*(parent->children_n));
	struct tree_element* child = new_element();
	child->parent = parent;
	(parent->children)[parent->children_n-1] = child;
	return child;
}

// Returns the bytes written
#define html_escape(output_buffer, input) sprintf(output_buffer, "&#x%X;", input)

// Reallocs the string dest to fit src, then append
char* realloc_append(char* dest, char* src) {
	//printf("Dest:%sSrc:%s\n", dest ? dest : "", src ? src : "");
	size_t dest_len = dest ? strlen(dest) : 0;
	dest = realloc(dest, dest_len + (src ? strlen(src) : 0) + 1);
	if(src)
		strcpy(dest + dest_len, src);
	return dest;
}

#define p_html "<p>%s</p>\n"
#define br_html "<br/>"
#define h_html "<h%d>%s</h%d>\n"
#define em_html "<em>%s</p>\n"
#define b_html "<b>%s</b>\n"
#define img_html "<img src=\"%s\" alt=\"%s\" title=\"\"/>\n"
#define a_html "<a href=%s>%s</a>\n"
#define ol_html "<ol>%s</ol>\n"
#define ul_html "<ul>%s</ul>\n"
#define li_html "<li>%s</li>\n"
// Resolve a tree to html
char* tree_to_html(struct tree_element* root) {
	char* html=NULL;
	char* inner_html = NULL;
	for(int i = 0; i < root->children_n; i++) {
		struct tree_element* child = root->children[i];
		switch(child->type) {
			case(t_inner):
				// Append the inner html to buffer
				inner_html = realloc_append(inner_html, child->value);
			break;
			default:
				char* child_html = tree_to_html(child);
				inner_html = realloc_append(inner_html, child_html);
				free(child_html);
			break;
		}
	}
//	printf("%s\n", inner_html ? inner_html : "(EMPTY)");
	#define realloc_for_html(html_pattern) realloc(html, (inner_html ? strlen(inner_html) : 0) + strlen(html_pattern) + 1);
	switch(root->type) {
		case(t_p):	
			html = realloc_for_html(p_html);
			sprintf(html, p_html, inner_html ? inner_html : "");
		break;
		case(t_h):
			html = realloc_for_html(h_html);
			sprintf(html, h_html, *(int*)(root->value), inner_html ? inner_html : "", *(int*)(root->value));
		break;
		case(t_str):
			html = realloc_for_html(em_html);
			sprintf(html, em_html, inner_html ? inner_html : "");
		break;
		case(t_br):
			html = realloc_for_html(b_html);
			strcpy(html, br_html);
		break;
		default:
			html=inner_html;
		break;
	}
	return html;
}

// This appends the cur_char to active element / it creates a new active element if the active element can not have text
void append_char_to_active(struct tree_element* root, struct tree_element** active_element, char cur_char) {
	// We are not allowed to add inner to this element so we'll start a new paragraph
	struct tree_element* new_active_element = *active_element;
	if(!(new_active_element->allow_inner) && new_active_element->type != t_inner) {
		new_active_element = new_child(root);
		new_active_element->type = t_p;
		new_active_element->allow_inner = true;
	}
	if(new_active_element->type != t_inner) {
		new_active_element = new_child(new_active_element);
		new_active_element->type = t_inner;
	}
	if((cur_char <= 47 ||
	   (cur_char >=58 && cur_char <=64) ||
	   (cur_char >=91 && cur_char <=96) ||
	   cur_char > 122) && cur_char != 0x20) {
		// Escape just to be safe
		char append[8] = "";
		html_escape(append, cur_char);
		new_active_element->value = realloc_append(new_active_element->value, append);
	} else {
		// This is stupid, improve this later xD
		char append[2] = {cur_char, '\0'};
		new_active_element->value = realloc_append(new_active_element->value, append);
	}
	*active_element = new_active_element;
}

// The program needs to loop through the loop again to cose all the open things at the end, THIS NEEDS TO BE IMPLEMENTED for xhtml
int parse_markdown(char* input, char* buffer, size_t buffer_size) {
	clock_t before = clock();
	memset(buffer, 0, buffer_size);
	bool escaped = false;
	bool newline = true;
	
	int hash_chain = 0;

	struct tree_element* root = new_element();
	struct tree_element* active_element = root;
	for(char* cur_char = input; *cur_char != '\0'; cur_char++) {
		if(escaped) {
			escaped = false;
			if(*cur_char == '\n' || *cur_char == '\r') {
				if(active_element->parent)
					active_element = active_element->parent;
				struct tree_element* br_child = new_child(active_element);
				br_child->type = t_br;
			} else {
				append_char_to_active(root, &active_element, *cur_char);
			}
			continue;
		}

		if(hash_chain > 0) {
			if(active_element->type != t_h) {
				if(active_element->parent ? active_element->parent->type == t_h : false) {
					active_element = active_element->parent;
				} else {
					active_element = new_child(root);
					active_element->allow_inner = true;
					active_element->type = t_h;
					active_element->value = malloc(sizeof(int));
				}
			}
			*(int*)(active_element->value) = hash_chain;
		}

		switch(*cur_char) {
			// Character escaping
			case('\\'):
				escaped = true;
			break;
			// Tabs
			case('\t'):
			
			break;
			// Newline
			case('\r'):
				// Ignoring \r goes against the commonmark spec, but who cares
			break;
			case('\n'):
				if(hash_chain > 0)
					active_element = root;
				if(newline) {
					// A double new line means we return the active element to root
					active_element = root;
					newline = false;
				} else {
					newline = true;
				}
				hash_chain = 0;
			break;
			// Text strength
			case('*'):
				
			break;
			case('_'):
			
			break;
			case('`'):
			break;
			case('~'):
			break;
			// Titles
			case('='):
				if(newline) {
					// Make the last line a title, otherwise we fall through
					break;
				}
			case('-'):
				if(newline) {
					// Make the last line a title, otherwise we fall through
					break;
				}
			case('#'):
				printf("%s\n", newline ? "a" : "b");
				if(hash_chain == 0 || newline) {
					if(active_element == root || newline) {
						active_element = root;
						hash_chain = 1;
						newline = false;
						break;
					}
				} else {
					hash_chain++;
					break;
				}
			case(' '):
				// Trim spaces from newline
				if(active_element == root || newline) {
					break;
				}
			// Default character handling
			default:
				hash_chain = 0;
				newline = false;
				append_char_to_active(root, &active_element, *cur_char);
			break;
		}
	}
	char* html = tree_to_html(root);
	printf("%s\n", html ? html : "" );
	// Tear down the tree
	free_tree(root);
	strncpy(buffer, html, buffer_size - 1);
	free(html);
	printf("Time to process in ns: %ld\n", (clock() - before) / (CLOCKS_PER_SEC / 1000000));
	return 0;
}

// This function outputs a pointer that points past leading spaces
// it returns the number of spaces skippen where \t = 4 spaces
int trim_space(char* input, char** output) {
	char* trimmed = input;
	int count = 0;
	while(*trimmed == ' ' || *trimmed == '\t') {
		if(*trimmed == '\t') {
			count += 4;
		} else {
			count ++;
		}
		trimmed++;
	}
	*output = trimmed;
	return count;
}

// Append in_src to in_dst, then return length of new string
size_t append(char* in_dest, char* in_src) {
	strcat(in_dest, in_src);
	// for pure safety reasons I'll put a terminating \0 at the end of the destination string
	in_dest[LINE_MAX-1] = '\0';
	return strlen(in_dest);
}

// Prepend in_src to in_dst, then return length of new string
size_t prepend(char* in_dest, char* in_src) {	
	char prepended_string[LINE_MAX] = {'\0'};
	strncpy(prepended_string, in_src, LINE_MAX - 1);
	strncat(prepended_string, in_dest, LINE_MAX - 1);
	memcpy(in_dest, prepended_string, LINE_MAX);
	// for pure safety reasons I'll put a terminating \0 at the end of the destination string
	in_dest[LINE_MAX-1] = '\0';
	return strlen(in_dest);
}

// start is the first curly bracket we have
// Returns pointer to last round bracket
// free the returned pointers yourself
char* get_link_components(char* start, char** out_text, char** out_loc, size_t* out_len) {
	// Search for the next closing bracket
	char* closing_sqr_bracket = strchr(start, ']');
	if(closing_sqr_bracket == NULL) {
		return NULL;
	}
	if(*(closing_sqr_bracket + 1) != '(') {
		return NULL;
	}
	char* closing_rnd_bracket = strchr(closing_sqr_bracket + 1, ')');
	if(closing_rnd_bracket == NULL) {
		return NULL;
	}
	size_t link_text_len = closing_sqr_bracket - start - 1;
	size_t link_loc_len = closing_rnd_bracket - closing_sqr_bracket - 2;
	
	char* link_text = calloc(link_text_len + 1, 1);
	if(link_text == NULL) {
		jb_log(LL_ERR, true, "calloc error");
		return NULL;
	}
	char* link_loc = calloc(link_loc_len + 1, 1);
	if(link_text == NULL) {
		jb_log(LL_ERR, true, "calloc error");
		free(link_text);
		return NULL;
	}

	
	memcpy(link_text, start + 1, link_text_len);
	memcpy(link_loc, closing_sqr_bracket + 2, link_loc_len);
	*out_text = link_text;
	*out_loc = link_loc;
	*out_len = link_text_len + link_loc_len;

	return closing_rnd_bracket;
}
Jeremias Stotters git repositories generated by CGIT