Simple HTML render

This commit is contained in:
2026-07-14 15:39:06 +02:00
parent 7f6950b8fe
commit dc49129999
3 changed files with 111 additions and 1 deletions
+83
View File
@@ -0,0 +1,83 @@
package main
import "core:fmt"
print_html :: proc(token: ^Token) {
switch token.type {
case TokenType.Root:
for child in token.children {
print_html(child)
}
case TokenType.Header:
level := 1
if v, ok := token.value.(int); ok {
level = v
}
fmt.printf("<h%d>", level)
for child in token.children {
print_html(child)
}
fmt.printf("</h%d>\n", level)
case TokenType.Paragraph:
fmt.print("<p>")
for child in token.children {
print_html(child)
}
fmt.print("</p>\n")
case TokenType.Blockquote:
fmt.print("<blockquote>\n")
for child in token.children {
print_html(child)
}
fmt.print("</blockquote>\n")
case TokenType.UnorderedList:
fmt.print("<ul>\n")
for child in token.children {
print_html(child)
}
fmt.print("</ul>\n")
case TokenType.OrderedList:
fmt.print("<ol>\n")
for child in token.children {
print_html(child)
}
fmt.print("</ol>\n")
case TokenType.ListItem:
fmt.print("<li>")
for child in token.children {
print_html(child)
}
fmt.print("</li>\n")
case TokenType.Bold:
fmt.print("<strong>")
for child in token.children {
print_html(child)
}
fmt.print("</strong>")
case TokenType.Italics:
fmt.print("<em>")
for child in token.children {
print_html(child)
}
fmt.print("</em>")
case TokenType.BreakLine:
fmt.print("<br>\n")
case TokenType.Text:
if v, ok := token.value.(string); ok {
fmt.print(v)
}
for child in token.children {
print_html(child)
}
}
}
+1 -1
View File
@@ -62,7 +62,7 @@ print_token :: proc(token: ^Token, depth: int = 0) {
main :: proc() {
lines := read_stdin()
parsed := parse(lines)
// print_html(&parsed)
print_html(&parsed)
fmt.println("<hr>")
fmt.println("<h1>Token Tree</h1>")
fmt.println("<p>")
+27
View File
@@ -122,6 +122,27 @@ pass_through_children :: proc(token: ^Token) {
}
}
add_breaklines :: proc(token: ^Token) {
if token.children == nil {
return
}
new_children: [dynamic]^Token
for i := 0; i < len(token.children); i += 1 {
child := token.children[i]
add_breaklines(child)
append(&new_children, child)
if child.type == TokenType.Text &&
i + 1 < len(token.children) &&
token.children[i + 1].type == TokenType.Text {
br := new(Token)
br^ = Token{TokenType.BreakLine, nil, nil, token}
append(&new_children, br)
}
}
token.children = new_children
}
parse :: proc(lines: []string, allocator := context.allocator) -> Token {
root := Token{TokenType.Root, nil, nil, nil}
current_token := &root
@@ -201,6 +222,12 @@ parse :: proc(lines: []string, allocator := context.allocator) -> Token {
// SECOND PASS
for token in root.children {
add_breaklines(token)
}
// THIRD PASS
for token in root.children {
pass_through_children(token)
}