Skip to content

Commit c2ca7dc

Browse files
authored
fix: handle doc-like comments when forcing a leading space (#25)
1 parent 606cd79 commit c2ca7dc

File tree

3 files changed

+44
-3
lines changed

3 files changed

+44
-3
lines changed

src/generation/generate.rs

+24-3
Original file line numberDiff line numberDiff line change
@@ -397,8 +397,11 @@ fn gen_comment<'a>(comment: SyntaxToken, context: &mut Context<'a>) -> PrintItem
397397
items.extend({
398398
if context.config.comment_force_leading_space {
399399
let info = get_comment_text_info(comment.text());
400-
let after_hash_text = &comment.text()[info.leading_hashes_count..].trim_end();
400+
let after_hash_text = &comment.text()[info.start_text_index..].trim_end();
401401
let mut text = "#".repeat(info.leading_hashes_count);
402+
if info.has_exclamation_point {
403+
text.push('!');
404+
}
402405
if !after_hash_text.is_empty() {
403406
if !info.has_leading_whitespace {
404407
text.push(' ');
@@ -416,15 +419,31 @@ fn gen_comment<'a>(comment: SyntaxToken, context: &mut Context<'a>) -> PrintItem
416419

417420
struct CommentTextInfo {
418421
pub has_leading_whitespace: bool,
422+
pub has_exclamation_point: bool,
419423
pub leading_hashes_count: usize,
424+
pub start_text_index: usize,
420425
}
421426

422427
fn get_comment_text_info(text: &str) -> CommentTextInfo {
423428
let mut leading_hashes_count = 0;
424429
let mut has_leading_whitespace = false;
425-
for c in text.chars() {
430+
let mut has_exclamation_point = false;
431+
let mut start_text_index = 0;
432+
let mut chars = text.char_indices();
433+
for (index, c) in chars.by_ref() {
426434
match c {
427-
'#' => leading_hashes_count += 1,
435+
'#' if !has_exclamation_point => {
436+
leading_hashes_count += 1;
437+
start_text_index = index + 1;
438+
}
439+
'!' if leading_hashes_count == 1 => {
440+
has_exclamation_point = true;
441+
start_text_index = index + 1;
442+
if matches!(chars.next(), Some((_, ' ' | '\t'))) {
443+
has_leading_whitespace = true;
444+
}
445+
break;
446+
}
428447
' ' | '\t' => {
429448
has_leading_whitespace = true;
430449
break;
@@ -434,7 +453,9 @@ fn get_comment_text_info(text: &str) -> CommentTextInfo {
434453
}
435454
CommentTextInfo {
436455
leading_hashes_count,
456+
has_exclamation_point,
437457
has_leading_whitespace,
458+
start_text_index,
438459
}
439460
}
440461

tests/specs/Comments/Comments_ForceLeadingSpace_False.txt

+10
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,13 @@
2020

2121
[expect]
2222
# test
23+
24+
== should not force when is #! ==
25+
#! Test
26+
#!Test
27+
#!## Test
28+
29+
[expect]
30+
#! Test
31+
#!Test
32+
#!## Test

tests/specs/Comments/Comments_ForceLeadingSpace_True.txt

+10
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,13 @@
1616
# test
1717
# test
1818
# test
19+
20+
== should force when is #! ==
21+
#! Test
22+
#!Test
23+
#!## Test
24+
25+
[expect]
26+
#! Test
27+
#! Test
28+
#! ## Test

0 commit comments

Comments
 (0)