Skip to content

Commit

Permalink
Unify list of PAIRS in helix-core
Browse files Browse the repository at this point in the history
Merge the list of pairs from `surround.rs` and `match_brackets.rs`. Move all functions related to `PAIRS` to `match_brackets.rs`.
  • Loading branch information
woojiq committed Oct 13, 2023
1 parent 4806508 commit 9382224
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 50 deletions.
53 changes: 41 additions & 12 deletions helix-core/src/match_brackets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,17 @@ use crate::Syntax;
const MAX_PLAINTEXT_SCAN: usize = 10000;
const MATCH_LIMIT: usize = 16;

// Limit matching pairs to only ( ) { } [ ] < > ' ' " "
const PAIRS: &[(char, char)] = &[
// Limit matching pairs
pub const PAIRS: &[(char, char)] = &[
('(', ')'),
('{', '}'),
('[', ']'),
('<', '>'),
('\'', '\''),
('\"', '\"'),
('«', '»'),
('「', '」'),
('(', ')'),
];

/// Returns the position of the matching bracket under cursor.
Expand All @@ -36,16 +39,16 @@ pub fn find_matching_bracket(syntax: &Syntax, doc: RopeSlice, pos: usize) -> Opt
find_pair(syntax, doc, pos, false)
}

// Returns the position of the bracket that is closing the current scope.
//
// If the cursor is on an opening or closing bracket, the function
// behaves equivalent to [`find_matching_bracket`].
//
// If the cursor position is within a scope, the function searches
// for the surrounding scope that is surrounded by brackets and
// returns the position of the closing bracket for that scope.
//
// If no surrounding scope is found, the function returns `None`.
/// Returns the position of the bracket that is closing the current scope.
///
/// If the cursor is on an opening or closing bracket, the function
/// behaves equivalent to [`find_matching_bracket`].
///
/// If the cursor position is within a scope, the function searches
/// for the surrounding scope that is surrounded by brackets and
/// returns the position of the closing bracket for that scope.
///
/// If no surrounding scope is found, the function returns `None`.
#[must_use]
pub fn find_matching_bracket_fuzzy(syntax: &Syntax, doc: RopeSlice, pos: usize) -> Option<usize> {
find_pair(syntax, doc, pos, true)
Expand Down Expand Up @@ -187,6 +190,32 @@ pub fn find_matching_bracket_plaintext(doc: RopeSlice, cursor_pos: usize) -> Opt
None
}

/// Given any char in [`PAIRS`], return the open and closing chars. If not found in
/// [`PAIRS`] return (ch, ch).
///
/// ```
/// use helix_core::match_brackets::get_pair;
///
/// assert_eq!(get_pair('['), ('[', ']'));
/// assert_eq!(get_pair('}'), ('{', '}'));
/// assert_eq!(get_pair('"'), ('"', '"'));
/// ```
pub fn get_pair(ch: char) -> (char, char) {
PAIRS
.iter()
.find(|(open, close)| *open == ch || *close == ch)
.copied()
.unwrap_or((ch, ch))
}

pub fn is_open_pair(ch: char) -> bool {
PAIRS.iter().any(|(open, _)| *open == ch)
}

pub fn is_close_pair(ch: char) -> bool {
PAIRS.iter().any(|(_, close)| *close == ch)
}

fn is_valid_bracket(c: char) -> bool {
PAIRS.iter().any(|(l, r)| *l == c || *r == c)
}
Expand Down
41 changes: 6 additions & 35 deletions helix-core/src/surround.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,14 @@ use std::fmt::Display;

use crate::{
graphemes::next_grapheme_boundary,
match_brackets::{find_matching_bracket, find_matching_bracket_fuzzy},
match_brackets::{
find_matching_bracket, find_matching_bracket_fuzzy, get_pair, is_close_pair, is_open_pair,
},
movement::Direction,
search, Range, Selection, Syntax,
};
use ropey::RopeSlice;

pub const PAIRS: &[(char, char)] = &[
('(', ')'),
('[', ']'),
('{', '}'),
('<', '>'),
('«', '»'),
('「', '」'),
('(', ')'),
];

#[derive(Debug, PartialEq, Eq)]
pub enum Error {
PairNotFound,
Expand All @@ -39,27 +31,11 @@ impl Display for Error {

type Result<T> = std::result::Result<T, Error>;

/// Given any char in [PAIRS], return the open and closing chars. If not found in
/// [PAIRS] return (ch, ch).
///
/// ```
/// use helix_core::surround::get_pair;
/// Find the position of surround pairs of any [`crate::match_brackets::PAIRS`] using tree-sitter when possible.
///
/// assert_eq!(get_pair('['), ('[', ']'));
/// assert_eq!(get_pair('}'), ('{', '}'));
/// assert_eq!(get_pair('"'), ('"', '"'));
/// ```
pub fn get_pair(ch: char) -> (char, char) {
PAIRS
.iter()
.find(|(open, close)| *open == ch || *close == ch)
.copied()
.unwrap_or((ch, ch))
}

/// Find the position of surround pairs of any [`PAIRS`] using tree-sitter when possible.
/// # Returns
///
/// Returns a tuple `(anchor, head)`, meaning it is not always ordered.
/// Tuple `(anchor, head)`, meaning it is not always ordered.
pub fn find_nth_closest_pairs_pos(
syntax: Option<&Syntax>,
text: RopeSlice,
Expand All @@ -78,8 +54,6 @@ fn find_nth_closest_pairs_ts(
range: Range,
skip: usize,
) -> Result<(usize, usize)> {
let is_close_pair = |ch| PAIRS.iter().any(|(_, close)| *close == ch);

let cursor = range.cursor(text);
let Some(mut closing) = find_matching_bracket_fuzzy(syntax, text, cursor) else {
return Err(Error::PairNotFound);
Expand Down Expand Up @@ -113,9 +87,6 @@ fn find_nth_closest_pairs_plain(
range: Range,
mut skip: usize,
) -> Result<(usize, usize)> {
let is_open_pair = |ch| PAIRS.iter().any(|(open, _)| *open == ch);
let is_close_pair = |ch| PAIRS.iter().any(|(_, close)| *close == ch);

let mut stack = Vec::with_capacity(2);
let pos = range.from();
let mut close_pos = pos.saturating_sub(1);
Expand Down
6 changes: 3 additions & 3 deletions helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5200,7 +5200,7 @@ fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) {
("a", "Argument/parameter (tree-sitter)"),
("c", "Comment (tree-sitter)"),
("T", "Test (tree-sitter)"),
("m", "Closest surrounding pair"),
("m", "Closest surrounding pair (tree-sitter)"),
(" ", "... or any character acting as a pair"),
];

Expand All @@ -5213,7 +5213,7 @@ fn surround_add(cx: &mut Context) {
// surround_len is the number of new characters being added.
let (open, close, surround_len) = match event.char() {
Some(ch) => {
let (o, c) = surround::get_pair(ch);
let (o, c) = match_brackets::get_pair(ch);
let mut open = Tendril::new();
open.push(o);
let mut close = Tendril::new();
Expand Down Expand Up @@ -5286,7 +5286,7 @@ fn surround_replace(cx: &mut Context) {
Some(to) => to,
None => return doc.set_selection(view.id, selection),
};
let (open, close) = surround::get_pair(to);
let (open, close) = match_brackets::get_pair(to);
let transaction = Transaction::change(
doc.text(),
change_pos.iter().enumerate().map(|(i, &pos)| {
Expand Down

0 comments on commit 9382224

Please sign in to comment.