diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index c534a004b77633e539563ce524df73dd91d8fb9f..2d57b6579272a5c57c991e73af35efe2cfce0c4c 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -154,6 +154,17 @@ fn test_random_edits(mut rng: StdRng) { #[test] fn test_line_endings() { + assert_eq!(LineEnding::detect(&"🍐✅\n".repeat(1000)), LineEnding::Unix); + assert_eq!(LineEnding::detect(&"abcd\n".repeat(1000)), LineEnding::Unix); + assert_eq!( + LineEnding::detect(&"🍐✅\r\n".repeat(1000)), + LineEnding::Windows + ); + assert_eq!( + LineEnding::detect(&"abcd\r\n".repeat(1000)), + LineEnding::Windows + ); + let mut buffer = Buffer::new(0, 0, "one\r\ntwo".into()); assert_eq!(buffer.text(), "one\ntwo"); assert_eq!(buffer.line_ending(), LineEnding::Windows); diff --git a/crates/text/src/text.rs b/crates/text/src/text.rs index 7e564d3eca79cb3698cf905dcb51a1b9e3450feb..4d1e50b2749c5ebc291cee824c1e31cdc2c540e8 100644 --- a/crates/text/src/text.rs +++ b/crates/text/src/text.rs @@ -2353,9 +2353,13 @@ impl LineEnding { } pub fn detect(text: &str) -> Self { - if let Some(ix) = text[..cmp::min(text.len(), 1000)].find(&['\n']) { - let text = text.as_bytes(); - if ix > 0 && text[ix - 1] == b'\r' { + let mut max_ix = cmp::min(text.len(), 1000); + while !text.is_char_boundary(max_ix) { + max_ix -= 1; + } + + if let Some(ix) = text[..max_ix].find(&['\n']) { + if ix > 0 && text.as_bytes()[ix - 1] == b'\r' { Self::Windows } else { Self::Unix