aboutsummaryrefslogtreecommitdiff
path: root/md.c
blob: ab0798fb5beaf622089a3f16bf21f683fffb134d (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
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
// 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>

#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?

// @todo when implementing the cycling through characters replace tabs with 4 spaces

// 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'};
	memcpy(prepended_string, in_src, LINE_MAX);
	strcat(prepended_string, in_dest);
	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
	bool no_link = false;
	char* closing_sqr_bracket = strchr(start, ']');
	if(closing_sqr_bracket == NULL) {
		no_link = true;
	}
	if(*(closing_sqr_bracket + 1) != '(') {
		no_link = true;
	}
	char* closing_rnd_bracket = strchr(closing_sqr_bracket + 1, ')');
	if(closing_rnd_bracket == NULL) {
		no_link = true;
	}
	if(no_link) {
		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);
	char* link_loc = calloc(link_loc_len + 1, 1);

	if(link_text == NULL || link_loc == NULL) {
		perror("calloc error");
		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;
}

// @todo NEXT
// 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) {
	char* parsed_text = NULL;
	size_t text_length = 0;
	bool empty_line_carry = true;
	bool spaced_codeblock = false;
	bool in_paragraph = false;
	// This is the offset in parsed_text
	size_t offset = 0;
	// This describes the spaces the last list level had
	int list_spaces = 0;
	int list_level = 0;
	bool in_list = false;
	char* next_line = input;
	// Different indicators for all the inline things
	// How strongly are we currently emphasized? * = 1; ** = 2; *** = 3
	int strength_level = 0;
	int inline_code_level = 0;
	bool in_mono = false;
	bool in_cut = false;
	bool in_quotes = false;
	// Signal we are on the last line, for safety reasons we just insert an empty paragraph
	bool on_lastline = false;
	for(char* line = input; next_line != NULL; line = next_line) {
		// Compute the next line and put a '\0' at the end of the current line
		{
			char* line_end = strchr(line, '\n');
			if(line_end != NULL) {
				*line_end = '\0';
				next_line = line_end + 1;
			} else {
				empty_line_carry = true;
				on_lastline = true;
			}
		}
		size_t line_length = 0;
		size_t line_offset = 0;
		char line_buffer[LINE_MAX] = {'\0'};
		bool no_special = true;
		// The pre_line_buffer contains html headers that are needed before content of the current line
		char pre_line_buffer[LINE_MAX] = "\0";
		char* trimmed_line = NULL;
		// When this is true we can format text with things like <em>, <b>, etc.
		bool format_allow = true;
		int spaces_skipped = 0;
		bool empty_line = false;
		// Check if we have an empty line
		if(empty_line_carry) {
			empty_line_carry = false;
			empty_line = true;
		}

		if(!on_lastline) {
			spaces_skipped = trim_space(line, &trimmed_line);
			if(*trimmed_line == '\0' || *trimmed_line == '\r') {
				empty_line_carry = true;
				continue;
			}
		}

		if(on_lastline) {
			empty_line = true;
			trimmed_line = "\0";
			line = "\0";
		}

		// Blockquotes
		/*
						       I love me some spaghetti bolognese ;P
						       Luckily there is enough spaghetti here
						                    for everyone

						                ----|
						                ----|------------
						            \//\----|
						            ||/\||\
						            |/|||||\
						         ---------------
						         \             /
						          \-----------/
		*/
		if(*trimmed_line == '>') {
			// We are in a blockquote!
			// Set the new line to after the quote marker
			line = trimmed_line + 1;
			// trim again
			spaces_skipped = trim_space(line, &trimmed_line);
			if(!in_quotes) {
				if(in_paragraph) {
					strncat(pre_line_buffer, "</p><blockquote>", LINE_MAX -1);
					in_paragraph = false;
				} else {
					line_length = prepend(line_buffer, "<blockquote>");
				}
				in_quotes = true;
			}
		} else if(in_quotes) {
			if(in_paragraph) {
				strncat(pre_line_buffer, "</p></blockquote>", LINE_MAX-1);
				in_paragraph = false;
			} else {
				strncat(pre_line_buffer, "</blockquote>", LINE_MAX-1);
			}
			in_quotes = false;
		}
		// / Blockquotes

		// Unordered Lists ------------------------------------------------
		if(spaces_skipped < 4 + list_spaces && *trimmed_line == '*' && *(trimmed_line + 1) == ' ') {
			if(!in_list) {
				strncat(pre_line_buffer, "<ul>", LINE_MAX-1);
				in_list = true;
			} else {
				strncat(pre_line_buffer, "</li>\n", LINE_MAX-1);
			}
			if(spaces_skipped < list_spaces) {
				for(int i = (list_spaces - spaces_skipped) >> 1; i > 0; i--) {
					strncat(pre_line_buffer, "</ul>\n", LINE_MAX-1);
					list_level--;
				}
			} else if(spaces_skipped > list_spaces) {
				for(int i = (spaces_skipped - list_spaces) >> 1; i > 0; i--) {
					strncat(pre_line_buffer, "<ul>", LINE_MAX-1);
					list_level++;
				}
			}

			strncat(pre_line_buffer, "<li>", LINE_MAX-1);
			trimmed_line = trimmed_line + 2;
			list_spaces = spaces_skipped;
		} else if(in_list && empty_line) {
			strncat(pre_line_buffer, "</li></ul>\n", LINE_MAX-1);
			for(int i = 0; i < list_level; i++) {
				strncat(pre_line_buffer, "</ul>\n", LINE_MAX-1);
			}
			in_list = false;
			list_spaces = 0;
		}
		// / Unordered List -----------------------------------------------
		// @todo Ordered list

		// Spaced codeblocks ----------------------------------------------
		// Also check if we have a list
		if(spaces_skipped >= 4 && !in_list) {
			// If this is true we are already in a codeblock
			if(spaced_codeblock) {
				line_length = prepend(line_buffer, "\n");
				no_special = false;
				format_allow = false;
			} else {
				line_length = prepend(line_buffer, "<pre><code>");
				line_length = append(line_buffer, "<p>");
				spaced_codeblock = true;
				no_special = false;
				format_allow = false;
			} // Replace any leading tabs with 4 spaces
			char* code_replaced = line;
			for(int i = 0; i < 4;) {
				if(*(line + i) == '\t') {
					code_replaced ++;
					i += 4;
				} else if(*(line + i) == ' ') {
					code_replaced++;
					i++;
				} else {
					break;
				}
			}
			line_length = append(line_buffer, code_replaced);
		} else if(spaced_codeblock) {	
			spaced_codeblock = false;
			strncat(pre_line_buffer, "</p></code></pre>\n", LINE_MAX-1);
		}
		// / Spaced codeblocks --------------------------------------------
	

		// Titles (#) -----------------------------------------------------
		// @todo allow enclosing titles bracket style
		if(no_special && *trimmed_line == '#') {
			int header_depth = 1;
			while(header_depth < 6) {
				if(*(trimmed_line + header_depth) == '#')
					header_depth++;
				else
					break;
			}
			char* trimmed_title = NULL;
			if(trim_space(trimmed_line + header_depth,
			              &trimmed_title) > 0) {
				no_special = false;
				
				char title[LINE_MAX + 1] = "";
				if(snprintf(title, LINE_MAX + 1, "<h%d>%s</h%d>\n",
							header_depth,
							trimmed_title,
							header_depth
						   ) > LINE_MAX) {
					fprintf(stderr, "Title too long");
					return -1;
				}
				line_length = append(line_buffer, title);
			}
		// / Titles -------------------------------------------------------
		// Thematic brakes ------------------------------------------------
		} else if(no_special && (*trimmed_line == '-' || *trimmed_line == '*' || *trimmed_line == '_')) {
			int i = 1;
			for(; *(trimmed_line+i) == *(trimmed_line+i-1); i++) {
			}
			if(*(trimmed_line+i) == '\0') {
				no_special = false;
				line_length = append(line_buffer, "<hr/>\n");
			}
		}
		// / Thematic brakes ----------------------------------------------
		

		// Plain Text -----------------------------------------------------
		if(no_special) {
			line_length = append(line_buffer, trimmed_line);
			// Handle newline via slash/*
			if(*(line_buffer + line_length -1) == '\\') {
				*(line_buffer + line_length -1) = '\n';
				if(*(line_buffer + line_length -2) != '\\') {
					empty_line_carry = true;
				}
			}
			// Handle newlines
			if(empty_line && in_paragraph) {
				strncat(pre_line_buffer, "</p>\n", LINE_MAX-1);
				in_paragraph = false;
			}
			// If we are not in a paragraph enter one
			if(!in_paragraph && !in_list) {
				line_length = prepend(line_buffer, "<p>");
				in_paragraph = true;
			} else { // If we are in a paragraph the newline will be converted to a space
				line_length = prepend(line_buffer, " ");
			}
		} else if(in_paragraph) {
			line_length = prepend(line_buffer, "</p>\n");
			in_paragraph = false;
		}

		if(format_allow) {
			bool escaped = false;
			char format_line_buffer[LINE_MAX] = {0};
			for(char* line_position = line_buffer; *line_position != '\0'; line_position++) {
				// Handle a previously escaped character
				if(escaped) {
					char escaped_char[2] = {*line_position, '\0'};
					// Also check if we have an escaped newline
					strncat(format_line_buffer, *line_position == '\n' ? "\\" : escaped_char, LINE_MAX-1);
					escaped = false;
					continue;
				}
				switch(*line_position) {
					// Text strength, for sake of simplicity, we'll treat * and _ the same
					case '*' :
					case '_' :
						{
							// Look ahead if the next ones are also strength indicators
							int strength_indicators = 0;
							for(; strength_level > 0 ? strength_indicators<strength_level : true ; strength_indicators++) {
								if(!(*(line_position + strength_indicators) == '*' || 
								   *(line_position + strength_indicators) == '_')) {
									break;
								   }
							}

							if(strength_level == 0) {
								if(strength_indicators == 1) {
									strncat(format_line_buffer, "<em>", LINE_MAX-1);
								} else if(strength_indicators == 2) {
									strncat(format_line_buffer, "<b>", LINE_MAX-1);
								} else {
									strncat(format_line_buffer, "<b><em>", LINE_MAX-1);
								}
								strength_level = strength_indicators;
								line_position += strength_indicators -1;
							} else {
								if(strength_level >= 3 && strength_indicators >= 3) {
									strncat(format_line_buffer, "</em></b>", LINE_MAX-1);
								} else if(strength_level == 2 && strength_indicators >= 2) {
									strncat(format_line_buffer, "</b>", LINE_MAX-1);
								} else {
									strncat(format_line_buffer, "</em>", LINE_MAX-1);
								}
								strength_level = strength_level - strength_indicators;
								line_position += strength_indicators -1;
							}
						}
						break;
					// Inline code
					case '`':
						{
							if(in_mono) {
								strncat(format_line_buffer, "</code>", LINE_MAX);
								in_mono = false;
							} else {
								strncat(format_line_buffer, "<code>", LINE_MAX);
								in_mono = true;
							}
						}
						break;
					// Cut text
					case '~':
						{
							// Look ahead, we only want to cut if there are two tildes
							if(*(line_position + 1) != '~') {
								strncat(format_line_buffer, "~", LINE_MAX);
								break;
							}
							if(in_cut) {
								// Close
								strncat(format_line_buffer, "</s>", LINE_MAX);
								in_cut = false;
							} else {
								in_cut = true;
								strncat(format_line_buffer, "<s>", LINE_MAX);
							}
							line_position++;
						}
						break;
					// brackets
					case '[':
						{
							char* link_text = NULL;
							char* link_loc = NULL;
							size_t link_loctxt_len = 0;
							char* closing_rnd_bracket = get_link_components(line_position, &link_text, &link_loc, &link_loctxt_len);
							// This is 16 characters long (add one for good measure (: ):
							//<a href=""></a>\0
							char* link_html = calloc(link_loctxt_len + 17, 1);
							if(link_html == NULL || closing_rnd_bracket == NULL) {
								strncat(format_line_buffer, "[", LINE_MAX);
								if(link_html != NULL) free(link_html);
								if(link_text != NULL) free(link_text);
								if(link_loc != NULL) free(link_loc);
								break;
							}

							sprintf(link_html, "<a href=\"%s\">%s</a>", link_loc, link_text);

							strncat(format_line_buffer, link_html, LINE_MAX - 1);
							line_position = closing_rnd_bracket;
							free(link_html);
							free(link_text);
							free(link_loc);
						}
						break;
					case ']':
						{
						}
						break;
					case '(':
						{
						}
						break;
					case ')':
						{
						}
						break;
					// Images
					case '!':
						{
							char* img_alt = NULL;
							char* img_src = NULL;
							size_t img_altsrc_len = 0;
							if(*(line_position + 1) == '\0') {
								strncat(format_line_buffer, "!", LINE_MAX);
								break;
							}
							char* closing_rnd_bracket = get_link_components(line_position + 1, &img_alt, &img_src, &img_altsrc_len);
							// This is 21 characters long, again we add one more to be safe
							//<img alt="" src=""/>\0
							char* img_html = calloc(img_altsrc_len + 22, 1);
							if(img_html == NULL || closing_rnd_bracket == NULL) {
								strncat(format_line_buffer, "!", LINE_MAX);
								if(img_html != NULL) free(img_html);
								if(img_alt != NULL) free(img_alt);
								if(img_src != NULL) free(img_src);
								break;
							}	
							sprintf(img_html, "<img alt=\"%s\" src=\"%s\"/>", img_alt, img_src);

							strncat(format_line_buffer, img_html, LINE_MAX - 1);
							line_position = closing_rnd_bracket;
							free(img_html);
							free(img_alt);
							free(img_src);
						}
						break;
					// escape
					case '\\':
						{
							escaped = true;
						}
						break;
					default:
						{
							// See how much text we have
							size_t text_found_n = strcspn(line_position, "*_`[]()!\\~");
							char text_found[LINE_MAX] = {'\0'};
							memcpy(text_found, line_position, text_found_n);	
							text_found[text_found_n+1] = '\0';
							append(format_line_buffer, text_found);
							line_position += text_found_n-1;
						}
				}
			}
			memcpy(line_buffer, format_line_buffer, LINE_MAX-1);
			line_length = strnlen(format_line_buffer, LINE_MAX);
		}

		// Prepend the pre_line_buffer to the line_buffer
		line_length = prepend(line_buffer, pre_line_buffer);

		//printf("%ld: %s\n",line_length , line_buffer);

		if(offset + line_length > buffer_size) {
			fprintf(stderr, "Too long!\n");
			return -1;
		}

		memcpy(buffer + offset, line_buffer, line_length);
		offset += line_length;
		if(on_lastline) {
			strncat(buffer, "</p>", buffer_size);
			break;
		}
	}
	return 0;
}
Jeremias Stotters git repositories generated by CGIT