rule.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include "txt2html.h"
  2. size_t rule_len(NodeType type)
  3. {
  4. if (type & CLOSE) return 2;
  5. int len = 0;
  6. switch (type) {
  7. case OPEN+OL+LI:
  8. return 3;
  9. case OPEN+UL+LI:
  10. return 2;
  11. case OPEN+PRE:
  12. return 1;
  13. }
  14. return len;
  15. }
  16. bool rule_match(const char *str, NodeType type)
  17. {
  18. assert(str);
  19. if ((type & CLOSE) && strlen(str) >= 2)
  20. return (str[0] == '\n' && str[1] == '\n');
  21. bool match = false;
  22. switch (type) {
  23. case H1:
  24. match = (rule_match_heading(str) == H1);
  25. break;
  26. case H2:
  27. match = (rule_match_heading(str) == H2);
  28. break;
  29. case OPEN+OL+LI:
  30. if (strlen(str) >= rule_len(OPEN+OL+LI))
  31. match = (isalnum(str[0]) && str[1] == '.' && str[2] == ' ');
  32. break;
  33. case OPEN+UL+LI:
  34. if (strlen(str) >= rule_len(OPEN+UL+LI))
  35. match = ((str[0] == '-' || str[0] == '*') && str[1] == ' ');
  36. break;
  37. case OPEN+PRE:
  38. // +1 to peek and make sure next char is print
  39. if (strlen(str) >= rule_len(OPEN+PRE)+1)
  40. match = (str[0] == '\t' && isprint(str[1]));
  41. break;
  42. default:
  43. match = false;
  44. }
  45. return match;
  46. }
  47. NodeType rule_match_heading(const char *str)
  48. {
  49. assert(str);
  50. NodeType heading = 0;
  51. while (*str && *str++ != '\n'); // skip line
  52. if (strlen(str) >= 3) {
  53. if (*str == '=' && *(str+1) == '=' && *(str+2) == '=')
  54. heading = H1;
  55. else if (*str == '-' && *(str+1) == '-' && *(str+2) == '-')
  56. heading = H2;
  57. }
  58. return heading;
  59. }