forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkdown.rs
More file actions
194 lines (168 loc) · 5.86 KB
/
Copy pathmarkdown.rs
File metadata and controls
194 lines (168 loc) · 5.86 KB
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
//! Markdown to HTML rendering with syntax highlighting
use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd, html};
/// Render markdown to HTML with Fe syntax highlighting for code blocks
pub fn render_markdown(markdown: &str) -> String {
let mut options = Options::empty();
options.insert(Options::ENABLE_STRIKETHROUGH);
options.insert(Options::ENABLE_TABLES);
// Convert single newlines to hard breaks (two trailing spaces)
// This preserves line breaks in doc comments as users expect
let processed = preserve_line_breaks(markdown);
let parser = Parser::new_ext(&processed, options);
// Process events, handling code blocks specially
let parser = CodeBlockHighlighter::new(parser);
let mut html_output = String::new();
html::push_html(&mut html_output, parser);
html_output
}
/// Iterator adapter that highlights code blocks
struct CodeBlockHighlighter<I> {
inner: I,
in_code_block: bool,
code_lang: Option<String>,
code_buffer: String,
}
impl<'a, I> CodeBlockHighlighter<I>
where
I: Iterator<Item = Event<'a>>,
{
fn new(inner: I) -> Self {
Self {
inner,
in_code_block: false,
code_lang: None,
code_buffer: String::new(),
}
}
fn highlight_code(&self, code: &str, lang: Option<&str>) -> String {
// Fe code blocks are emitted as raw <fe-code-block> — client-side
// FeHighlighter handles syntax highlighting and type linking.
if let Some(l) = lang
&& (l == "fe" || l.starts_with("fe,") || l.starts_with("fe "))
{
return format!(
"<fe-code-block lang=\"fe\">{}</fe-code-block>",
html_escape(code)
);
}
// Fallback for other languages: html-escaped <pre><code>
let lang_class = lang
.map(|l| format!(" class=\"language-{}\"", html_escape(l)))
.unwrap_or_default();
format!(
"<pre><code{}>{}</code></pre>",
lang_class,
html_escape(code)
)
}
}
impl<'a, I> Iterator for CodeBlockHighlighter<I>
where
I: Iterator<Item = Event<'a>>,
{
type Item = Event<'a>;
fn next(&mut self) -> Option<Self::Item> {
loop {
let event = self.inner.next()?;
match &event {
Event::Start(Tag::CodeBlock(kind)) => {
self.in_code_block = true;
self.code_buffer.clear();
self.code_lang = match kind {
pulldown_cmark::CodeBlockKind::Fenced(lang) => {
let lang_str = lang.as_ref();
if lang_str.is_empty() {
None
} else {
Some(lang_str.to_string())
}
}
pulldown_cmark::CodeBlockKind::Indented => None,
};
continue;
}
Event::End(TagEnd::CodeBlock) => {
self.in_code_block = false;
let highlighted =
self.highlight_code(&self.code_buffer, self.code_lang.as_deref());
return Some(Event::Html(highlighted.into()));
}
Event::Text(text) if self.in_code_block => {
self.code_buffer.push_str(text);
continue;
}
_ => return Some(event),
}
}
}
}
/// Convert single newlines to markdown hard breaks (two trailing spaces + newline)
/// This preserves line breaks in doc comments while still allowing paragraph breaks (double newlines)
fn preserve_line_breaks(text: &str) -> String {
let mut result = String::with_capacity(text.len() * 2);
let mut in_code_block = false;
let mut prev_was_newline = false;
for line in text.lines() {
// Track code block state
if line.trim().starts_with("```") {
in_code_block = !in_code_block;
}
if !result.is_empty() {
if prev_was_newline {
// Double newline - keep as paragraph break
result.push('\n');
} else if !in_code_block && !line.is_empty() {
// Single newline outside code block - add hard break
result.push_str(" \n");
} else {
result.push('\n');
}
}
prev_was_newline = line.is_empty();
result.push_str(line);
}
result
}
/// Escape HTML special characters
fn html_escape(s: &str) -> String {
crate::escape::escape_html(s)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_basic_markdown() {
let md = "# Hello\n\nThis is a **test**.";
let html = render_markdown(md);
assert!(html.contains("<h1>Hello</h1>"));
assert!(html.contains("<strong>test</strong>"));
}
#[test]
fn test_code_block() {
let md = "```fe\nfn main() {}\n```";
let html = render_markdown(md);
assert!(
html.contains("fe-code-block"),
"should wrap in <fe-code-block>: {html}"
);
// Raw text content (client-side highlighting handles syntax colors)
assert!(
html.contains("fn main()"),
"should contain raw code text: {html}"
);
}
#[test]
fn test_multiline_preserves_breaks() {
let md = "Line 1\nLine 2\nLine 3";
let html = render_markdown(md);
// Each line should have a <br> tag (from hard break)
assert!(html.contains("<br"));
}
#[test]
fn test_paragraph_breaks_preserved() {
let md = "Paragraph 1\n\nParagraph 2";
let html = render_markdown(md);
// Should have two <p> tags
assert!(html.matches("<p>").count() == 2);
}
}