Debian Codegraph @

helix-core/src/line_ending.rs

raw symbols SCIP
1 use crate::{Rope, RopeSlice};
2
3 #[cfg(target_os = "windows")]
4 pub const NATIVE_LINE_ENDING: LineEnding = LineEnding::Crlf;
5 #[cfg(not(target_os = "windows"))]
6 pub const NATIVE_LINE_ENDING: LineEnding = LineEnding::LF;
7
8 /// Represents one of the valid Unicode line endings.
9 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
10 pub enum LineEnding {
11 Crlf, // CarriageReturn followed by LineFeed
12 LF, // U+000A -- LineFeed
13 #[cfg(feature = "unicode-lines")]
14 VT, // U+000B -- VerticalTab
15 #[cfg(feature = "unicode-lines")]
16 FF, // U+000C -- FormFeed
17 #[cfg(feature = "unicode-lines")]
18 CR, // U+000D -- CarriageReturn
19 #[cfg(feature = "unicode-lines")]
20 Nel, // U+0085 -- NextLine
21 #[cfg(feature = "unicode-lines")]
22 LS, // U+2028 -- Line Separator
23 #[cfg(feature = "unicode-lines")]
24 PS, // U+2029 -- ParagraphSeparator
25 }
26
27 impl LineEnding {
28 #[inline]
29 pub const fn len_chars(&self) -> usize {
30 match self {
31 Self::Crlf => 2,
32 _ => 1,
33 }
34 }
35
36 #[inline]
37 pub const fn as_str(&self) -> &'static str {
38 match self {
39 Self::Crlf => "\u{000D}\u{000A}",
40 Self::LF => "\u{000A}",
41 #[cfg(feature = "unicode-lines")]
42 Self::VT => "\u{000B}",
43 #[cfg(feature = "unicode-lines")]
44 Self::FF => "\u{000C}",
45 #[cfg(feature = "unicode-lines")]
46 Self::CR => "\u{000D}",
47 #[cfg(feature = "unicode-lines")]
48 Self::Nel => "\u{0085}",
49 #[cfg(feature = "unicode-lines")]
50 Self::LS => "\u{2028}",
51 #[cfg(feature = "unicode-lines")]
52 Self::PS => "\u{2029}",
53 }
54 }
55
56 #[inline]
57 pub const fn from_char(ch: char) -> Option<LineEnding> {
58 match ch {
59 '\u{000A}' => Some(LineEnding::LF),
60 #[cfg(feature = "unicode-lines")]
61 '\u{000B}' => Some(LineEnding::VT),
62 #[cfg(feature = "unicode-lines")]
63 '\u{000C}' => Some(LineEnding::FF),
64 #[cfg(feature = "unicode-lines")]
65 '\u{000D}' => Some(LineEnding::CR),
66 #[cfg(feature = "unicode-lines")]
67 '\u{0085}' => Some(LineEnding::Nel),
68 #[cfg(feature = "unicode-lines")]
69 '\u{2028}' => Some(LineEnding::LS),
70 #[cfg(feature = "unicode-lines")]
71 '\u{2029}' => Some(LineEnding::PS),
72 // Not a line ending
73 _ => None,
74 }
75 }
76
77 // Normally we'd want to implement the FromStr trait, but in this case
78 // that would force us into a different return type than from_char or
79 // or from_rope_slice, which would be weird.
80 #[allow(clippy::should_implement_trait)]
81 #[inline]
82 pub fn from_str(g: &str) -> Option<LineEnding> {
83 match g {
84 "\u{000D}\u{000A}" => Some(LineEnding::Crlf),
85 "\u{000A}" => Some(LineEnding::LF),
86 #[cfg(feature = "unicode-lines")]
87 "\u{000B}" => Some(LineEnding::VT),
88 #[cfg(feature = "unicode-lines")]
89 "\u{000C}" => Some(LineEnding::FF),
90 #[cfg(feature = "unicode-lines")]
91 "\u{000D}" => Some(LineEnding::CR),
92 #[cfg(feature = "unicode-lines")]
93 "\u{0085}" => Some(LineEnding::Nel),
94 #[cfg(feature = "unicode-lines")]
95 "\u{2028}" => Some(LineEnding::LS),
96 #[cfg(feature = "unicode-lines")]
97 "\u{2029}" => Some(LineEnding::PS),
98 // Not a line ending
99 _ => None,
100 }
101 }
102
103 #[inline]
104 pub fn from_rope_slice(g: &RopeSlice) -> Option<LineEnding> {
105 if let Some(text) = g.as_str() {
106 LineEnding::from_str(text)
107 } else {
108 // Non-contiguous, so it can't be a line ending.
109 // Specifically, Ropey guarantees that CRLF is always
110 // contiguous. And the remaining line endings are all
111 // single `char`s, and therefore trivially contiguous.
112 None
113 }
114 }
115 }
116
117 #[inline]
118 pub fn str_is_line_ending(s: &str) -> bool {
119 LineEnding::from_str(s).is_some()
120 }
121
122 #[inline]
123 pub fn rope_is_line_ending(r: RopeSlice) -> bool {
124 r.chunks().all(str_is_line_ending)
125 }
126
127 /// Attempts to detect what line ending the passed document uses.
128 pub fn auto_detect_line_ending(doc: &Rope) -> Option<LineEnding> {
129 // Return first matched line ending. Not all possible line endings
130 // are being matched, as they might be special-use only
131 for line in doc.lines().take(100) {
132 match get_line_ending(&line) {
133 None => {}
134 #[cfg(feature = "unicode-lines")]
135 Some(LineEnding::VT) | Some(LineEnding::FF) | Some(LineEnding::PS) => {}
136 ending => return ending,
137 }
138 }
139 None
140 }
141
142 /// Returns the passed line's line ending, if any.
143 pub fn get_line_ending(line: &RopeSlice) -> Option<LineEnding> {
144 // Last character as str.
145 let g1 = line
146 .slice(line.len_chars().saturating_sub(1)..)
147 .as_str()
148 .unwrap();
149
150 // Last two characters as str, or empty str if they're not contiguous.
151 // It's fine to punt on the non-contiguous case, because Ropey guarantees
152 // that CRLF is always contiguous.
153 let g2 = line
154 .slice(line.len_chars().saturating_sub(2)..)
155 .as_str()
156 .unwrap_or("");
157
158 // First check the two-character case for CRLF, then check the single-character case.
159 LineEnding::from_str(g2).or_else(|| LineEnding::from_str(g1))
160 }
161
162 #[cfg(not(feature = "unicode-lines"))]
163 /// Returns the passed line's line ending, if any.
164 pub fn get_line_ending_of_str(line: &str) -> Option<LineEnding> {
165 if line.ends_with("\u{000D}\u{000A}") {
166 Some(LineEnding::Crlf)
167 } else if line.ends_with('\u{000A}') {
168 Some(LineEnding::LF)
169 } else {
170 None
171 }
172 }
173
174 #[cfg(feature = "unicode-lines")]
175 /// Returns the passed line's line ending, if any.
176 pub fn get_line_ending_of_str(line: &str) -> Option<LineEnding> {
177 if line.ends_with("\u{000D}\u{000A}") {
178 Some(LineEnding::Crlf)
179 } else if line.ends_with('\u{000A}') {
180 Some(LineEnding::LF)
181 } else if line.ends_with('\u{000B}') {
182 Some(LineEnding::VT)
183 } else if line.ends_with('\u{000C}') {
184 Some(LineEnding::FF)
185 } else if line.ends_with('\u{000D}') {
186 Some(LineEnding::CR)
187 } else if line.ends_with('\u{0085}') {
188 Some(LineEnding::Nel)
189 } else if line.ends_with('\u{2028}') {
190 Some(LineEnding::LS)
191 } else if line.ends_with('\u{2029}') {
192 Some(LineEnding::PS)
193 } else {
194 None
195 }
196 }
197
198 /// Returns the char index of the end of the given line, not including its line ending.
199 pub fn line_end_char_index(slice: &RopeSlice, line: usize) -> usize {
200 slice.line_to_char(line + 1)
201 - get_line_ending(&slice.line(line))
202 .map(|le| le.len_chars())
203 .unwrap_or(0)
204 }
205
206 pub fn line_end_byte_index(slice: &RopeSlice, line: usize) -> usize {
207 slice.line_to_byte(line + 1)
208 - get_line_ending(&slice.line(line))
209 .map(|le| le.as_str().len())
210 .unwrap_or(0)
211 }
212
213 /// Fetches line `line_idx` from the passed rope slice, sans any line ending.
214 pub fn line_without_line_ending<'a>(slice: &'a RopeSlice, line_idx: usize) -> RopeSlice<'a> {
215 let start = slice.line_to_char(line_idx);
216 let end = line_end_char_index(slice, line_idx);
217 slice.slice(start..end)
218 }
219
220 /// Returns the char index of the end of the given RopeSlice, not including
221 /// any final line ending.
222 pub fn rope_end_without_line_ending(slice: &RopeSlice) -> usize {
223 slice.len_chars() - get_line_ending(slice).map(|le| le.len_chars()).unwrap_or(0)
224 }
225
226 #[cfg(test)]
227 mod line_ending_tests {
228 use super::*;
229
230 #[test]
231 fn line_ending_autodetect() {
232 assert_eq!(
233 auto_detect_line_ending(&Rope::from_str("\n")),
234 Some(LineEnding::LF)
235 );
236 assert_eq!(
237 auto_detect_line_ending(&Rope::from_str("\r\n")),
238 Some(LineEnding::Crlf)
239 );
240 assert_eq!(auto_detect_line_ending(&Rope::from_str("hello")), None);
241 assert_eq!(auto_detect_line_ending(&Rope::from_str("")), None);
242 assert_eq!(
243 auto_detect_line_ending(&Rope::from_str("hello\nhelix\r\n")),
244 Some(LineEnding::LF)
245 );
246 assert_eq!(
247 auto_detect_line_ending(&Rope::from_str("a formfeed\u{000C}")),
248 None
249 );
250 assert_eq!(
251 auto_detect_line_ending(&Rope::from_str("\n\u{000A}\n \u{000A}")),
252 Some(LineEnding::LF)
253 );
254 assert_eq!(
255 auto_detect_line_ending(&Rope::from_str(
256 "a formfeed\u{000C} with a\u{000C} linefeed\u{000A}"
257 )),
258 Some(LineEnding::LF)
259 );
260 assert_eq!(auto_detect_line_ending(&Rope::from_str("a formfeed\u{000C} with a\u{000C} carriage return linefeed\u{000D}\u{000A} and a linefeed\u{000A}")), Some(LineEnding::Crlf));
261 }
262
263 #[test]
264 fn str_to_line_ending() {
265 #[cfg(feature = "unicode-lines")]
266 assert_eq!(LineEnding::from_str("\r"), Some(LineEnding::CR));
267 assert_eq!(LineEnding::from_str("\n"), Some(LineEnding::LF));
268 assert_eq!(LineEnding::from_str("\r\n"), Some(LineEnding::Crlf));
269 assert_eq!(LineEnding::from_str("hello\n"), None);
270 }
271
272 #[test]
273 fn rope_slice_to_line_ending() {
274 let r = Rope::from_str("hello\r\n");
275 #[cfg(feature = "unicode-lines")]
276 assert_eq!(
277 LineEnding::from_rope_slice(&r.slice(5..6)),
278 Some(LineEnding::CR)
279 );
280 assert_eq!(
281 LineEnding::from_rope_slice(&r.slice(6..7)),
282 Some(LineEnding::LF)
283 );
284 assert_eq!(
285 LineEnding::from_rope_slice(&r.slice(5..7)),
286 Some(LineEnding::Crlf)
287 );
288 assert_eq!(LineEnding::from_rope_slice(&r.slice(..)), None);
289 }
290
291 #[test]
292 fn get_line_ending_rope_slice() {
293 let r = Rope::from_str("Hello\rworld\nhow\r\nare you?");
294 #[cfg(feature = "unicode-lines")]
295 assert_eq!(get_line_ending(&r.slice(..6)), Some(LineEnding::CR));
296 assert_eq!(get_line_ending(&r.slice(..12)), Some(LineEnding::LF));
297 assert_eq!(get_line_ending(&r.slice(..17)), Some(LineEnding::Crlf));
298 assert_eq!(get_line_ending(&r.slice(..)), None);
299 }
300
301 #[test]
302 fn get_line_ending_str() {
303 let text = "Hello\rworld\nhow\r\nare you?";
304 #[cfg(feature = "unicode-lines")]
305 assert_eq!(get_line_ending_of_str(&text[..6]), Some(LineEnding::CR));
306 assert_eq!(get_line_ending_of_str(&text[..12]), Some(LineEnding::LF));
307 assert_eq!(get_line_ending_of_str(&text[..17]), Some(LineEnding::Crlf));
308 assert_eq!(get_line_ending_of_str(text), None);
309 }
310
311 #[test]
312 fn line_end_char_index_rope_slice() {
313 let r = Rope::from_str("Hello\rworld\nhow\r\nare you?");
314 let s = &r.slice(..);
315 #[cfg(not(feature = "unicode-lines"))]
316 {
317 assert_eq!(line_end_char_index(s, 0), 11);
318 assert_eq!(line_end_char_index(s, 1), 15);
319 assert_eq!(line_end_char_index(s, 2), 25);
320 }
321 #[cfg(feature = "unicode-lines")]
322 {
323 assert_eq!(line_end_char_index(s, 0), 5);
324 assert_eq!(line_end_char_index(s, 1), 11);
325 assert_eq!(line_end_char_index(s, 2), 15);
326 }
327 }
328 }