1 //! Transforms markdown
3 const RUSTDOC_FENCE: &str = "```";
4 const RUSTDOC_CODE_BLOCK_ATTRIBUTES_RUST_SPECIFIC: &[&str] = &[
16 pub(crate) fn format_docs(src: &str) -> String {
17 let mut processed_lines = Vec::new();
18 let mut in_code_block = false;
19 let mut is_rust = false;
21 for mut line in src.lines() {
22 if in_code_block && is_rust && code_line_ignored_by_rustdoc(line) {
26 if let Some(header) = line.strip_prefix(RUSTDOC_FENCE) {
27 in_code_block ^= true;
32 .all(|sub| RUSTDOC_CODE_BLOCK_ATTRIBUTES_RUST_SPECIFIC.contains(&sub.trim()));
40 processed_lines.push(line);
42 processed_lines.join("\n")
45 fn code_line_ignored_by_rustdoc(line: &str) -> bool {
46 let trimmed = line.trim();
47 trimmed == "#" || trimmed.starts_with("# ") || trimmed.starts_with("#\t")
55 fn test_format_docs_adds_rust() {
56 let comment = "```\nfn some_rust() {}\n```";
57 assert_eq!(format_docs(comment), "```rust\nfn some_rust() {}\n```");
61 fn test_format_docs_handles_plain_text() {
62 let comment = "```text\nthis is plain text\n```";
63 assert_eq!(format_docs(comment), "```text\nthis is plain text\n```");
67 fn test_format_docs_handles_non_rust() {
68 let comment = "```sh\nsupposedly shell code\n```";
69 assert_eq!(format_docs(comment), "```sh\nsupposedly shell code\n```");
73 fn test_format_docs_handles_rust_alias() {
74 let comment = "```ignore\nlet z = 55;\n```";
75 assert_eq!(format_docs(comment), "```rust\nlet z = 55;\n```");
79 fn test_format_docs_handles_complex_code_block_attrs() {
80 let comment = "```rust,no_run\nlet z = 55;\n```";
81 assert_eq!(format_docs(comment), "```rust\nlet z = 55;\n```");
85 fn test_format_docs_skips_comments_in_rust_block() {
87 "```rust\n # skip1\n# skip2\n#stay1\nstay2\n#\n #\n # \n #\tskip3\n\t#\t\n```";
88 assert_eq!(format_docs(comment), "```rust\n#stay1\nstay2\n```");
92 fn test_format_docs_does_not_skip_lines_if_plain_text() {
94 "```text\n # stay1\n# stay2\n#stay3\nstay4\n#\n #\n # \n #\tstay5\n\t#\t\n```";
97 "```text\n # stay1\n# stay2\n#stay3\nstay4\n#\n #\n # \n #\tstay5\n\t#\t\n```",
102 fn test_format_docs_keeps_comments_outside_of_rust_block() {
103 let comment = " # stay1\n# stay2\n#stay3\nstay4\n#\n #\n # \n #\tstay5\n\t#\t";
104 assert_eq!(format_docs(comment), comment);
108 fn test_format_docs_preserves_newlines() {
109 let comment = "this\nis\nultiline";
110 assert_eq!(format_docs(comment), comment);
114 fn test_code_blocks_in_comments_marked_as_rust() {
115 let comment = r#"```rust
124 format_docs(comment),
125 "```rust\nfn main(){}\n```\nSome comment.\n```rust\nlet a = 1;\n```"
130 fn test_code_blocks_in_comments_marked_as_text() {
131 let comment = r#"```text
141 format_docs(comment),
142 "```text\nfiller\ntext\n```\nSome comment.\n```rust\nlet a = 1;\n```"