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
use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::macros::{line, span};
/// Parse markdown and convert to styled ratatui Lines
pub fn parse_markdown(input: &str) -> Vec<Line<'static>> {
let mut options = Options::empty();
options.insert(Options::ENABLE_STRIKETHROUGH);
options.insert(Options::ENABLE_TABLES);
let parser = Parser::new_ext(input, options);
let mut lines = Vec::new();
let mut current_line_spans = Vec::new();
let mut style_stack = vec![Style::default()];
let mut in_code_block = false;
let mut code_block_content = String::new();
let mut list_depth: usize = 0;
// Table state
let mut in_table = false;
let mut table_rows: Vec<Vec<String>> = Vec::new();
let mut current_row: Vec<String> = Vec::new();
let mut current_cell = String::new();
let mut table_header_len: usize = 0;
for event in parser {
match event {
Event::Start(tag) => {
let new_style = match tag {
Tag::Heading { level, .. } => {
// Start new line for headers
if !current_line_spans.is_empty() {
lines.push(Line::from(std::mem::take(&mut current_line_spans)));
}
// Add blank line before heading (except for first heading)
if !lines.is_empty() {
lines.push(Line::from(""));
}
// Apply style based on level (without visible prefix)
let style = match level {
HeadingLevel::H1 => Style::new().fg(Color::Cyan).bold(),
HeadingLevel::H2 => Style::new().fg(Color::Blue).bold(),
HeadingLevel::H3 => Style::new().fg(Color::Green).bold(),
_ => Style::new().fg(Color::Yellow).bold(),
};
style
},
Tag::Emphasis => style_stack.last().copied().unwrap_or_default().italic(),
Tag::Strong => style_stack.last().copied().unwrap_or_default().bold(),
Tag::Strikethrough => style_stack
.last()
.copied()
.unwrap_or_default()
.crossed_out(),
Tag::CodeBlock(kind) => {
in_code_block = true;
code_block_content.clear();
// Start new line for code block
if !current_line_spans.is_empty() {
lines.push(Line::from(std::mem::take(&mut current_line_spans)));
}
// Show language label if present, otherwise just a blank separator
let lang = match kind {
CodeBlockKind::Fenced(lang) => lang.to_string(),
CodeBlockKind::Indented => "".to_string(),
};
if !lang.is_empty() {
lines.push(line![span!(Color::DarkGray; &lang)]);
}
Style::default().fg(Color::Gray)
},
Tag::List(_) => {
list_depth += 1;
if !current_line_spans.is_empty() {
lines.push(Line::from(std::mem::take(&mut current_line_spans)));
}
style_stack.last().copied().unwrap_or_default()
},
Tag::Item => {
// Add bullet point with 2-space base indentation plus nesting levels
// list_depth=1: 2 spaces, list_depth=2: 4 spaces, etc.
let indent = " ".repeat(list_depth);
current_line_spans.push(Span::raw(indent));
current_line_spans
.push(Span::styled("• ", Style::default().fg(Color::Yellow)));
style_stack.last().copied().unwrap_or_default()
},
Tag::Table(_alignments) => {
in_table = true;
table_rows.clear();
table_header_len = 0;
// Flush any pending spans
if !current_line_spans.is_empty() {
lines.push(Line::from(std::mem::take(&mut current_line_spans)));
}
style_stack.last().copied().unwrap_or_default()
},
Tag::TableHead => {
current_row.clear();
style_stack.last().copied().unwrap_or_default()
},
Tag::TableRow => {
current_row.clear();
style_stack.last().copied().unwrap_or_default()
},
Tag::TableCell => {
current_cell.clear();
style_stack.last().copied().unwrap_or_default()
},
Tag::Link { .. } => {
current_line_spans
.push(Span::styled("[", Style::default().fg(Color::Blue)));
Style::default()
.fg(Color::Blue)
.add_modifier(Modifier::UNDERLINED)
},
Tag::BlockQuote(_) => {
if !current_line_spans.is_empty() {
lines.push(Line::from(std::mem::take(&mut current_line_spans)));
}
current_line_spans
.push(Span::styled("│ ", Style::default().fg(Color::DarkGray)));
Style::default()
.fg(Color::Gray)
.add_modifier(Modifier::ITALIC)
},
_ => style_stack.last().copied().unwrap_or_default(),
};
style_stack.push(new_style);
},
Event::End(tag) => {
style_stack.pop();
match tag {
TagEnd::Heading(_) => {
if !current_line_spans.is_empty() {
lines.push(Line::from(std::mem::take(&mut current_line_spans)));
}
// Don't add blank line here - let lists flow directly from headings
// Blank line before next heading is added by Tag::Heading
},
TagEnd::Paragraph | TagEnd::Item => {
if !current_line_spans.is_empty() {
lines.push(Line::from(std::mem::take(&mut current_line_spans)));
}
},
TagEnd::CodeBlock => {
in_code_block = false;
// Render code block content (no fence markers)
for line in code_block_content.lines() {
lines.push(Line::from(vec![Span::styled(
line.to_string(),
Style::default().fg(Color::Gray),
)]));
}
code_block_content.clear();
},
TagEnd::List(_) => {
list_depth = list_depth.saturating_sub(1);
// Add blank line after list ends (when returning to depth 0)
if list_depth == 0 {
lines.push(Line::from(""));
}
},
TagEnd::TableCell => {
current_row.push(std::mem::take(&mut current_cell));
},
TagEnd::TableHead => {
table_header_len = current_row.len();
table_rows.push(std::mem::take(&mut current_row));
},
TagEnd::TableRow => {
table_rows.push(std::mem::take(&mut current_row));
},
TagEnd::Table => {
in_table = false;
// Compute column widths
let num_cols = table_rows.iter().map(|r| r.len()).max().unwrap_or(0);
let mut col_widths = vec![0usize; num_cols];
for row in &table_rows {
for (i, cell) in row.iter().enumerate() {
if i < num_cols {
col_widths[i] = col_widths[i].max(cell.len());
}
}
}
// Minimum column width of 3
for w in &mut col_widths {
*w = (*w).max(3);
}
let border_style = Style::default().fg(Color::DarkGray);
let header_style = Style::default().fg(Color::Cyan).bold();
let cell_style = Style::default().fg(Color::White);
for (row_idx, row) in table_rows.iter().enumerate() {
let mut spans = Vec::new();
spans.push(Span::styled("| ", border_style));
for (col_idx, cell) in row.iter().enumerate() {
let width = col_widths.get(col_idx).copied().unwrap_or(3);
let padded = format!("{:<width$}", cell, width = width);
let style = if row_idx == 0 && table_header_len > 0 {
header_style
} else {
cell_style
};
spans.push(Span::styled(padded, style));
spans.push(Span::styled(" | ", border_style));
}
lines.push(Line::from(spans));
// Add separator after header row
if row_idx == 0 && table_header_len > 0 {
let mut sep_spans = Vec::new();
sep_spans.push(Span::styled("|-", border_style));
for (col_idx, _) in row.iter().enumerate() {
let width = col_widths.get(col_idx).copied().unwrap_or(3);
let dashes = "-".repeat(width);
sep_spans.push(Span::styled(dashes, border_style));
sep_spans.push(Span::styled("-|-", border_style));
}
lines.push(Line::from(sep_spans));
}
}
// Blank line after table
lines.push(Line::from(""));
table_rows.clear();
},
TagEnd::Link => {
current_line_spans
.push(Span::styled("]", Style::default().fg(Color::Blue)));
},
TagEnd::BlockQuote(_) => {
if !current_line_spans.is_empty() {
lines.push(Line::from(std::mem::take(&mut current_line_spans)));
}
},
_ => {},
}
},
Event::Text(text) => {
if in_code_block {
code_block_content.push_str(&text);
} else if in_table {
current_cell.push_str(&text);
} else {
let style = style_stack.last().copied().unwrap_or_default();
current_line_spans.push(Span::styled(text.to_string(), style));
}
},
Event::Code(code) => {
if in_table {
current_cell.push_str(&code);
} else {
let style = Style::default()
.fg(Color::Yellow)
.bg(Color::Rgb(40, 40, 40));
current_line_spans.push(Span::styled(format!(" {} ", code), style));
}
},
Event::SoftBreak | Event::HardBreak => {
if !current_line_spans.is_empty() {
lines.push(Line::from(std::mem::take(&mut current_line_spans)));
}
},
_ => {},
}
}
// Add any remaining spans as a line
if !current_line_spans.is_empty() {
lines.push(Line::from(current_line_spans));
}
lines
}