use std::collections::HashMap;
use std::sync::LazyLock;
use serde::Deserialize;
use serde_json::{Value, json};
use unicode_width::UnicodeWidthChar;
use crate::analysis::{Form, forms};
use crate::intel::View;
use crate::navigation::Lines;
use crate::position::{Encoding, Position, Range, line_ranges};
use crate::syntax::{Kind, Node};
#[derive(Clone, Copy, PartialEq, Eq)]
enum Indent {
Arguments(usize),
Defun,
Dynamic,
}
static STANDARD: LazyLock<HashMap<&'static str, Indent>> = LazyLock::new(|| {
include_str!("indent_specs.txt")
.lines()
.filter_map(|line| {
let (name, spec) = line.split_once(' ')?;
Some((name, parse_spec(spec)))
})
.collect()
});
fn parse_spec(text: &str) -> Indent {
match text {
"defun" => Indent::Defun,
_ => text
.parse()
.map(Indent::Arguments)
.unwrap_or(Indent::Dynamic),
}
}
fn atom<'a>(form: &Form, text: &'a str) -> Option<&'a str> {
match *form {
Form::Atom { start, end, .. } => Some(&text[start..end]),
_ => None,
}
}
fn indentation_specs(view: View, specs: &mut HashMap<String, Indent>) {
for form in forms(view.tree) {
let Some(items) = form.items() else { continue };
let Some(head) = items.first().and_then(|head| atom(head, view.text)) else {
continue;
};
match (head, items) {
("put" | "function-put", [_, name, property, value]) => {
let Some(name) = name.quoted().and_then(|name| atom(name, view.text)) else {
continue;
};
let Some("lisp-indent-function" | "lisp-indent-hook") = property
.quoted()
.and_then(|property| atom(property, view.text))
else {
continue;
};
let spec = atom(value.quoted().unwrap_or(value), view.text)
.map_or(Indent::Dynamic, parse_spec);
specs.insert(name.to_owned(), spec);
}
(
"defun" | "defmacro" | "defsubst" | "cl-defun" | "cl-defmacro" | "cl-defsubst"
| "define-inline",
[_, name, _, body @ ..],
) => {
let Some(name) = atom(name, view.text) else {
continue;
};
for declaration in body.iter().filter_map(Form::items) {
if declaration.first().and_then(|head| atom(head, view.text)) != Some("declare")
{
continue;
}
for option in declaration[1..].iter().filter_map(Form::items) {
if let [key, spec] = option
&& atom(key, view.text) == Some("indent")
{
let spec = atom(spec, view.text).map_or(Indent::Dynamic, parse_spec);
specs.insert(name.to_owned(), spec);
}
}
}
}
_ => {}
}
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Options {
tab_size: u32,
insert_spaces: bool,
}
pub(crate) enum Selection {
Document,
Range(Range),
Line(Position),
}
type Span = (usize, usize);
struct Frame {
start: usize,
end: usize,
items: Vec<Span>,
spec: Option<Indent>,
closed: bool,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Context {
Expression,
LocalBindings,
LocalDefinition,
}
struct Layout {
frames: Vec<Frame>,
protected: Vec<Span>,
}
fn has_unclosed_string(node: &Node) -> bool {
(node.kind == Kind::String && node.error) || node.children.iter().any(has_unclosed_string)
}
fn children(node: &Node, start: usize) -> impl Iterator<Item = (&Node, usize)> {
let mut offset = start;
node.children.iter().map(move |child| {
let at = offset;
offset += child.len;
(child, at)
})
}
impl Layout {
fn new(view: View, others: &[View]) -> Self {
let mut specs = HashMap::new();
for &other in others {
if other.uri != view.uri {
indentation_specs(other, &mut specs);
}
}
indentation_specs(view, &mut specs);
let mut layout = Self {
frames: Vec::new(),
protected: Vec::new(),
};
for (node, start) in children(&view.tree.root, 0) {
if has_unclosed_string(node) {
layout.protected.push((start, start + node.len));
} else {
layout.walk(view.text, node, start, &specs, Context::Expression);
}
}
layout
}
fn walk(
&mut self,
text: &str,
node: &Node,
start: usize,
specs: &HashMap<String, Indent>,
context: Context,
) {
let end = start + node.len;
if node.is_token() {
if node.kind != Kind::Whitespace
&& (node.kind == Kind::Skip || text[start..end].contains(['\r', '\n']))
{
self.protected.push((start + 1, end));
}
return;
}
let mut local_definitions = None;
if matches!(node.kind, Kind::List | Kind::Vector) {
let entries: Vec<_> = children(node, start)
.filter(|(child, _)| {
!child.kind.is_trivia()
&& !matches!(
child.kind,
Kind::Open
| Kind::HashOpen
| Kind::RecordOpen
| Kind::OpenBracket
| Kind::HashBracket
| Kind::CharTableOpen
| Kind::Close
| Kind::CloseBracket
)
})
.collect();
let head = entries
.first()
.filter(|(child, _)| child.kind == Kind::Symbol)
.map(|(child, at)| &text[*at..*at + child.len]);
let regular_list = node
.children
.first()
.is_some_and(|child| child.kind == Kind::Open);
let spec = if context == Context::LocalDefinition {
Some(Indent::Defun)
} else if regular_list {
head.and_then(|head| specs.get(head).or_else(|| STANDARD.get(head)))
.copied()
} else {
None
};
if spec == Some(Indent::Dynamic) {
self.protected.push((start, end));
return;
}
if matches!(
head,
Some("cl-flet" | "cl-flet*" | "cl-labels" | "cl-macrolet")
) {
local_definitions = entries.get(1).map(|(_, offset)| *offset);
}
self.frames.push(Frame {
start,
end,
items: entries
.iter()
.map(|(child, at)| (*at, *at + child.len))
.collect(),
spec,
closed: node
.children
.last()
.is_some_and(|child| matches!(child.kind, Kind::Close | Kind::CloseBracket)),
});
}
for (child, offset) in children(node, start) {
let context = if context == Context::LocalBindings && child.kind == Kind::List {
Context::LocalDefinition
} else if local_definitions == Some(offset) {
Context::LocalBindings
} else {
Context::Expression
};
self.walk(text, child, offset, specs, context);
}
}
}
struct Columns<'a> {
text: &'a str,
starts: Vec<usize>,
leading: Vec<usize>,
indents: Vec<usize>,
tab: usize,
}
impl Columns<'_> {
fn line(&self, offset: usize) -> usize {
self.starts.partition_point(|&start| start <= offset) - 1
}
fn width(&self, text: &str, initial: usize) -> usize {
text.chars().fold(initial, |column, ch| {
if ch == '\t' {
column + self.tab - column % self.tab
} else {
column + ch.width().unwrap_or(1)
}
})
}
fn at(&self, offset: usize) -> usize {
let line = self.line(offset);
let start = self.leading[line].min(offset);
self.width(&self.text[start..offset], self.indents[line])
}
fn indent(&self, frame: &Frame, line: usize, first: usize) -> usize {
let open = self.at(frame.start);
let before = frame
.items
.partition_point(|item| item.1 <= self.starts[line]);
let Some(last) = before.checked_sub(1) else {
return open + 1;
};
let first_item = frame.items[0].0;
let last_line = self.line(frame.items[last].0);
let open_line = self.line(frame.start);
let first_on_last = frame
.items
.partition_point(|item| item.0 < self.starts[last_line]);
let mut normal = self.at(frame.items[first_on_last].0);
if last_line == open_line
&& before > 1
&& first_item == frame.start + 1
&& self.text.as_bytes()[first_item] != b'('
{
normal = self.at(frame.items[1].0);
}
match frame.spec {
Some(Indent::Arguments(count)) if before - 1 < count && before <= 2 => open + 4,
Some(Indent::Arguments(count))
if before - 1 == count && (count == 0 || normal >= open + 2) =>
{
open + 2
}
Some(Indent::Defun) if last_line == open_line => open + 2,
_ => {
if self.text.as_bytes().get(first) == Some(&b':') && first_on_last > 0 {
for &(at, _) in frame.items[first_on_last..before].iter().take(2) {
if self.text.as_bytes()[at] == b':' {
return self.at(at);
}
}
}
normal
}
}
}
}
pub(crate) fn edits(
view: View,
others: &[View],
encoding: Encoding,
options: Options,
selection: Selection,
) -> Option<Value> {
if !(1..=256).contains(&options.tab_size) {
return None;
}
let lines = Lines::new(view.text, encoding);
let is_on_type = matches!(selection, Selection::Line(_));
let (start, end) = match selection {
Selection::Document => (0, usize::MAX),
Selection::Range(range) => {
let start = lines.offset(range.start)?;
let end = lines.offset(range.end)?;
if end < start {
return None;
}
if start == end {
return Some(json!([]));
}
let last = lines.line(end);
(
lines.line(start),
last + usize::from(lines.line_start(last) != Some(end)),
)
}
Selection::Line(position) => {
lines.offset(position)?;
let line = position.line as usize;
(line, line + 1)
}
};
let layout = Layout::new(view, others);
let ranges: Vec<_> = line_ranges(view.text).collect();
let mut columns = Columns {
text: view.text,
starts: ranges.iter().map(|&(start, _)| start).collect(),
leading: Vec::with_capacity(ranges.len()),
indents: Vec::with_capacity(ranges.len()),
tab: options.tab_size as usize,
};
let mut result = Vec::new();
let mut next = 0;
let mut protected = 0;
let mut stack: Vec<&Frame> = Vec::new();
for (line, (at, end_of_line)) in ranges.into_iter().enumerate().take(end) {
let text = &view.text[at..end_of_line];
let old = text.len() - text.trim_start_matches([' ', '\t']).len();
let first = at + old;
let remainder = &text[old..];
columns.leading.push(first);
let existing = columns.width(&text[..old], 0);
columns.indents.push(existing);
while layout
.protected
.get(protected)
.is_some_and(|span| span.1 <= at)
{
protected += 1;
}
while let Some(frame) = layout.frames.get(next).filter(|frame| frame.start < at) {
while stack.last().is_some_and(|parent| parent.end <= frame.start) {
stack.pop();
}
stack.push(frame);
next += 1;
}
while stack
.last()
.is_some_and(|frame| frame.end < at || (frame.closed && frame.end == at))
{
stack.pop();
}
if line < start
|| (remainder.is_empty() && !is_on_type)
|| (remainder.starts_with(';')
&& (!remainder.starts_with(";;") || remainder.starts_with(";;;")))
|| layout.protected.get(protected).is_some_and(|span| {
(span.0 <= at && at < span.1) || (span.0 == first && first < span.1)
})
{
continue;
}
let indent = stack
.last()
.map_or(0, |frame| columns.indent(frame, line, first));
columns.indents[line] = indent;
let new_text = if options.insert_spaces {
" ".repeat(indent)
} else {
"\t".repeat(indent / columns.tab) + &" ".repeat(indent % columns.tab)
};
if text[..old] != new_text {
result.push(json!({"range": lines.range(at, first), "newText": new_text}));
}
}
Some(json!(result))
}