Skip to main content

logicaffeine_lsp/
formatting.rs

1use lsp_types::TextEdit;
2
3use crate::document::DocumentState;
4
5/// Range formatting: the whole-document structural format (a line's depth
6/// depends on the lines above it — depth is a document-level fact), filtered
7/// to the edits whose lines intersect the requested range. Sound because
8/// `format_source` is line-count preserving: every edit stays on its line.
9pub fn format_range(doc: &DocumentState, range: lsp_types::Range) -> Vec<TextEdit> {
10    format_document(doc)
11        .into_iter()
12        .filter(|edit| {
13            edit.range.start.line <= range.end.line && edit.range.end.line >= range.start.line
14        })
15        .collect()
16}
17
18/// Handle document formatting request.
19///
20/// Formats the WHOLE document through the canonical LOGOS formatter
21/// ([`logicaffeine_language::source_format::format_source`] — identical to
22/// `largo fmt`, structural reindent and string/prose protection included)
23/// and emits per-line [`TextEdit`]s for the lines that changed.
24pub fn format_document(doc: &DocumentState) -> Vec<TextEdit> {
25    let mut edits = Vec::new();
26
27    let formatted = logicaffeine_language::source_format::format_source(&doc.source);
28    let mut formatted_lines = formatted.lines();
29
30    for (line_num, line) in doc.source.lines().enumerate() {
31        // format_source is line-count preserving by construction.
32        let new_line = formatted_lines.next().unwrap_or_default().to_string();
33
34        if new_line != line {
35            let line_start = doc.line_index.line_start_offset(line_num);
36            // The line's content ends at `line_start + line.len()` (always a
37            // char boundary). Terminated lines extend the range up to the
38            // `\n` so a `\r` (CRLF) is replaced away too; the final
39            // unterminated line ends exactly at EOF — never one byte short,
40            // which would duplicate the last character (or split a
41            // multibyte one and panic).
42            let content_end = line_start + line.len();
43            let next_start = doc.line_index.line_start_offset(line_num + 1);
44            let line_end = if next_start > content_end
45                && doc.source.as_bytes().get(next_start.saturating_sub(1)) == Some(&b'\n')
46            {
47                next_start - 1
48            } else {
49                content_end
50            };
51
52            let start = doc.line_index.position(line_start);
53            let end = doc.line_index.position(line_end);
54
55            edits.push(TextEdit {
56                range: lsp_types::Range { start, end },
57                new_text: new_line,
58            });
59        }
60    }
61
62    edits
63}
64
65#[cfg(test)]
66#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/formatting/tests.rs"]
67mod tests;