format.c 3.0 KB

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