aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: 40a63bc861fbba09b3402283c03b370b62e019e5 (plain)
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include "bstrlib.h"
  4. #include "stmd.h"
  5. #include "debug.h"
  6. void print_usage()
  7. {
  8. printf("Usage: stmd [FILE*]\n");
  9. printf("Options: --help, -h Print usage information\n");
  10. printf(" --ast Print AST instead of HTML\n");
  11. printf(" --version Print version\n");
  12. }
  13. int main(int argc, char *argv[]) {
  14. int i;
  15. bool ast = false;
  16. int g = 0;
  17. int numfps = 0;
  18. int files[argc];
  19. for (i=1; i < argc; i++) {
  20. if (strcmp(argv[i], "--version") == 0) {
  21. printf("stmd %s", VERSION);
  22. printf(" - standard markdown converter (c) 2014 John MacFarlane\n");
  23. exit(0);
  24. } else if ((strcmp(argv[i], "--help") == 0) ||
  25. (strcmp(argv[i], "-h") == 0)) {
  26. print_usage();
  27. exit(0);
  28. } else if (strcmp(argv[i], "--ast") == 0) {
  29. ast = true;
  30. } else if (*argv[i] == '-') {
  31. print_usage();
  32. exit(1);
  33. } else { // treat as file argument
  34. files[g] = i;
  35. g++;
  36. }
  37. }
  38. numfps = g;
  39. bstring s = NULL;
  40. bstring html;
  41. g = 0;
  42. block * cur = make_document();
  43. int linenum = 1;
  44. extern int errno;
  45. FILE * fp = NULL;
  46. if (numfps == 0) {
  47. // read from stdin
  48. while ((s = bgets((bNgetc) fgetc, stdin, '\n'))) {
  49. check(incorporate_line(s, linenum, &cur) == 0,
  50. "error incorporating line %d", linenum);
  51. bdestroy(s);
  52. linenum++;
  53. }
  54. } else {
  55. // iterate over input file pointers
  56. for (g=0; g < numfps; g++) {
  57. fp = fopen(argv[files[g]], "r");
  58. if (fp == NULL) {
  59. fprintf(stderr, "Error opening file %s: %s\n",
  60. argv[files[g]], strerror(errno));
  61. exit(1);
  62. }
  63. struct bStream *stream = bsopen((bNread)fread, fp);
  64. if (stream == NULL) {
  65. printf("Error opening stream\n");
  66. }
  67. while (bsreadln(s, stream, '\n') != BSTR_ERR) {
  68. check(incorporate_line(s, linenum, &cur) == 0,
  69. "error incorporating line %d of %s", linenum, argv[files[g]]);
  70. linenum++;
  71. }
  72. bsclose(stream);
  73. }
  74. }
  75. while (cur != cur->top) {
  76. finalize(cur, linenum);
  77. cur = cur->parent;
  78. }
  79. check(cur == cur->top, "problems finalizing open containers");
  80. finalize(cur, linenum);
  81. process_inlines(cur, cur->attributes.refmap);
  82. if (ast) {
  83. print_blocks(cur, 0);
  84. } else {
  85. check(blocks_to_html(cur, &html, false) == 0, "could not format as HTML");
  86. printf("%s", html->data);
  87. bdestroy(html);
  88. }
  89. free_blocks(cur);
  90. return 0;
  91. error:
  92. return -1;
  93. }