html.c 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. /* snac - A simple, minimalistic ActivityPub instance */
  2. /* copyright (c) 2022 grunfink - MIT license */
  3. #include "xs.h"
  4. #include "xs_io.h"
  5. #include "xs_json.h"
  6. #include "xs_regex.h"
  7. #include "snac.h"
  8. d_char *not_really_markdown(char *content, d_char **f_content)
  9. /* formats a content using some Markdown rules */
  10. {
  11. d_char *s = NULL;
  12. int in_pre = 0;
  13. int in_blq = 0;
  14. xs *list;
  15. char *p, *v;
  16. xs *wrk = xs_str_new(NULL);
  17. {
  18. /* split by special markup */
  19. xs *sm = xs_regex_split(content,
  20. "(`[^`]+`|\\*\\*?[^\\*]+\\*?\\*|https?:/" "/[^ ]*)");
  21. int n = 0;
  22. p = sm;
  23. while (xs_list_iter(&p, &v)) {
  24. if ((n & 0x1)) {
  25. /* markup */
  26. if (xs_startswith(v, "`")) {
  27. xs *s1 = xs_crop(xs_dup(v), 1, -1);
  28. xs *s2 = xs_fmt("<code>%s</code>", s1);
  29. wrk = xs_str_cat(wrk, s2);
  30. }
  31. else
  32. if (xs_startswith(v, "**")) {
  33. xs *s1 = xs_crop(xs_dup(v), 2, -2);
  34. xs *s2 = xs_fmt("<b>%s</b>", s1);
  35. wrk = xs_str_cat(wrk, s2);
  36. }
  37. else
  38. if (xs_startswith(v, "*")) {
  39. xs *s1 = xs_crop(xs_dup(v), 1, -1);
  40. xs *s2 = xs_fmt("<i>%s</i>", s1);
  41. wrk = xs_str_cat(wrk, s2);
  42. }
  43. else
  44. if (xs_startswith(v, "http")) {
  45. xs *s1 = xs_fmt("<a href=\"%s\">%s</a>", v, v);
  46. wrk = xs_str_cat(wrk, s1);
  47. }
  48. else
  49. /* what the hell is this */
  50. wrk = xs_str_cat(wrk, v);
  51. }
  52. else
  53. /* surrounded text, copy directly */
  54. wrk = xs_str_cat(wrk, v);
  55. n++;
  56. }
  57. }
  58. /* now work by lines */
  59. p = list = xs_split(wrk, "\n");
  60. s = xs_str_new(NULL);
  61. while (xs_list_iter(&p, &v)) {
  62. xs *ss = xs_strip(xs_dup(v));
  63. if (xs_startswith(ss, "```")) {
  64. if (!in_pre)
  65. s = xs_str_cat(s, "<pre>");
  66. else
  67. s = xs_str_cat(s, "</pre>");
  68. in_pre = !in_pre;
  69. continue;
  70. }
  71. if (xs_startswith(ss, ">")) {
  72. /* delete the > and subsequent spaces */
  73. ss = xs_strip(xs_crop(ss, 1, 0));
  74. if (!in_blq) {
  75. s = xs_str_cat(s, "<blockquote>");
  76. in_blq = 1;
  77. }
  78. s = xs_str_cat(s, ss);
  79. s = xs_str_cat(s, "<br>");
  80. continue;
  81. }
  82. if (in_blq) {
  83. s = xs_str_cat(s, "</blockquote>");
  84. in_blq = 0;
  85. }
  86. s = xs_str_cat(s, ss);
  87. s = xs_str_cat(s, "<br>");
  88. }
  89. if (in_blq)
  90. s = xs_str_cat(s, "</blockquote>");
  91. if (in_pre)
  92. s = xs_str_cat(s, "</pre>");
  93. /* some beauty fixes */
  94. s = xs_replace_i(s, "</blockquote><br>", "</blockquote>");
  95. *f_content = s;
  96. return *f_content;
  97. }