Skip to content

Commit 5a2a96e

Browse files
committed
continue-comments: Fix panic case and add test
1 parent aca48e8 commit 5a2a96e

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

helix-core/src/comment.rs

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,25 @@ use std::borrow::Cow;
1212
pub const DEFAULT_COMMENT_TOKEN: &str = "//";
1313

1414
/// Returns the longest matching comment token of the given line (if it exists).
15-
pub fn get_comment_token<'a>(
15+
pub fn get_comment_token<'a, S: AsRef<str>>(
1616
text: RopeSlice,
17-
tokens: &'a [String],
17+
tokens: &'a [S],
1818
line_num: usize,
1919
) -> Option<&'a str> {
2020
let mut used_token: Option<&'a str> = None;
2121

2222
let line = text.line(line_num);
23-
let start = line.char_to_byte(line.first_non_whitespace_char()?);
23+
let start = line.first_non_whitespace_char()?;
2424

25+
let mut max_token_len = 0;
2526
for token in tokens {
26-
let end = std::cmp::min(start + token.len(), line.len_bytes());
27-
if line.byte_slice(start..end) == *token {
28-
used_token = Some(token.as_str());
27+
let token_str = token.as_ref();
28+
let end = std::cmp::min(start + token_str.len(), line.len_bytes());
29+
30+
let matches_token = line.slice(start..end).starts_with(token_str);
31+
if matches_token && token_str.len() >= max_token_len {
32+
used_token = Some(token_str);
33+
max_token_len = token_str.len();
2934
}
3035
}
3136

@@ -481,4 +486,17 @@ mod test {
481486
transaction.apply(&mut doc);
482487
assert_eq!(doc, "");
483488
}
489+
490+
// Test, if `get_comment_tokens` works, even if the content of the file includes chars, whose
491+
// byte size unequal the amount of chars
492+
#[test]
493+
fn test_get_comment_with_char_boundaries() {
494+
let rope = Rope::from("··");
495+
let tokens = ["//", "///"];
496+
497+
assert_eq!(
498+
super::get_comment_token(rope.slice(..), tokens.as_slice(), 0),
499+
None
500+
);
501+
}
484502
}

0 commit comments

Comments
 (0)