comparison 3rdparty/maddy/codeblockparser.h @ 0:a4671277546c tip

created the repository for the thymian project
author ferencd
date Tue, 17 Aug 2021 11:19:54 +0200
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:a4671277546c
1 /*
2 * This project is licensed under the MIT license. For more information see the
3 * LICENSE file.
4 */
5 #pragma once
6
7 // -----------------------------------------------------------------------------
8
9 #include <functional>
10 #include <string>
11 #include <regex>
12
13 #include "maddy/blockparser.h"
14
15 // -----------------------------------------------------------------------------
16
17 namespace maddy {
18
19 // -----------------------------------------------------------------------------
20
21 /**
22 * CodeBlockParser
23 *
24 * From Markdown: 3 times surrounded code (without space in the beginning)
25 *
26 * ```
27 * ```
28 * some code
29 * ```
30 * ```
31 *
32 * To HTML:
33 *
34 * ```
35 * <pre><code>
36 * some code
37 * </code></pre>
38 * ```
39 *
40 * @class
41 */
42 class CodeBlockParser : public BlockParser
43 {
44 public:
45 /**
46 * ctor
47 *
48 * @method
49 * @param {std::function<void(std::string&)>} parseLineCallback
50 * @param {std::function<std::shared_ptr<BlockParser>(const std::string& line)>} getBlockParserForLineCallback
51 */
52 CodeBlockParser(
53 std::function<void(std::string&)> parseLineCallback,
54 std::function<std::shared_ptr<BlockParser>(const std::string& line)> getBlockParserForLineCallback
55 )
56 : BlockParser(parseLineCallback, getBlockParserForLineCallback)
57 , isStarted(false)
58 , isFinished(false)
59 {}
60
61 /**
62 * IsStartingLine
63 *
64 * If the line starts with three code signs, then it is a code block.
65 *
66 * ```
67 * ```
68 * ```
69 *
70 * @method
71 * @param {const std::string&} line
72 * @return {bool}
73 */
74 static bool
75 IsStartingLine(const std::string& line)
76 {
77 static std::regex re("^(?:`){3}$");
78 return std::regex_match(line, re);
79 }
80
81 /**
82 * IsFinished
83 *
84 * @method
85 * @return {bool}
86 */
87 bool
88 IsFinished() const override
89 {
90 return this->isFinished;
91 }
92
93 protected:
94 bool
95 isInlineBlockAllowed() const override
96 {
97 return false;
98 }
99
100 bool
101 isLineParserAllowed() const override
102 {
103 return false;
104 }
105
106 void
107 parseBlock(std::string& line) override
108 {
109 if (line == "```")
110 {
111 if (!this->isStarted)
112 {
113 line = "<pre><code>\n";
114 this->isStarted = true;
115 this->isFinished = false;
116 return;
117 }
118 else
119 {
120 line = "</code></pre>";
121 this->isFinished = true;
122 this->isStarted = false;
123 return;
124 }
125 }
126
127 line += "\n";
128 }
129
130 private:
131 bool isStarted;
132 bool isFinished;
133 }; // class CodeBlockParser
134
135 // -----------------------------------------------------------------------------
136
137 } // namespace maddy