Skip to content

Commit

Permalink
Merge branch 'master' into clear_jump_list
Browse files Browse the repository at this point in the history
  • Loading branch information
grv07 committed Jun 5, 2023
2 parents 4264542 + a2b8cfd commit dc57716
Show file tree
Hide file tree
Showing 11 changed files with 276 additions and 55 deletions.
1 change: 1 addition & 0 deletions book/src/generated/lang-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
| beancount || | | |
| bibtex || | | `texlab` |
| bicep || | | `bicep-langserver` |
| blueprint || | | `blueprint-compiler` |
| c |||| `clangd` |
| c-sharp ||| | `OmniSharp` |
| cabal | | | | |
Expand Down
4 changes: 3 additions & 1 deletion book/src/install.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,9 +204,11 @@ HELIX_RUNTIME=/home/user-name/src/helix/runtime
Or, create a symlink in `~/.config/helix` that links to the source code directory:

```sh
ln -s $PWD/runtime ~/.config/helix/runtime
ln -Ts $PWD/runtime ~/.config/helix/runtime
```

If the above command fails to create a symbolic link because the file exists either move `~/.config/helix/runtime` to a new location or delete it, then run the symlink command above again.

#### Windows

Either set the `HELIX_RUNTIME` environment variable to point to the runtime files using the Windows setting (search for
Expand Down
2 changes: 1 addition & 1 deletion book/src/themes.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ These scopes are used for theming the editor interface:
| `ui.window` | Borderlines separating splits |
| `ui.help` | Description box for commands |
| `ui.text` | Command prompts, popup text, etc. |
| `ui.text.focus` | |
| `ui.text.focus` | The currently selected line in the picker |
| `ui.text.inactive` | Same as `ui.text` but when the text is inactive (e.g. suggestions) |
| `ui.text.info` | The key: command text in `ui.popup.info` boxes |
| `ui.virtual.ruler` | Ruler columns (see the [`editor.rulers` config][editor-section]) |
Expand Down
10 changes: 5 additions & 5 deletions book/src/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,13 @@ function or block of code.
| `(`, `[`, `'`, etc. | Specified surround pairs |
| `m` | The closest surround pair |
| `f` | Function |
| `c` | Class |
| `t` | Type (or Class) |
| `a` | Argument/parameter |
| `o` | Comment |
| `t` | Test |
| `c` | Comment |
| `T` | Test |
| `g` | Change |

> 💡 `f`, `c`, etc. need a tree-sitter grammar active for the current
> 💡 `f`, `t`, etc. need a tree-sitter grammar active for the current
document and a special tree-sitter query file to work properly. [Only
some grammars][lang-support] currently have the query file implemented.
Contributions are welcome!
Expand All @@ -112,7 +112,7 @@ Contributions are welcome!
Navigating between functions, classes, parameters, and other elements is
possible using tree-sitter and textobject queries. For
example to move to the next function use `]f`, to move to previous
class use `[c`, and so on.
type use `[t`, and so on.

![Tree-sitter-nav-demo][tree-sitter-nav-demo]

Expand Down
121 changes: 112 additions & 9 deletions helix-core/src/match_brackets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ use tree_sitter::Node;

use crate::{Rope, Syntax};

const MAX_PLAINTEXT_SCAN: usize = 10000;

// Limit matching pairs to only ( ) { } [ ] < > ' ' " "
const PAIRS: &[(char, char)] = &[
('(', ')'),
('{', '}'),
Expand All @@ -11,15 +14,15 @@ const PAIRS: &[(char, char)] = &[
('\"', '\"'),
];

// limit matching pairs to only ( ) { } [ ] < > ' ' " "

// Returns the position of the matching bracket under cursor.
//
// If the cursor is one the opening bracket, the position of
// the closing bracket is returned. If the cursor in the closing
// bracket, the position of the opening bracket is returned.
//
// If the cursor is not on a bracket, `None` is returned.
/// Returns the position of the matching bracket under cursor.
///
/// If the cursor is on the opening bracket, the position of
/// the closing bracket is returned. If the cursor on the closing
/// bracket, the position of the opening bracket is returned.
///
/// If the cursor is not on a bracket, `None` is returned.
///
/// If no matching bracket is found, `None` is returned.
#[must_use]
pub fn find_matching_bracket(syntax: &Syntax, doc: &Rope, pos: usize) -> Option<usize> {
if pos >= doc.len_chars() || !is_valid_bracket(doc.char(pos)) {
Expand Down Expand Up @@ -70,10 +73,77 @@ fn find_pair(syntax: &Syntax, doc: &Rope, pos: usize, traverse_parents: bool) ->
}
}

/// Returns the position of the matching bracket under cursor.
/// This function works on plain text and ignores tree-sitter grammar.
/// The search is limited to `MAX_PLAINTEXT_SCAN` characters
///
/// If the cursor is on the opening bracket, the position of
/// the closing bracket is returned. If the cursor on the closing
/// bracket, the position of the opening bracket is returned.
///
/// If the cursor is not on a bracket, `None` is returned.
///
/// If no matching bracket is found, `None` is returned.
#[must_use]
pub fn find_matching_bracket_current_line_plaintext(
doc: &Rope,
cursor_pos: usize,
) -> Option<usize> {
// Don't do anything when the cursor is not on top of a bracket.
let bracket = doc.char(cursor_pos);
if !is_valid_bracket(bracket) {
return None;
}

// Determine the direction of the matching.
let is_fwd = is_forward_bracket(bracket);
let chars_iter = if is_fwd {
doc.chars_at(cursor_pos + 1)
} else {
doc.chars_at(cursor_pos).reversed()
};

let mut open_cnt = 1;

for (i, candidate) in chars_iter.take(MAX_PLAINTEXT_SCAN).enumerate() {
if candidate == bracket {
open_cnt += 1;
} else if is_valid_pair(
doc,
if is_fwd {
cursor_pos
} else {
cursor_pos - i - 1
},
if is_fwd {
cursor_pos + i + 1
} else {
cursor_pos
},
) {
// Return when all pending brackets have been closed.
if open_cnt == 1 {
return Some(if is_fwd {
cursor_pos + i + 1
} else {
cursor_pos - i - 1
});
}
open_cnt -= 1;
}
}

None
}

fn is_valid_bracket(c: char) -> bool {
PAIRS.iter().any(|(l, r)| *l == c || *r == c)
}

fn is_forward_bracket(c: char) -> bool {
PAIRS.iter().any(|(l, _)| *l == c)
}

fn is_valid_pair(doc: &Rope, start_char: usize, end_char: usize) -> bool {
PAIRS.contains(&(doc.char(start_char), doc.char(end_char)))
}
Expand All @@ -90,3 +160,36 @@ fn surrounding_bytes(doc: &Rope, node: &Node) -> Option<(usize, usize)> {

Some((start_byte, end_byte))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_find_matching_bracket_current_line_plaintext() {
let assert = |input: &str, pos, expected| {
let input = &Rope::from(input);
let actual = find_matching_bracket_current_line_plaintext(input, pos);
assert_eq!(expected, actual.unwrap());

let actual = find_matching_bracket_current_line_plaintext(input, expected);
assert_eq!(pos, actual.unwrap(), "expected symmetrical behaviour");
};

assert("(hello)", 0, 6);
assert("((hello))", 0, 8);
assert("((hello))", 1, 7);
assert("(((hello)))", 2, 8);

assert("key: ${value}", 6, 12);
assert("key: ${value} # (some comment)", 16, 29);

assert("(paren (paren {bracket}))", 0, 24);
assert("(paren (paren {bracket}))", 7, 23);
assert("(paren (paren {bracket}))", 14, 22);

assert("(prev line\n ) (middle) ( \n next line)", 0, 12);
assert("(prev line\n ) (middle) ( \n next line)", 14, 21);
assert("(prev line\n ) (middle) ( \n next line)", 23, 36);
}
}
26 changes: 21 additions & 5 deletions helix-term/src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,14 @@ impl Application {
#[cfg(windows)]
let signals = futures_util::stream::empty();
#[cfg(not(windows))]
let signals = Signals::new([signal::SIGTSTP, signal::SIGCONT, signal::SIGUSR1])
.context("build signal handler")?;
let signals = Signals::new([
signal::SIGTSTP,
signal::SIGCONT,
signal::SIGUSR1,
signal::SIGTERM,
signal::SIGINT,
])
.context("build signal handler")?;

let app = Self {
compositor,
Expand Down Expand Up @@ -318,7 +324,9 @@ impl Application {
biased;

Some(signal) = self.signals.next() => {
self.handle_signals(signal).await;
if !self.handle_signals(signal).await {
return false;
};
}
Some(event) = input_stream.next() => {
self.handle_terminal_events(event).await;
Expand Down Expand Up @@ -442,10 +450,12 @@ impl Application {

#[cfg(windows)]
// no signal handling available on windows
pub async fn handle_signals(&mut self, _signal: ()) {}
pub async fn handle_signals(&mut self, _signal: ()) -> bool {
true
}

#[cfg(not(windows))]
pub async fn handle_signals(&mut self, signal: i32) {
pub async fn handle_signals(&mut self, signal: i32) -> bool {
match signal {
signal::SIGTSTP => {
self.restore_term().unwrap();
Expand Down Expand Up @@ -499,8 +509,14 @@ impl Application {
self.refresh_config();
self.render().await;
}
signal::SIGTERM | signal::SIGINT => {
self.restore_term().unwrap();
return false;
}
_ => unreachable!(),
}

true
}

pub async fn handle_idle_timeout(&mut self) {
Expand Down
29 changes: 16 additions & 13 deletions helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4528,20 +4528,23 @@ fn select_prev_sibling(cx: &mut Context) {

fn match_brackets(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
let is_select = cx.editor.mode == Mode::Select;
let text = doc.text();
let text_slice = text.slice(..);

if let Some(syntax) = doc.syntax() {
let text = doc.text().slice(..);
let selection = doc.selection(view.id).clone().transform(|range| {
if let Some(pos) =
match_brackets::find_matching_bracket_fuzzy(syntax, doc.text(), range.cursor(text))
{
range.put_cursor(text, pos, cx.editor.mode == Mode::Select)
} else {
range
}
});
doc.set_selection(view.id, selection);
}
let selection = doc.selection(view.id).clone().transform(|range| {
let pos = range.cursor(text_slice);
if let Some(matched_pos) = doc.syntax().map_or_else(
|| match_brackets::find_matching_bracket_current_line_plaintext(text, pos),
|syntax| match_brackets::find_matching_bracket_fuzzy(syntax, text, pos),
) {
range.put_cursor(text_slice, matched_pos, is_select)
} else {
range
}
});

doc.set_selection(view.id, selection);
}

//
Expand Down
49 changes: 37 additions & 12 deletions helix-term/src/commands/typed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use helix_core::{encoding, shellwords::Shellwords};
use helix_view::document::DEFAULT_LANGUAGE_NAME;
use helix_view::editor::{Action, CloseError, ConfigEvent};
use helix_view::view::JumpList;
use serde_json::Value;
use ui::completers::{self, Completer};

#[derive(Clone)]
Expand Down Expand Up @@ -1802,8 +1801,8 @@ fn toggle_option(
return Ok(());
}

if args.len() != 1 {
anyhow::bail!("Bad arguments. Usage: `:toggle key`");
if args.is_empty() {
anyhow::bail!("Bad arguments. Usage: `:toggle key [values]?`");
}
let key = &args[0].to_lowercase();

Expand All @@ -1813,22 +1812,48 @@ fn toggle_option(
let pointer = format!("/{}", key.replace('.', "/"));
let value = config.pointer_mut(&pointer).ok_or_else(key_error)?;

let Value::Bool(old_value) = *value else {
anyhow::bail!("Key `{}` is not toggle-able", key)
*value = match value.as_bool() {
Some(value) => {
ensure!(
args.len() == 1,
"Bad arguments. For boolean configurations use: `:toggle key`"
);
serde_json::Value::Bool(!value)
}
None => {
ensure!(
args.len() > 2,
"Bad arguments. For non-boolean configurations use: `:toggle key val1 val2 ...`",
);
ensure!(
value.is_string(),
"Bad configuration. Cannot cycle non-string configurations"
);

let value = value
.as_str()
.expect("programming error: should have been ensured before");

serde_json::Value::String(
args[1..]
.iter()
.skip_while(|e| *e != value)
.nth(1)
.unwrap_or_else(|| &args[1])
.to_string(),
)
}
};

let new_value = !old_value;
*value = Value::Bool(new_value);
// This unwrap should never fail because we only replace one boolean value
// with another, maintaining a valid json config
let config = serde_json::from_value(config).unwrap();
let status = format!("'{key}' is now set to {value}");
let config = serde_json::from_value(config)
.map_err(|_| anyhow::anyhow!("Could not parse field: `{:?}`", &args))?;

cx.editor
.config_events
.0
.send(ConfigEvent::Update(config))?;
cx.editor
.set_status(format!("Option `{}` is now set to `{}`", key, new_value));
cx.editor.set_status(status);
Ok(())
}

Expand Down
Loading

0 comments on commit dc57716

Please sign in to comment.