I created a simple markdown to html parser called m2h. I wanted to implement the basic markdown syntax, I found one from this cheat-sheet. And implemented it over a weekend.
It is a cli tool and can be found in codeberg.
It is used as follows:
m2h name_of_file.md
It prints to stdout, so I tend to do this.
m2h name_of_file.md > name_of_file.html
Some interesting things about the code are that it is only a big for loop with a switch statement inside.
for (size_t i = 0; i < lines.size(); i++) {
size_t size_of_line = line.size() - 1;
line = lines[i];
switch (line[0]) {
case '#': {
// titles
...
}
case '>': {
// quotes
...
}
case '-': {
// horizontal rule or list
...
}
case '`': {
// codeblocks
...
}
default: {
// numbered list
// process default text
...
}
}
}
A pattern that came up multiple times was the following:
std::cout << "<blockquote>";
while (line[0] == '>') {
std::cout << line.substr(2, size_of_line) << " ";
i++;
line = lines[i];
}
std::cout << "</blockquote>" << std::endl;
Print the beginning block first, then go ahead multiple lines and finish the block.
And to beautify the text, it is the same idea of going through a line and checking each character in a big switch statement.
for (size_t i = 0; i < line.size(); i++) {
switch (line[i]) {
case '*': {
...
}
case '`': {
...
}
case '[': {
...
}
case '!': {
...
}
default: {
std::cout << line[i];
}
}
}
All of the code fits in 230 lines. I think it could be even more compact, but for now, it works as I want to.
I really liked programming this project. I am going to use it a lot for my website and I feel like I build something in a weekend. It was a fun experiment to get back into coding personal projects.
Maybe I will use this as a building block for SSG. Creating tools is fun. It can get really out of scope, so that is why I am just sticking with what I actually need.
For now, just a markdown to html translator is fine.