summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibMarkdown/CommentBlock.cpp
blob: 7b4f892100cf9f6a1d61c9bada25187375626263 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
 * Copyright (c) 2021, Ben Wiederhake <BenWiederhake.GitHub@gmx.de>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/StringBuilder.h>
#include <LibMarkdown/CommentBlock.h>
#include <LibMarkdown/Visitor.h>

namespace Markdown {

String CommentBlock::render_to_html(bool) const
{
    StringBuilder builder;

    builder.append("<!--");
    builder.append(escape_html_entities(m_comment));
    // TODO: This is probably incorrect, because we technically need to escape "--" in some form. However, Browser does not care about this.
    builder.append("-->\n");

    return builder.build();
}

String CommentBlock::render_for_terminal(size_t) const
{
    return "";
}

RecursionDecision CommentBlock::walk(Visitor& visitor) const
{
    RecursionDecision rd = visitor.visit(*this);
    if (rd != RecursionDecision::Recurse)
        return rd;

    // Normalize return value.
    return RecursionDecision::Continue;
}

OwnPtr<CommentBlock> CommentBlock::parse(LineIterator& lines)
{
    if (lines.is_end())
        return {};

    constexpr auto comment_start = "<!--"sv;
    constexpr auto comment_end = "-->"sv;

    StringView line = *lines;
    if (!line.starts_with(comment_start))
        return {};
    line = line.substring_view(comment_start.length());

    StringBuilder builder;

    while (true) {
        // Invariant: At the beginning of the loop, `line` is valid and should be added the the builder.
        bool ends_here = line.ends_with(comment_end);
        if (ends_here)
            line = line.substring_view(0, line.length() - comment_end.length());
        builder.append(line);
        if (!ends_here)
            builder.append('\n');

        ++lines;
        if (lines.is_end() || ends_here) {
            break;
        }
        line = *lines;
    }

    return make<CommentBlock>(builder.build());
}

}