Skip to main content

lax_css/
format_text.rs

1use std::path::Path;
2
3use anyhow::Result;
4use dprint_core::configuration::resolve_new_line_kind;
5use dprint_core::formatting::PrintOptions;
6
7use crate::configuration::Configuration;
8use crate::generation;
9
10pub fn format_text(_path: &Path, text: &str, config: &Configuration) -> Result<Option<String>> {
11  let result = format_text_inner(text, config)?;
12  if result == text { Ok(None) } else { Ok(Some(result)) }
13}
14
15fn format_text_inner(text: &str, config: &Configuration) -> Result<String> {
16  let text = text.strip_prefix('\u{FEFF}').unwrap_or(text);
17  let tokens = generation::tokenize(text);
18  if has_ignore_file_comment(&tokens, &config.ignore_file_comment_text) {
19    return Ok(text.to_string());
20  }
21  let statements = generation::parse(&tokens, text);
22  if statements.is_empty() {
23    return Ok(String::new());
24  }
25  if config.single_line {
26    return Ok(generation::generate_inline(&statements, text));
27  }
28  Ok(dprint_core::formatting::format(
29    || generation::generate(&statements, text, config),
30    PrintOptions {
31      indent_width: config.indent_width,
32      max_width: config.line_width,
33      use_tabs: config.use_tabs,
34      new_line_text: resolve_new_line_kind(text, config.new_line_kind),
35    },
36  ))
37}
38
39fn has_ignore_file_comment(tokens: &[generation::Token], directive: &str) -> bool {
40  lax_core::has_ignore_file_comment(
41    tokens.iter().map(|token| match token.kind {
42      generation::TokenKind::Whitespace { newlines } => lax_core::HeaderToken::Whitespace { newlines },
43      generation::TokenKind::LineComment | generation::TokenKind::BlockComment => {
44        lax_core::HeaderToken::Comment(token.text)
45      }
46      _ => lax_core::HeaderToken::Other,
47    }),
48    directive,
49  )
50}