webgen.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <ctype.h>
  6. #include "html.h"
  7. #include "utils.h"
  8. #define LENGTH(x) (sizeof (x) / sizeof (*x))
  9. char *line = NULL;
  10. unsigned linenum = 0;
  11. size_t linelen;
  12. char *params[9] = { 0 };
  13. int nparams;
  14. int inparagraph = 0;
  15. struct {
  16. char *name;
  17. int(*fun)(void);
  18. } tokens[] = { //TODO: make the recognition not dependent on length+order
  19. { ".img", spitimg },
  20. { ".ref", spithref },
  21. { ".br", spitlinebreak },
  22. { ".cw", spitmonospace },
  23. { ".hr", spithorizontalrule },
  24. { ".pp", newparagraph },
  25. { ".b", spitbold },
  26. { ".i", spititalic },
  27. //{ "", newparagraph },
  28. };
  29. char *
  30. nextword(char *p)
  31. {
  32. // find the end of current word
  33. for (;; p++) {
  34. if (*p == '\0') {
  35. return NULL;
  36. } else if (isspace(*p)) {
  37. //TODO: is this correct?
  38. *p = '\0';
  39. p++;
  40. break;
  41. }
  42. }
  43. // find the first letter of next word
  44. for (;; p++) {
  45. if (*p == '\0') {
  46. return NULL;
  47. } else if (!isspace(*p)) {
  48. break;
  49. }
  50. }
  51. return p;
  52. }
  53. int
  54. paramize(void)
  55. {
  56. char *p = line;
  57. char *w = line;
  58. nparams = 0;
  59. while ((w = nextword(p)) != NULL) {
  60. params[nparams++] = w;
  61. //puts(w);
  62. p = w;
  63. }
  64. return 0;
  65. }
  66. int
  67. spit(void)
  68. {
  69. // TODO: should we always spit the original?
  70. return fputs(line, stdout);
  71. }
  72. int
  73. tokenp(void)
  74. {
  75. int i;
  76. // implicit new paragraph via an empty line is a special case
  77. if (line[0] == '\n') {
  78. newparagraph();
  79. return 0;
  80. }
  81. for (i = 0; i < LENGTH(tokens); i++) {
  82. const char * t = tokens[i].name;
  83. if (!strncmp(line, t, strlen(t))) {
  84. paramize();
  85. tokens[i].fun();
  86. return 1;
  87. }
  88. }
  89. spit();
  90. return 0;
  91. }
  92. int
  93. main(int argc, char *argv[])
  94. {
  95. FILE *stream = stdin;
  96. size_t len = 0;
  97. ssize_t nread;
  98. spitheader();
  99. while ((nread = getline(&line, &len, stream)) != -1) {
  100. linenum++;
  101. tokenp();
  102. }
  103. free(line);
  104. if (inparagraph) {
  105. puts("</p>");
  106. }
  107. spitfooter();
  108. return 0;
  109. }