use super::*;
impl Editor {
pub fn gutter_width(&self) -> usize {
if self.document.is_empty() {
0
} else {
self.show_diagnostics as usize
+ self.document.len().to_string().len()
+ 1
+ self.git_base.is_some() as usize
}
}
pub fn scroll(&mut self, width: usize, height: usize) {
self.page_rows = height;
self.row_offset = self.folds.header_of(self.row_offset.min(self.cursor_y));
if height > 0 && self.folds.rows_between(self.row_offset, self.cursor_y) >= height {
let mut top = self.cursor_y;
for _ in 1..height {
match self.folds.prev_visible(top) {
Some(above) => top = above,
None => break,
}
}
self.row_offset = top;
}
let column = self.column_of(self.cursor_x, self.cursor_y);
if column < self.col_offset {
self.col_offset = column;
}
if width > 0 && column >= self.col_offset + width {
self.col_offset = column - width + 1;
}
}
pub(super) fn column_of(&self, x: usize, y: usize) -> usize {
let Some(line) = self.document.lines.get(y) else {
return x;
};
if line.is_ascii() && !line.contains('\t') {
return x;
}
let cells = cells(line);
cells.iter().position(|(index, _)| *index >= x).unwrap_or(cells.len())
}
pub(super) fn char_at(&self, column: usize, y: usize) -> usize {
let Some(line) = self.document.lines.get(y) else {
return 0;
};
match cells(line).get(column) {
Some((index, _)) => *index,
None => line.chars().count(),
}
}
pub(super) fn display_line(&self, y: usize) -> String {
let line = &self.document.lines[y];
match self.folds.end_of(y) {
Some(_) if self.language.is_some_and(Language::blocks_by_indent) => format!("{line} ..."),
Some(end) => format!("{line} ... {}", self.document.lines[end].trim()),
None => line.clone(),
}
}
pub(super) fn status_row(&self, width: usize) -> Row {
let mut left: Vec<(Style, String)> = Vec::new();
if let Some(prompt) = &self.prompt {
let note = match self.message.as_str() {
"" => String::new(),
message => format!(" ({message})"),
};
left.push((Style::Bar, format!("{}{}{note}", self.prompt_label(prompt.kind), prompt.text)));
} else if !self.message.is_empty() {
left.push((Style::Bar, self.message.clone()));
} else if let Some(diagnostic) = self.diagnostic_on(self.cursor_y) {
let (style, kind) = match diagnostic.severity {
Severity::Error => (Style::BarError, "error"),
Severity::Warning => (Style::BarWarn, "warning"),
Severity::Info => (Style::Bar, "info"),
};
left.push((style, format!("{kind}: {}", diagnostic.message)));
} else {
left.push((Style::BarBold, self.name().to_string()));
if self.document.dirty {
left.push((Style::BarWarn, " [modified]".into()));
}
let count = |severity| {
self.diagnostics
.iter()
.filter(|diagnostic| diagnostic.severity == severity)
.count()
};
let (errors, warnings) = (count(Severity::Error), count(Severity::Warning));
if errors + warnings > 0 {
let style = |count, style| if count > 0 { style } else { Style::BarDim };
left.push((style(errors, Style::BarError), format!(" E:{errors}")));
left.push((style(warnings, Style::BarWarn), format!(" W:{warnings}")));
}
}
let mut right: Vec<(Style, String)> = Vec::new();
if let Some(branch) = &self.branch {
right.push((Style::BarDim, format!("{branch} ")));
}
if let Some(language) = self.language {
right.push((Style::BarDim, format!("{} ", language.name())));
}
right.push((Style::Bar, format!("Ln {}, Col {}", self.cursor_y + 1, self.cursor_x + 1)));
let cells = |parts: &[(Style, String)]| -> usize {
parts.iter().map(|(_, text)| widen(text).chars().count()).sum()
};
while right.len() > 1 && cells(&left) + 1 + cells(&right) > width {
right.remove(0);
}
if cells(&left) + 1 + cells(&right) > width {
right.clear();
}
let gap = width.saturating_sub(cells(&left) + cells(&right));
left.push((Style::Bar, " ".repeat(gap)));
left.extend(right);
let mut row = Row::new();
let mut room = width;
for (style, text) in left {
let text: String = widen(&text).chars().take(room).collect();
room -= text.chars().count();
if !text.is_empty() {
row.push(Span::new(style, text));
}
}
row
}
pub fn branch_columns(&self, width: usize) -> Option<(usize, usize)> {
let name = format!("{} ", self.branch.as_ref()?);
let mut at = 0;
for span in self.status_row(width) {
let cells = span.text.chars().count();
if span.style == Style::BarDim && span.text == widen(&name) {
return Some((at, at + cells - 2));
}
at += cells;
}
None
}
#[cfg(test)]
pub(super) fn status_line(&self, width: usize) -> String {
self.status_row(width).iter().map(|span| span.text.as_str()).collect()
}
pub(super) fn mark_on(&self, y: usize) -> Mark {
let Some(base) = &self.git_base else {
return Mark::Same;
};
let marks = self
.marks
.get_or_init(|| diff::marks(base, &self.document.lines));
marks.get(y).copied().unwrap_or_default()
}
pub(super) fn render_line(&self, y: usize, gutter: usize, text_width: usize) -> Row {
let mut row = Row::new();
let mut number_width = gutter - 1 - self.git_base.is_some() as usize;
if self.show_diagnostics {
number_width -= 1;
row.push(match self.diagnostic_on(y).map(|d| d.severity) {
Some(Severity::Error) => Span::new(Style::Error, "E"),
Some(Severity::Warning) => Span::new(Style::Warning, "W"),
Some(Severity::Info) => Span::new(Style::Dim, "i"),
None => Span::new(Style::Plain, " "),
});
}
let marker = if self.folds.end_of(y).is_some() {
'+'
} else if self.blocks().end(y).is_some() {
'-'
} else {
' '
};
let current = y == self.cursor_y;
row.push(Span::new(
Style::LineNumber(current),
format!("{:>number_width$}{marker}", y + 1),
));
if self.git_base.is_some() {
row.push(match self.mark_on(y) {
Mark::Added => Span::new(Style::Colored(Color::Green), "▎"),
Mark::Modified => Span::new(Style::Colored(Color::Yellow), "▎"),
Mark::RemovedBelow => Span::new(Style::Colored(Color::Red), "▁"),
Mark::RemovedAbove => Span::new(Style::Colored(Color::Red), "▔"),
Mark::Same if y == self.cursor_y => {
let on_line = Decoration { current: true, ..Decoration::default() };
Span::new(Style::Code(on_line), " ")
}
Mark::Same => Span::new(Style::Plain, " "),
});
}
let decorations = self.decorations(y);
let line = cells(&self.display_line(y));
let last = (self.col_offset + text_width).min(line.len());
let mut visible: Vec<(usize, char)> = line.get(self.col_offset..last).unwrap_or_default().to_vec();
if let Some(first) = visible.first_mut().filter(|cell| cell.1 == WIDE_PAD) {
first.1 = ' ';
}
if line.get(last).is_some_and(|cell| cell.1 == WIDE_PAD)
&& let Some(cut) = visible.last_mut()
{
cut.1 = ' ';
}
let mut piece: Option<(Decoration, String)> = None;
for (x, c) in visible {
let mut decoration = decorations.get(x).copied().unwrap_or_default();
decoration.current = current;
match &mut piece {
Some((same, text)) if *same == decoration => text.push(c),
_ => {
row.extend(piece.take().map(code_span));
piece = Some((decoration, c.to_string()));
}
}
}
row.extend(piece.map(code_span));
if current {
let rest = Decoration { current: true, ..Decoration::default() };
row.push(Span::new(Style::Code(rest), ""));
}
row
}
pub(super) fn decorations(&self, y: usize) -> Vec<Decoration> {
let line = &self.document.lines[y];
let len = line.chars().count();
let mut decorations = vec![Decoration::default(); len];
let mut scanned = Vec::new();
if let Some(language) = self.language {
let state = self.line_states.get(y).copied().unwrap_or_default();
highlight::lex_line(line, language, state, &mut scanned);
}
for token in scanned.iter().chain(self.highlights.on(y)) {
for decoration in &mut decorations[token.start.min(len)..token.end.min(len)] {
decoration.kind = token.kind;
}
}
if let Some((start, end)) = self.selection()
&& (start.1..=end.1).contains(&y)
{
let from = if y == start.1 { start.0 } else { 0 };
let to = if y == end.1 { end.0 } else { len };
for decoration in &mut decorations[from.min(len)..to.min(len)] {
decoration.marked = true;
}
}
if let Some(text) = self.shown_query() {
let width = text.chars().count();
for start in search::matches(line, text) {
for decoration in &mut decorations[start..(start + width).min(len)] {
decoration.marked = true;
}
}
}
let encoding = self.encoding();
for diagnostic in &self.diagnostics {
if diagnostic.line > y {
break;
}
if diagnostic.end_line < y {
continue;
}
let start = if diagnostic.line == y {
encoding.to_chars(line, diagnostic.start)
} else {
0
};
let mut end = if diagnostic.end_line == y {
encoding.to_chars(line, diagnostic.end)
} else {
len
};
if diagnostic.line == diagnostic.end_line {
end = end.max(start + 1).min(len);
}
let underlined = matches!(diagnostic.severity, Severity::Error | Severity::Warning);
for decoration in decorations.iter_mut().take(end).skip(start) {
decoration.underlined |= underlined;
decoration.faded |= diagnostic.unnecessary;
decoration.struck |= diagnostic.deprecated;
}
}
decorations
}
pub fn render(&self, width: usize, height: usize) -> Vec<Row> {
let text_rows = height.saturating_sub(1);
let gutter = self.gutter_width();
let text_width = width.saturating_sub(gutter);
let mut rows = Vec::with_capacity(height);
let mut next_line = Some(self.row_offset).filter(|y| *y < self.document.len());
for row in 0..text_rows {
if let Some(y) = next_line {
rows.push(self.render_line(y, gutter, text_width));
next_line = self.folds.next_visible(y, self.document.len());
} else if self.document.is_empty() && row == text_rows / 3 {
let msg = concat!("curd editor -- v", env!("CARGO_PKG_VERSION"));
let padding = width.saturating_sub(msg.len()) / 2;
let text = format!("~{}{}", " ".repeat(padding), msg);
rows.push(vec![Span::new(Style::Plain, text)]);
} else {
rows.push(vec![Span::new(Style::Plain, "~")]);
}
}
self.render_completion(&mut rows, width, text_rows);
let panel = self.info.len().min(text_rows / 2);
if panel > 0 {
let cursor_row = self.folds.rows_between(self.row_offset, self.cursor_y);
let top = if cursor_row >= text_rows - panel { 0 } else { text_rows - panel };
for (offset, line) in self.info.iter().take(panel).enumerate() {
let text = fit(&format!(" {line}"), width);
rows[top + offset] = vec![Span::new(Style::Menu, text)];
}
}
if height > 0 {
rows.push(self.status_row(width));
}
rows
}
pub(super) fn render_completion(&self, rows: &mut [Row], width: usize, text_rows: usize) {
let Some(completion) = &self.completion else {
return;
};
let cursor_row = self.folds.rows_between(self.row_offset, self.cursor_y);
let below = text_rows.saturating_sub(cursor_row + 1);
let wanted = completion.shown.len().min(MENU_ROWS);
let (top, count) = if below >= wanted || below >= cursor_row {
(cursor_row + 1, wanted.min(below))
} else {
let count = wanted.min(cursor_row);
(cursor_row - count, count)
};
let first = (completion.selected + 1).saturating_sub(count);
let lines: Vec<String> = completion.shown[first..first + count]
.iter()
.map(|index| {
let item = &completion.items[*index];
format!(" {} {}", item.label, item.detail).trim_end().to_string() + " "
})
.collect();
let widest = lines.iter().map(|line| line.chars().count()).max().unwrap_or(0);
let menu_width = widest.min(MENU_WIDTH).min(width);
let x = (self.gutter_width() + self.column_of(completion.start, completion.y))
.saturating_sub(self.col_offset + 1)
.min(width - menu_width);
for (offset, line) in lines.iter().enumerate() {
let style = if first + offset == completion.selected {
Style::Selected
} else {
Style::Menu
};
overlay(&mut rows[top + offset], x, &Span::new(style, fit(line, menu_width)));
}
}
pub fn cursor_on_screen(&self) -> (usize, usize) {
if let Some(prompt) = &self.prompt {
let typed = widen(&self.prompt_label(prompt.kind)).chars().count()
+ widen(&prompt.text).chars().count();
return (typed, self.page_rows);
}
let column = self.column_of(self.cursor_x, self.cursor_y);
(
self.gutter_width() + column.saturating_sub(self.col_offset),
self.folds.rows_between(self.row_offset, self.cursor_y),
)
}
pub fn click(&mut self, x: usize, y: usize) {
self.anchor = None;
let on_a_line = self.point_at(x, y);
let foldable = self.folds.end_of(self.cursor_y).is_some()
|| self.blocks().end(self.cursor_y).is_some();
if on_a_line && x < self.gutter_width() && foldable {
self.toggle_fold();
}
}
pub fn drag(&mut self, x: usize, y: usize) {
self.anchor.get_or_insert((self.cursor_x, self.cursor_y));
self.point_at(x, y);
}
pub(super) fn point_at(&mut self, x: usize, y: usize) -> bool {
self.message.clear();
self.info.clear();
self.completion = None;
let mut line = self.row_offset;
let mut on_a_line = line < self.document.len();
for _ in 0..y {
match self.folds.next_visible(line, self.document.len()) {
Some(next) => line = next,
None => {
on_a_line = false;
break;
}
}
}
if line < self.document.len() {
self.cursor_y = line;
let column = x.saturating_sub(self.gutter_width()) + self.col_offset;
self.cursor_x = self.char_at(column, line);
}
on_a_line
}
pub fn wheel(&mut self, lines: isize) {
self.completion = None;
for _ in 0..lines.unsigned_abs() {
let next = if lines > 0 {
self.folds.next_visible(self.cursor_y, self.document.len())
} else {
self.folds.prev_visible(self.cursor_y)
};
match next {
Some(y) => self.cursor_y = y,
None => break,
}
}
self.clamp_cursor_x();
}
}