use std::cmp::Ordering;
use super::Cursor;
use super::line::{
byte_at_display, clamp_boundary, first_non_blank, is_diff_change_line, is_pair_character,
last_column, next_column,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct Position {
pub(super) line: usize,
pub(super) column: usize,
}
impl From<Position> for Cursor {
fn from(value: Position) -> Self {
Self::new(value.line, value.column)
}
}
#[derive(Clone, Copy)]
pub(super) enum WordMotion {
StartForward,
EndForward,
StartBackward,
EndBackward,
}
#[derive(Clone, Copy)]
pub(super) enum WordStyle {
Word,
BigWord,
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub(super) enum ScanDirection {
Forward,
Backward,
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum SentenceStart {
Punctuation,
Paragraph,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PreprocessorDirective {
If,
Else,
EndIf,
}
pub(super) struct TextBuffer<'a> {
lines: &'a [&'a str],
}
impl<'a> TextBuffer<'a> {
pub(super) fn new(lines: &'a [&'a str]) -> Self {
Self { lines }
}
pub(super) fn len(&self) -> usize {
self.lines.len().max(1)
}
pub(super) fn last_line(&self) -> usize {
self.len().saturating_sub(1)
}
pub(super) fn line(&self, index: usize) -> &str {
self.lines.get(index).copied().unwrap_or("")
}
pub(super) fn clamp(&self, position: Cursor) -> Position {
let line = position.line().min(self.last_line());
let text = self.line(line);
let mut column = position.byte_column().min(text.len());
while !text.is_char_boundary(column) {
column = column.saturating_sub(1);
}
if column == text.len() && !text.is_empty() {
column = last_column(text);
}
Position { line, column }
}
pub(super) fn move_lines(&self, cursor: Position, delta: isize) -> Position {
let line = cursor
.line
.saturating_add_signed(delta)
.min(self.last_line());
self.move_to_line(cursor, line)
}
pub(super) fn move_to_line(&self, cursor: Position, line: usize) -> Position {
let line = line.min(self.last_line());
let text = self.line(line);
let mut column = cursor.column.min(last_column(text));
while !text.is_char_boundary(column) {
column = column.saturating_sub(1);
}
Position { line, column }
}
pub(super) fn move_lines_to_display(
&self,
cursor: Position,
delta: isize,
display_column: usize,
) -> Position {
let line = cursor
.line
.saturating_add_signed(delta)
.min(self.last_line());
self.move_to_line_display(cursor, line, display_column)
}
pub(super) fn move_to_line_display(
&self,
_cursor: Position,
line: usize,
display_column: usize,
) -> Position {
let line = line.min(self.last_line());
let text = self.line(line);
let column = if display_column == usize::MAX {
last_column(text)
} else {
byte_at_display(text, display_column)
};
Position {
line,
column: column.min(last_column(text)),
}
}
pub(super) fn byte_offset(&self, one_based: usize) -> Position {
let mut remaining = one_based.saturating_sub(1);
for line in 0..self.len() {
let text = self.line(line);
if remaining <= text.len() {
return Position {
line,
column: clamp_boundary(text, remaining).min(last_column(text)),
};
}
if line == self.last_line() {
return Position {
line,
column: last_column(text),
};
}
remaining = remaining.saturating_sub(text.len().saturating_add(1));
}
Position {
line: self.last_line(),
column: last_column(self.line(self.last_line())),
}
}
pub(super) fn word_motion(
&self,
cursor: Position,
mut count: usize,
motion: WordMotion,
style: WordStyle,
) -> Position {
let direction = if matches!(motion, WordMotion::StartForward | WordMotion::EndForward) {
ScanDirection::Forward
} else {
ScanDirection::Backward
};
for line in self.line_indices(cursor.line, direction) {
let text = self.line(line);
if text.is_empty() && !matches!(motion, WordMotion::EndForward) {
let position = Position { line, column: 0 };
if position != cursor {
count -= 1;
if count == 0 {
return position;
}
}
continue;
}
let mut chars = line_characters(text, line, cursor, direction).peekable();
while let Some((edge, character)) = chars.next() {
let class = CharacterClass::of(character, style);
if class == CharacterClass::Space {
continue;
}
let mut opposite = edge;
while chars
.peek()
.is_some_and(|(_, c)| CharacterClass::of(*c, style) == class)
{
if let Some((column, _)) = chars.next() {
opposite = column;
}
}
let column =
if matches!(motion, WordMotion::StartForward | WordMotion::StartBackward) {
edge.min(opposite)
} else {
edge.max(opposite)
};
let position = Position { line, column };
if position != cursor {
count -= 1;
if count == 0 {
return position;
}
}
}
}
if direction == ScanDirection::Forward {
Position {
line: self.last_line(),
column: last_column(self.line(self.last_line())),
}
} else {
Position { line: 0, column: 0 }
}
}
pub(super) fn sentence_forward(&self, cursor: Position) -> Position {
if self.line(cursor.line).is_empty() {
for line in cursor.line.saturating_add(1)..self.len() {
if !self.line(line).is_empty() {
return self.skip_sentence_blanks(Position { line, column: 0 });
}
}
} else {
for line in cursor.line..self.len() {
let text = self.line(line);
if text.is_empty() {
return Position { line, column: 0 };
}
for (column, _) in line_characters(text, line, cursor, ScanDirection::Forward) {
let candidate = Position { line, column };
let boundary = self.sentence_start(candidate);
if candidate != cursor
&& boundary.is_some()
&& !(line == cursor.line && boundary == Some(SentenceStart::Paragraph))
{
return candidate;
}
}
}
}
Position {
line: self.last_line(),
column: last_column(self.line(self.last_line())),
}
}
pub(super) fn sentence_backward(&self, cursor: Position) -> Position {
let mut skipping_empty = self.line(cursor.line).is_empty();
for line in (0..=cursor.line).rev() {
let text = self.line(line);
if text.is_empty() {
if !skipping_empty {
return Position { line, column: 0 };
}
continue;
}
skipping_empty = false;
for (column, _) in line_characters(text, line, cursor, ScanDirection::Backward) {
let candidate = Position { line, column };
if candidate != cursor && self.sentence_start(candidate).is_some() {
return candidate;
}
}
}
Position { line: 0, column: 0 }
}
fn skip_sentence_blanks(&self, cursor: Position) -> Position {
for line in cursor.line..self.len() {
let text = self.line(line);
if text.is_empty() {
return Position { line, column: 0 };
}
if let Some((column, _)) = text.char_indices().find(|(_, c)| !c.is_whitespace()) {
return Position { line, column };
}
}
Position {
line: self.last_line(),
column: last_column(self.line(self.last_line())),
}
}
fn sentence_start(&self, position: Position) -> Option<SentenceStart> {
let text = self.line(position.line);
if text[position.column..].starts_with(char::is_whitespace) {
return None;
}
let mut before = text[..position.column].chars().rev();
if position.column > 0 && !before.next().is_some_and(char::is_whitespace) {
return None;
}
let mut closing = false;
for line in (0..=position.line).rev() {
let prefix = if line == position.line {
&text[..position.column]
} else {
self.line(line)
};
if line < position.line && prefix.is_empty() {
return Some(SentenceStart::Paragraph);
}
for c in prefix.chars().rev() {
if !closing && c.is_whitespace() {
continue;
}
if matches!(c, ')' | ']' | '\"' | '\'') {
closing = true;
continue;
}
return matches!(c, '.' | '!' | '?').then_some(SentenceStart::Punctuation);
}
if closing {
return None;
}
}
None
}
pub(super) fn paragraph_forward(&self, cursor: Position) -> Position {
let mut line = cursor.line;
if self.line(line).is_empty() {
while line < self.len() && self.line(line).is_empty() {
line = line.saturating_add(1);
}
} else {
line = line.saturating_add(1);
}
while line < self.len() && !self.line(line).is_empty() {
line = line.saturating_add(1);
}
if line < self.len() {
Position { line, column: 0 }
} else {
let line = self.last_line();
Position {
line,
column: last_column(self.line(line)),
}
}
}
pub(super) fn paragraph_backward(&self, cursor: Position) -> Position {
let mut line = cursor.line;
if self.line(line).is_empty() {
while line > 0 && self.line(line.saturating_sub(1)).is_empty() {
line = line.saturating_sub(1);
}
line = line.saturating_sub(1);
} else if line > 0 && self.line(line.saturating_sub(1)).is_empty() {
return Position {
line: line.saturating_sub(1),
column: 0,
};
}
while line > 0 && !self.line(line.saturating_sub(1)).is_empty() {
line = line.saturating_sub(1);
}
if line > 0 {
line = line.saturating_sub(1);
}
Position { line, column: 0 }
}
pub(super) fn section(
&self,
cursor: Position,
direction: ScanDirection,
target: char,
) -> Position {
let found = if direction == ScanDirection::Forward {
((cursor.line + 1)..self.len()).find(|line| self.line(*line).starts_with(target))
} else {
(0..cursor.line)
.rev()
.find(|line| self.line(*line).starts_with(target))
};
let line = found.unwrap_or(if direction == ScanDirection::Forward {
self.last_line()
} else {
0
});
Position {
line,
column: first_non_blank(self.line(line)),
}
}
pub(super) fn matching_pair(
&self,
cursor: Position,
direction: ScanDirection,
) -> Option<Position> {
let text = self.line(cursor.line);
let directive = preprocessor_directive(text);
if direction == ScanDirection::Backward {
let (column, _) =
line_characters(text, cursor.line, cursor, direction).find(|(column, c)| {
is_pair_character(*c)
|| text[*column..].starts_with("/*")
|| text[*column..].starts_with("*/")
|| directive.is_some_and(|(at, _)| at == *column)
})?;
return self.matching_pair(
Position {
line: cursor.line,
column,
},
ScanDirection::Forward,
);
}
if let Some((column, kind)) = directive
&& cursor.column <= column
{
return self.preprocessor_match(cursor.line, kind);
}
for column in [cursor.column, cursor.column.saturating_sub(1)] {
let tail = text.get(column..).unwrap_or("");
let origin = Position {
line: cursor.line,
column,
};
if tail.starts_with("/*") {
return self.comment_match(origin, ScanDirection::Forward);
}
if tail.starts_with("*/") {
return self.comment_match(origin, ScanDirection::Backward);
}
}
let found = line_characters(text, cursor.line, cursor, direction)
.find(|(_, c)| is_pair_character(*c));
if let Some((column, character)) = found {
let start = Position {
line: cursor.line,
column,
};
let (target, delta) = pair_for(character)?;
let direction = if delta > 0 {
ScanDirection::Forward
} else {
ScanDirection::Backward
};
let mut depth = 0usize;
for (position, c) in self.characters(start, direction).skip(1) {
if c == character {
depth = depth.saturating_add(1);
} else if c == target {
if depth == 0 {
return Some(position);
}
depth -= 1;
}
}
None
} else {
directive.and_then(|(_, kind)| self.preprocessor_match(cursor.line, kind))
}
}
fn comment_match(&self, origin: Position, direction: ScanDirection) -> Option<Position> {
let needle = if direction == ScanDirection::Forward {
"*/"
} else {
"/*"
};
for line in self.line_indices(origin.line, direction) {
let text = self.line(line);
let column = if direction == ScanDirection::Forward {
let start = if line == origin.line {
origin.column.saturating_add(1)
} else {
0
};
text.get(start..)
.and_then(|tail| tail.find(needle))
.map(|column| start + column + 1)
} else {
let end = if line == origin.line {
origin.column
} else {
text.len()
};
text[..end].rfind(needle)
};
if let Some(column) = column {
return Some(Position { line, column });
}
}
None
}
fn preprocessor_match(
&self,
origin_line: usize,
origin: PreprocessorDirective,
) -> Option<Position> {
if origin == PreprocessorDirective::EndIf {
let mut depth = 0usize;
for line in (0..origin_line).rev() {
let Some((column, directive)) = preprocessor_directive(self.line(line)) else {
continue;
};
match directive {
PreprocessorDirective::EndIf => depth = depth.saturating_add(1),
PreprocessorDirective::If if depth == 0 => {
return Some(Position { line, column });
}
PreprocessorDirective::If => depth = depth.saturating_sub(1),
PreprocessorDirective::Else => {}
}
}
return None;
}
let mut depth = 0usize;
for line in origin_line.saturating_add(1)..self.len() {
let Some((column, directive)) = preprocessor_directive(self.line(line)) else {
continue;
};
match directive {
PreprocessorDirective::If => depth = depth.saturating_add(1),
PreprocessorDirective::EndIf if depth == 0 => {
return Some(Position { line, column });
}
PreprocessorDirective::EndIf => depth = depth.saturating_sub(1),
PreprocessorDirective::Else if depth == 0 => {
return Some(Position { line, column });
}
PreprocessorDirective::Else => {}
}
}
None
}
pub(super) fn unmatched_open(&self, cursor: Position, open: char) -> Position {
let close = match open {
'(' => ')',
'{' => '}',
'[' => ']',
_ => return cursor,
};
let mut depth = 0usize;
for (position, character) in self
.characters(cursor, ScanDirection::Backward)
.filter(|(at, _)| *at != cursor)
{
if character == close {
depth = depth.saturating_add(1);
} else if character == open {
if depth == 0 {
return position;
}
depth = depth.saturating_sub(1);
}
}
cursor
}
pub(super) fn unmatched_close(&self, cursor: Position, close: char) -> Position {
let open = match close {
')' => '(',
'}' => '{',
']' => '[',
_ => return cursor,
};
let mut depth = 0usize;
for (position, character) in self
.characters(cursor, ScanDirection::Forward)
.filter(|(at, _)| *at != cursor)
{
if character == open {
depth = depth.saturating_add(1);
} else if character == close {
if depth == 0 {
return position;
}
depth = depth.saturating_sub(1);
}
}
cursor
}
pub(super) fn brace(
&self,
cursor: Position,
direction: ScanDirection,
target: char,
) -> Position {
self.characters(cursor, direction)
.filter(|(at, _)| *at != cursor)
.find(|(_, character)| *character == target)
.map_or(cursor, |(position, _)| position)
}
pub(super) fn preprocessor(&self, cursor: Position, direction: ScanDirection) -> Position {
let mut depth = 0usize;
if direction == ScanDirection::Forward {
for line in cursor.line.saturating_add(1)..self.len() {
let Some((column, directive)) = preprocessor_directive(self.line(line)) else {
continue;
};
match directive {
PreprocessorDirective::If => depth = depth.saturating_add(1),
PreprocessorDirective::EndIf if depth == 0 => {
return Position { line, column };
}
PreprocessorDirective::EndIf => depth = depth.saturating_sub(1),
PreprocessorDirective::Else if depth == 0 => {
return Position { line, column };
}
PreprocessorDirective::Else => {}
}
}
} else {
for line in (0..cursor.line).rev() {
let Some((column, directive)) = preprocessor_directive(self.line(line)) else {
continue;
};
match directive {
PreprocessorDirective::EndIf => depth = depth.saturating_add(1),
PreprocessorDirective::If if depth == 0 => {
return Position { line, column };
}
PreprocessorDirective::If => depth = depth.saturating_sub(1),
PreprocessorDirective::Else if depth == 0 => {
return Position { line, column };
}
PreprocessorDirective::Else => {}
}
}
}
cursor
}
pub(super) fn comment(&self, cursor: Position, direction: ScanDirection) -> Position {
let needle = if direction == ScanDirection::Forward {
"*/"
} else {
"/*"
};
let mut candidates = Vec::new();
for line in 0..self.len() {
let text = self.line(line);
for (column, _) in text.match_indices(needle) {
candidates.push(Position { line, column });
}
}
if direction == ScanDirection::Forward {
candidates
.into_iter()
.find(|position| compare(*position, cursor) == Ordering::Greater)
.map(|mut position| {
position.column = next_column(self.line(position.line), position.column);
position
})
.unwrap_or(cursor)
} else {
candidates
.into_iter()
.rev()
.find(|position| compare(*position, cursor) == Ordering::Less)
.unwrap_or(cursor)
}
}
pub(super) fn diff_change(&self, cursor: Position, direction: ScanDirection) -> Position {
let mut starts = (0..self.len()).filter(|line| {
is_diff_change_line(self.line(*line))
&& (*line == 0 || !is_diff_change_line(self.line(line.saturating_sub(1))))
});
let found = if direction == ScanDirection::Forward {
starts.find(|line| *line > cursor.line)
} else {
starts.rfind(|line| *line < cursor.line)
};
found.map_or(cursor, |line| Position { line, column: 0 })
}
fn line_indices(&self, start: usize, direction: ScanDirection) -> impl Iterator<Item = usize> {
let length = if direction == ScanDirection::Forward {
self.len() - start
} else {
start + 1
};
(0..length).map(move |offset| {
if direction == ScanDirection::Forward {
start + offset
} else {
start - offset
}
})
}
fn characters(
&self,
cursor: Position,
direction: ScanDirection,
) -> impl Iterator<Item = (Position, char)> {
self.line_indices(cursor.line, direction)
.flat_map(move |line| {
line_characters(self.line(line), line, cursor, direction)
.map(move |(column, character)| (Position { line, column }, character))
})
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CharacterClass {
Space,
Keyword,
Other,
}
impl CharacterClass {
fn of(character: char, style: WordStyle) -> Self {
if character.is_whitespace() {
Self::Space
} else if matches!(style, WordStyle::BigWord)
|| character.is_alphanumeric()
|| character == '_'
{
Self::Keyword
} else {
Self::Other
}
}
}
fn compare(left: Position, right: Position) -> Ordering {
(left.line, left.column).cmp(&(right.line, right.column))
}
fn line_characters(
text: &str,
line: usize,
cursor: Position,
direction: ScanDirection,
) -> impl Iterator<Item = (usize, char)> {
let start = if line == cursor.line && direction == ScanDirection::Forward {
cursor.column
} else {
0
};
let end = if line == cursor.line && direction == ScanDirection::Backward {
cursor.column
+ text[cursor.column..]
.chars()
.next()
.map_or(0, char::len_utf8)
} else {
text.len()
};
let mut chars = text[start..end].char_indices();
std::iter::from_fn(move || {
let next = if direction == ScanDirection::Forward {
chars.next()
} else {
chars.next_back()
};
next.map(|(column, c)| (column + start, c))
})
}
fn preprocessor_directive(line: &str) -> Option<(usize, PreprocessorDirective)> {
let column = first_non_blank(line);
let directive = line.get(column..)?.strip_prefix('#')?.trim_start();
let kind = if directive.starts_with("if") {
PreprocessorDirective::If
} else if directive.starts_with("else") || directive.starts_with("elif") {
PreprocessorDirective::Else
} else if directive.starts_with("endif") {
PreprocessorDirective::EndIf
} else {
return None;
};
Some((column, kind))
}
fn pair_for(character: char) -> Option<(char, isize)> {
match character {
'(' => Some((')', 1)),
'[' => Some((']', 1)),
'{' => Some(('}', 1)),
')' => Some(('(', -1)),
']' => Some(('[', -1)),
'}' => Some(('{', -1)),
_ => None,
}
}