#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WrapMode {
#[default]
Reflow,
Stable,
Sentence,
Semantic,
Preserve,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MathWrap {
#[default]
Auto,
Preserve,
SingleLine,
Break,
}
impl MathWrap {
#[must_use]
pub fn resolve(self, wrap: WrapMode) -> Self {
match self {
Self::Auto => {
if wrap == WrapMode::Preserve {
Self::Preserve
} else {
Self::Break
}
}
other => other,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineEnding {
#[default]
Auto,
Lf,
Crlf,
Native,
}
impl LineEnding {
#[must_use]
pub fn resolve(self, detected: Self) -> Self {
match self {
Self::Auto => match detected {
Self::Crlf => Self::Crlf,
_ => Self::Lf,
},
Self::Native => {
if cfg!(windows) {
Self::Crlf
} else {
Self::Lf
}
}
other => other,
}
}
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Crlf => "\r\n",
_ => "\n",
}
}
#[must_use]
pub fn detect(text: &str) -> Self {
match text.find('\n') {
Some(idx) if idx > 0 && text.as_bytes()[idx - 1] == b'\r' => Self::Crlf,
_ => Self::Lf,
}
}
}
pub(crate) fn detect_line_ending(text: &rowan::SyntaxText) -> LineEnding {
let mut detected = LineEnding::Lf;
let mut prev_cr = false;
let _: Result<(), ()> = text.try_for_each_chunk(|chunk| {
if let Some(idx) = chunk.find('\n') {
let crlf = if idx == 0 {
prev_cr
} else {
chunk.as_bytes()[idx - 1] == b'\r'
};
if crlf {
detected = LineEnding::Crlf;
}
return Err(());
}
prev_cr = chunk.ends_with('\r');
Ok(())
});
detected
}
pub(crate) fn apply_line_ending(out: &mut String, resolved: LineEnding) {
let needs_work = match resolved {
LineEnding::Crlf => out.contains('\n'),
_ => out.contains("\r\n"),
};
if !needs_work {
return;
}
let ending = resolved.as_str();
let mut result = String::with_capacity(out.len() + out.len() / 16);
for (i, segment) in out.split('\n').enumerate() {
if i > 0 {
result.push_str(ending);
}
result.push_str(segment.strip_suffix('\r').unwrap_or(segment));
}
*out = result;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FormatStyle {
pub line_width: usize,
pub indent_width: usize,
pub wrap: WrapMode,
pub math_wrap: MathWrap,
pub line_ending: LineEnding,
}
impl Default for FormatStyle {
fn default() -> Self {
Self {
line_width: 80,
indent_width: 2,
wrap: WrapMode::default(),
math_wrap: MathWrap::default(),
line_ending: LineEnding::default(),
}
}
}
pub(crate) const STABLE_WRAP_TARGET_OFFSET: usize = 15;
impl FormatStyle {
pub fn stable_wrap_target(self) -> usize {
self.line_width
.saturating_sub(STABLE_WRAP_TARGET_OFFSET)
.clamp(1, self.line_width.max(1))
}
}