Serenity Operating System
1/*
2 * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice, this
9 * list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include <AK/StringBuilder.h>
28#include <LibMarkdown/MDParagraph.h>
29
30String MDParagraph::render_to_html() const
31{
32 StringBuilder builder;
33 builder.appendf("<p>");
34 builder.append(m_text.render_to_html());
35 builder.appendf("</p>\n");
36 return builder.build();
37}
38
39String MDParagraph::render_for_terminal() const
40{
41 StringBuilder builder;
42 builder.append(m_text.render_for_terminal());
43 builder.appendf("\n\n");
44 return builder.build();
45}
46
47bool MDParagraph::parse(Vector<StringView>::ConstIterator& lines)
48{
49 if (lines.is_end())
50 return false;
51
52 bool first = true;
53 StringBuilder builder;
54
55 while (true) {
56 if (lines.is_end())
57 break;
58 StringView line = *lines;
59 if (line.is_empty())
60 break;
61 char ch = line[0];
62 // See if it looks like a blockquote
63 // or like an indented block.
64 if (ch == '>' || ch == ' ')
65 break;
66 if (line.length() > 1) {
67 // See if it looks like a heading.
68 if (ch == '#' && (line[1] == '#' || line[1] == ' '))
69 break;
70 // See if it looks like a code block.
71 if (ch == '`' && line[1] == '`')
72 break;
73 // See if it looks like a list.
74 if (ch == '*' || ch == '-')
75 if (line[1] == ' ')
76 break;
77 }
78
79 if (!first)
80 builder.append(' ');
81 builder.append(line);
82 first = false;
83 ++lines;
84 }
85
86 if (first)
87 return false;
88
89 bool success = m_text.parse(builder.build());
90 ASSERT(success);
91 return true;
92}