use std::collections::HashMap;
use crate::styled_buffer::StyledBuffer;
pub const DEFAULT_PAIRS: &[(char, char)] = &[
('(', ')'),
('{', '}'),
('[', ']'),
('\'', '\''),
('"', '"'),
('`', '`'),
];
pub trait AutoPair {
fn complete_pair(&self, buffer: &mut StyledBuffer);
}
pub struct DefaultAutoPair {
pairs: HashMap<char, char>,
}
impl Default for DefaultAutoPair {
fn default() -> Self {
let mut pairs = HashMap::with_capacity(DEFAULT_PAIRS.len());
for pair in DEFAULT_PAIRS {
pairs.insert(pair.0, pair.1);
}
Self { pairs }
}
}
impl DefaultAutoPair {
pub fn with_pairs(pairs: HashMap<char, char>) -> Self {
Self { pairs }
}
}
impl AutoPair for DefaultAutoPair {
fn complete_pair(&self, buffer: &mut StyledBuffer) {
if buffer.position() == buffer.len() {
if let Some(last_char) = buffer.buffer().last() {
if let Some(pair) = self.pairs.get(last_char) {
buffer.insert_char(*pair);
buffer.move_char_left();
}
}
}
}
}