Skip to main content

editor_core/
line_ending.rs

1//! Line ending helpers.
2//!
3//! `editor-core` stores text internally using LF (`'\n'`) newlines.
4//! When opening a file that uses CRLF (`"\r\n"`), the content is normalized on load, but the
5//! preferred line ending can be tracked for saving.
6
7/// The preferred newline sequence used when saving a document.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum LineEnding {
10    /// Unix-style LF (`'\n'`).
11    Lf,
12    /// Windows-style CRLF (`"\r\n"`).
13    Crlf,
14}
15
16impl LineEnding {
17    /// Detect the dominant line ending from a source text.
18    ///
19    /// Policy: if the input contains any CRLF (`"\r\n"`), returns [`LineEnding::Crlf`],
20    /// otherwise [`LineEnding::Lf`].
21    pub fn detect_in_text(text: &str) -> Self {
22        if text.contains("\r\n") {
23            Self::Crlf
24        } else {
25            Self::Lf
26        }
27    }
28
29    /// Convert an LF-normalized text to this line ending for saving.
30    pub fn apply_to_text(self, text: &str) -> String {
31        match self {
32            Self::Lf => text.to_string(),
33            Self::Crlf => text.replace('\n', "\r\n"),
34        }
35    }
36}