#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(rename_all = "kebab-case")
)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum WrapMode {
#[default]
Reflow,
Stable,
Sentence,
Semantic,
Preserve,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(rename_all = "kebab-case")
)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
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)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(rename_all = "kebab-case")
)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum LineEnding {
#[default]
Auto,
Lf,
Crlf,
Native,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(rename_all = "kebab-case")
)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum ItemIndent {
#[default]
Hang,
Indent,
None,
}
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)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(default, rename_all = "kebab-case")
)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct FormatStyle {
pub line_width: usize,
pub indent_width: usize,
pub item_indent: ItemIndent,
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,
item_indent: ItemIndent::default(),
wrap: WrapMode::default(),
math_wrap: MathWrap::default(),
line_ending: LineEnding::default(),
}
}
}
pub(crate) const STABLE_WRAP_TARGET_OFFSET: usize = 15;
pub(crate) const UNLIMITED_LINE_WIDTH: usize = usize::MAX / 2;
impl FormatStyle {
pub(crate) fn effective_line_width(self) -> usize {
if self.line_width == 0 {
UNLIMITED_LINE_WIDTH
} else {
self.line_width
}
}
pub fn stable_wrap_target(self) -> usize {
if self.line_width == 0 {
return 0;
}
self.line_width
.saturating_sub(STABLE_WRAP_TARGET_OFFSET)
.clamp(1, self.line_width.max(1))
}
}
#[cfg(all(test, feature = "serde"))]
mod serde_tests {
use super::{FormatStyle, ItemIndent, LineEnding, MathWrap, WrapMode};
fn wrap_wire(mode: WrapMode) -> &'static str {
match mode {
WrapMode::Reflow => "reflow",
WrapMode::Stable => "stable",
WrapMode::Sentence => "sentence",
WrapMode::Semantic => "semantic",
WrapMode::Preserve => "preserve",
}
}
fn math_wrap_wire(mode: MathWrap) -> &'static str {
match mode {
MathWrap::Auto => "auto",
MathWrap::Preserve => "preserve",
MathWrap::SingleLine => "single-line",
MathWrap::Break => "break",
}
}
fn line_ending_wire(ending: LineEnding) -> &'static str {
match ending {
LineEnding::Auto => "auto",
LineEnding::Lf => "lf",
LineEnding::Crlf => "crlf",
LineEnding::Native => "native",
}
}
fn item_indent_wire(indent: ItemIndent) -> &'static str {
match indent {
ItemIndent::Hang => "hang",
ItemIndent::Indent => "indent",
ItemIndent::None => "none",
}
}
fn round_trip<T>(value: T, expected: &str)
where
T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
{
let json = serde_json::to_string(&value).expect("serializes");
assert_eq!(json, format!("\"{expected}\""));
let back: T = serde_json::from_str(&json).expect("deserializes");
assert_eq!(back, value);
}
#[test]
fn wrap_modes_use_their_toml_spelling() {
for mode in [
WrapMode::Reflow,
WrapMode::Stable,
WrapMode::Sentence,
WrapMode::Semantic,
WrapMode::Preserve,
] {
round_trip(mode, wrap_wire(mode));
}
}
#[test]
fn math_wraps_use_their_toml_spelling() {
for mode in [
MathWrap::Auto,
MathWrap::Preserve,
MathWrap::SingleLine,
MathWrap::Break,
] {
round_trip(mode, math_wrap_wire(mode));
}
}
#[test]
fn line_endings_use_their_toml_spelling() {
for ending in [
LineEnding::Auto,
LineEnding::Lf,
LineEnding::Crlf,
LineEnding::Native,
] {
round_trip(ending, line_ending_wire(ending));
}
}
#[test]
fn item_indents_use_their_toml_spelling() {
for indent in [ItemIndent::Hang, ItemIndent::Indent, ItemIndent::None] {
round_trip(indent, item_indent_wire(indent));
}
}
#[test]
fn format_style_keys_are_kebab_case_and_default_the_rest() {
let json = serde_json::to_value(FormatStyle::default()).expect("serializes");
let object = json.as_object().expect("an object");
let mut keys: Vec<_> = object.keys().map(String::as_str).collect();
keys.sort_unstable();
assert_eq!(
keys,
[
"indent-width",
"item-indent",
"line-ending",
"line-width",
"math-wrap",
"wrap"
]
);
let partial: FormatStyle =
serde_json::from_str(r#"{"line-width": 100}"#).expect("deserializes");
assert_eq!(
partial,
FormatStyle {
line_width: 100,
..FormatStyle::default()
}
);
}
}
#[cfg(all(test, feature = "schema"))]
mod schema_tests {
use super::{ItemIndent, LineEnding, MathWrap, WrapMode};
fn variants(schema: schemars::Schema) -> Vec<String> {
let json = serde_json::to_value(schema).expect("schema serializes");
let mut values: Vec<String> = json
.get("oneOf")
.and_then(|one_of| one_of.as_array())
.expect("an enum schema is a oneOf")
.iter()
.map(|variant| {
variant
.get("const")
.and_then(|value| value.as_str())
.expect("each variant is a const")
.to_string()
})
.collect();
values.sort();
values
}
#[test]
fn enums_advertise_their_wire_values() {
assert_eq!(
variants(schemars::schema_for!(WrapMode)),
["preserve", "reflow", "semantic", "sentence", "stable"]
);
assert_eq!(
variants(schemars::schema_for!(MathWrap)),
["auto", "break", "preserve", "single-line"]
);
assert_eq!(
variants(schemars::schema_for!(LineEnding)),
["auto", "crlf", "lf", "native"]
);
assert_eq!(
variants(schemars::schema_for!(ItemIndent)),
["hang", "indent", "none"]
);
}
}