cmark-writer 0.6.2

A CommonMark writer implementation in Rust for serializing AST nodes to CommonMark format
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
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
//! CommonMark writer implementation.
//!
//! This file contains the implementation of the CommonMarkWriter class, which serializes AST nodes to CommonMark-compliant text.

#[cfg(feature = "gfm")]
use crate::ast::TableAlignment;
use crate::ast::{
    CodeBlockType, CustomNode, CustomNodeWriter, HeadingType, HtmlElement, ListItem, Node,
};
use crate::error::{WriteError, WriteResult};
use crate::options::WriterOptions;
use std::fmt::{self};

use super::processors::{
    BlockNodeProcessor, CustomNodeProcessor, InlineNodeProcessor, NodeProcessor,
};

/// CommonMark writer
///
/// This struct is responsible for serializing AST nodes to CommonMark-compliant text.
#[derive(Debug)]
pub struct CommonMarkWriter {
    options: WriterOptions,
    buffer: String,
}

impl CommonMarkWriter {
    /// Create a new CommonMark writer with default options
    ///
    /// # Example
    ///
    /// ```
    /// use cmark_writer::writer::CommonMarkWriter;
    /// use cmark_writer::ast::Node;
    ///
    /// let mut writer = CommonMarkWriter::new();
    /// writer.write(&Node::Text("Hello".to_string())).unwrap();
    /// assert_eq!(writer.into_string(), "Hello");
    /// ```
    pub fn new() -> Self {
        Self::with_options(WriterOptions::default())
    }

    /// Create a new CommonMark writer with specified options
    ///
    /// # Parameters
    ///
    /// * `options` - Custom CommonMark formatting options
    ///
    /// # Example
    ///
    /// ```
    /// use cmark_writer::writer::CommonMarkWriter;
    /// use cmark_writer::options::WriterOptions;
    ///
    /// let options = WriterOptions {
    ///     strict: true,
    ///     hard_break_spaces: false,  // Use backslash for line breaks
    ///     indent_spaces: 2,          // Use 2 spaces for indentation
    ///     ..Default::default()       // Other options can be set as needed
    /// };
    /// let writer = CommonMarkWriter::with_options(options);
    /// ```
    pub fn with_options(options: WriterOptions) -> Self {
        Self {
            options,
            buffer: String::new(),
        }
    }

    /// Whether the writer is in strict mode
    pub(crate) fn is_strict_mode(&self) -> bool {
        self.options.strict
    }

    /// Apply a specific prefix to multi-line text, used for handling container node indentation
    ///
    /// # Parameters
    ///
    /// * `content` - The multi-line content to process
    /// * `prefix` - The prefix to apply to each line
    /// * `first_line_prefix` - The prefix to apply to the first line (can be different from other lines)
    ///
    /// # Returns
    ///
    /// Returns a string with applied indentation
    fn apply_prefix(&self, content: &str, prefix: &str, first_line_prefix: Option<&str>) -> String {
        if content.is_empty() {
            return String::new();
        }

        let mut result = String::new();
        let lines: Vec<&str> = content.lines().collect();

        if !lines.is_empty() {
            let actual_prefix = first_line_prefix.unwrap_or(prefix);
            result.push_str(actual_prefix);
            result.push_str(lines[0]);
        }

        for line in &lines[1..] {
            result.push('\n');
            result.push_str(prefix);
            result.push_str(line);
        }

        result
    }

    /// Write an AST node as CommonMark format
    ///
    /// # Parameters
    ///
    /// * `node` - The AST node to write
    ///
    /// # Returns
    ///
    /// If writing succeeds, returns `Ok(())`, otherwise returns `Err(WriteError)`
    ///
    /// # Example
    ///
    /// ```
    /// use cmark_writer::writer::CommonMarkWriter;
    /// use cmark_writer::ast::Node;
    ///
    /// let mut writer = CommonMarkWriter::new();
    /// writer.write(&Node::Text("Hello".to_string())).unwrap();
    /// ```
    pub fn write(&mut self, node: &Node) -> WriteResult<()> {
        if let Node::Custom(_) = node {
            return CustomNodeProcessor.process(self, node);
        }

        if node.is_block() {
            BlockNodeProcessor.process(self, node)
        } else if node.is_inline() {
            InlineNodeProcessor.process(self, node)
        } else {
            // Keep this branch for future implementation needs
            Err(WriteError::UnsupportedNodeType)
        }
    }

    /// Write a custom node using its implementation
    #[allow(clippy::borrowed_box)]
    pub(crate) fn write_custom_node(&mut self, node: &Box<dyn CustomNode>) -> WriteResult<()> {
        node.write(self)
    }

    /// Get context description for a node, used for error reporting
    pub(crate) fn get_context_for_node(&self, node: &Node) -> String {
        match node {
            Node::Text(_) => "Text".to_string(),
            Node::Emphasis(_) => "Emphasis".to_string(),
            Node::Strong(_) => "Strong".to_string(),
            #[cfg(feature = "gfm")]
            Node::Strikethrough(_) => "Strikethrough".to_string(),
            Node::InlineCode(_) => "InlineCode".to_string(),
            Node::Link { .. } => "Link content".to_string(),
            Node::Image { .. } => "Image alt text".to_string(),
            Node::HtmlElement(_) => "HtmlElement content".to_string(),
            Node::Custom(_) => "Custom node".to_string(),
            _ => "Unknown inline element".to_string(),
        }
    }

    /// Check if the inline node contains a newline character and return an error if it does
    pub(crate) fn check_no_newline(&self, node: &Node, context: &str) -> WriteResult<()> {
        if Self::node_contains_newline(node) {
            return Err(WriteError::NewlineInInlineElement(context.to_string()));
        }
        Ok(())
    }

    /// Check if the inline node contains a newline character recursively
    fn node_contains_newline(node: &Node) -> bool {
        match node {
            Node::Text(s) | Node::InlineCode(s) => s.contains('\n'),
            Node::Emphasis(children) | Node::Strong(children) => {
                children.iter().any(Self::node_contains_newline)
            }
            #[cfg(feature = "gfm")]
            Node::Strikethrough(children) => children.iter().any(Self::node_contains_newline),
            Node::HtmlElement(element) => element.children.iter().any(Self::node_contains_newline),
            Node::Link { content, .. } => content.iter().any(Self::node_contains_newline),
            Node::Image { alt, .. } => alt.iter().any(Self::node_contains_newline),
            Node::SoftBreak | Node::HardBreak => true,
            // Custom nodes are handled separately
            Node::Custom(_) => false,
            _ => false,
        }
    }

    /// Writes text content with character escaping
    pub(crate) fn write_text_content(&mut self, content: &str) -> WriteResult<()> {
        let escaped = content
            .replace('\\', "\\\\")
            .replace('*', "\\*")
            .replace('_', "\\_")
            .replace('[', "\\[")
            .replace(']', "\\]")
            .replace('<', "\\<")
            .replace('>', "\\>")
            .replace('`', "\\`");

        self.write_str(&escaped)?;
        Ok(())
    }

    /// Writes inline code content
    pub(crate) fn write_code_content(&mut self, content: &str) -> WriteResult<()> {
        self.write_char('`')?;
        self.write_str(content)?;
        self.write_char('`')?;
        Ok(())
    }

    /// Helper function for writing content with delimiters
    pub(crate) fn write_delimited(&mut self, content: &[Node], delimiter: &str) -> WriteResult<()> {
        self.write_str(delimiter)?;

        for node in content {
            self.write(node)?;
        }

        self.write_str(delimiter)?;
        Ok(())
    }

    /// Write a document node
    pub(crate) fn write_document(&mut self, children: &[Node]) -> WriteResult<()> {
        for (i, child) in children.iter().enumerate() {
            if i > 0 {
                self.write_str("\n")?;
            }
            self.write(child)?;
        }
        Ok(())
    }

    /// Write a heading node
    pub(crate) fn write_heading(
        &mut self,
        level: u8,
        content: &[Node],
        heading_type: &HeadingType,
    ) -> WriteResult<()> {
        // 验证标题级别
        if level == 0 || level > 6 {
            return Err(WriteError::InvalidHeadingLevel(level));
        }

        match heading_type {
            // ATX heading, using # character
            HeadingType::Atx => {
                for _ in 0..level {
                    self.write_char('#')?;
                }
                self.write_char(' ')?;

                for node in content {
                    self.write(node)?;
                }

                self.write_char('\n')?;
            }

            HeadingType::Setext => {
                // First write the heading content
                for node in content {
                    self.write(node)?;
                }
                self.write_char('\n')?;

                // Add underline characters based on level
                // Setext only supports level 1 and 2 headings
                let underline_char = if level == 1 { '=' } else { '-' };

                // For good readability, we add underlines at least as long as the heading text
                // Calculate a reasonable underline length (at least 3 characters)
                let min_len = 3;

                // Write the underline characters
                for _ in 0..min_len {
                    self.write_char(underline_char)?;
                }

                // Add a newline to end the heading
                self.write_char('\n')?;
            }
        }

        Ok(())
    }

    /// Write a paragraph node
    pub(crate) fn write_paragraph(&mut self, content: &[Node]) -> WriteResult<()> {
        for node in content.iter() {
            self.write(node)?;
        }

        Ok(())
    }

    /// Write a blockquote node
    pub(crate) fn write_blockquote(&mut self, content: &[Node]) -> WriteResult<()> {
        // Create a temporary writer buffer to write all blockquote content
        let mut temp_writer = CommonMarkWriter::with_options(self.options.clone());

        // Write all content to temporary buffer
        for (i, node) in content.iter().enumerate() {
            if i > 0 {
                temp_writer.write_char('\n')?;
            }
            // Write all nodes uniformly
            temp_writer.write(node)?;
        }

        // Get all content
        let all_content = temp_writer.into_string();

        // Apply blockquote prefix "> " uniformly
        let prefix = "> ";
        let formatted_content = self.apply_prefix(&all_content, prefix, Some(prefix));

        // Write formatted content
        self.buffer.push_str(&formatted_content);
        Ok(())
    }

    /// Write a thematic break (horizontal rule)
    pub(crate) fn write_thematic_break(&mut self) -> WriteResult<()> {
        let char = self.options.thematic_break_char;
        self.write_str(&format!("{}{}{}", char, char, char))?;
        Ok(())
    }

    /// Write a code block node
    pub(crate) fn write_code_block(
        &mut self,
        language: &Option<String>,
        content: &str,
        block_type: &CodeBlockType,
    ) -> WriteResult<()> {
        match block_type {
            CodeBlockType::Indented => {
                let indent = "    ";
                let indented_content = self.apply_prefix(content, indent, Some(indent));
                self.buffer.push_str(&indented_content);
            }
            CodeBlockType::Fenced => {
                let max_backticks = content
                    .chars()
                    .fold((0, 0), |(max, current), c| {
                        if c == '`' {
                            (max.max(current + 1), current + 1)
                        } else {
                            (max, 0)
                        }
                    })
                    .0;

                let fence_len = std::cmp::max(max_backticks + 1, 3);
                let fence = "`".repeat(fence_len);

                self.write_str(&fence)?;
                if let Some(lang) = language {
                    self.write_str(lang)?;
                }
                self.write_char('\n')?;

                self.buffer.push_str(content);
                if !content.ends_with('\n') {
                    self.write_char('\n')?;
                }

                self.write_str(&fence)?;
            }
        }

        Ok(())
    }

    /// Write an unordered list node
    pub(crate) fn write_unordered_list(&mut self, items: &[ListItem]) -> WriteResult<()> {
        let list_marker = self.options.list_marker;
        let prefix = format!("{} ", list_marker);

        for (i, item) in items.iter().enumerate() {
            if i > 0 {
                self.write_char('\n')?;
            }
            self.write_list_item(item, &prefix)?;
        }

        Ok(())
    }

    /// Write an ordered list node
    pub(crate) fn write_ordered_list(&mut self, start: u32, items: &[ListItem]) -> WriteResult<()> {
        // Track the current item number
        let mut current_number = start;

        for (i, item) in items.iter().enumerate() {
            if i > 0 {
                self.write_char('\n')?;
            }

            match item {
                // For ordered list items, check if there's a custom number
                ListItem::Ordered { number, content: _ } => {
                    if let Some(custom_num) = number {
                        // Use custom numbering
                        let prefix = format!("{}. ", custom_num);
                        self.write_list_item(item, &prefix)?;
                        // Next expected number
                        current_number = custom_num + 1;
                    } else {
                        // No custom number, use the current calculated number
                        let prefix = format!("{}. ", current_number);
                        self.write_list_item(item, &prefix)?;
                        current_number += 1;
                    }
                }
                // For other types of list items, still use the current number
                _ => {
                    let prefix = format!("{}. ", current_number);
                    self.write_list_item(item, &prefix)?;
                    current_number += 1;
                }
            }
        }

        Ok(())
    }

    /// Write a list item
    fn write_list_item(&mut self, item: &ListItem, prefix: &str) -> WriteResult<()> {
        match item {
            ListItem::Unordered { content } => {
                self.write_str(prefix)?;
                self.write_list_item_content(content, prefix.len())?;
            }
            ListItem::Ordered { number, content } => {
                if let Some(num) = number {
                    let custom_prefix = format!("{}. ", num);
                    self.write_str(&custom_prefix)?;
                    self.write_list_item_content(content, custom_prefix.len())?;
                } else {
                    self.write_str(prefix)?;
                    self.write_list_item_content(content, prefix.len())?;
                }
            }
            #[cfg(feature = "gfm")]
            ListItem::Task { status, content } => {
                // Only use task list syntax if GFM task lists are enabled
                if self.options.gfm_tasklists {
                    let checkbox = match status {
                        crate::ast::TaskListStatus::Checked => "[x] ",
                        crate::ast::TaskListStatus::Unchecked => "[ ] ",
                    };

                    // Use the original list marker (- or number) and append the checkbox
                    let task_prefix = format!("{}{}", prefix, checkbox);
                    self.write_str(&task_prefix)?;
                    self.write_list_item_content(content, task_prefix.len())?;
                } else {
                    // If GFM task lists are disabled, just write a normal list item
                    self.write_str(prefix)?;
                    self.write_list_item_content(content, prefix.len())?;
                }
            }
        }

        Ok(())
    }

    /// Write list item content
    fn write_list_item_content(&mut self, content: &[Node], prefix_len: usize) -> WriteResult<()> {
        if content.is_empty() {
            return Ok(());
        }

        let mut temp_writer = CommonMarkWriter::with_options(self.options.clone());

        for (i, node) in content.iter().enumerate() {
            if i > 0 {
                temp_writer.write_char('\n')?;
            }

            temp_writer.write(node)?;
        }

        let all_content = temp_writer.into_string();

        let indent = " ".repeat(prefix_len);

        let formatted_content = self.apply_prefix(&all_content, &indent, Some(""));

        self.buffer.push_str(&formatted_content);

        Ok(())
    }

    /// Write a table
    pub(crate) fn write_table(&mut self, headers: &[Node], rows: &[Vec<Node>]) -> WriteResult<()> {
        // Write header
        self.write_char('|')?;
        for header in headers {
            self.check_no_newline(header, "Table Header")?;
            self.write_char(' ')?;
            self.write(header)?;
            self.write_str(" |")?;
        }
        self.write_char('\n')?;

        // Write alignment row (default to centered if no alignments provided)
        self.write_char('|')?;
        for _ in 0..headers.len() {
            self.write_str(" --- |")?;
        }
        self.write_char('\n')?;

        // Write table content
        for row in rows {
            self.write_char('|')?;
            for cell in row {
                self.check_no_newline(cell, "Table Cell")?;
                self.write_char(' ')?;
                self.write(cell)?;
                self.write_str(" |")?;
            }
            self.write_char('\n')?;
        }

        Ok(())
    }

    #[cfg(feature = "gfm")]
    /// Write a table with alignment (GFM extension)
    pub(crate) fn write_table_with_alignment(
        &mut self,
        headers: &[Node],
        alignments: &[TableAlignment],
        rows: &[Vec<Node>],
    ) -> WriteResult<()> {
        // Only use alignment when GFM tables are enabled
        if !self.options.gfm_tables {
            return self.write_table(headers, rows);
        }

        // Write header
        self.write_char('|')?;
        for header in headers {
            self.check_no_newline(header, "Table Header")?;
            self.write_char(' ')?;
            self.write(header)?;
            self.write_str(" |")?;
        }
        self.write_char('\n')?;

        // Write alignment row

        self.write_char('|')?;

        // Use provided alignments, or default to center if not enough alignments provided
        for i in 0..headers.len() {
            let alignment = if i < alignments.len() {
                &alignments[i]
            } else {
                &TableAlignment::Center
            };

            match alignment {
                TableAlignment::Left => self.write_str(" :--- |")?,
                TableAlignment::Center => self.write_str(" :---: |")?,
                TableAlignment::Right => self.write_str(" ---: |")?,
                TableAlignment::None => self.write_str(" --- |")?,
            }
        }

        self.write_char('\n')?;

        // Write table content
        for row in rows {
            self.write_char('|')?;
            for cell in row {
                self.check_no_newline(cell, "Table Cell")?;
                self.write_char(' ')?;
                self.write(cell)?;
                self.write_str(" |")?;
            }
            self.write_char('\n')?;
        }

        Ok(())
    }

    /// Write a link
    pub(crate) fn write_link(
        &mut self,
        url: &str,
        title: &Option<String>,
        content: &[Node],
    ) -> WriteResult<()> {
        for node in content {
            self.check_no_newline(node, "Link Text")?;
        }
        self.write_char('[')?;

        for node in content {
            self.write(node)?;
        }

        self.write_str("](")?;
        self.write_str(url)?;

        if let Some(title_text) = title {
            self.write_str(" \"")?;
            self.write_str(title_text)?;
            self.write_char('"')?;
        }

        self.write_char(')')?;
        Ok(())
    }

    /// Write an image
    pub(crate) fn write_image(
        &mut self,
        url: &str,
        title: &Option<String>,
        alt: &[Node],
    ) -> WriteResult<()> {
        // Check for newlines in alt text content
        for node in alt {
            self.check_no_newline(node, "Image alt text")?;
        }

        self.write_str("![")?;

        // Write alt text content
        for node in alt {
            self.write(node)?;
        }

        self.write_str("](")?;
        self.write_str(url)?;

        if let Some(title_text) = title {
            self.write_str(" \"")?;
            self.write_str(title_text)?;
            self.write_char('"')?;
        }

        self.write_char(')')?;
        Ok(())
    }

    /// Write a soft line break
    pub(crate) fn write_soft_break(&mut self) -> WriteResult<()> {
        self.write_char('\n')?;
        Ok(())
    }

    /// Write a hard line break
    pub(crate) fn write_hard_break(&mut self) -> WriteResult<()> {
        if self.options.hard_break_spaces {
            self.write_str("  \n")?;
        } else {
            self.write_str("\\\n")?;
        }
        Ok(())
    }

    /// Write an HTML block
    pub(crate) fn write_html_block(&mut self, content: &str) -> WriteResult<()> {
        self.buffer.push_str(content);

        Ok(())
    }

    /// Write an autolink (URI or email address wrapped in < and >)
    pub(crate) fn write_autolink(&mut self, url: &str, is_email: bool) -> WriteResult<()> {
        // Autolinks shouldn't contain newlines
        if url.contains('\n') {
            return Err(WriteError::NewlineInInlineElement(
                "Autolink URL".to_string(),
            ));
        }

        // Write the autolink with < and > delimiters
        self.write_char('<')?;

        // For email autolinks, we don't need to add any prefix
        // For URI autolinks, ensure it has a scheme
        if !is_email && !url.contains(':') {
            // Default to https if no scheme is provided
            self.write_str("https://")?;
        }

        self.write_str(url)?;
        self.write_char('>')?;

        Ok(())
    }

    /// Write an extended autolink (GFM extension)
    #[cfg(feature = "gfm")]
    pub(crate) fn write_extended_autolink(&mut self, url: &str) -> WriteResult<()> {
        if !self.options.gfm_autolinks {
            // If GFM autolinks are disabled, write as plain text
            self.write_text_content(url)?;
            return Ok(());
        }

        // Autolinks shouldn't contain newlines
        if url.contains('\n') {
            return Err(WriteError::NewlineInInlineElement(
                "Extended Autolink URL".to_string(),
            ));
        }

        // Just write the URL as plain text for extended autolinks (no angle brackets)
        self.write_str(url)?;

        Ok(())
    }

    /// Write a link reference definition
    pub(crate) fn write_link_reference_definition(
        &mut self,
        label: &str,
        destination: &str,
        title: &Option<String>,
    ) -> WriteResult<()> {
        // Format: [label]: destination "optional title"
        self.write_char('[')?;
        self.write_str(label)?;
        self.write_str("]: ")?;
        self.write_str(destination)?;

        if let Some(title_text) = title {
            self.write_str(" \"")?;
            self.write_str(title_text)?;
            self.write_char('"')?;
        }

        Ok(())
    }

    /// Write a reference link
    pub(crate) fn write_reference_link(
        &mut self,
        label: &str,
        content: &[Node],
    ) -> WriteResult<()> {
        // Check for newlines in content
        for node in content {
            self.check_no_newline(node, "Reference Link Text")?;
        }

        // If content is empty or exactly matches the label (as plain text),
        // this is a shortcut reference link: [label]
        if content.is_empty() {
            self.write_char('[')?;
            self.write_str(label)?;
            self.write_char(']')?;
            return Ok(());
        }

        // Check if content is exactly the same as the label (to use shortcut syntax)
        let is_shortcut =
            content.len() == 1 && matches!(&content[0], Node::Text(text) if text == label);

        if is_shortcut {
            // Use shortcut reference link syntax: [label]
            self.write_char('[')?;
            self.write_str(label)?;
            self.write_char(']')?;
        } else {
            // Use full reference link syntax: [content][label]
            self.write_char('[')?;

            for node in content {
                self.write(node)?;
            }

            self.write_str("][")?;
            self.write_str(label)?;
            self.write_char(']')?;
        }

        Ok(())
    }

    /// Write an HTML element
    pub(crate) fn write_html_element(&mut self, element: &HtmlElement) -> WriteResult<()> {
        // Check if the HTML element is disallowed in GFM mode
        #[cfg(feature = "gfm")]
        if self.options.enable_gfm
            && self
                .options
                .gfm_disallowed_html_tags
                .iter()
                .any(|tag| tag.eq_ignore_ascii_case(&element.tag))
        {
            // If the tag is disallowed, write it as escaped text to prevent HTML rendering
            self.write_str("&lt;")?;
            self.write_str(&element.tag)?;

            for attr in &element.attributes {
                self.write_char(' ')?;
                self.write_str(&attr.name)?;
                self.write_str("=\"")?;
                self.write_str(&escape_attribute_value(&attr.value))?;
                self.write_char('"')?;
            }

            if element.self_closing {
                self.write_str(" /&gt;")?;
                return Ok(());
            }

            self.write_str("&gt;")?;

            for child in &element.children {
                self.write(child)?;
            }

            self.write_str("&lt;/")?;
            self.write_str(&element.tag)?;
            self.write_str("&gt;")?;
            return Ok(());
        }

        // 检查标签名是否包含潜在危险字符
        if !is_safe_tag_name(&element.tag) {
            return Err(WriteError::InvalidHtmlTag(element.tag.clone()));
        }

        // Normal HTML element rendering if not disallowed or if GFM mode is not enabled
        self.write_char('<')?;
        self.write_str(&element.tag)?;

        for attr in &element.attributes {
            // 检查属性名是否安全
            if !is_safe_attribute_name(&attr.name) {
                return Err(WriteError::InvalidHtmlAttribute(attr.name.clone()));
            }

            self.write_char(' ')?;
            self.write_str(&attr.name)?;
            self.write_str("=\"")?;
            self.write_str(&escape_attribute_value(&attr.value))?;
            self.write_char('"')?;
        }

        if element.self_closing {
            self.write_str(" />")?;
            return Ok(());
        }

        self.write_char('>')?;

        for child in &element.children {
            // HTML element content can contain newlines, so no strict check here
            self.write(child)?;
        }

        self.write_str("</")?;
        self.write_str(&element.tag)?;
        self.write_char('>')?;
        Ok(())
    }

    /// Get the generated CommonMark format text
    ///
    /// Consumes the writer and returns the generated string
    ///
    /// # Example
    ///
    /// ```
    /// use cmark_writer::writer::CommonMarkWriter;
    /// use cmark_writer::ast::Node;
    ///
    /// let mut writer = CommonMarkWriter::new();
    /// writer.write(&Node::Text("Hello".to_string())).unwrap();
    /// let result = writer.into_string();
    /// assert_eq!(result, "Hello");
    /// ```
    pub fn into_string(self) -> String {
        self.buffer
    }
    /// Ensure content ends with a newline (for consistent handling at the end of block nodes)
    ///
    /// Adds a newline character if the content doesn't already end with one; does nothing if it already ends with a newline
    pub(crate) fn ensure_trailing_newline(&mut self) -> WriteResult<()> {
        if !self.buffer.ends_with('\n') {
            self.write_char('\n')?;
        }
        Ok(())
    }

    /// Write an emphasis (italic) node with custom delimiter
    pub(crate) fn write_emphasis(&mut self, content: &[Node]) -> WriteResult<()> {
        let delimiter = self.options.emphasis_char.to_string();
        self.write_delimited(content, &delimiter)
    }

    /// Write a strong emphasis (bold) node with custom delimiter
    pub(crate) fn write_strong(&mut self, content: &[Node]) -> WriteResult<()> {
        let char = self.options.strong_char;
        let delimiter = format!("{}{}", char, char);
        self.write_delimited(content, &delimiter)
    }

    /// Write a strikethrough node (GFM extension)
    #[cfg(feature = "gfm")]
    pub(crate) fn write_strikethrough(&mut self, content: &[Node]) -> WriteResult<()> {
        if !self.options.enable_gfm || !self.options.gfm_strikethrough {
            // If GFM strikethrough is disabled, just write the content without strikethrough
            for node in content.iter() {
                self.write(node)?;
            }
            return Ok(());
        }

        // Write content with ~~ delimiters
        self.write_delimited(content, "~~")
    }
}

impl Default for CommonMarkWriter {
    fn default() -> Self {
        Self::new()
    }
}

// Implement Display trait for Node structure
impl fmt::Display for Node {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut writer = CommonMarkWriter::new();
        match writer.write(self) {
            Ok(_) => write!(f, "{}", writer.into_string()),
            Err(e) => write!(f, "Error writing Node: {}", e),
        }
    }
}

// Implement CustomNodeWriter trait for CommonMarkWriter
impl CustomNodeWriter for CommonMarkWriter {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.buffer.push_str(s);
        Ok(())
    }

    fn write_char(&mut self, c: char) -> fmt::Result {
        self.buffer.push(c);
        Ok(())
    }
}
// Helper functions for HTML safety

/// Check if an HTML tag name is safe
///
/// Tag names should only contain letters, numbers, underscores, colons, and hyphens
fn is_safe_tag_name(tag: &str) -> bool {
    !tag.is_empty()
        && tag
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == ':' || c == '-')
}

/// Check if an HTML attribute name is safe
///
/// Attribute names should only contain letters, numbers, underscores, colons, dots, and hyphens
fn is_safe_attribute_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == ':' || c == '-' || c == '.')
}

/// Escape special characters in HTML attribute values
///
/// Converts quotes, less-than signs, greater-than signs, and other special characters to HTML entities
fn escape_attribute_value(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}