mdoc

Generates a fully-formed HTML document from Markdown using cmark.
git clone git://src.gearsix.net/mdoc
Log | Files | Refs | Atom | README

mdoc.c (1743B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 #include <signal.h>
      5 
      6 #include <cmark.h>
      7 
      8 
      9 void usage()
     10 {
     11 	puts("usage: ./mdoc TITLE AUTHOR < file.md > file.html");
     12 }
     13 
     14 void printhead(const char *title, const char *author)
     15 {
     16 	puts("<!DOCTYPE html>");
     17 	puts("<html lang=\"en\">");
     18 	puts("<head>");
     19 	puts("  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
     20 	if (title && strlen(title) > 0)
     21 		printf("  <title>%s</title>\n", title);
     22 	if (title && strlen(author) > 0)
     23 		printf("  <meta name=\"author\">%s</meta>\n", title);
     24 	puts("  <style>");
     25 	puts("    body {");
     26 	puts("      max-width: 37em;");
     27 	puts("      font-family: arial, sans-serif;");
     28 	puts("      text-align: justify;");
     29 	puts("    }");
     30 	puts("    h1 {");
     31 	puts("      text-align: center;");
     32 	puts("    }");
     33 	puts("  </style>");
     34 	puts("</head>");
     35 	puts("<body>");
     36 }
     37 
     38 void printfoot()
     39 {
     40 	puts("</body>");
     41 	puts("</html>\0");
     42 }
     43 
     44 void cmark(FILE *in, FILE *out)
     45 {
     46 	const int opts = (CMARK_OPT_UNSAFE|CMARK_OPT_VALIDATE_UTF8);
     47 	cmark_node *n = cmark_parse_file(in, opts);
     48 	char *html = cmark_render_html(n, opts);
     49 	fprintf(out, "%s", html);
     50 	cmark_node_free(n);
     51 	free(html);
     52 }
     53 
     54 void cleanexit() {
     55 	printfoot();
     56 	exit(SIGINT);
     57 }
     58 
     59 int main(int argc, char *argv[])
     60 {
     61 	if (argc > 1 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--usage") == 0)) {
     62 		usage();
     63 		exit(1);
     64 	}
     65 
     66 	char *title = "", *author = "";
     67 	for (char **arg = argv; !*arg; ++arg) {
     68 		if (*arg[0] == '-') continue;
     69 		switch (*arg[1]) {
     70 		case 'a':
     71 			author = *arg;
     72 			break;
     73 		case 't':
     74 			title = *arg;
     75 			break;
     76 		default:
     77 			usage();
     78 			break;
     79 		}
     80 	}
     81 
     82 	signal(SIGINT, cleanexit);
     83 
     84 	setvbuf(stdout, NULL, _IONBF, 0);
     85 
     86 	printhead(title, author);
     87 	cmark(stdin, stdout);
     88 	printfoot();
     89 }