Serenity Operating System
1/*
2 * Copyright (c) 2021, Ben Wiederhake <BenWiederhake.GitHub@gmx.de>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <AK/Forward.h>
8#include <AK/StringBuilder.h>
9#include <LibMarkdown/CommentBlock.h>
10#include <LibMarkdown/Visitor.h>
11
12namespace Markdown {
13
14DeprecatedString CommentBlock::render_to_html(bool) const
15{
16 StringBuilder builder;
17
18 builder.append("<!--"sv);
19 builder.append(escape_html_entities(m_comment));
20 // TODO: This is probably incorrect, because we technically need to escape "--" in some form. However, Browser does not care about this.
21 builder.append("-->\n"sv);
22
23 return builder.to_deprecated_string();
24}
25
26Vector<DeprecatedString> CommentBlock::render_lines_for_terminal(size_t) const
27{
28 return Vector<DeprecatedString> {};
29}
30
31RecursionDecision CommentBlock::walk(Visitor& visitor) const
32{
33 RecursionDecision rd = visitor.visit(*this);
34 if (rd != RecursionDecision::Recurse)
35 return rd;
36
37 // Normalize return value.
38 return RecursionDecision::Continue;
39}
40
41OwnPtr<CommentBlock> CommentBlock::parse(LineIterator& lines)
42{
43 if (lines.is_end())
44 return {};
45
46 constexpr auto comment_start = "<!--"sv;
47 constexpr auto comment_end = "-->"sv;
48
49 StringView line = *lines;
50 if (!line.starts_with(comment_start))
51 return {};
52 line = line.substring_view(comment_start.length());
53
54 StringBuilder builder;
55
56 while (true) {
57 // Invariant: At the beginning of the loop, `line` is valid and should be added to the builder.
58 bool ends_here = line.ends_with(comment_end);
59 if (ends_here)
60 line = line.substring_view(0, line.length() - comment_end.length());
61 builder.append(line);
62 if (!ends_here)
63 builder.append('\n');
64
65 ++lines;
66 if (lines.is_end() || ends_here) {
67 break;
68 }
69 line = *lines;
70 }
71
72 return make<CommentBlock>(builder.to_deprecated_string());
73}
74
75}