mdoc

markdown -> html document
git clone git://git.gearsix.net/mdoc
Log | Files | Refs | Atom | README

mdoc.c (1760B)


      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>");
     42 }
     43 
     44 size_t cmark(const size_t bufsiz, FILE *in, FILE *out)
     45 {
     46 	char buf[bufsiz];
     47 	size_t n = fread(buf, sizeof(char), BUFSIZ, in);
     48 	char *html = cmark_markdown_to_html(buf, strlen(buf), 0);
     49 	fprintf(out, "%s", html);
     50 	free(html);
     51 	return n;
     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 	void (*sig)(int) = 0;
     83 	sig = signal(SIGINT, cleanexit);
     84 
     85 	printhead(title, author);
     86 	while (!sig && cmark(BUFSIZ, stdin, stdout) == BUFSIZ);
     87 	printfoot();
     88 }