Text.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. /*
  2. * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. * Copyright (c) 2021, Peter Elliott <pelliott@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Debug.h>
  8. #include <AK/ScopeGuard.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibMarkdown/Text.h>
  11. #include <ctype.h>
  12. #include <string.h>
  13. namespace Markdown {
  14. void Text::EmphasisNode::render_to_html(StringBuilder& builder) const
  15. {
  16. builder.append((strong) ? "<strong>" : "<em>");
  17. child->render_to_html(builder);
  18. builder.append((strong) ? "</strong>" : "</em>");
  19. }
  20. void Text::EmphasisNode::render_for_terminal(StringBuilder& builder) const
  21. {
  22. if (strong) {
  23. builder.append("\e[1m");
  24. child->render_for_terminal(builder);
  25. builder.append("\e[22m");
  26. } else {
  27. builder.append("\e[3m");
  28. child->render_for_terminal(builder);
  29. builder.append("\e[23m");
  30. }
  31. }
  32. size_t Text::EmphasisNode::terminal_length() const
  33. {
  34. return child->terminal_length();
  35. }
  36. void Text::CodeNode::render_to_html(StringBuilder& builder) const
  37. {
  38. builder.append("<code>");
  39. code->render_to_html(builder);
  40. builder.append("</code>");
  41. }
  42. void Text::CodeNode::render_for_terminal(StringBuilder& builder) const
  43. {
  44. builder.append("\e[1m");
  45. code->render_for_terminal(builder);
  46. builder.append("\e[22m");
  47. }
  48. size_t Text::CodeNode::terminal_length() const
  49. {
  50. return code->terminal_length();
  51. }
  52. void Text::BreakNode::render_to_html(StringBuilder& builder) const
  53. {
  54. builder.append("<br />");
  55. }
  56. void Text::BreakNode::render_for_terminal(StringBuilder&) const
  57. {
  58. }
  59. size_t Text::BreakNode::terminal_length() const
  60. {
  61. return 0;
  62. }
  63. void Text::TextNode::render_to_html(StringBuilder& builder) const
  64. {
  65. builder.append(escape_html_entities(text));
  66. }
  67. void Text::TextNode::render_for_terminal(StringBuilder& builder) const
  68. {
  69. if (collapsible && (text == "\n" || text.is_whitespace())) {
  70. builder.append(" ");
  71. } else {
  72. builder.append(text);
  73. }
  74. }
  75. size_t Text::TextNode::terminal_length() const
  76. {
  77. if (collapsible && text.is_whitespace()) {
  78. return 1;
  79. }
  80. return text.length();
  81. }
  82. void Text::LinkNode::render_to_html(StringBuilder& builder) const
  83. {
  84. if (is_image) {
  85. builder.append("<img src=\"");
  86. builder.append(escape_html_entities(href));
  87. builder.append("\" alt=\"");
  88. text->render_to_html(builder);
  89. builder.append("\" >");
  90. } else {
  91. builder.append("<a href=\"");
  92. builder.append(escape_html_entities(href));
  93. builder.append("\">");
  94. text->render_to_html(builder);
  95. builder.append("</a>");
  96. }
  97. }
  98. void Text::LinkNode::render_for_terminal(StringBuilder& builder) const
  99. {
  100. bool is_linked = href.contains("://");
  101. if (is_linked) {
  102. builder.append("\e]8;;");
  103. builder.append(href);
  104. builder.append("\e\\");
  105. }
  106. text->render_for_terminal(builder);
  107. if (is_linked) {
  108. builder.appendff(" <{}>", href);
  109. builder.append("\033]8;;\033\\");
  110. }
  111. }
  112. size_t Text::LinkNode::terminal_length() const
  113. {
  114. return text->terminal_length();
  115. }
  116. void Text::MultiNode::render_to_html(StringBuilder& builder) const
  117. {
  118. for (auto& child : children) {
  119. child.render_to_html(builder);
  120. }
  121. }
  122. void Text::MultiNode::render_for_terminal(StringBuilder& builder) const
  123. {
  124. for (auto& child : children) {
  125. child.render_for_terminal(builder);
  126. }
  127. }
  128. size_t Text::MultiNode::terminal_length() const
  129. {
  130. size_t length = 0;
  131. for (auto& child : children) {
  132. length += child.terminal_length();
  133. }
  134. return length;
  135. }
  136. size_t Text::terminal_length() const
  137. {
  138. return m_node->terminal_length();
  139. }
  140. String Text::render_to_html() const
  141. {
  142. StringBuilder builder;
  143. m_node->render_to_html(builder);
  144. return builder.build().trim(" \n\t");
  145. }
  146. String Text::render_for_terminal() const
  147. {
  148. StringBuilder builder;
  149. m_node->render_for_terminal(builder);
  150. return builder.build().trim(" \n\t");
  151. }
  152. Text Text::parse(StringView const& str)
  153. {
  154. Text text;
  155. auto const tokens = tokenize(str);
  156. auto iterator = tokens.begin();
  157. text.m_node = parse_sequence(iterator, false);
  158. return text;
  159. }
  160. static bool flanking(StringView const& str, size_t start, size_t end, int dir)
  161. {
  162. ssize_t next = ((dir > 0) ? end : start) + dir;
  163. if (next < 0 || next >= (ssize_t)str.length())
  164. return false;
  165. if (isspace(str[next]))
  166. return false;
  167. if (!ispunct(str[next]))
  168. return true;
  169. ssize_t prev = ((dir > 0) ? start : end) - dir;
  170. if (prev < 0 || prev >= (ssize_t)str.length())
  171. return true;
  172. return isspace(str[prev]) || ispunct(str[prev]);
  173. }
  174. Vector<Text::Token> Text::tokenize(StringView const& str)
  175. {
  176. Vector<Token> tokens;
  177. StringBuilder current_token;
  178. auto flush_run = [&](bool left_flanking, bool right_flanking, bool punct_before, bool punct_after, bool is_run) {
  179. if (current_token.is_empty())
  180. return;
  181. tokens.append({
  182. current_token.build(),
  183. left_flanking,
  184. right_flanking,
  185. punct_before,
  186. punct_after,
  187. is_run,
  188. });
  189. current_token.clear();
  190. };
  191. auto flush_token = [&]() {
  192. flush_run(false, false, false, false, false);
  193. };
  194. bool in_space = false;
  195. for (size_t offset = 0; offset < str.length(); ++offset) {
  196. auto has = [&](StringView const& seq) {
  197. if (offset + seq.length() > str.length())
  198. return false;
  199. return str.substring_view(offset, seq.length()) == seq;
  200. };
  201. auto expect = [&](StringView const& seq) {
  202. VERIFY(has(seq));
  203. flush_token();
  204. current_token.append(seq);
  205. flush_token();
  206. offset += seq.length() - 1;
  207. };
  208. char ch = str[offset];
  209. if (ch != ' ' && in_space) {
  210. flush_token();
  211. in_space = false;
  212. }
  213. if (ch == '\\' && offset + 1 < str.length()) {
  214. current_token.append(str[offset + 1]);
  215. ++offset;
  216. } else if (ch == '*' || ch == '_' || ch == '`') {
  217. flush_token();
  218. char delim = ch;
  219. size_t run_offset;
  220. for (run_offset = offset; run_offset < str.length() && str[run_offset] == delim; ++run_offset) {
  221. current_token.append(str[run_offset]);
  222. }
  223. flush_run(flanking(str, offset, run_offset - 1, +1),
  224. flanking(str, offset, run_offset - 1, -1),
  225. offset > 0 && ispunct(str[offset - 1]),
  226. run_offset < str.length() && ispunct(str[run_offset]),
  227. true);
  228. offset = run_offset - 1;
  229. } else if (ch == ' ') {
  230. if (!in_space) {
  231. flush_token();
  232. in_space = true;
  233. }
  234. current_token.append(ch);
  235. } else if (has("\n")) {
  236. expect("\n");
  237. } else if (has("[")) {
  238. expect("[");
  239. } else if (has("![")) {
  240. expect("![");
  241. } else if (has("](")) {
  242. expect("](");
  243. } else if (has(")")) {
  244. expect(")");
  245. } else {
  246. current_token.append(ch);
  247. }
  248. }
  249. flush_token();
  250. return tokens;
  251. }
  252. NonnullOwnPtr<Text::MultiNode> Text::parse_sequence(Vector<Token>::ConstIterator& tokens, bool in_link)
  253. {
  254. auto node = make<MultiNode>();
  255. for (; !tokens.is_end(); ++tokens) {
  256. if (tokens->is_space()) {
  257. node->children.append(parse_break(tokens));
  258. } else if (*tokens == "\n") {
  259. node->children.append(parse_newline(tokens));
  260. } else if (tokens->is_run) {
  261. switch (tokens->run_char()) {
  262. case '*':
  263. case '_':
  264. node->children.append(parse_emph(tokens, in_link));
  265. break;
  266. case '`':
  267. node->children.append(parse_code(tokens));
  268. break;
  269. }
  270. } else if (!in_link && (*tokens == "[" || *tokens == "![")) {
  271. node->children.append(parse_link(tokens));
  272. } else if (in_link && *tokens == "](") {
  273. return node;
  274. } else {
  275. node->children.append(make<TextNode>(tokens->data));
  276. }
  277. if (in_link && !tokens.is_end() && *tokens == "](")
  278. return node;
  279. if (tokens.is_end())
  280. break;
  281. }
  282. return node;
  283. }
  284. NonnullOwnPtr<Text::Node> Text::parse_break(Vector<Token>::ConstIterator& tokens)
  285. {
  286. auto next_tok = tokens + 1;
  287. if (next_tok.is_end() || *next_tok != "\n")
  288. return make<TextNode>(tokens->data);
  289. if (tokens->data.length() >= 2)
  290. return make<BreakNode>();
  291. return make<MultiNode>();
  292. }
  293. NonnullOwnPtr<Text::Node> Text::parse_newline(Vector<Token>::ConstIterator& tokens)
  294. {
  295. auto node = make<TextNode>(tokens->data);
  296. auto next_tok = tokens + 1;
  297. if (!next_tok.is_end() && next_tok->is_space())
  298. // Skip whitespace after newline.
  299. ++tokens;
  300. return node;
  301. }
  302. bool Text::can_open(Token const& opening)
  303. {
  304. return (opening.run_char() == '*' && opening.left_flanking) || (opening.run_char() == '_' && opening.left_flanking && (!opening.right_flanking || opening.punct_before));
  305. }
  306. bool Text::can_close_for(Token const& opening, Text::Token const& closing)
  307. {
  308. if (opening.run_char() != closing.run_char())
  309. return false;
  310. if (opening.run_length() != closing.run_length())
  311. return false;
  312. return (opening.run_char() == '*' && closing.right_flanking) || (opening.run_char() == '_' && closing.right_flanking && (!closing.left_flanking || closing.punct_after));
  313. }
  314. NonnullOwnPtr<Text::Node> Text::parse_emph(Vector<Token>::ConstIterator& tokens, bool in_link)
  315. {
  316. auto opening = *tokens;
  317. // Check that the opening delimiter run is properly flanking.
  318. if (!can_open(opening))
  319. return make<TextNode>(opening.data);
  320. auto child = make<MultiNode>();
  321. for (++tokens; !tokens.is_end(); ++tokens) {
  322. if (tokens->is_space()) {
  323. child->children.append(parse_break(tokens));
  324. } else if (*tokens == "\n") {
  325. child->children.append(parse_newline(tokens));
  326. } else if (tokens->is_run) {
  327. if (can_close_for(opening, *tokens)) {
  328. return make<EmphasisNode>(opening.run_length() >= 2, move(child));
  329. }
  330. switch (tokens->run_char()) {
  331. case '*':
  332. case '_':
  333. child->children.append(parse_emph(tokens, in_link));
  334. break;
  335. case '`':
  336. child->children.append(parse_code(tokens));
  337. break;
  338. }
  339. } else if (*tokens == "[" || *tokens == "![") {
  340. child->children.append(parse_link(tokens));
  341. } else if (in_link && *tokens == "](") {
  342. child->children.prepend(make<TextNode>(opening.data));
  343. return child;
  344. } else {
  345. child->children.append(make<TextNode>(tokens->data));
  346. }
  347. if (in_link && !tokens.is_end() && *tokens == "](") {
  348. child->children.prepend(make<TextNode>(opening.data));
  349. return child;
  350. }
  351. if (tokens.is_end())
  352. break;
  353. }
  354. child->children.prepend(make<TextNode>(opening.data));
  355. return child;
  356. }
  357. NonnullOwnPtr<Text::Node> Text::parse_code(Vector<Token>::ConstIterator& tokens)
  358. {
  359. auto opening = *tokens;
  360. auto is_closing = [&](Token const& token) {
  361. return token.is_run && token.run_char() == '`' && token.run_length() == opening.run_length();
  362. };
  363. bool is_all_whitespace = true;
  364. auto code = make<MultiNode>();
  365. for (auto iterator = tokens + 1; !iterator.is_end(); ++iterator) {
  366. if (is_closing(*iterator)) {
  367. tokens = iterator;
  368. // Strip first and last space, when appropriate.
  369. if (!is_all_whitespace) {
  370. auto& first = dynamic_cast<TextNode&>(code->children.first());
  371. auto& last = dynamic_cast<TextNode&>(code->children.last());
  372. if (first.text.starts_with(" ") && last.text.ends_with(" ")) {
  373. first.text = first.text.substring(1);
  374. last.text = last.text.substring(0, last.text.length() - 1);
  375. }
  376. }
  377. return make<CodeNode>(move(code));
  378. }
  379. is_all_whitespace = is_all_whitespace && iterator->data.is_whitespace();
  380. code->children.append(make<TextNode>((*iterator == "\n") ? " " : iterator->data, false));
  381. }
  382. return make<TextNode>(opening.data);
  383. }
  384. NonnullOwnPtr<Text::Node> Text::parse_link(Vector<Token>::ConstIterator& tokens)
  385. {
  386. auto opening = *tokens++;
  387. bool is_image = opening == "![";
  388. auto link_text = parse_sequence(tokens, true);
  389. if (tokens.is_end() || *tokens != "](") {
  390. link_text->children.prepend(make<TextNode>(opening.data));
  391. return link_text;
  392. }
  393. auto separator = *tokens;
  394. VERIFY(separator == "](");
  395. StringBuilder address;
  396. for (auto iterator = tokens + 1; !iterator.is_end(); ++iterator) {
  397. if (*iterator == ")") {
  398. tokens = iterator;
  399. return make<LinkNode>(is_image, move(link_text), address.build());
  400. }
  401. address.append(iterator->data);
  402. }
  403. link_text->children.prepend(make<TextNode>(opening.data));
  404. link_text->children.append(make<TextNode>(separator.data));
  405. return link_text;
  406. }
  407. }