md-formatter 0.4.1

A fast, opinionated Markdown formatter
Documentation
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
use pulldown_cmark::{CowStr, Event, Tag};
use std::str::FromStr;

/// How to handle prose wrapping
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WrapMode {
    /// Wrap prose if it exceeds the print width
    Always,
    /// Un-wrap each block of prose into one line
    Never,
    /// Do nothing, leave prose as-is (default)
    #[default]
    Preserve,
}

impl FromStr for WrapMode {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "always" => Ok(Self::Always),
            "never" => Ok(Self::Never),
            "preserve" => Ok(Self::Preserve),
            _ => Err(format!(
                "Invalid wrap mode: '{}'. Expected: always, never, preserve",
                s
            )),
        }
    }
}

/// How to handle ordered list numbering
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OrderedListMode {
    /// Renumber items sequentially (1, 2, 3, ...) - default
    #[default]
    Ascending,
    /// Use 1. for all items
    One,
    // Note: Preserve mode is not currently possible because pulldown-cmark
    // doesn't provide the original item numbers in the event stream
}

impl FromStr for OrderedListMode {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "ascending" => Ok(Self::Ascending),
            "one" => Ok(Self::One),
            _ => Err(format!(
                "Invalid ordered list mode: '{}'. Expected: ascending, one",
                s
            )),
        }
    }
}

/// Represents an inline element that can be buffered before wrapping
#[derive(Debug, Clone)]
enum InlineElement {
    /// Regular text content
    Text(String),
    /// Inline code (`code`)
    Code(String),
    /// Start of emphasis (*)
    EmphasisStart,
    /// End of emphasis (*)
    EmphasisEnd,
    /// Start of strong (**)
    StrongStart,
    /// End of strong (**)
    StrongEnd,
    /// Start of strikethrough (~~)
    StrikethroughStart,
    /// End of strikethrough (~~)
    StrikethroughEnd,
    /// Start of link ([)
    LinkStart,
    /// End of link with URL](url)
    LinkEnd(String),
    /// Start of image (![)
    ImageStart,
    /// End of image with URL and optional title](url "title")
    ImageEnd { url: String, title: String },
    /// Hard break from source (preserve as `  \n`)
    HardBreak,
    /// Soft break from source (treat as space)
    SoftBreak,
}

/// Context for tracking where we are in the document
#[derive(Debug, Clone, PartialEq)]
pub enum Context {
    Paragraph,
    Heading { level: u32 },
    List { ordered: bool, item_count: usize },
    ListItem,
    Blockquote,
    CodeBlock,
    Strong,
    Emphasis,
    Strikethrough,
    Link { url: String },
    Image { url: String, title: String },
}

/// Main formatter struct
pub struct Formatter {
    /// Final output
    output: String,
    /// Target line width
    line_width: usize,
    /// How to handle prose wrapping
    wrap_mode: WrapMode,
    /// How to handle ordered list numbering
    ordered_list_mode: OrderedListMode,
    /// Buffer for accumulating inline elements before wrapping
    inline_buffer: Vec<InlineElement>,
    /// Context stack for tracking nesting
    context_stack: Vec<Context>,
    /// Current list nesting depth
    list_depth: usize,
    /// Current blockquote nesting depth
    blockquote_depth: usize,
    /// Are we inside a code block?
    in_code_block: bool,
}

impl Formatter {
    /// Create a new formatter with the given line width and wrap mode
    pub fn new(line_width: usize) -> Self {
        Self::with_options(line_width, WrapMode::default(), OrderedListMode::default())
    }

    /// Create a new formatter with the given line width and wrap mode
    pub fn with_wrap_mode(line_width: usize, wrap_mode: WrapMode) -> Self {
        Self::with_options(line_width, wrap_mode, OrderedListMode::default())
    }

    /// Create a new formatter with all options
    pub fn with_options(
        line_width: usize,
        wrap_mode: WrapMode,
        ordered_list_mode: OrderedListMode,
    ) -> Self {
        Self {
            output: String::new(),
            line_width,
            wrap_mode,
            ordered_list_mode,
            inline_buffer: Vec::new(),
            context_stack: Vec::new(),
            list_depth: 0,
            blockquote_depth: 0,
            in_code_block: false,
        }
    }

    /// Format markdown from a list of events
    pub fn format(&mut self, events: Vec<Event>) -> String {
        for event in events {
            self.process_event(event);
        }

        // Flush any remaining content
        self.flush_inline_buffer();

        // Ensure single trailing newline
        let result = self.output.trim_end().to_string();
        if result.is_empty() {
            result
        } else {
            result + "\n"
        }
    }

    fn process_event(&mut self, event: Event) {
        match event {
            Event::Start(tag) => self.handle_start_tag(tag),
            Event::End(tag) => self.handle_end_tag(tag),
            Event::Text(text) => self.handle_text(text),
            Event::Code(code) => self.handle_inline_code(code),
            Event::Html(html) => self.handle_html(html),
            Event::SoftBreak => self.handle_soft_break(),
            Event::HardBreak => self.handle_hard_break(),
            Event::Rule => self.handle_rule(),
            Event::FootnoteReference(_) => {}
            Event::TaskListMarker(checked) => self.handle_task_list_marker(checked),
        }
    }

    /// Get the prefix for the current line (blockquote markers)
    fn get_line_prefix(&self) -> String {
        let mut prefix = String::new();
        for _ in 0..self.blockquote_depth {
            prefix.push_str("> ");
        }
        prefix
    }

    /// Get the continuation indent for wrapped lines
    fn get_continuation_indent(&self) -> String {
        let mut indent = self.get_line_prefix();

        // Add list indentation for continuation lines
        if self.list_depth > 0 {
            // Each list level needs indentation, plus space for the marker
            indent.push_str(&"  ".repeat(self.list_depth));
        }

        indent
    }

    /// Convert inline buffer to a flat string (for wrapping), preserving structure
    fn render_inline_buffer(&self) -> String {
        let mut result = String::new();
        for elem in &self.inline_buffer {
            match elem {
                InlineElement::Text(s) => result.push_str(s),
                InlineElement::Code(s) => {
                    result.push('`');
                    result.push_str(s);
                    result.push('`');
                }
                InlineElement::EmphasisStart => result.push('*'),
                InlineElement::EmphasisEnd => result.push('*'),
                InlineElement::StrongStart => result.push_str("**"),
                InlineElement::StrongEnd => result.push_str("**"),
                InlineElement::StrikethroughStart => result.push_str("~~"),
                InlineElement::StrikethroughEnd => result.push_str("~~"),
                InlineElement::LinkStart => result.push('['),
                InlineElement::LinkEnd(url) => {
                    result.push_str("](");
                    result.push_str(url);
                    result.push(')');
                }
                InlineElement::ImageStart => result.push_str("!["),
                InlineElement::ImageEnd { url, title } => {
                    result.push_str("](");
                    result.push_str(url);
                    if !title.is_empty() {
                        result.push_str(" \"");
                        result.push_str(title);
                        result.push('"');
                    }
                    result.push(')');
                }
                InlineElement::HardBreak => result.push('\u{FFFF}'), // Placeholder for hard break
                InlineElement::SoftBreak => {
                    match self.wrap_mode {
                        WrapMode::Preserve => result.push('\u{FFFE}'), // Placeholder for preserved line break
                        WrapMode::Always | WrapMode::Never => result.push(' '),
                    }
                }
            }
        }
        result
    }

    /// Wrap text to fit within line_width
    /// Returns wrapped text with proper line prefixes
    fn wrap_text(&self, text: &str, first_line_prefix: &str, continuation_prefix: &str) -> String {
        let hard_break_placeholder = "\u{FFFF}";
        let soft_break_placeholder = "\u{FFFE}";

        match self.wrap_mode {
            WrapMode::Preserve => {
                // Preserve mode: keep line breaks as-is, just add prefixes
                self.wrap_text_preserve(
                    text,
                    first_line_prefix,
                    continuation_prefix,
                    hard_break_placeholder,
                    soft_break_placeholder,
                )
            }
            WrapMode::Never => {
                // Never mode: unwrap everything to single lines (per paragraph)
                self.wrap_text_never(text, first_line_prefix, hard_break_placeholder)
            }
            WrapMode::Always => {
                // Always mode: reflow text to fit width
                self.wrap_text_always(
                    text,
                    first_line_prefix,
                    continuation_prefix,
                    hard_break_placeholder,
                )
            }
        }
    }

    /// Preserve mode: keep original line breaks
    fn wrap_text_preserve(
        &self,
        text: &str,
        first_line_prefix: &str,
        continuation_prefix: &str,
        hard_break_placeholder: &str,
        soft_break_placeholder: &str,
    ) -> String {
        let mut result = String::new();
        let mut is_first_line = true;

        // Split on both hard and soft break placeholders
        // We need to track which type of break it was
        let mut remaining = text;

        while !remaining.is_empty() {
            // Find the next break (either hard or soft)
            let hard_pos = remaining.find(hard_break_placeholder);
            let soft_pos = remaining.find(soft_break_placeholder);

            let (segment, break_type, rest) = match (hard_pos, soft_pos) {
                (Some(h), Some(s)) if h < s => {
                    let (seg, rest) = remaining.split_at(h);
                    (seg, Some("hard"), &rest[hard_break_placeholder.len()..])
                }
                (Some(h), Some(s)) if s < h => {
                    let (seg, rest) = remaining.split_at(s);
                    (seg, Some("soft"), &rest[soft_break_placeholder.len()..])
                }
                (Some(h), None) => {
                    let (seg, rest) = remaining.split_at(h);
                    (seg, Some("hard"), &rest[hard_break_placeholder.len()..])
                }
                (None, Some(s)) => {
                    let (seg, rest) = remaining.split_at(s);
                    (seg, Some("soft"), &rest[soft_break_placeholder.len()..])
                }
                (Some(h), Some(_)) => {
                    // h == s, shouldn't happen, but handle it
                    let (seg, rest) = remaining.split_at(h);
                    (seg, Some("hard"), &rest[hard_break_placeholder.len()..])
                }
                (None, None) => (remaining, None, ""),
            };

            // Add the prefix
            let prefix = if is_first_line {
                first_line_prefix
            } else {
                continuation_prefix
            };
            result.push_str(prefix);

            // Add the segment content (normalize internal whitespace but preserve words)
            let words: Vec<&str> = segment.split_whitespace().collect();
            result.push_str(&words.join(" "));

            // Add the appropriate line ending
            match break_type {
                Some("hard") => {
                    result.push_str("  \n");
                }
                Some("soft") => {
                    result.push('\n');
                }
                None => {}
                _ => {}
            }

            remaining = rest;
            is_first_line = false;
        }

        result
    }

    /// Never mode: unwrap to single line
    fn wrap_text_never(
        &self,
        text: &str,
        first_line_prefix: &str,
        hard_break_placeholder: &str,
    ) -> String {
        // Split on hard breaks - those we preserve
        let segments: Vec<&str> = text.split(hard_break_placeholder).collect();
        let mut result = String::new();

        for (seg_idx, segment) in segments.iter().enumerate() {
            let words: Vec<&str> = segment.split_whitespace().collect();

            if seg_idx == 0 {
                result.push_str(first_line_prefix);
            }

            result.push_str(&words.join(" "));

            // Add hard break if not the last segment
            if seg_idx < segments.len() - 1 {
                result.push_str("  \n");
                result.push_str(first_line_prefix);
            }
        }

        result
    }

    /// Always mode: reflow text to fit width (original behavior)
    fn wrap_text_always(
        &self,
        text: &str,
        first_line_prefix: &str,
        continuation_prefix: &str,
        hard_break_placeholder: &str,
    ) -> String {
        // First, handle hard breaks by splitting on them
        let segments: Vec<&str> = text.split(hard_break_placeholder).collect();

        let mut result = String::new();

        for (seg_idx, segment) in segments.iter().enumerate() {
            // Normalize whitespace within this segment
            let words: Vec<&str> = segment.split_whitespace().collect();

            if words.is_empty() {
                if seg_idx < segments.len() - 1 {
                    // There was a hard break here, add it
                    if !result.is_empty() {
                        result.push_str("  \n");
                        result.push_str(continuation_prefix);
                    }
                }
                continue;
            }

            let prefix = if seg_idx == 0 && result.is_empty() {
                first_line_prefix
            } else {
                continuation_prefix
            };

            let mut current_line = if result.is_empty() || result.ends_with('\n') {
                prefix.to_string()
            } else {
                String::new()
            };

            let mut first_word_on_line = result.is_empty() || result.ends_with('\n');

            for word in &words {
                let space_needed = if first_word_on_line { 0 } else { 1 };
                let would_be_length = current_line.len() + space_needed + word.len();

                if !first_word_on_line && would_be_length > self.line_width {
                    // Wrap to new line (use plain \n - NOT hard break)
                    result.push_str(&current_line);
                    result.push('\n');
                    current_line = continuation_prefix.to_string();
                    current_line.push_str(word);
                    first_word_on_line = false;
                } else {
                    if !first_word_on_line {
                        current_line.push(' ');
                    }
                    current_line.push_str(word);
                    first_word_on_line = false;
                }
            }

            result.push_str(&current_line);

            // Add hard break if not the last segment
            if seg_idx < segments.len() - 1 {
                result.push_str("  \n");
                result.push_str(continuation_prefix);
            }
        }

        result
    }

    /// Flush the inline buffer, wrapping text appropriately
    fn flush_inline_buffer(&mut self) {
        if self.inline_buffer.is_empty() {
            return;
        }

        let rendered = self.render_inline_buffer();

        if rendered.trim().is_empty() {
            self.inline_buffer.clear();
            return;
        }

        let prefix = self.get_line_prefix();
        let continuation = self.get_continuation_indent();

        let wrapped = self.wrap_text(&rendered, &prefix, &continuation);
        self.output.push_str(&wrapped);
        self.inline_buffer.clear();
    }

    /// Ensure there's a blank line before the next block element
    fn ensure_blank_line(&mut self) {
        if self.output.is_empty() {
            return;
        }
        if !self.output.ends_with("\n\n") {
            if self.output.ends_with('\n') {
                self.output.push('\n');
            } else {
                self.output.push_str("\n\n");
            }
        }
    }

    fn handle_start_tag(&mut self, tag: Tag) {
        match tag {
            Tag::Heading(level, _, _) => {
                self.flush_inline_buffer();
                self.ensure_blank_line();
                let level_num = level as usize;
                self.output.push_str(&"#".repeat(level_num));
                self.output.push(' ');
                self.context_stack.push(Context::Heading {
                    level: level_num as u32,
                });
            }

            Tag::Paragraph => {
                self.flush_inline_buffer();
                // Don't add blank line if we're directly inside a list item
                // (list items implicitly contain paragraphs)
                let in_list_item = self.context_stack.last() == Some(&Context::ListItem);
                if !in_list_item {
                    self.ensure_blank_line();
                }
                // Don't add prefix here - wrap_text will handle it
                self.context_stack.push(Context::Paragraph);
            }

            Tag::List(first_item_number) => {
                self.flush_inline_buffer();
                // Only add blank line before top-level lists, not nested ones
                // A nested list is one that starts while we're inside a ListItem
                let in_list_item = self.context_stack.last() == Some(&Context::ListItem);
                if !in_list_item {
                    self.ensure_blank_line();
                }
                self.list_depth += 1;
                self.context_stack.push(Context::List {
                    ordered: first_item_number.is_some(),
                    item_count: 0,
                });
            }

            Tag::Item => {
                self.flush_inline_buffer();
                if !self.output.ends_with('\n') && !self.output.is_empty() {
                    self.output.push('\n');
                }

                // Increment the item count for the current list
                let (is_ordered, item_number) = self
                    .context_stack
                    .iter_mut()
                    .rev()
                    .find_map(|c| match c {
                        Context::List {
                            ordered,
                            item_count,
                        } => {
                            *item_count += 1;
                            Some((*ordered, *item_count))
                        }
                        _ => None,
                    })
                    .unwrap_or((false, 1));

                // Add blockquote prefix
                let prefix = self.get_line_prefix();
                self.output.push_str(&prefix);

                // Add list indentation (for nested lists)
                if self.list_depth > 1 {
                    self.output.push_str(&"  ".repeat(self.list_depth - 1));
                }

                // Add list marker
                if is_ordered {
                    match self.ordered_list_mode {
                        OrderedListMode::One => self.output.push_str("1. "),
                        OrderedListMode::Ascending => {
                            self.output.push_str(&format!("{}. ", item_number));
                        }
                    }
                } else {
                    self.output.push_str("- ");
                }

                self.context_stack.push(Context::ListItem);
            }

            Tag::BlockQuote => {
                self.flush_inline_buffer();
                self.ensure_blank_line();
                self.blockquote_depth += 1;
                self.context_stack.push(Context::Blockquote);
            }

            Tag::CodeBlock(kind) => {
                self.flush_inline_buffer();
                self.ensure_blank_line();
                self.in_code_block = true;

                // Extract language if specified
                let lang = match kind {
                    pulldown_cmark::CodeBlockKind::Fenced(lang) if !lang.is_empty() => {
                        lang.to_string()
                    }
                    _ => String::new(),
                };

                self.output.push_str("```");
                self.output.push_str(&lang);
                self.output.push('\n');
                self.context_stack.push(Context::CodeBlock);
            }

            Tag::Strong => {
                self.inline_buffer.push(InlineElement::StrongStart);
                self.context_stack.push(Context::Strong);
            }

            Tag::Emphasis => {
                self.inline_buffer.push(InlineElement::EmphasisStart);
                self.context_stack.push(Context::Emphasis);
            }

            Tag::Strikethrough => {
                self.inline_buffer.push(InlineElement::StrikethroughStart);
                self.context_stack.push(Context::Strikethrough);
            }

            Tag::Link(_, url, _) => {
                self.inline_buffer.push(InlineElement::LinkStart);
                self.context_stack.push(Context::Link {
                    url: url.to_string(),
                });
            }

            Tag::Image(_, url, title) => {
                self.inline_buffer.push(InlineElement::ImageStart);
                self.context_stack.push(Context::Image {
                    url: url.to_string(),
                    title: title.to_string(),
                });
            }

            _ => {}
        }
    }

    fn handle_end_tag(&mut self, tag: Tag) {
        match tag {
            Tag::Heading { .. } => {
                self.flush_inline_buffer();
                self.output.push('\n');
                self.context_stack.pop();
            }

            Tag::Paragraph => {
                self.flush_inline_buffer();
                self.output.push('\n');
                self.context_stack.pop();
            }

            Tag::List(_) => {
                self.flush_inline_buffer();
                if !self.output.ends_with('\n') {
                    self.output.push('\n');
                }
                self.list_depth = self.list_depth.saturating_sub(1);
                self.context_stack.pop();
            }

            Tag::Item => {
                self.flush_inline_buffer();
                self.context_stack.pop();
            }

            Tag::BlockQuote => {
                self.flush_inline_buffer();
                if !self.output.ends_with('\n') {
                    self.output.push('\n');
                }
                self.blockquote_depth = self.blockquote_depth.saturating_sub(1);
                self.context_stack.pop();
            }

            Tag::CodeBlock(_) => {
                self.output.push_str("```\n");
                self.in_code_block = false;
                self.context_stack.pop();
            }

            Tag::Strong => {
                self.inline_buffer.push(InlineElement::StrongEnd);
                self.context_stack.pop();
            }

            Tag::Emphasis => {
                self.inline_buffer.push(InlineElement::EmphasisEnd);
                self.context_stack.pop();
            }

            Tag::Strikethrough => {
                self.inline_buffer.push(InlineElement::StrikethroughEnd);
                self.context_stack.pop();
            }

            Tag::Link(_, _, _) => {
                // Get the URL from context
                if let Some(Context::Link { url }) = self.context_stack.pop() {
                    self.inline_buffer.push(InlineElement::LinkEnd(url));
                }
            }

            Tag::Image(_, _, _) => {
                // Get the URL and title from context
                if let Some(Context::Image { url, title }) = self.context_stack.pop() {
                    self.inline_buffer
                        .push(InlineElement::ImageEnd { url, title });
                }
            }

            _ => {}
        }
    }

    fn handle_text(&mut self, text: CowStr) {
        if self.in_code_block {
            // Code blocks: preserve exactly
            self.output.push_str(&text);
        } else {
            // Regular text: add to inline buffer
            self.inline_buffer
                .push(InlineElement::Text(text.to_string()));
        }
    }

    fn handle_inline_code(&mut self, code: CowStr) {
        self.inline_buffer
            .push(InlineElement::Code(code.to_string()));
    }

    fn handle_html(&mut self, html: CowStr) {
        self.flush_inline_buffer();
        self.ensure_blank_line();
        self.output.push_str(&html);
        if !html.ends_with('\n') {
            self.output.push('\n');
        }
    }

    fn handle_soft_break(&mut self) {
        if !self.in_code_block {
            // Soft break = space (will be normalized during flush)
            self.inline_buffer.push(InlineElement::SoftBreak);
        }
    }

    fn handle_hard_break(&mut self) {
        // Hard break from source - preserve it!
        self.inline_buffer.push(InlineElement::HardBreak);
    }

    fn handle_rule(&mut self) {
        self.flush_inline_buffer();
        self.ensure_blank_line();
        self.output.push_str("---\n");
    }

    fn handle_task_list_marker(&mut self, checked: bool) {
        if checked {
            self.inline_buffer
                .push(InlineElement::Text("[x] ".to_string()));
        } else {
            self.inline_buffer
                .push(InlineElement::Text("[ ] ".to_string()));
        }
    }
}