1 //! Transforms markdown
2 use ide_db::helpers::rust_doc::is_rust_fence;
4 const RUSTDOC_FENCE: &str = "```";
6 pub(crate) fn format_docs(src: &str) -> String {
7 let mut processed_lines = Vec::new();
8 let mut in_code_block = false;
9 let mut is_rust = false;
11 for mut line in src.lines() {
12 if in_code_block && is_rust && code_line_ignored_by_rustdoc(line) {
16 if let Some(header) = line.strip_prefix(RUSTDOC_FENCE) {
17 in_code_block ^= true;
20 is_rust = is_rust_fence(header);
28 processed_lines.push(line);
30 processed_lines.join("\n")
33 fn code_line_ignored_by_rustdoc(line: &str) -> bool {
34 let trimmed = line.trim();
35 trimmed == "#" || trimmed.starts_with("# ") || trimmed.starts_with("#\t")
43 fn test_format_docs_adds_rust() {
44 let comment = "```\nfn some_rust() {}\n```";
45 assert_eq!(format_docs(comment), "```rust\nfn some_rust() {}\n```");
49 fn test_format_docs_handles_plain_text() {
50 let comment = "```text\nthis is plain text\n```";
51 assert_eq!(format_docs(comment), "```text\nthis is plain text\n```");
55 fn test_format_docs_handles_non_rust() {
56 let comment = "```sh\nsupposedly shell code\n```";
57 assert_eq!(format_docs(comment), "```sh\nsupposedly shell code\n```");
61 fn test_format_docs_handles_rust_alias() {
62 let comment = "```ignore\nlet z = 55;\n```";
63 assert_eq!(format_docs(comment), "```rust\nlet z = 55;\n```");
67 fn test_format_docs_handles_complex_code_block_attrs() {
68 let comment = "```rust,no_run\nlet z = 55;\n```";
69 assert_eq!(format_docs(comment), "```rust\nlet z = 55;\n```");
73 fn test_format_docs_handles_error_codes() {
74 let comment = "```compile_fail,E0641\nlet b = 0 as *const _;\n```";
75 assert_eq!(format_docs(comment), "```rust\nlet b = 0 as *const _;\n```");
79 fn test_format_docs_skips_comments_in_rust_block() {
81 "```rust\n # skip1\n# skip2\n#stay1\nstay2\n#\n #\n # \n #\tskip3\n\t#\t\n```";
82 assert_eq!(format_docs(comment), "```rust\n#stay1\nstay2\n```");
86 fn test_format_docs_does_not_skip_lines_if_plain_text() {
88 "```text\n # stay1\n# stay2\n#stay3\nstay4\n#\n #\n # \n #\tstay5\n\t#\t\n```";
91 "```text\n # stay1\n# stay2\n#stay3\nstay4\n#\n #\n # \n #\tstay5\n\t#\t\n```",
96 fn test_format_docs_keeps_comments_outside_of_rust_block() {
97 let comment = " # stay1\n# stay2\n#stay3\nstay4\n#\n #\n # \n #\tstay5\n\t#\t";
98 assert_eq!(format_docs(comment), comment);
102 fn test_format_docs_preserves_newlines() {
103 let comment = "this\nis\nmultiline";
104 assert_eq!(format_docs(comment), comment);
108 fn test_code_blocks_in_comments_marked_as_rust() {
109 let comment = r#"```rust
118 format_docs(comment),
119 "```rust\nfn main(){}\n```\nSome comment.\n```rust\nlet a = 1;\n```"
124 fn test_code_blocks_in_comments_marked_as_text() {
125 let comment = r#"```text
135 format_docs(comment),
136 "```text\nfiller\ntext\n```\nSome comment.\n```rust\nlet a = 1;\n```"