aboutsummaryrefslogtreecommitdiffstats
path: root/src/markdown_translator.cpp
blob: f9068999299a7bfa38609457633c5b2f19ba2730 (plain) (blame)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#include "markdown_translator.hpp"
#include <regex>
#include <iostream>
#include <algorithm>

MarkdownTranslator::MarkdownTranslator() : title("WikiMD2HTML"), cssPath("styles/carbon.css") {

}

MarkdownTranslator::~MarkdownTranslator() {
}

void MarkdownTranslator::prescanHeaders(std::stringstream& markdownStream) {
    auto savedPos = markdownStream.tellg();
    markdownStream.seekg(0);
    std::regex headerRegex(headerRegexStr);
    std::smatch matches;
    std::string line;
    while (std::getline(markdownStream, line)) {
        if (std::regex_match(line, matches, headerRegex)) {
            int level = matches[1].length();
            std::string content = matches[2];
            headers.push_back(std::to_string(level) + ":" + content);
        }
    }
    markdownStream.clear();
    markdownStream.seekg(savedPos);
}


void MarkdownTranslator::processMetadata(const std::vector<std::string>& lines){
    // format of keys -> key: value
    int externalLinkBuilderState{0};
    std::string currExternalLinkName;
    std::string currExternalLinkUrl;
    for(std::string currentLine : lines){
        size_t colonPos = currentLine.find(':');
        if (colonPos != std::string::npos) {
            std::string key = currentLine.substr(0, colonPos);
            std::string value = currentLine.substr(colonPos + 1);
            value.erase(0, value.find_first_not_of(" \t"));
            if (key == "title") {
                title = value;
            }
            else if (key == "external-name") {
                currExternalLinkName = value;
                externalLinkBuilderState = 1;
            }
            else if (key == "external-url") {
                if (externalLinkBuilderState != 0) {
                    currExternalLinkUrl = value;
                    if (!currExternalLinkName.empty() && !currExternalLinkUrl.empty()) {
                        addExternalMenuItem(currExternalLinkName, currExternalLinkUrl);
                        currExternalLinkName = "";
                        currExternalLinkUrl = "";
                        externalLinkBuilderState = 0;
                    }
                }
                else{
                    std::cout << "[WARNING] Unexpected external-url \"" << value << "\" found with no matching external-name. Ignoring...";
                }
            }
            else {
                std::cerr << "ERROR OCCURED IN METADATA. UNKNOWN KEY" << std::endl;
            }
            if (key == "title") {
                title = value;
            }
        }
    }
}

std::string MarkdownTranslator::translate(const std::string& markdownContent) {
    std::stringstream htmlOutput;
    std::stringstream markdownStream(markdownContent);
    std::string line;
    std::string currentLine;

    // Parse metadata section if it exists
    bool metadataExists{false};
    std::vector<std::string> metadataLines;
    if (std::getline(markdownStream, currentLine) && currentLine == "---") {
        metadataExists = true;
        while (std::getline(markdownStream, currentLine)) {
            if (currentLine == "---") {
                break;
            }
            metadataLines.push_back(currentLine);
        }
    }
    else {
        markdownStream.seekg(0);
    }

    // Process and apply metadata to curr object
    if(metadataExists)
        processMetadata(metadataLines);

    // Pre-scan for headers before generating sidebar
    prescanHeaders(markdownStream);

    htmlOutput << buildHTMLHeader(title);
    generateSideBar(htmlOutput);
    // Main content container
    htmlOutput << "    <div class=\"main-content\">\n";
    htmlOutput << "        <div class=\"container\">\n";

    // Process each line of markdown

    // State of current parse
    MarkdownTranslator::ParseState parseState = MarkdownTranslator::ParseState::REGULAR;
    std::vector<std::string> figureLines;

    std::vector<std::string> codeblockLines;
    std::string language;

    while (std::getline(markdownStream, line)) { // Start of figure block
        if(line.find(":::figure") == 0){
            parseState = MarkdownTranslator::ParseState::IN_FIGURE;
            figureLines.clear();
            continue;
        }
        if(parseState == MarkdownTranslator::ParseState::IN_FIGURE && line == ":::"){ // End of figure block
            parseState = MarkdownTranslator::ParseState::REGULAR;
            htmlOutput << "            " << processFigureBlock(figureLines) << "\n";
            continue;
        }
        else if(parseState == MarkdownTranslator::ParseState::IN_FIGURE){
            figureLines.push_back(line);
            continue;
        }

        if(line.find("```") == 0 && parseState != MarkdownTranslator::ParseState::IN_CODEBLOCK){
            parseState = MarkdownTranslator::ParseState::IN_CODEBLOCK;
            codeblockLines.clear();
            if(line.length() > 3) {
                language = line.substr(3);
            }
            std::cout << language << std::endl;
            continue;
        }
        else if(parseState == MarkdownTranslator::ParseState::IN_CODEBLOCK && line == "```"){ // End of figure block
            parseState = MarkdownTranslator::ParseState::REGULAR;
            htmlOutput << "            " << processCodeBlock(language, codeblockLines) << "\n";
            continue;
        }
        else if(parseState == MarkdownTranslator::ParseState::IN_CODEBLOCK){
            codeblockLines.push_back(line);
            continue;
        }

        if(line.find(">") == 0 && parseState != MarkdownTranslator::ParseState::IN_BLOCKQUOTE){
            parseState = MarkdownTranslator::ParseState::IN_BLOCKQUOTE;
            htmlOutput << "            <blockquote>";
            htmlOutput << "            " << processLine(line.substr(1));
            continue;
        }
        else if(parseState == MarkdownTranslator::ParseState::IN_BLOCKQUOTE && line.find(">") != 0 ){ // End of blockquote
            parseState = MarkdownTranslator::ParseState::REGULAR;
            htmlOutput << "            </blockquote>";
        }
        else if(parseState == MarkdownTranslator::ParseState::IN_BLOCKQUOTE){
             htmlOutput << "            " << processLine(line.substr(1));
             continue;
        }
        htmlOutput << "            " << processLine(line);
    }

    htmlOutput << buildHTMLFooter();

    return htmlOutput.str();
}

void MarkdownTranslator::generateSideBar(std::stringstream& output) {
    output << "    <div class=\"nav-sidebar\">\n";
    output << "        <div class=\"nav-logo\">\n";
    output << "            <h3>" + title + "</h3>\n";
    output << "        </div>\n";
    output << "        <ul class=\"nav-menu\">\n";
    if(externalMenuLinks.size() > 0){
        for(const ExternalMenuItem& menuItem : externalMenuLinks){
            output << "            <li><a href=\""+menuItem.link+"\">"+menuItem.name+"</a></li>\n";
        }
    }
    output << "            <h4>Table of Contents</h4>\n";
    output << "            <ul class=\"nav-submenu\">\n";

    for (const auto& header : headers) {
        size_t separatorPos = header.find(':');
        if (separatorPos != std::string::npos) {
            int level = std::stoi(header.substr(0, separatorPos));
            std::string content = header.substr(separatorPos + 1);

            // Create anchor ID from header content
            std::string anchorId = createAnchorId(content);

            // Add indentation based on header level
            std::string indentation = "                ";
            for (int i = 1; i < level; ++i) {
                indentation += "    ";
            }

            output << indentation << "<li class=\"level-" << level << "\"><a href=\"#" << anchorId << "\">" << content << "</a></li>\n";
        }
    }

    output << "            </ul>\n";
    output << "        </ul>\n";
    output << "    </div>\n";
}

std::string MarkdownTranslator::createAnchorId(const std::string& text) {
    std::string id = text;
    // Convert to lowercase
    std::transform(id.begin(), id.end(), id.begin(), ::tolower);

    // Replace spaces with hyphens
    std::replace(id.begin(), id.end(), ' ', '-');

    // Remove any non-alphanumeric characters except hyphens
    id.erase(
        std::remove_if(
            id.begin(),
            id.end(),
            [](char c) { return !(std::isalnum(c) || c == '-'); }
        ),
        id.end()
    );

    return id;
}

std::string MarkdownTranslator::processLine(const std::string& line) {
    std::string processed = line;
    processed = processHeaders(processed);
    if (processed == line) {
        processed = processBold(processed);
        processed = processItalic(processed);
        processed = processLinks(processed);
        if (!processed.empty() && processed[0] != '<') {
            processed = processParagraph(processed);
        }
    }

    return processed + "\n";
}

std::string MarkdownTranslator::processHeaders(const std::string& line) {
    // Check for H1-H6
    std::regex headerRegex(headerRegexStr);
    std::smatch matches;
    if (std::regex_match(line, matches, headerRegex)) {
        int level = matches[1].length();
        std::string content = matches[2];
        std::string anchorId = createAnchorId(content);
        return "<h" + std::to_string(level) + " id=\"" + anchorId + "\">" + content + "</h" + std::to_string(level) + ">";
    }

    return line;
}

std::string MarkdownTranslator::processBold(const std::string& text) {
     // Replace **text** or __text__ with <strong>text</strong>
    std::string result = text;
    std::regex boldRegex(boldRegexStr);
    result = std::regex_replace(result, boldRegex, "<strong>$1$2</strong>");
    return result;
}

std::string MarkdownTranslator::processItalic(const std::string& text) {
    // Replace *text* or _text_ with <em>text</em>
    std::string result = text;
    std::regex italicRegex(italicRegexStr);
    result = std::regex_replace(result, italicRegex, "<em>$1$2</em>");
    return result;
}

std::string MarkdownTranslator::processLinks(const std::string& text) {
    // Replace [text](url) with <a href="url">text</a>
    std::string result = text;
    std::regex linkRegex(linkRegexStr);
    result = std::regex_replace(result, linkRegex, "<a href=\"$2\">$1</a>");
    return result;
}

std::string MarkdownTranslator::processParagraph(const std::string& text) {
    if (text.empty()) return "";
    return "<p>" + text + "</p>";
}

std::string MarkdownTranslator::processSingleFigure(const std::string& text) {
    // Extract image details using regex
    std::regex imageRegex(imageRegexStr);
    std::smatch matches;

    if (std::regex_search(text, matches, imageRegex)) {
        std::string alt = matches[1].str();
        std::string src = matches[2].str();
        std::string title = matches.size() > 4 && matches[4].matched ? " title=\"" + matches[4].str() + "\"" : "";
        return "<img src=\"" + src + "\" alt=\"" + alt + "\"" + title + ">";
    }
    return text;
}

std::string MarkdownTranslator::processFigureBlock(const std::vector<std::string>& lines){
    std::stringstream html;
    std::string imageHtml;
    std::string caption;
    html << "<figure class=\"custom-figure\">\n";

    // Process each line in the figure block
    for (const auto& line : lines) {
        if (line.find("![") == 0) {
            // Process the image
            imageHtml = processSingleFigure(line);
            html << "    " << imageHtml << "\n";
        } else if (line.find("Caption:") == 0) {
            // Extract caption
            caption = line.substr(8);
            html << "    <figcaption>" << caption << "</figcaption>\n";
        } else if (!line.empty()) {
            // Process any other content
            html << "    <p>" << line << "</p>\n";
        }
    }
    html << "</figure>";
    return html.str();
}

std::string htmlEscape(const std::string& text) {
    std::string escaped;
    escaped.reserve(text.size());
    for (char c : text) {
        switch (c) {
            case '&': escaped += "&amp;"; break;
            case '<': escaped += "&lt;"; break;
            case '>': escaped += "&gt;"; break;
            case '"': escaped += "&quot;"; break;
            case '\'': escaped += "&#39;"; break;
            default: escaped += c; break;
        }
    }
    return escaped;
}
std::string MarkdownTranslator::processCodeBlock(
    const std::string& language,
    const std::vector<std::string>& lines
) {
    std::stringstream html;
    html << "<pre><code class=\"language-"<< language <<"\">";
    for (const auto& line : lines)
        html << htmlEscape(line) << '\n';
    html << "</code></pre>";
    return html.str();
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage