Merge remote-tracking branch 'origin/master' into line_ending_detection

pull/224/head
Jan Hrastnik 3 years ago
commit cdd9347457

5
Cargo.lock generated

@ -342,6 +342,7 @@ version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"crossterm", "crossterm",
"futures-util",
"helix-core", "helix-core",
"helix-lsp", "helix-lsp",
"helix-tui", "helix-tui",
@ -672,9 +673,9 @@ checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b"
[[package]] [[package]]
name = "ropey" name = "ropey"
version = "1.2.0" version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0f3ef16589fdbb3e8fbce3dca944c08e61f39c7f16064b21a257d68ea911a83" checksum = "e4b1996ad82fb6b8ac0711329432d80aa1ad5d70a0fe6edd1a9cf6fd2375fbb2"
dependencies = [ dependencies = [
"smallvec", "smallvec",
] ]

@ -4,4 +4,5 @@
- [Usage](./usage.md) - [Usage](./usage.md)
- [Configuration](./configuration.md) - [Configuration](./configuration.md)
- [Keymap](./keymap.md) - [Keymap](./keymap.md)
- [Key Remapping](./remapping.md)
- [Hooks](./hooks.md) - [Hooks](./hooks.md)

@ -1,5 +1,12 @@
# Configuration # Configuration
## LSP
To disable language server progress report from being displayed in the status bar add this option to your `config.toml`:
```toml
lsp-progress = false
```
## Theme ## Theme
Use a custom theme by placing a theme.toml in your config directory (i.e ~/.config/helix/theme.toml). The default theme.toml can be found [here](https://github.com/helix-editor/helix/blob/master/theme.toml), and user submitted themes [here](https://github.com/helix-editor/helix/blob/master/contrib/themes). Use a custom theme by placing a theme.toml in your config directory (i.e ~/.config/helix/theme.toml). The default theme.toml can be found [here](https://github.com/helix-editor/helix/blob/master/theme.toml), and user submitted themes [here](https://github.com/helix-editor/helix/blob/master/contrib/themes).
@ -32,11 +39,11 @@ Possible modifiers:
| `dim` | | `dim` |
| `italic` | | `italic` |
| `underlined` | | `underlined` |
| `slow\_blink` | | `slow_blink` |
| `rapid\_blink` | | `rapid_blink` |
| `reversed` | | `reversed` |
| `hidden` | | `hidden` |
| `crossed\_out` | | `crossed_out` |
Possible keys: Possible keys:
@ -87,3 +94,4 @@ Possible keys:
These keys match [tree-sitter scopes](https://tree-sitter.github.io/tree-sitter/syntax-highlighting#theme). We half-follow the common scopes from [macromates language grammars](https://macromates.com/manual/en/language_grammars) with some differences. These keys match [tree-sitter scopes](https://tree-sitter.github.io/tree-sitter/syntax-highlighting#theme). We half-follow the common scopes from [macromates language grammars](https://macromates.com/manual/en/language_grammars) with some differences.
For a given highlight produced, styling will be determined based on the longest matching theme key. So it's enough to provide function to highlight `function.macro` and `function.builtin` as well, but you can use more specific scopes to highlight specific cases differently. For a given highlight produced, styling will be determined based on the longest matching theme key. So it's enough to provide function to highlight `function.macro` and `function.builtin` as well, but you can use more specific scopes to highlight specific cases differently.

@ -4,9 +4,12 @@ We provide pre-built binaries on the [GitHub Releases page](https://github.com/h
## OSX ## OSX
TODO: brew tap A Homebrew tap is available:
Please use a pre-built binary release for the time being. ```
brew tap helix-editor/helix
brew install helix
```
## Linux ## Linux

@ -0,0 +1,48 @@
# Key Remapping
One-way key remapping is temporarily supported via a simple TOML configuration
file. (More powerful solutions such as rebinding via commands will be
available in the feature).
To remap keys, write a `config.toml` file in your `helix` configuration
directory (default `~/.config/helix` in Linux systems) with a structure like
this:
```toml
# At most one section each of 'keys.normal', 'keys.insert' and 'keys.select'
[keys.normal]
a = "move_char_left" # Maps the 'a' key to the move_char_left command
w = "move_line_up" # Maps the 'w' key move_line_up
C-S-esc = "select_line" # Maps Control-Shift-Escape to select_line
[keys.insert]
A-x = "normal_mode" # Maps Alt-X to enter normal mode
```
Control, Shift and Alt modifiers are encoded respectively with the prefixes
`C-`, `S-` and `A-`. Special keys are encoded as follows:
* Backspace => "backspace"
* Space => "space"
* Return/Enter => "ret"
* < => "lt"
* \> => "gt"
* \+ => "plus"
* \- => "minus"
* ; => "semicolon"
* % => "percent"
* Left => "left"
* Right => "right"
* Up => "up"
* Home => "home"
* End => "end"
* Page Up => "pageup"
* Page Down => "pagedown"
* Tab => "tab"
* Back Tab => "backtab"
* Delete => "del"
* Insert => "ins"
* Null => "null"
* Escape => "esc"
Commands can be found in the source code at `../../helix-term/src/commands.rs`

@ -31,7 +31,8 @@
"ui.background" = { bg = "#161c23" } "ui.background" = { bg = "#161c23" }
"ui.linenr" = { fg = "#415367" } "ui.linenr" = { fg = "#415367" }
"ui.linenr.selected" = { fg = "#e5ded6" } # TODO "ui.linenr.selected" = { fg = "#e5ded6" } # TODO
"ui.statusline" = { bg = "#232d38" } "ui.statusline" = { fg = "#e5ded6", bg = "#232d38" }
"ui.statusline.inactive" = { fg = "#c6b8ad", bg = "#232d38" }
"ui.popup" = { bg = "#232d38" } "ui.popup" = { bg = "#232d38" }
"ui.window" = { bg = "#232d38" } "ui.window" = { bg = "#232d38" }
"ui.help" = { bg = "#232d38", fg = "#e5ded6" } "ui.help" = { bg = "#232d38", fg = "#e5ded6" }
@ -39,7 +40,7 @@
"ui.text" = { fg = "#e5ded6" } "ui.text" = { fg = "#e5ded6" }
"ui.text.focus" = { fg = "#e5ded6", modifiers= ["bold"] } "ui.text.focus" = { fg = "#e5ded6", modifiers= ["bold"] }
"ui.selection" = { bg = "#540099" } "ui.selection" = { bg = "#313f4e" }
"ui.menu.selected" = { fg = "#e5ded6", bg = "#313f4e" } "ui.menu.selected" = { fg = "#e5ded6", bg = "#313f4e" }
"warning" = "#dc7759" "warning" = "#dc7759"

@ -31,7 +31,8 @@
"ui.background" = { bg = "#FFFCFD" } "ui.background" = { bg = "#FFFCFD" }
"ui.linenr" = { fg = "#bbbbbb" } "ui.linenr" = { fg = "#bbbbbb" }
"ui.linenr.selected" = { fg = "#F3EAE9" } # TODO "ui.linenr.selected" = { fg = "#F3EAE9" } # TODO
"ui.statusline" = { bg = "#F3EAE9" } "ui.statusline" = { fg = "#250E07", bg = "#F3EAE9" }
"ui.statusline.inactive" = { fg = "#7b91b3", bg = "#F3EAE9" }
"ui.popup" = { bg = "#F3EAE9" } "ui.popup" = { bg = "#F3EAE9" }
"ui.window" = { bg = "#D8B8B3" } "ui.window" = { bg = "#D8B8B3" }
"ui.help" = { bg = "#D8B8B3", fg = "#250E07" } "ui.help" = { bg = "#D8B8B3", fg = "#250E07" }

@ -36,6 +36,7 @@
"ui.linenr.selected" = { fg = "#ABB2BF" } "ui.linenr.selected" = { fg = "#ABB2BF" }
"ui.popup" = { bg = "#3E4452" } "ui.popup" = { bg = "#3E4452" }
"ui.statusline" = { fg = "#ABB2BF", bg = "#2C323C" } "ui.statusline" = { fg = "#ABB2BF", bg = "#2C323C" }
"ui.statusline.inactive" = { fg = "#ABB2Bf", bg = "#2C323C" }
"ui.selection" = { bg = "#3E4452" } "ui.selection" = { bg = "#3E4452" }
"ui.text" = { fg = "#ABB2BF", bg = "#282C34" } "ui.text" = { fg = "#ABB2BF", bg = "#282C34" }
"ui.text.focus" = { fg = "#ABB2BF", bg = "#2C323C", modifiers = ['bold'] } "ui.text.focus" = { fg = "#ABB2BF", bg = "#2C323C", modifiers = ['bold'] }

@ -34,11 +34,11 @@
"helix": { "helix": {
"flake": false, "flake": false,
"locked": { "locked": {
"lastModified": 1623545930, "lastModified": 1624077450,
"narHash": "sha256-14ASoYbxXHU/qPGctiUymb4fMRCoih9c7YujjxqEkdU=", "narHash": "sha256-gcL519tetuEv0N+oBP8X3U4bPjwcAgzbPdgwW19qeVI=",
"ref": "master", "ref": "master",
"rev": "9640ed1425f2db904fb42cd0c54dc6fbc05ca292", "rev": "1c2585202145467f0fde7ad9c571e462081c3656",
"revCount": 821, "revCount": 894,
"submodules": true, "submodules": true,
"type": "git", "type": "git",
"url": "https://github.com/helix-editor/helix.git" "url": "https://github.com/helix-editor/helix.git"
@ -58,11 +58,11 @@
"rustOverlay": "rustOverlay" "rustOverlay": "rustOverlay"
}, },
"locked": { "locked": {
"lastModified": 1623591988, "lastModified": 1624070370,
"narHash": "sha256-a8E5LYKxYjHmBWZsFxKnCBVGsWHFEWrKjeAJkplWrfI=", "narHash": "sha256-sfFqfmerCYvk0jDeP1gfuskz7AaqDsgV8aiQrEUGdsc=",
"owner": "yusdacra", "owner": "yusdacra",
"repo": "nix-cargo-integration", "repo": "nix-cargo-integration",
"rev": "8254b71eddd4e85173eddc189174b873fad85360", "rev": "85e6c1ba4c0e3e6dec5a7d1f65bcc036d2ea6ae3",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -73,11 +73,11 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1623324058, "lastModified": 1623580589,
"narHash": "sha256-Jm9GUTXdjXz56gWDKy++EpFfjrBaxqXlLvTLfgEi8lo=", "narHash": "sha256-Ayp1cjXpwFCkAiWUE46rj9APTltsiEBdIs2+cj+U7+c=",
"owner": "nixos", "owner": "nixos",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "432fc2d9a67f92e05438dff5fdc2b39d33f77997", "rev": "fa0326ce5233f7d592271df52c9d0812bec47b84",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -98,11 +98,11 @@
"rustOverlay": { "rustOverlay": {
"flake": false, "flake": false,
"locked": { "locked": {
"lastModified": 1623550815, "lastModified": 1624069337,
"narHash": "sha256-RumRrkE6OTJDndHV4qZNZv8kUGnzwRHZQSyzx29r6/g=", "narHash": "sha256-9mTcx7osE4biF2Hm/GU19s1T3+KvphWj4QaUcJh39lU=",
"owner": "oxalica", "owner": "oxalica",
"repo": "rust-overlay", "repo": "rust-overlay",
"rev": "9824f142cbd7bc3e2a92eefbb79addfff8704cd3", "rev": "67dc2a9543a7c24591e6cb102ad0121c3a704aab",
"type": "github" "type": "github"
}, },
"original": { "original": {

@ -4,17 +4,19 @@ version = "0.2.0"
authors = ["Blaž Hrastnik <blaz@mxxn.io>"] authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
edition = "2018" edition = "2018"
license = "MPL-2.0" license = "MPL-2.0"
description = "Helix editor core editing primitives"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html categories = ["editor"]
repository = "https://github.com/helix-editor/helix"
homepage = "https://helix-editor.com"
include = ["src/**/*", "README.md"]
[features] [features]
embed_runtime = ["rust-embed"] embed_runtime = ["rust-embed"]
[dependencies] [dependencies]
helix-syntax = { path = "../helix-syntax" } helix-syntax = { version = "0.2", path = "../helix-syntax" }
ropey = "1.2" ropey = "1.3"
smallvec = "1.4" smallvec = "1.4"
tendril = "0.4.2" tendril = "0.4.2"
unicode-segmentation = "1.7.1" unicode-segmentation = "1.7.1"

@ -90,6 +90,8 @@ pub fn cache_dir() -> std::path::PathBuf {
path path
} }
pub use etcetera::home_dir;
use etcetera::base_strategy::{choose_base_strategy, BaseStrategy}; use etcetera::base_strategy::{choose_base_strategy, BaseStrategy};
pub use ropey::{Rope, RopeSlice}; pub use ropey::{Rope, RopeSlice};

@ -4,11 +4,15 @@ version = "0.2.0"
authors = ["Blaž Hrastnik <blaz@mxxn.io>"] authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
edition = "2018" edition = "2018"
license = "MPL-2.0" license = "MPL-2.0"
description = "LSP client implementation for Helix project"
categories = ["editor"]
repository = "https://github.com/helix-editor/helix"
homepage = "https://helix-editor.com"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
helix-core = { path = "../helix-core" } helix-core = { version = "0.2", path = "../helix-core" }
anyhow = "1.0" anyhow = "1.0"
futures-executor = "0.3" futures-executor = "0.3"

@ -18,6 +18,7 @@ use tokio::{
#[derive(Debug)] #[derive(Debug)]
pub struct Client { pub struct Client {
id: usize,
_process: Child, _process: Child,
server_tx: UnboundedSender<Payload>, server_tx: UnboundedSender<Payload>,
request_counter: AtomicU64, request_counter: AtomicU64,
@ -26,7 +27,11 @@ pub struct Client {
} }
impl Client { impl Client {
pub fn start(cmd: &str, args: &[String]) -> Result<(Self, UnboundedReceiver<Call>)> { pub fn start(
cmd: &str,
args: &[String],
id: usize,
) -> Result<(Self, UnboundedReceiver<(usize, Call)>)> {
let process = Command::new(cmd) let process = Command::new(cmd)
.args(args) .args(args)
.stdin(Stdio::piped()) .stdin(Stdio::piped())
@ -43,9 +48,10 @@ impl Client {
let reader = BufReader::new(process.stdout.take().expect("Failed to open stdout")); let reader = BufReader::new(process.stdout.take().expect("Failed to open stdout"));
let stderr = BufReader::new(process.stderr.take().expect("Failed to open stderr")); let stderr = BufReader::new(process.stderr.take().expect("Failed to open stderr"));
let (server_rx, server_tx) = Transport::start(reader, writer, stderr); let (server_rx, server_tx) = Transport::start(reader, writer, stderr, id);
let client = Self { let client = Self {
id,
_process: process, _process: process,
server_tx, server_tx,
request_counter: AtomicU64::new(0), request_counter: AtomicU64::new(0),
@ -59,6 +65,10 @@ impl Client {
Ok((client, server_rx)) Ok((client, server_rx))
} }
pub fn id(&self) -> usize {
self.id
}
fn next_request_id(&self) -> jsonrpc::Id { fn next_request_id(&self) -> jsonrpc::Id {
let id = self.request_counter.fetch_add(1, Ordering::Relaxed); let id = self.request_counter.fetch_add(1, Ordering::Relaxed);
jsonrpc::Id::Num(id) jsonrpc::Id::Num(id)
@ -165,13 +175,16 @@ impl Client {
} }
/// Reply to a language server RPC call. /// Reply to a language server RPC call.
pub async fn reply( pub fn reply(
&self, &self,
id: jsonrpc::Id, id: jsonrpc::Id,
result: core::result::Result<Value, jsonrpc::Error>, result: core::result::Result<Value, jsonrpc::Error>,
) -> Result<()> { ) -> impl Future<Output = Result<()>> {
use jsonrpc::{Failure, Output, Success, Version}; use jsonrpc::{Failure, Output, Success, Version};
let server_tx = self.server_tx.clone();
async move {
let output = match result { let output = match result {
Ok(result) => Output::Success(Success { Ok(result) => Output::Success(Success {
jsonrpc: Some(Version::V2), jsonrpc: Some(Version::V2),
@ -185,12 +198,13 @@ impl Client {
}), }),
}; };
self.server_tx server_tx
.send(Payload::Response(output)) .send(Payload::Response(output))
.map_err(|e| Error::Other(e.into()))?; .map_err(|e| Error::Other(e.into()))?;
Ok(()) Ok(())
} }
}
// ------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------
// General messages // General messages
@ -229,8 +243,7 @@ impl Client {
..Default::default() ..Default::default()
}), }),
window: Some(lsp::WindowClientCapabilities { window: Some(lsp::WindowClientCapabilities {
// TODO: temporarily disabled until we implement handling for window/workDoneProgress/create work_done_progress: Some(true),
// work_done_progress: Some(true),
..Default::default() ..Default::default()
}), }),
..Default::default() ..Default::default()
@ -259,6 +272,21 @@ impl Client {
self.notify::<lsp::notification::Exit>(()) self.notify::<lsp::notification::Exit>(())
} }
/// Tries to shut down the language server but returns
/// early if server responds with an error.
pub async fn shutdown_and_exit(&self) -> Result<()> {
self.shutdown().await?;
self.exit().await
}
/// Forcefully shuts down the language server ignoring any errors.
pub async fn force_shutdown(&self) -> Result<()> {
if let Err(e) = self.shutdown().await {
log::warn!("language server failed to terminate gracefully - {}", e);
}
self.exit().await
}
// ------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------
// Text document // Text document
// ------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------
@ -465,6 +493,7 @@ impl Client {
&self, &self,
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
position: lsp::Position, position: lsp::Position,
work_done_token: Option<lsp::ProgressToken>,
) -> impl Future<Output = Result<Value>> { ) -> impl Future<Output = Result<Value>> {
// ) -> Result<Vec<lsp::CompletionItem>> { // ) -> Result<Vec<lsp::CompletionItem>> {
let params = lsp::CompletionParams { let params = lsp::CompletionParams {
@ -473,9 +502,7 @@ impl Client {
position, position,
}, },
// TODO: support these tokens by async receiving and updating the choice list // TODO: support these tokens by async receiving and updating the choice list
work_done_progress_params: lsp::WorkDoneProgressParams { work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
work_done_token: None,
},
partial_result_params: lsp::PartialResultParams { partial_result_params: lsp::PartialResultParams {
partial_result_token: None, partial_result_token: None,
}, },
@ -490,15 +517,14 @@ impl Client {
&self, &self,
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
position: lsp::Position, position: lsp::Position,
work_done_token: Option<lsp::ProgressToken>,
) -> impl Future<Output = Result<Value>> { ) -> impl Future<Output = Result<Value>> {
let params = lsp::SignatureHelpParams { let params = lsp::SignatureHelpParams {
text_document_position_params: lsp::TextDocumentPositionParams { text_document_position_params: lsp::TextDocumentPositionParams {
text_document, text_document,
position, position,
}, },
work_done_progress_params: lsp::WorkDoneProgressParams { work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
work_done_token: None,
},
context: None, context: None,
// lsp::SignatureHelpContext // lsp::SignatureHelpContext
}; };
@ -510,15 +536,14 @@ impl Client {
&self, &self,
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
position: lsp::Position, position: lsp::Position,
work_done_token: Option<lsp::ProgressToken>,
) -> impl Future<Output = Result<Value>> { ) -> impl Future<Output = Result<Value>> {
let params = lsp::HoverParams { let params = lsp::HoverParams {
text_document_position_params: lsp::TextDocumentPositionParams { text_document_position_params: lsp::TextDocumentPositionParams {
text_document, text_document,
position, position,
}, },
work_done_progress_params: lsp::WorkDoneProgressParams { work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
work_done_token: None,
},
// lsp::SignatureHelpContext // lsp::SignatureHelpContext
}; };
@ -531,6 +556,7 @@ impl Client {
&self, &self,
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
options: lsp::FormattingOptions, options: lsp::FormattingOptions,
work_done_token: Option<lsp::ProgressToken>,
) -> anyhow::Result<Vec<lsp::TextEdit>> { ) -> anyhow::Result<Vec<lsp::TextEdit>> {
let capabilities = self.capabilities.as_ref().unwrap(); let capabilities = self.capabilities.as_ref().unwrap();
@ -545,9 +571,7 @@ impl Client {
let params = lsp::DocumentFormattingParams { let params = lsp::DocumentFormattingParams {
text_document, text_document,
options, options,
work_done_progress_params: lsp::WorkDoneProgressParams { work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
work_done_token: None,
},
}; };
let response = self.request::<lsp::request::Formatting>(params).await?; let response = self.request::<lsp::request::Formatting>(params).await?;
@ -560,6 +584,7 @@ impl Client {
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
range: lsp::Range, range: lsp::Range,
options: lsp::FormattingOptions, options: lsp::FormattingOptions,
work_done_token: Option<lsp::ProgressToken>,
) -> anyhow::Result<Vec<lsp::TextEdit>> { ) -> anyhow::Result<Vec<lsp::TextEdit>> {
let capabilities = self.capabilities.as_ref().unwrap(); let capabilities = self.capabilities.as_ref().unwrap();
@ -575,9 +600,7 @@ impl Client {
text_document, text_document,
range, range,
options, options,
work_done_progress_params: lsp::WorkDoneProgressParams { work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
work_done_token: None,
},
}; };
let response = self let response = self
@ -596,15 +619,14 @@ impl Client {
&self, &self,
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
position: lsp::Position, position: lsp::Position,
work_done_token: Option<lsp::ProgressToken>,
) -> impl Future<Output = Result<Value>> { ) -> impl Future<Output = Result<Value>> {
let params = lsp::GotoDefinitionParams { let params = lsp::GotoDefinitionParams {
text_document_position_params: lsp::TextDocumentPositionParams { text_document_position_params: lsp::TextDocumentPositionParams {
text_document, text_document,
position, position,
}, },
work_done_progress_params: lsp::WorkDoneProgressParams { work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
work_done_token: None,
},
partial_result_params: lsp::PartialResultParams { partial_result_params: lsp::PartialResultParams {
partial_result_token: None, partial_result_token: None,
}, },
@ -617,30 +639,42 @@ impl Client {
&self, &self,
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
position: lsp::Position, position: lsp::Position,
work_done_token: Option<lsp::ProgressToken>,
) -> impl Future<Output = Result<Value>> { ) -> impl Future<Output = Result<Value>> {
self.goto_request::<lsp::request::GotoDefinition>(text_document, position) self.goto_request::<lsp::request::GotoDefinition>(text_document, position, work_done_token)
} }
pub fn goto_type_definition( pub fn goto_type_definition(
&self, &self,
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
position: lsp::Position, position: lsp::Position,
work_done_token: Option<lsp::ProgressToken>,
) -> impl Future<Output = Result<Value>> { ) -> impl Future<Output = Result<Value>> {
self.goto_request::<lsp::request::GotoTypeDefinition>(text_document, position) self.goto_request::<lsp::request::GotoTypeDefinition>(
text_document,
position,
work_done_token,
)
} }
pub fn goto_implementation( pub fn goto_implementation(
&self, &self,
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
position: lsp::Position, position: lsp::Position,
work_done_token: Option<lsp::ProgressToken>,
) -> impl Future<Output = Result<Value>> { ) -> impl Future<Output = Result<Value>> {
self.goto_request::<lsp::request::GotoImplementation>(text_document, position) self.goto_request::<lsp::request::GotoImplementation>(
text_document,
position,
work_done_token,
)
} }
pub fn goto_reference( pub fn goto_reference(
&self, &self,
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
position: lsp::Position, position: lsp::Position,
work_done_token: Option<lsp::ProgressToken>,
) -> impl Future<Output = Result<Value>> { ) -> impl Future<Output = Result<Value>> {
let params = lsp::ReferenceParams { let params = lsp::ReferenceParams {
text_document_position: lsp::TextDocumentPositionParams { text_document_position: lsp::TextDocumentPositionParams {
@ -650,9 +684,7 @@ impl Client {
context: lsp::ReferenceContext { context: lsp::ReferenceContext {
include_declaration: true, include_declaration: true,
}, },
work_done_progress_params: lsp::WorkDoneProgressParams { work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
work_done_token: None,
},
partial_result_params: lsp::PartialResultParams { partial_result_params: lsp::PartialResultParams {
partial_result_token: None, partial_result_token: None,
}, },

@ -13,7 +13,10 @@ use helix_core::syntax::LanguageConfiguration;
use std::{ use std::{
collections::{hash_map::Entry, HashMap}, collections::{hash_map::Entry, HashMap},
sync::Arc, sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -181,6 +184,30 @@ pub mod util {
} }
} }
#[derive(Debug, PartialEq, Clone)]
pub enum MethodCall {
WorkDoneProgressCreate(lsp::WorkDoneProgressCreateParams),
}
impl MethodCall {
pub fn parse(method: &str, params: jsonrpc::Params) -> Option<MethodCall> {
use lsp::request::Request;
let request = match method {
lsp::request::WorkDoneProgressCreate::METHOD => {
let params: lsp::WorkDoneProgressCreateParams = params
.parse()
.expect("Failed to parse WorkDoneCreate params");
Self::WorkDoneProgressCreate(params)
}
_ => {
log::warn!("unhandled lsp request: {}", method);
return None;
}
};
Some(request)
}
}
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Clone)]
pub enum Notification { pub enum Notification {
PublishDiagnostics(lsp::PublishDiagnosticsParams), PublishDiagnostics(lsp::PublishDiagnosticsParams),
@ -230,9 +257,10 @@ impl Notification {
#[derive(Debug)] #[derive(Debug)]
pub struct Registry { pub struct Registry {
inner: HashMap<LanguageId, Arc<Client>>, inner: HashMap<LanguageId, (usize, Arc<Client>)>,
pub incoming: SelectAll<UnboundedReceiverStream<Call>>, counter: AtomicUsize,
pub incoming: SelectAll<UnboundedReceiverStream<(usize, Call)>>,
} }
impl Default for Registry { impl Default for Registry {
@ -245,10 +273,18 @@ impl Registry {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
inner: HashMap::new(), inner: HashMap::new(),
counter: AtomicUsize::new(0),
incoming: SelectAll::new(), incoming: SelectAll::new(),
} }
} }
pub fn get_by_id(&mut self, id: usize) -> Option<&Client> {
self.inner
.values()
.find(|(client_id, _)| client_id == &id)
.map(|(_, client)| client.as_ref())
}
pub fn get(&mut self, language_config: &LanguageConfiguration) -> Result<Arc<Client>> { pub fn get(&mut self, language_config: &LanguageConfiguration) -> Result<Arc<Client>> {
if let Some(config) = &language_config.language_server { if let Some(config) = &language_config.language_server {
// avoid borrow issues // avoid borrow issues
@ -256,16 +292,17 @@ impl Registry {
let s_incoming = &mut self.incoming; let s_incoming = &mut self.incoming;
match inner.entry(language_config.scope.clone()) { match inner.entry(language_config.scope.clone()) {
Entry::Occupied(language_server) => Ok(language_server.get().clone()), Entry::Occupied(entry) => Ok(entry.get().1.clone()),
Entry::Vacant(entry) => { Entry::Vacant(entry) => {
// initialize a new client // initialize a new client
let (mut client, incoming) = Client::start(&config.command, &config.args)?; let id = self.counter.fetch_add(1, Ordering::Relaxed);
let (mut client, incoming) = Client::start(&config.command, &config.args, id)?;
// TODO: run this async without blocking // TODO: run this async without blocking
futures_executor::block_on(client.initialize())?; futures_executor::block_on(client.initialize())?;
s_incoming.push(UnboundedReceiverStream::new(incoming)); s_incoming.push(UnboundedReceiverStream::new(incoming));
let client = Arc::new(client); let client = Arc::new(client);
entry.insert(client.clone()); entry.insert((id, client.clone()));
Ok(client) Ok(client)
} }
} }
@ -273,6 +310,84 @@ impl Registry {
Err(Error::LspNotDefined) Err(Error::LspNotDefined)
} }
} }
pub fn iter_clients(&self) -> impl Iterator<Item = &Arc<Client>> {
self.inner.values().map(|(_, client)| client)
}
}
#[derive(Debug)]
pub enum ProgressStatus {
Created,
Started(lsp::WorkDoneProgress),
}
impl ProgressStatus {
pub fn progress(&self) -> Option<&lsp::WorkDoneProgress> {
match &self {
ProgressStatus::Created => None,
ProgressStatus::Started(progress) => Some(&progress),
}
}
}
#[derive(Default, Debug)]
/// Acts as a container for progress reported by language servers. Each server
/// has a unique id assigned at creation through [`Registry`]. This id is then used
/// to store the progress in this map.
pub struct LspProgressMap(HashMap<usize, HashMap<lsp::ProgressToken, ProgressStatus>>);
impl LspProgressMap {
pub fn new() -> Self {
Self::default()
}
/// Returns a map of all tokens coresponding to the lanaguage server with `id`.
pub fn progress_map(&self, id: usize) -> Option<&HashMap<lsp::ProgressToken, ProgressStatus>> {
self.0.get(&id)
}
/// Returns last progress status for a given server with `id` and `token`.
pub fn progress(&self, id: usize, token: &lsp::ProgressToken) -> Option<&ProgressStatus> {
self.0.get(&id).and_then(|values| values.get(token))
}
/// Checks if progress `token` for server with `id` is created.
pub fn is_created(&mut self, id: usize, token: &lsp::ProgressToken) -> bool {
self.0
.get(&id)
.map(|values| values.get(token).is_some())
.unwrap_or_default()
}
pub fn create(&mut self, id: usize, token: lsp::ProgressToken) {
self.0
.entry(id)
.or_default()
.insert(token, ProgressStatus::Created);
}
/// Ends the progress by removing the `token` from server with `id`, if removed returns the value.
pub fn end_progress(
&mut self,
id: usize,
token: &lsp::ProgressToken,
) -> Option<ProgressStatus> {
self.0.get_mut(&id).and_then(|vals| vals.remove(token))
}
/// Updates the progess of `token` for server with `id` to `status`, returns the value replaced or `None`.
pub fn update(
&mut self,
id: usize,
token: lsp::ProgressToken,
status: lsp::WorkDoneProgress,
) -> Option<ProgressStatus> {
self.0
.entry(id)
.or_default()
.insert(token, ProgressStatus::Started(status))
}
} }
// REGISTRY = HashMap<LanguageId, Lazy/OnceCell<Arc<RwLock<Client>>> // REGISTRY = HashMap<LanguageId, Lazy/OnceCell<Arc<RwLock<Client>>>

@ -1,4 +1,5 @@
use crate::Result; use crate::Result;
use anyhow::Context;
use jsonrpc_core as jsonrpc; use jsonrpc_core as jsonrpc;
use log::{error, info}; use log::{error, info};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -33,7 +34,8 @@ enum ServerMessage {
#[derive(Debug)] #[derive(Debug)]
pub struct Transport { pub struct Transport {
client_tx: UnboundedSender<jsonrpc::Call>, id: usize,
client_tx: UnboundedSender<(usize, jsonrpc::Call)>,
client_rx: UnboundedReceiver<Payload>, client_rx: UnboundedReceiver<Payload>,
pending_requests: HashMap<jsonrpc::Id, Sender<Result<Value>>>, pending_requests: HashMap<jsonrpc::Id, Sender<Result<Value>>>,
@ -48,11 +50,16 @@ impl Transport {
server_stdout: BufReader<ChildStdout>, server_stdout: BufReader<ChildStdout>,
server_stdin: BufWriter<ChildStdin>, server_stdin: BufWriter<ChildStdin>,
server_stderr: BufReader<ChildStderr>, server_stderr: BufReader<ChildStderr>,
) -> (UnboundedReceiver<jsonrpc::Call>, UnboundedSender<Payload>) { id: usize,
) -> (
UnboundedReceiver<(usize, jsonrpc::Call)>,
UnboundedSender<Payload>,
) {
let (client_tx, rx) = unbounded_channel(); let (client_tx, rx) = unbounded_channel();
let (tx, client_rx) = unbounded_channel(); let (tx, client_rx) = unbounded_channel();
let transport = Self { let transport = Self {
id,
server_stdout, server_stdout,
server_stdin, server_stdin,
server_stderr, server_stderr,
@ -84,7 +91,7 @@ impl Transport {
match (parts.next(), parts.next(), parts.next()) { match (parts.next(), parts.next(), parts.next()) {
(Some("Content-Length"), Some(value), None) => { (Some("Content-Length"), Some(value), None) => {
content_length = Some(value.parse().unwrap()); content_length = Some(value.parse().context("invalid content length")?);
} }
(Some(_), Some(_), None) => {} (Some(_), Some(_), None) => {}
_ => { _ => {
@ -97,12 +104,12 @@ impl Transport {
} }
} }
let content_length = content_length.unwrap(); let content_length = content_length.context("missing content length")?;
//TODO: reuse vector //TODO: reuse vector
let mut content = vec![0; content_length]; let mut content = vec![0; content_length];
reader.read_exact(&mut content).await?; reader.read_exact(&mut content).await?;
let msg = String::from_utf8(content).unwrap(); let msg = String::from_utf8(content).context("invalid utf8 from server")?;
info!("<- {}", msg); info!("<- {}", msg);
@ -156,7 +163,9 @@ impl Transport {
match msg { match msg {
ServerMessage::Output(output) => self.process_request_response(output).await?, ServerMessage::Output(output) => self.process_request_response(output).await?,
ServerMessage::Call(call) => { ServerMessage::Call(call) => {
self.client_tx.send(call).unwrap(); self.client_tx
.send((self.id, call))
.context("failed to send a message to server")?;
// let notification = Notification::parse(&method, params); // let notification = Notification::parse(&method, params);
} }
}; };

@ -4,8 +4,11 @@ version = "0.2.0"
authors = ["Blaž Hrastnik <blaz@mxxn.io>"] authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
edition = "2018" edition = "2018"
license = "MPL-2.0" license = "MPL-2.0"
description = "Tree-sitter grammars support"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html categories = ["editor"]
repository = "https://github.com/helix-editor/helix"
homepage = "https://helix-editor.com"
include = ["src/**/*", "languages/**/*", "build.rs", "!**/docs/**/*", "!**/test/**/*", "!**/examples/**/*", "!**/build/**/*"]
[dependencies] [dependencies]
tree-sitter = "0.19" tree-sitter = "0.19"

@ -5,6 +5,10 @@ description = "A post-modern text editor."
authors = ["Blaž Hrastnik <blaz@mxxn.io>"] authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
edition = "2018" edition = "2018"
license = "MPL-2.0" license = "MPL-2.0"
categories = ["editor", "command-line-utilities"]
repository = "https://github.com/helix-editor/helix"
homepage = "https://helix-editor.com"
include = ["src/**/*", "README.md"]
[package.metadata.nix] [package.metadata.nix]
build = true build = true
@ -18,9 +22,9 @@ name = "hx"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [dependencies]
helix-core = { path = "../helix-core" } helix-core = { version = "0.2", path = "../helix-core" }
helix-view = { path = "../helix-view", features = ["term"]} helix-view = { version = "0.2", path = "../helix-view", features = ["term"]}
helix-lsp = { path = "../helix-lsp"} helix-lsp = { version = "0.2", path = "../helix-lsp"}
anyhow = "1" anyhow = "1"
once_cell = "1.8" once_cell = "1.8"

@ -1,7 +1,7 @@
use helix_lsp::lsp; use helix_lsp::{lsp, LspProgressMap};
use helix_view::{document::Mode, Document, Editor, Theme, View}; use helix_view::{document::Mode, Document, Editor, Theme, View};
use crate::{args::Args, compositor::Compositor, ui}; use crate::{args::Args, compositor::Compositor, config::Config, ui};
use log::{error, info}; use log::{error, info};
@ -9,6 +9,7 @@ use std::{
future::Future, future::Future,
io::{self, stdout, Stdout, Write}, io::{self, stdout, Stdout, Write},
path::PathBuf, path::PathBuf,
pin::Pin,
sync::Arc, sync::Arc,
time::Duration, time::Duration,
}; };
@ -22,8 +23,7 @@ use crossterm::{
use tui::layout::Rect; use tui::layout::Rect;
use futures_util::stream::FuturesUnordered; use futures_util::{future, stream::FuturesUnordered};
use std::pin::Pin;
type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>; type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
pub type LspCallback = pub type LspCallback =
@ -37,16 +37,20 @@ pub struct Application {
editor: Editor, editor: Editor,
callbacks: LspCallbacks, callbacks: LspCallbacks,
lsp_progress: LspProgressMap,
lsp_progress_enabled: bool,
} }
impl Application { impl Application {
pub fn new(mut args: Args) -> Result<Self, Error> { pub fn new(mut args: Args, config: Config) -> Result<Self, Error> {
use helix_view::editor::Action; use helix_view::editor::Action;
let mut compositor = Compositor::new()?; let mut compositor = Compositor::new()?;
let size = compositor.size(); let size = compositor.size();
let mut editor = Editor::new(size); let mut editor = Editor::new(size);
compositor.push(Box::new(ui::EditorView::new())); let mut editor_view = Box::new(ui::EditorView::new(config.keys));
compositor.push(editor_view);
if !args.files.is_empty() { if !args.files.is_empty() {
let first = &args.files[0]; // we know it's not empty let first = &args.files[0]; // we know it's not empty
@ -73,6 +77,8 @@ impl Application {
editor, editor,
callbacks: FuturesUnordered::new(), callbacks: FuturesUnordered::new(),
lsp_progress: LspProgressMap::new(),
lsp_progress_enabled: config.global.lsp_progress,
}; };
Ok(app) Ok(app)
@ -108,8 +114,8 @@ impl Application {
event = reader.next() => { event = reader.next() => {
self.handle_terminal_events(event) self.handle_terminal_events(event)
} }
Some(call) = self.editor.language_servers.incoming.next() => { Some((id, call)) = self.editor.language_servers.incoming.next() => {
self.handle_language_server_message(call).await self.handle_language_server_message(call, id).await
} }
Some(callback) = &mut self.callbacks.next() => { Some(callback) = &mut self.callbacks.next() => {
self.handle_language_server_callback(callback) self.handle_language_server_callback(callback)
@ -152,8 +158,12 @@ impl Application {
} }
} }
pub async fn handle_language_server_message(&mut self, call: helix_lsp::Call) { pub async fn handle_language_server_message(
use helix_lsp::{Call, Notification}; &mut self,
call: helix_lsp::Call,
server_id: usize,
) {
use helix_lsp::{Call, MethodCall, Notification};
match call { match call {
Call::Notification(helix_lsp::jsonrpc::Notification { method, params, .. }) => { Call::Notification(helix_lsp::jsonrpc::Notification { method, params, .. }) => {
let notification = match Notification::parse(&method, params) { let notification = match Notification::parse(&method, params) {
@ -241,64 +251,130 @@ impl Application {
log::warn!("unhandled window/logMessage: {:?}", params); log::warn!("unhandled window/logMessage: {:?}", params);
} }
Notification::ProgressMessage(params) => { Notification::ProgressMessage(params) => {
let token = match params.token { let lsp::ProgressParams { token, value } = params;
lsp::NumberOrString::Number(n) => n.to_string(),
lsp::NumberOrString::String(s) => s, let lsp::ProgressParamsValue::WorkDone(work) = value;
}; let parts = match &work {
let msg = {
let lsp::ProgressParamsValue::WorkDone(work) = params.value;
let parts = match work {
lsp::WorkDoneProgress::Begin(lsp::WorkDoneProgressBegin { lsp::WorkDoneProgress::Begin(lsp::WorkDoneProgressBegin {
title, title,
message, message,
percentage, percentage,
.. ..
}) => (Some(title), message, percentage.map(|n| n.to_string())), }) => (Some(title), message, percentage),
lsp::WorkDoneProgress::Report(lsp::WorkDoneProgressReport { lsp::WorkDoneProgress::Report(lsp::WorkDoneProgressReport {
message, message,
percentage, percentage,
.. ..
}) => (None, message, percentage.map(|n| n.to_string())), }) => (None, message, percentage),
lsp::WorkDoneProgress::End(lsp::WorkDoneProgressEnd { lsp::WorkDoneProgress::End(lsp::WorkDoneProgressEnd { message }) => {
message, if message.is_some() {
}) => { (None, message, &None)
if let Some(message) = message {
(None, Some(message), None)
} else { } else {
self.lsp_progress.end_progress(server_id, &token);
self.editor.clear_status(); self.editor.clear_status();
return; return;
} }
} }
}; };
match parts { let token_d: &dyn std::fmt::Display = match &token {
lsp::NumberOrString::Number(n) => n,
lsp::NumberOrString::String(s) => s,
};
let status = match parts {
(Some(title), Some(message), Some(percentage)) => { (Some(title), Some(message), Some(percentage)) => {
format!("{}% {} - {}", percentage, title, message) format!("[{}] {}% {} - {}", token_d, percentage, title, message)
} }
(Some(title), None, Some(percentage)) => { (Some(title), None, Some(percentage)) => {
format!("{}% {}", percentage, title) format!("[{}] {}% {}", token_d, percentage, title)
} }
(Some(title), Some(message), None) => { (Some(title), Some(message), None) => {
format!("{} - {}", title, message) format!("[{}] {} - {}", token_d, title, message)
} }
(None, Some(message), Some(percentage)) => { (None, Some(message), Some(percentage)) => {
format!("{}% {}", percentage, message) format!("[{}] {}% {}", token_d, percentage, message)
}
(Some(title), None, None) => {
format!("[{}] {}", token_d, title)
} }
(Some(title), None, None) => title, (None, Some(message), None) => {
(None, Some(message), None) => message, format!("[{}] {}", token_d, message)
(None, None, Some(percentage)) => format!("{}%", percentage),
(None, None, None) => "".into(),
} }
(None, None, Some(percentage)) => {
format!("[{}] {}%", token_d, percentage)
}
(None, None, None) => format!("[{}]", token_d),
}; };
let status = format!("[{}] {}", token, msg);
if let lsp::WorkDoneProgress::End(_) = work {
self.lsp_progress.end_progress(server_id, &token);
} else {
self.lsp_progress.update(server_id, token, work);
}
if self.lsp_progress_enabled {
self.editor.set_status(status); self.editor.set_status(status);
self.render(); self.render();
} }
}
_ => unreachable!(), _ => unreachable!(),
} }
} }
Call::MethodCall(call) => { Call::MethodCall(helix_lsp::jsonrpc::MethodCall {
error!("Method not found {}", call.method); method,
params,
jsonrpc,
id,
}) => {
let call = match MethodCall::parse(&method, params) {
Some(call) => call,
None => {
error!("Method not found {}", method);
return;
}
};
match call {
MethodCall::WorkDoneProgressCreate(params) => {
self.lsp_progress.create(server_id, params.token);
let doc = self.editor.documents().find(|doc| {
doc.language_server()
.map(|server| server.id() == server_id)
.unwrap_or_default()
});
match doc {
Some(doc) => {
// it's ok to unwrap, we check for the language server before
let server = doc.language_server().unwrap();
tokio::spawn(server.reply(id, Ok(serde_json::Value::Null)));
}
None => {
if let Some(server) =
self.editor.language_servers.get_by_id(server_id)
{
log::warn!(
"missing document with language server id `{}`",
server_id
);
tokio::spawn(server.reply(
id,
Err(helix_lsp::jsonrpc::Error {
code: helix_lsp::jsonrpc::ErrorCode::InternalError,
message: "document missing".to_string(),
data: None,
}),
));
} else {
log::warn!(
"can't find language server with id `{}`",
server_id
);
}
}
}
}
}
// self.language_server.reply( // self.language_server.reply(
// call.id, // call.id,
// // TODO: make a Into trait that can cast to Err(jsonrpc::Error) // // TODO: make a Into trait that can cast to Err(jsonrpc::Error)
@ -330,6 +406,8 @@ impl Application {
self.event_loop().await; self.event_loop().await;
self.editor.close_language_servers(None).await;
// reset cursor shape // reset cursor shape
write!(stdout, "\x1B[2 q"); write!(stdout, "\x1B[2 q");

File diff suppressed because it is too large Load Diff

@ -0,0 +1,63 @@
use serde::Deserialize;
use crate::commands::Command;
use crate::keymap::Keymaps;
#[derive(Debug, PartialEq, Deserialize)]
pub struct GlobalConfig {
pub lsp_progress: bool,
}
impl Default for GlobalConfig {
fn default() -> Self {
Self { lsp_progress: true }
}
}
#[derive(Debug, Default, PartialEq, Deserialize)]
#[serde(default)]
pub struct Config {
pub global: GlobalConfig,
pub keys: Keymaps,
}
#[test]
fn parsing_keymaps_config_file() {
use helix_core::hashmap;
use helix_view::document::Mode;
use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
let sample_keymaps = r#"
[keys.insert]
y = "move_line_down"
S-C-a = "delete_selection"
[keys.normal]
A-F12 = "move_next_word_end"
"#;
assert_eq!(
toml::from_str::<Config>(sample_keymaps).unwrap(),
Config {
global: Default::default(),
keys: Keymaps(hashmap! {
Mode::Insert => hashmap! {
KeyEvent {
code: KeyCode::Char('y'),
modifiers: KeyModifiers::NONE,
} => Command::move_line_down,
KeyEvent {
code: KeyCode::Char('a'),
modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL,
} => Command::delete_selection,
},
Mode::Normal => hashmap! {
KeyEvent {
code: KeyCode::F(12),
modifiers: KeyModifiers::ALT,
} => Command::move_next_word_end,
},
})
}
);
}

@ -1,7 +1,16 @@
use crate::commands::{self, Command}; use crate::commands;
pub use crate::commands::Command;
use anyhow::{anyhow, Error, Result};
use helix_core::hashmap; use helix_core::hashmap;
use helix_view::document::Mode; use helix_view::document::Mode;
use std::collections::HashMap; use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
use serde::Deserialize;
use std::{
collections::HashMap,
fmt::Display,
ops::{Deref, DerefMut},
str::FromStr,
};
// Kakoune-inspired: // Kakoune-inspired:
// mode = { // mode = {
@ -92,12 +101,6 @@ use std::collections::HashMap;
// D] = last diagnostic // D] = last diagnostic
// } // }
// #[cfg(feature = "term")]
pub use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
pub type Keymap = HashMap<KeyEvent, Command>;
pub type Keymaps = HashMap<Mode, Keymap>;
#[macro_export] #[macro_export]
macro_rules! key { macro_rules! key {
($key:ident) => { ($key:ident) => {
@ -132,67 +135,80 @@ macro_rules! alt {
}; };
} }
pub fn default() -> Keymaps { #[derive(Debug, PartialEq, Deserialize)]
#[serde(transparent)]
pub struct Keymaps(pub HashMap<Mode, HashMap<KeyEvent, Command>>);
impl Deref for Keymaps {
type Target = HashMap<Mode, HashMap<KeyEvent, Command>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Default for Keymaps {
fn default() -> Keymaps {
let normal = hashmap!( let normal = hashmap!(
key!('h') => commands::move_char_left as Command, key!('h') => Command::move_char_left,
key!('j') => commands::move_line_down, key!('j') => Command::move_line_down,
key!('k') => commands::move_line_up, key!('k') => Command::move_line_up,
key!('l') => commands::move_char_right, key!('l') => Command::move_char_right,
key!(Left) => commands::move_char_left, key!(Left) => Command::move_char_left,
key!(Down) => commands::move_line_down, key!(Down) => Command::move_line_down,
key!(Up) => commands::move_line_up, key!(Up) => Command::move_line_up,
key!(Right) => commands::move_char_right, key!(Right) => Command::move_char_right,
key!('t') => commands::find_till_char, key!('t') => Command::find_till_char,
key!('f') => commands::find_next_char, key!('f') => Command::find_next_char,
key!('T') => commands::till_prev_char, key!('T') => Command::till_prev_char,
key!('F') => commands::find_prev_char, key!('F') => Command::find_prev_char,
// and matching set for select mode (extend) // and matching set for select mode (extend)
// //
key!('r') => commands::replace, key!('r') => Command::replace,
key!('R') => commands::replace_with_yanked, key!('R') => Command::replace_with_yanked,
key!(Home) => commands::move_line_start, key!(Home) => Command::move_line_start,
key!(End) => commands::move_line_end, key!(End) => Command::move_line_end,
key!('w') => commands::move_next_word_start, key!('w') => Command::move_next_word_start,
key!('b') => commands::move_prev_word_start, key!('b') => Command::move_prev_word_start,
key!('e') => commands::move_next_word_end, key!('e') => Command::move_next_word_end,
key!('v') => commands::select_mode, key!('v') => Command::select_mode,
key!('g') => commands::goto_mode, key!('g') => Command::goto_mode,
key!(':') => commands::command_mode, key!(':') => Command::command_mode,
key!('i') => commands::insert_mode, key!('i') => Command::insert_mode,
key!('I') => commands::prepend_to_line, key!('I') => Command::prepend_to_line,
key!('a') => commands::append_mode, key!('a') => Command::append_mode,
key!('A') => commands::append_to_line, key!('A') => Command::append_to_line,
key!('o') => commands::open_below, key!('o') => Command::open_below,
key!('O') => commands::open_above, key!('O') => Command::open_above,
// [<space> ]<space> equivalents too (add blank new line, no edit) // [<space> ]<space> equivalents too (add blank new line, no edit)
key!('d') => commands::delete_selection, key!('d') => Command::delete_selection,
// TODO: also delete without yanking // TODO: also delete without yanking
key!('c') => commands::change_selection, key!('c') => Command::change_selection,
// TODO: also change delete without yanking // TODO: also change delete without yanking
// key!('r') => commands::replace_with_char, // key!('r') => Command::replace_with_char,
key!('s') => commands::select_regex, key!('s') => Command::select_regex,
alt!('s') => commands::split_selection_on_newline, alt!('s') => Command::split_selection_on_newline,
key!('S') => commands::split_selection, key!('S') => Command::split_selection,
key!(';') => commands::collapse_selection, key!(';') => Command::collapse_selection,
alt!(';') => commands::flip_selections, alt!(';') => Command::flip_selections,
key!('%') => commands::select_all, key!('%') => Command::select_all,
key!('x') => commands::select_line, key!('x') => Command::select_line,
key!('X') => commands::extend_line, key!('X') => Command::extend_line,
// or select mode X? // or select mode X?
// extend_to_whole_line, crop_to_whole_line // extend_to_whole_line, crop_to_whole_line
key!('m') => commands::match_brackets, key!('m') => Command::match_brackets,
// TODO: refactor into // TODO: refactor into
// key!('m') => commands::select_to_matching, // key!('m') => commands::select_to_matching,
// key!('M') => commands::back_select_to_matching, // key!('M') => commands::back_select_to_matching,
@ -202,39 +218,39 @@ pub fn default() -> Keymaps {
// repeat_select // repeat_select
// TODO: figure out what key to use // TODO: figure out what key to use
// key!('[') => commands::expand_selection, ?? // key!('[') => Command::expand_selection, ??
key!('[') => commands::left_bracket_mode, key!('[') => Command::left_bracket_mode,
key!(']') => commands::right_bracket_mode, key!(']') => Command::right_bracket_mode,
key!('/') => commands::search, key!('/') => Command::search,
// ? for search_reverse // ? for search_reverse
key!('n') => commands::search_next, key!('n') => Command::search_next,
key!('N') => commands::extend_search_next, key!('N') => Command::extend_search_next,
// N for search_prev // N for search_prev
key!('*') => commands::search_selection, key!('*') => Command::search_selection,
key!('u') => commands::undo, key!('u') => Command::undo,
key!('U') => commands::redo, key!('U') => Command::redo,
key!('y') => commands::yank, key!('y') => Command::yank,
// yank_all // yank_all
key!('p') => commands::paste_after, key!('p') => Command::paste_after,
// paste_all // paste_all
key!('P') => commands::paste_before, key!('P') => Command::paste_before,
key!('>') => commands::indent, key!('>') => Command::indent,
key!('<') => commands::unindent, key!('<') => Command::unindent,
key!('=') => commands::format_selections, key!('=') => Command::format_selections,
key!('J') => commands::join_selections, key!('J') => Command::join_selections,
// TODO: conflicts hover/doc // TODO: conflicts hover/doc
key!('K') => commands::keep_selections, key!('K') => Command::keep_selections,
// TODO: and another method for inverse // TODO: and another method for inverse
// TODO: clashes with space mode // TODO: clashes with space mode
key!(' ') => commands::keep_primary_selection, key!(' ') => Command::keep_primary_selection,
// key!('q') => commands::record_macro, // key!('q') => Command::record_macro,
// key!('Q') => commands::replay_macro, // key!('Q') => Command::replay_macro,
// ~ / apostrophe => change case // ~ / apostrophe => change case
// & align selections // & align selections
@ -242,31 +258,31 @@ pub fn default() -> Keymaps {
// C / altC = copy (repeat) selections on prev/next lines // C / altC = copy (repeat) selections on prev/next lines
key!(Esc) => commands::normal_mode, key!(Esc) => Command::normal_mode,
key!(PageUp) => commands::page_up, key!(PageUp) => Command::page_up,
key!(PageDown) => commands::page_down, key!(PageDown) => Command::page_down,
ctrl!('b') => commands::page_up, ctrl!('b') => Command::page_up,
ctrl!('f') => commands::page_down, ctrl!('f') => Command::page_down,
ctrl!('u') => commands::half_page_up, ctrl!('u') => Command::half_page_up,
ctrl!('d') => commands::half_page_down, ctrl!('d') => Command::half_page_down,
ctrl!('w') => commands::window_mode, ctrl!('w') => Command::window_mode,
// move under <space>c // move under <space>c
ctrl!('c') => commands::toggle_comments, ctrl!('c') => Command::toggle_comments,
key!('K') => commands::hover, key!('K') => Command::hover,
// z family for save/restore/combine from/to sels from register // z family for save/restore/combine from/to sels from register
// supposedly ctrl!('i') but did not work // supposedly ctrl!('i') but did not work
key!(Tab) => commands::jump_forward, key!(Tab) => Command::jump_forward,
ctrl!('o') => commands::jump_backward, ctrl!('o') => Command::jump_backward,
// ctrl!('s') => commands::save_selection, // ctrl!('s') => Command::save_selection,
key!(' ') => commands::space_mode, key!(' ') => Command::space_mode,
key!('z') => commands::view_mode, key!('z') => Command::view_mode,
key!('"') => commands::select_register, key!('"') => Command::select_register,
); );
// TODO: decide whether we want normal mode to also be select mode (kakoune-like), or whether // TODO: decide whether we want normal mode to also be select mode (kakoune-like), or whether
// we keep this separate select mode. More keys can fit into normal mode then, but it's weird // we keep this separate select mode. More keys can fit into normal mode then, but it's weird
@ -274,46 +290,52 @@ pub fn default() -> Keymaps {
let mut select = normal.clone(); let mut select = normal.clone();
select.extend( select.extend(
hashmap!( hashmap!(
key!('h') => commands::extend_char_left as Command, key!('h') => Command::extend_char_left,
key!('j') => commands::extend_line_down, key!('j') => Command::extend_line_down,
key!('k') => commands::extend_line_up, key!('k') => Command::extend_line_up,
key!('l') => commands::extend_char_right, key!('l') => Command::extend_char_right,
key!(Left) => commands::extend_char_left, key!(Left) => Command::extend_char_left,
key!(Down) => commands::extend_line_down, key!(Down) => Command::extend_line_down,
key!(Up) => commands::extend_line_up, key!(Up) => Command::extend_line_up,
key!(Right) => commands::extend_char_right, key!(Right) => Command::extend_char_right,
key!('w') => commands::extend_next_word_start, key!('w') => Command::extend_next_word_start,
key!('b') => commands::extend_prev_word_start, key!('b') => Command::extend_prev_word_start,
key!('e') => commands::extend_next_word_end, key!('e') => Command::extend_next_word_end,
key!('t') => commands::extend_till_char, key!('t') => Command::extend_till_char,
key!('f') => commands::extend_next_char, key!('f') => Command::extend_next_char,
key!('T') => commands::extend_till_prev_char, key!('T') => Command::extend_till_prev_char,
key!('F') => commands::extend_prev_char, key!('F') => Command::extend_prev_char,
key!(Home) => commands::extend_line_start, key!(Home) => Command::extend_line_start,
key!(End) => commands::extend_line_end, key!(End) => Command::extend_line_end,
key!(Esc) => commands::exit_select_mode, key!(Esc) => Command::exit_select_mode,
) )
.into_iter(), .into_iter(),
); );
hashmap!( Keymaps(hashmap!(
// as long as you cast the first item, rust is able to infer the other cases // as long as you cast the first item, rust is able to infer the other cases
// TODO: select could be normal mode with some bindings merged over // TODO: select could be normal mode with some bindings merged over
Mode::Normal => normal, Mode::Normal => normal,
Mode::Select => select, Mode::Select => select,
Mode::Insert => hashmap!( Mode::Insert => hashmap!(
key!(Esc) => commands::normal_mode as Command, key!(Esc) => Command::normal_mode as Command,
key!(Backspace) => commands::insert::delete_char_backward, key!(Backspace) => Command::delete_char_backward,
key!(Delete) => commands::insert::delete_char_forward, key!(Delete) => Command::delete_char_forward,
key!(Enter) => commands::insert::insert_newline, key!(Enter) => Command::insert_newline,
key!(Tab) => commands::insert::insert_tab, key!(Tab) => Command::insert_tab,
key!(Left) => Command::move_char_left,
ctrl!('x') => commands::completion, key!(Down) => Command::move_line_down,
ctrl!('w') => commands::insert::delete_word_backward, key!(Up) => Command::move_line_up,
key!(Right) => Command::move_char_right,
key!(PageUp) => Command::page_up,
key!(PageDown) => Command::page_down,
ctrl!('x') => Command::completion,
ctrl!('w') => Command::delete_word_backward,
), ),
) ))
}
} }

@ -1,8 +1,12 @@
#![allow(unused)] #![allow(unused)]
#[macro_use]
extern crate helix_view;
pub mod application; pub mod application;
pub mod args; pub mod args;
pub mod commands; pub mod commands;
pub mod compositor; pub mod compositor;
pub mod config;
pub mod keymap; pub mod keymap;
pub mod ui; pub mod ui;

@ -1,10 +1,9 @@
use anyhow::{Context, Error, Result};
use helix_term::application::Application; use helix_term::application::Application;
use helix_term::args::Args; use helix_term::args::Args;
use helix_term::config::Config;
use std::path::PathBuf; use std::path::PathBuf;
use anyhow::{Context, Result};
fn setup_logging(logpath: PathBuf, verbosity: u64) -> Result<()> { fn setup_logging(logpath: PathBuf, verbosity: u64) -> Result<()> {
let mut base_config = fern::Dispatch::new(); let mut base_config = fern::Dispatch::new();
@ -89,10 +88,16 @@ FLAGS:
std::fs::create_dir_all(&conf_dir).ok(); std::fs::create_dir_all(&conf_dir).ok();
} }
let config = match std::fs::read_to_string(conf_dir.join("config.toml")) {
Ok(config) => toml::from_str(&config)?,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Config::default(),
Err(err) => return Err(Error::new(err)),
};
setup_logging(logpath, args.verbosity).context("failed to initialize logging")?; setup_logging(logpath, args.verbosity).context("failed to initialize logging")?;
// TODO: use the thread local executor to spawn the application task separately from the work pool // TODO: use the thread local executor to spawn the application task separately from the work pool
let mut app = Application::new(args).context("unable to create new appliction")?; let mut app = Application::new(args, config).context("unable to create new application")?;
app.run().await.unwrap(); app.run().await.unwrap();
Ok(()) Ok(())

@ -89,7 +89,7 @@ impl Completion {
// doc.state = snapshot.clone(); // doc.state = snapshot.clone();
} }
PromptEvent::Validate => { PromptEvent::Validate => {
let (view, doc) = editor.current(); let (view, doc) = current!(editor);
// revert state to what it was before the last update // revert state to what it was before the last update
// doc.state = snapshot.clone(); // doc.state = snapshot.clone();
@ -169,7 +169,7 @@ impl Completion {
pub fn update(&mut self, cx: &mut commands::Context) { pub fn update(&mut self, cx: &mut commands::Context) {
// recompute menu based on matches // recompute menu based on matches
let menu = self.popup.contents_mut(); let menu = self.popup.contents_mut();
let (view, doc) = cx.editor.current(); let (view, doc) = current!(cx.editor);
// cx.hooks() // cx.hooks()
// cx.add_hook(enum type, ||) // cx.add_hook(enum type, ||)
@ -233,7 +233,7 @@ impl Component for Completion {
// --- // ---
// option.documentation // option.documentation
let (view, doc) = cx.editor.current(); let (view, doc) = current!(cx.editor);
let language = doc let language = doc
.language() .language()
.and_then(|scope| scope.strip_prefix("source.")) .and_then(|scope| scope.strip_prefix("source."))

@ -11,15 +11,13 @@ use helix_core::{
syntax::{self, HighlightEvent}, syntax::{self, HighlightEvent},
Position, Range, Position, Range,
}; };
use helix_view::{ use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
document::{IndentStyle, Mode}, use helix_view::{document::Mode, Document, Editor, Theme, View};
Document, Editor, Theme, View,
};
use std::borrow::Cow; use std::borrow::Cow;
use crossterm::{ use crossterm::{
cursor, cursor,
event::{read, Event, EventStream, KeyCode, KeyEvent, KeyModifiers}, event::{read, Event, EventStream},
}; };
use tui::{ use tui::{
backend::CrosstermBackend, backend::CrosstermBackend,
@ -30,7 +28,7 @@ use tui::{
}; };
pub struct EditorView { pub struct EditorView {
keymap: Keymaps, keymaps: Keymaps,
on_next_key: Option<Box<dyn FnOnce(&mut commands::Context, KeyEvent)>>, on_next_key: Option<Box<dyn FnOnce(&mut commands::Context, KeyEvent)>>,
last_insert: (commands::Command, Vec<KeyEvent>), last_insert: (commands::Command, Vec<KeyEvent>),
completion: Option<Completion>, completion: Option<Completion>,
@ -40,16 +38,16 @@ const OFFSET: u16 = 7; // 1 diagnostic + 5 linenr + 1 gutter
impl Default for EditorView { impl Default for EditorView {
fn default() -> Self { fn default() -> Self {
Self::new() Self::new(Keymaps::default())
} }
} }
impl EditorView { impl EditorView {
pub fn new() -> Self { pub fn new(keymaps: Keymaps) -> Self {
Self { Self {
keymap: keymap::default(), keymaps,
on_next_key: None, on_next_key: None,
last_insert: (commands::normal_mode, Vec::new()), last_insert: (commands::Command::normal_mode, Vec::new()),
completion: None, completion: None,
} }
} }
@ -479,18 +477,15 @@ impl EditorView {
Mode::Select => "SEL", Mode::Select => "SEL",
Mode::Normal => "NOR", Mode::Normal => "NOR",
}; };
let text_color = if is_focused { let style = if is_focused {
theme.get("ui.text.focus") theme.get("ui.statusline")
} else { } else {
theme.get("ui.text") theme.get("ui.statusline.inactive")
}; };
// statusline // statusline
surface.set_style( surface.set_style(Rect::new(viewport.x, viewport.y, viewport.width, 1), style);
Rect::new(viewport.x, viewport.y, viewport.width, 1),
theme.get("ui.statusline"),
);
if is_focused { if is_focused {
surface.set_string(viewport.x + 1, viewport.y, mode, text_color); surface.set_string(viewport.x + 1, viewport.y, mode, style);
} }
if let Some(path) = doc.relative_path() { if let Some(path) = doc.relative_path() {
@ -502,7 +497,7 @@ impl EditorView {
viewport.y, viewport.y,
title, title,
viewport.width.saturating_sub(6) as usize, viewport.width.saturating_sub(6) as usize,
text_color, style,
); );
} }
@ -541,13 +536,13 @@ impl EditorView {
viewport.x + viewport.width.saturating_sub(text_len), viewport.x + viewport.width.saturating_sub(text_len),
viewport.y, viewport.y,
right_side_text, right_side_text,
text_color, style,
); );
} }
fn insert_mode(&self, cx: &mut commands::Context, event: KeyEvent) { fn insert_mode(&self, cx: &mut commands::Context, event: KeyEvent) {
if let Some(command) = self.keymap[&Mode::Insert].get(&event) { if let Some(command) = self.keymaps[&Mode::Insert].get(&event) {
command(cx); command.execute(cx);
} else if let KeyEvent { } else if let KeyEvent {
code: KeyCode::Char(ch), code: KeyCode::Char(ch),
.. ..
@ -568,7 +563,7 @@ impl EditorView {
// special handling for repeat operator // special handling for repeat operator
key!('.') => { key!('.') => {
// first execute whatever put us into insert mode // first execute whatever put us into insert mode
(self.last_insert.0)(cxt); self.last_insert.0.execute(cxt);
// then replay the inputs // then replay the inputs
for key in &self.last_insert.1 { for key in &self.last_insert.1 {
self.insert_mode(cxt, *key) self.insert_mode(cxt, *key)
@ -584,8 +579,8 @@ impl EditorView {
// set the register // set the register
cxt.selected_register = cxt.editor.selected_register.take(); cxt.selected_register = cxt.editor.selected_register.take();
if let Some(command) = self.keymap[&mode].get(&event) { if let Some(command) = self.keymaps[&mode].get(&event) {
command(cxt); command.execute(cxt);
} }
} }
} }
@ -613,12 +608,13 @@ impl Component for EditorView {
cx.editor.resize(Rect::new(0, 0, width, height - 1)); cx.editor.resize(Rect::new(0, 0, width, height - 1));
EventResult::Consumed(None) EventResult::Consumed(None)
} }
Event::Key(mut key) => { Event::Key(key) => {
let mut key = KeyEvent::from(key);
canonicalize_key(&mut key); canonicalize_key(&mut key);
// clear status // clear status
cx.editor.status_msg = None; cx.editor.status_msg = None;
let (view, doc) = cx.editor.current(); let (view, doc) = current!(cx.editor);
let mode = doc.mode(); let mode = doc.mode();
let mut cxt = commands::Context { let mut cxt = commands::Context {
@ -687,7 +683,7 @@ impl Component for EditorView {
return EventResult::Ignored; return EventResult::Ignored;
} }
let (view, doc) = cx.editor.current(); let (view, doc) = current!(cx.editor);
view.ensure_cursor_in_view(doc); view.ensure_cursor_in_view(doc);
// mode transitions // mode transitions
@ -699,7 +695,7 @@ impl Component for EditorView {
// how we entered insert mode is important, and we should track that so // how we entered insert mode is important, and we should track that so
// we can repeat the side effect. // we can repeat the side effect.
self.last_insert.0 = self.keymap[&mode][&key]; self.last_insert.0 = self.keymaps[&mode][&key];
self.last_insert.1.clear(); self.last_insert.1.clear();
} }
(Mode::Insert, Mode::Normal) => { (Mode::Insert, Mode::Normal) => {

@ -30,8 +30,9 @@ pub fn regex_prompt(
prompt: String, prompt: String,
fun: impl Fn(&mut View, &mut Document, &mut Registers, Regex) + 'static, fun: impl Fn(&mut View, &mut Document, &mut Registers, Regex) + 'static,
) -> Prompt { ) -> Prompt {
let view_id = cx.view().id; let (view, doc) = current!(cx.editor);
let snapshot = cx.doc().selection(view_id).clone(); let view_id = view.id;
let snapshot = doc.selection(view_id).clone();
Prompt::new( Prompt::new(
prompt, prompt,
@ -40,7 +41,7 @@ pub fn regex_prompt(
match event { match event {
PromptEvent::Abort => { PromptEvent::Abort => {
// TODO: also revert text // TODO: also revert text
let (view, doc) = editor.current(); let (view, doc) = current!(editor);
doc.set_selection(view.id, snapshot.clone()); doc.set_selection(view.id, snapshot.clone());
} }
PromptEvent::Validate => { PromptEvent::Validate => {
@ -54,7 +55,8 @@ pub fn regex_prompt(
match Regex::new(input) { match Regex::new(input) {
Ok(regex) => { Ok(regex) => {
let (view, doc, registers) = editor.current_with_registers(); let (view, doc) = current!(editor);
let registers = &mut editor.registers;
// revert state to what it was before the last update // revert state to what it was before the last update
// TODO: also revert text // TODO: also revert text
@ -124,10 +126,11 @@ pub mod completers {
use ignore::WalkBuilder; use ignore::WalkBuilder;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
let path = Path::new(input); let is_tilde = input.starts_with('~') && input.len() == 1;
let path = helix_view::document::expand_tilde(Path::new(input));
let (dir, file_name) = if input.ends_with('/') { let (dir, file_name) = if input.ends_with('/') {
(path.into(), None) (path, None)
} else { } else {
let file_name = path let file_name = path
.file_name() .file_name()
@ -152,7 +155,16 @@ pub mod completers {
let is_dir = entry.file_type().map_or(false, |entry| entry.is_dir()); let is_dir = entry.file_type().map_or(false, |entry| entry.is_dir());
let path = entry.path(); let path = entry.path();
let mut path = path.strip_prefix(&dir).unwrap_or(path).to_path_buf(); let mut path = if is_tilde {
// if it's a single tilde an absolute path is displayed so that when `TAB` is pressed on
// one of the directories the tilde will be replaced with a valid path not with a relative
// home directory name.
// ~ -> <TAB> -> /home/user
// ~/ -> <TAB> -> ~/first_entry
path.to_path_buf()
} else {
path.strip_prefix(&dir).unwrap_or(path).to_path_buf()
};
if is_dir { if is_dir {
path.push(""); path.push("");
@ -182,7 +194,7 @@ pub mod completers {
}) })
.collect(); .collect();
let range = ((input.len() - file_name.len())..); let range = ((input.len().saturating_sub(file_name.len()))..);
matches.sort_unstable_by_key(|(_file, score)| Reverse(*score)); matches.sort_unstable_by_key(|(_file, score)| Reverse(*score));
files = matches files = matches

@ -53,7 +53,16 @@ impl Prompt {
} }
pub fn insert_char(&mut self, c: char) { pub fn insert_char(&mut self, c: char) {
self.line.insert(self.cursor, c); let pos = if self.line.is_empty() {
0
} else {
self.line
.char_indices()
.nth(self.cursor)
.map(|(pos, _)| pos)
.unwrap_or_else(|| self.line.len())
};
self.line.insert(pos, c);
self.cursor += 1; self.cursor += 1;
self.completion = (self.completion_fn)(&self.line); self.completion = (self.completion_fn)(&self.line);
self.exit_selection(); self.exit_selection();
@ -79,7 +88,13 @@ impl Prompt {
pub fn delete_char_backwards(&mut self) { pub fn delete_char_backwards(&mut self) {
if self.cursor > 0 { if self.cursor > 0 {
self.line.remove(self.cursor - 1); let pos = self
.line
.char_indices()
.nth(self.cursor - 1)
.map(|(pos, _)| pos)
.expect("line is not empty");
self.line.remove(pos);
self.cursor -= 1; self.cursor -= 1;
self.completion = (self.completion_fn)(&self.line); self.completion = (self.completion_fn)(&self.line);
} }

@ -7,6 +7,10 @@ A library to build rich terminal user interfaces or dashboards
""" """
edition = "2018" edition = "2018"
license = "MPL-2.0" license = "MPL-2.0"
categories = ["editor"]
repository = "https://github.com/helix-editor/helix"
homepage = "https://helix-editor.com"
include = ["src/**/*", "README.md"]
[features] [features]
default = ["crossterm"] default = ["crossterm"]

@ -4,6 +4,10 @@ version = "0.2.0"
authors = ["Blaž Hrastnik <blaz@mxxn.io>"] authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
edition = "2018" edition = "2018"
license = "MPL-2.0" license = "MPL-2.0"
description = "UI abstractions for use in backends"
categories = ["editor"]
repository = "https://github.com/helix-editor/helix"
homepage = "https://helix-editor.com"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -13,8 +17,8 @@ default = ["term"]
[dependencies] [dependencies]
anyhow = "1" anyhow = "1"
helix-core = { path = "../helix-core" } helix-core = { version = "0.2", path = "../helix-core" }
helix-lsp = { path = "../helix-lsp"} helix-lsp = { version = "0.2", path = "../helix-lsp"}
# Conversion traits # Conversion traits
tui = { path = "../helix-tui", package = "helix-tui", default-features = false, features = ["crossterm"], optional = true } tui = { path = "../helix-tui", package = "helix-tui", default-features = false, features = ["crossterm"], optional = true }
@ -23,6 +27,7 @@ once_cell = "1.8"
url = "2" url = "2"
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
futures-util = { version = "0.3", features = ["std", "async-await"], default-features = false }
slotmap = "1" slotmap = "1"

@ -1,7 +1,11 @@
use anyhow::{Context, Error}; use anyhow::{anyhow, Context, Error};
use serde::de::{self, Deserialize, Deserializer};
use std::cell::Cell; use std::cell::Cell;
use std::collections::HashMap;
use std::fmt::Display;
use std::future::Future; use std::future::Future;
use std::path::{Component, Path, PathBuf}; use std::path::{Component, Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
use helix_core::{ use helix_core::{
@ -15,8 +19,6 @@ use helix_core::{
use crate::{DocumentId, ViewId}; use crate::{DocumentId, ViewId};
use std::collections::HashMap;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Mode { pub enum Mode {
Normal, Normal,
@ -24,6 +26,40 @@ pub enum Mode {
Insert, Insert,
} }
impl Display for Mode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Mode::Normal => f.write_str("normal"),
Mode::Select => f.write_str("select"),
Mode::Insert => f.write_str("insert"),
}
}
}
impl FromStr for Mode {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"normal" => Ok(Mode::Normal),
"select" => Ok(Mode::Select),
"insert" => Ok(Mode::Insert),
_ => Err(anyhow!("Invalid mode '{}'", s)),
}
}
}
// toml deserializer doesn't seem to recognize string as enum
impl<'de> Deserialize<'de> for Mode {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
s.parse().map_err(de::Error::custom)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum IndentStyle { pub enum IndentStyle {
Tabs, Tabs,
@ -105,6 +141,36 @@ where
} }
} }
/// Expands tilde `~` into users home directory if avilable, otherwise returns the path
/// unchanged. The tilde will only be expanded when present as the first component of the path
/// and only slash follows it.
pub fn expand_tilde(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
if let Some(Component::Normal(c)) = components.peek() {
if c == &"~" {
if let Ok(home) = helix_core::home_dir() {
// it's ok to unwrap, the path starts with `~`
return home.join(path.strip_prefix("~").unwrap());
}
}
}
path.to_path_buf()
}
/// Replaces users home directory from `path` with tilde `~` if the directory
/// is available, otherwise returns the path unchanged.
pub fn fold_home_dir(path: &Path) -> PathBuf {
if let Ok(home) = helix_core::home_dir() {
if path.starts_with(&home) {
// it's ok to unwrap, the path starts with home dir
return PathBuf::from("~").join(path.strip_prefix(&home).unwrap());
}
}
path.to_path_buf()
}
/// Normalize a path, removing things like `.` and `..`. /// Normalize a path, removing things like `.` and `..`.
/// ///
/// CAUTION: This does not resolve symlinks (unlike /// CAUTION: This does not resolve symlinks (unlike
@ -115,6 +181,7 @@ where
/// needs to improve on. /// needs to improve on.
/// Copied from cargo: https://github.com/rust-lang/cargo/blob/070e459c2d8b79c5b2ac5218064e7603329c92ae/crates/cargo-util/src/paths.rs#L81 /// Copied from cargo: https://github.com/rust-lang/cargo/blob/070e459c2d8b79c5b2ac5218064e7603329c92ae/crates/cargo-util/src/paths.rs#L81
pub fn normalize_path(path: &Path) -> PathBuf { pub fn normalize_path(path: &Path) -> PathBuf {
let path = expand_tilde(path);
let mut components = path.components().peekable(); let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() { let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
components.next(); components.next();
@ -141,12 +208,17 @@ pub fn normalize_path(path: &Path) -> PathBuf {
ret ret
} }
// Returns the canonical, absolute form of a path with all intermediate components normalized. /// Returns the canonical, absolute form of a path with all intermediate components normalized.
// ///
// This function is used instead of `std::fs::canonicalize` because we don't want to verify /// This function is used instead of `std::fs::canonicalize` because we don't want to verify
// here if the path exists, just normalize it's components. /// here if the path exists, just normalize it's components.
pub fn canonicalize_path(path: &Path) -> std::io::Result<PathBuf> { pub fn canonicalize_path(path: &Path) -> std::io::Result<PathBuf> {
std::env::current_dir().map(|current_dir| normalize_path(&current_dir.join(path))) let normalized = normalize_path(path);
if normalized.is_absolute() {
Ok(normalized)
} else {
std::env::current_dir().map(|current_dir| current_dir.join(normalized))
}
} }
use helix_lsp::lsp; use helix_lsp::lsp;
@ -210,10 +282,11 @@ impl Document {
pub fn format(&mut self, view_id: ViewId) { pub fn format(&mut self, view_id: ViewId) {
if let Some(language_server) = self.language_server() { if let Some(language_server) = self.language_server() {
// TODO: await, no blocking // TODO: await, no blocking
let transaction = helix_lsp::block_on( let transaction = helix_lsp::block_on(language_server.text_document_formatting(
language_server self.identifier(),
.text_document_formatting(self.identifier(), lsp::FormattingOptions::default()), lsp::FormattingOptions::default(),
) None,
))
.map(|edits| { .map(|edits| {
helix_lsp::util::generate_transaction_from_edits( helix_lsp::util::generate_transaction_from_edits(
self.text(), self.text(),
@ -696,12 +769,19 @@ impl Document {
&self.selections[&view_id] &self.selections[&view_id]
} }
pub fn relative_path(&self) -> Option<&Path> { pub fn relative_path(&self) -> Option<PathBuf> {
let cwdir = std::env::current_dir().expect("couldn't determine current directory"); let cwdir = std::env::current_dir().expect("couldn't determine current directory");
self.path self.path.as_ref().map(|path| {
.as_ref() let path = fold_home_dir(path);
.map(|path| path.strip_prefix(cwdir).unwrap_or(path)) if path.is_relative() {
path
} else {
path.strip_prefix(cwdir)
.map(|p| p.to_path_buf())
.unwrap_or(path)
}
})
} }
// pub fn slice<R>(&self, range: R) -> RopeSlice where R: RangeBounds { // pub fn slice<R>(&self, range: R) -> RopeSlice where R: RangeBounds {

@ -2,7 +2,9 @@ use crate::{theme::Theme, tree::Tree, Document, DocumentId, RegisterSelection, V
use tui::layout::Rect; use tui::layout::Rect;
use tui::terminal::CursorKind; use tui::terminal::CursorKind;
use futures_util::future;
use std::path::PathBuf; use std::path::PathBuf;
use std::time::Duration;
use slotmap::SlotMap; use slotmap::SlotMap;
@ -101,19 +103,19 @@ impl Editor {
match action { match action {
Action::Replace => { Action::Replace => {
let view = self.view(); let view = view!(self);
let jump = ( let jump = (
view.doc, view.doc,
self.documents[view.doc].selection(view.id).clone(), self.documents[view.doc].selection(view.id).clone(),
); );
let view = self.view_mut(); let view = view_mut!(self);
view.jumps.push(jump); view.jumps.push(jump);
view.last_accessed_doc = Some(view.doc); view.last_accessed_doc = Some(view.doc);
view.doc = id; view.doc = id;
view.first_line = 0; view.first_line = 0;
let (view, doc) = self.current(); let (view, doc) = current!(self);
// initialize selection for view // initialize selection for view
let selection = doc let selection = doc
@ -238,27 +240,6 @@ impl Editor {
self.tree.is_empty() self.tree.is_empty()
} }
pub fn current(&mut self) -> (&mut View, &mut Document) {
let view = self.tree.get_mut(self.tree.focus);
let doc = &mut self.documents[view.doc];
(view, doc)
}
pub fn current_with_registers(&mut self) -> (&mut View, &mut Document, &mut Registers) {
let view = self.tree.get_mut(self.tree.focus);
let doc = &mut self.documents[view.doc];
let registers = &mut self.registers;
(view, doc, registers)
}
pub fn view(&self) -> &View {
self.tree.get(self.tree.focus)
}
pub fn view_mut(&mut self) -> &mut View {
self.tree.get_mut(self.tree.focus)
}
pub fn ensure_cursor_in_view(&mut self, id: ViewId) { pub fn ensure_cursor_in_view(&mut self, id: ViewId) {
let view = self.tree.get_mut(id); let view = self.tree.get_mut(id);
let doc = &self.documents[view.doc]; let doc = &self.documents[view.doc];
@ -280,7 +261,7 @@ impl Editor {
pub fn cursor(&self) -> (Option<Position>, CursorKind) { pub fn cursor(&self) -> (Option<Position>, CursorKind) {
const OFFSET: u16 = 7; // 1 diagnostic + 5 linenr + 1 gutter const OFFSET: u16 = 7; // 1 diagnostic + 5 linenr + 1 gutter
let view = self.view(); let view = view!(self);
let doc = &self.documents[view.doc]; let doc = &self.documents[view.doc];
let cursor = doc.selection(view.id).cursor(); let cursor = doc.selection(view.id).cursor();
if let Some(mut pos) = view.screen_coords_at_pos(doc, doc.text().slice(..), cursor) { if let Some(mut pos) = view.screen_coords_at_pos(doc, doc.text().slice(..), cursor) {
@ -291,4 +272,22 @@ impl Editor {
(None, CursorKind::Hidden) (None, CursorKind::Hidden)
} }
} }
/// Closes language servers with timeout. The default timeout is 500 ms, use
/// `timeout` parameter to override this.
pub async fn close_language_servers(
&self,
timeout: Option<u64>,
) -> Result<(), tokio::time::error::Elapsed> {
tokio::time::timeout(
Duration::from_millis(timeout.unwrap_or(500)),
future::join_all(
self.language_servers
.iter_clients()
.map(|client| client.force_shutdown()),
),
)
.await
.map(|_| ())
}
} }

@ -0,0 +1,226 @@
//! Input event handling, currently backed by crossterm.
use anyhow::{anyhow, Error};
use crossterm::event;
use serde::de::{self, Deserialize, Deserializer};
use std::fmt;
pub use crossterm::event::{KeyCode, KeyModifiers};
/// Represents a key event.
// We use a newtype here because we want to customize Deserialize and Display.
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy, Hash)]
pub struct KeyEvent {
pub code: KeyCode,
pub modifiers: KeyModifiers,
}
impl fmt::Display for KeyEvent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"{}{}{}",
if self.modifiers.contains(KeyModifiers::SHIFT) {
"S-"
} else {
""
},
if self.modifiers.contains(KeyModifiers::ALT) {
"A-"
} else {
""
},
if self.modifiers.contains(KeyModifiers::CONTROL) {
"C-"
} else {
""
},
))?;
match self.code {
KeyCode::Backspace => f.write_str("backspace")?,
KeyCode::Enter => f.write_str("ret")?,
KeyCode::Left => f.write_str("left")?,
KeyCode::Right => f.write_str("right")?,
KeyCode::Up => f.write_str("up")?,
KeyCode::Down => f.write_str("down")?,
KeyCode::Home => f.write_str("home")?,
KeyCode::End => f.write_str("end")?,
KeyCode::PageUp => f.write_str("pageup")?,
KeyCode::PageDown => f.write_str("pagedown")?,
KeyCode::Tab => f.write_str("tab")?,
KeyCode::BackTab => f.write_str("backtab")?,
KeyCode::Delete => f.write_str("del")?,
KeyCode::Insert => f.write_str("ins")?,
KeyCode::Null => f.write_str("null")?,
KeyCode::Esc => f.write_str("esc")?,
KeyCode::Char('<') => f.write_str("lt")?,
KeyCode::Char('>') => f.write_str("gt")?,
KeyCode::Char('+') => f.write_str("plus")?,
KeyCode::Char('-') => f.write_str("minus")?,
KeyCode::Char(';') => f.write_str("semicolon")?,
KeyCode::Char('%') => f.write_str("percent")?,
KeyCode::F(i) => f.write_fmt(format_args!("F{}", i))?,
KeyCode::Char(c) => f.write_fmt(format_args!("{}", c))?,
};
Ok(())
}
}
impl std::str::FromStr for KeyEvent {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut tokens: Vec<_> = s.split('-').collect();
let code = match tokens.pop().ok_or_else(|| anyhow!("Missing key code"))? {
"backspace" => KeyCode::Backspace,
"space" => KeyCode::Char(' '),
"ret" => KeyCode::Enter,
"lt" => KeyCode::Char('<'),
"gt" => KeyCode::Char('>'),
"plus" => KeyCode::Char('+'),
"minus" => KeyCode::Char('-'),
"semicolon" => KeyCode::Char(';'),
"percent" => KeyCode::Char('%'),
"left" => KeyCode::Left,
"right" => KeyCode::Right,
"up" => KeyCode::Down,
"home" => KeyCode::Home,
"end" => KeyCode::End,
"pageup" => KeyCode::PageUp,
"pagedown" => KeyCode::PageDown,
"tab" => KeyCode::Tab,
"backtab" => KeyCode::BackTab,
"del" => KeyCode::Delete,
"ins" => KeyCode::Insert,
"null" => KeyCode::Null,
"esc" => KeyCode::Esc,
single if single.len() == 1 => KeyCode::Char(single.chars().next().unwrap()),
function if function.len() > 1 && function.starts_with('F') => {
let function: String = function.chars().skip(1).collect();
let function = str::parse::<u8>(&function)?;
(function > 0 && function < 13)
.then(|| KeyCode::F(function))
.ok_or_else(|| anyhow!("Invalid function key '{}'", function))?
}
invalid => return Err(anyhow!("Invalid key code '{}'", invalid)),
};
let mut modifiers = KeyModifiers::empty();
for token in tokens {
let flag = match token {
"S" => KeyModifiers::SHIFT,
"A" => KeyModifiers::ALT,
"C" => KeyModifiers::CONTROL,
_ => return Err(anyhow!("Invalid key modifier '{}-'", token)),
};
if modifiers.contains(flag) {
return Err(anyhow!("Repeated key modifier '{}-'", token));
}
modifiers.insert(flag);
}
Ok(KeyEvent { code, modifiers })
}
}
impl<'de> Deserialize<'de> for KeyEvent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
s.parse().map_err(de::Error::custom)
}
}
impl From<event::KeyEvent> for KeyEvent {
fn from(event::KeyEvent { code, modifiers }: event::KeyEvent) -> KeyEvent {
KeyEvent { code, modifiers }
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn parsing_unmodified_keys() {
assert_eq!(
str::parse::<KeyEvent>("backspace").unwrap(),
KeyEvent {
code: KeyCode::Backspace,
modifiers: KeyModifiers::NONE
}
);
assert_eq!(
str::parse::<KeyEvent>("left").unwrap(),
KeyEvent {
code: KeyCode::Left,
modifiers: KeyModifiers::NONE
}
);
assert_eq!(
str::parse::<KeyEvent>(",").unwrap(),
KeyEvent {
code: KeyCode::Char(','),
modifiers: KeyModifiers::NONE
}
);
assert_eq!(
str::parse::<KeyEvent>("w").unwrap(),
KeyEvent {
code: KeyCode::Char('w'),
modifiers: KeyModifiers::NONE
}
);
assert_eq!(
str::parse::<KeyEvent>("F12").unwrap(),
KeyEvent {
code: KeyCode::F(12),
modifiers: KeyModifiers::NONE
}
);
}
#[test]
fn parsing_modified_keys() {
assert_eq!(
str::parse::<KeyEvent>("S-minus").unwrap(),
KeyEvent {
code: KeyCode::Char('-'),
modifiers: KeyModifiers::SHIFT
}
);
assert_eq!(
str::parse::<KeyEvent>("C-A-S-F12").unwrap(),
KeyEvent {
code: KeyCode::F(12),
modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL | KeyModifiers::ALT
}
);
assert_eq!(
str::parse::<KeyEvent>("S-C-2").unwrap(),
KeyEvent {
code: KeyCode::Char('2'),
modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL
}
);
}
#[test]
fn parsing_nonsensical_keys_fails() {
assert!(str::parse::<KeyEvent>("F13").is_err());
assert!(str::parse::<KeyEvent>("F0").is_err());
assert!(str::parse::<KeyEvent>("aaa").is_err());
assert!(str::parse::<KeyEvent>("S-S-a").is_err());
assert!(str::parse::<KeyEvent>("C-A-S-C-1").is_err());
assert!(str::parse::<KeyEvent>("FU").is_err());
assert!(str::parse::<KeyEvent>("123").is_err());
assert!(str::parse::<KeyEvent>("S--").is_err());
}
}

@ -1,13 +1,18 @@
#[macro_use]
pub mod macros;
pub mod document; pub mod document;
pub mod editor; pub mod editor;
pub mod input;
pub mod register_selection; pub mod register_selection;
pub mod theme; pub mod theme;
pub mod tree; pub mod tree;
pub mod view; pub mod view;
use slotmap::new_key_type; slotmap::new_key_type! {
new_key_type! { pub struct DocumentId; } pub struct DocumentId;
new_key_type! { pub struct ViewId; } pub struct ViewId;
}
pub use document::Document; pub use document::Document;
pub use editor::Editor; pub use editor::Editor;

@ -0,0 +1,29 @@
#[macro_export]
macro_rules! current {
( $( $editor:ident ).+ ) => {{
let view = $crate::view_mut!( $( $editor ).+ );
let doc = &mut $( $editor ).+ .documents[view.doc];
(view, doc)
}};
}
#[macro_export]
macro_rules! doc_mut {
( $( $editor:ident ).+ ) => {{
$crate::current!( $( $editor ).+ ).1
}};
}
#[macro_export]
macro_rules! view_mut {
( $( $editor:ident ).+ ) => {{
$( $editor ).+ .tree.get_mut($( $editor ).+ .tree.focus)
}};
}
#[macro_export]
macro_rules! view {
( $( $editor:ident ).+ ) => {{
$( $editor ).+ .tree.get($( $editor ).+ .tree.focus)
}};
}

@ -41,7 +41,8 @@
"ui.background" = { bg = "#3b224c" } # midnight "ui.background" = { bg = "#3b224c" } # midnight
"ui.linenr" = { fg = "#5a5977" } # comet "ui.linenr" = { fg = "#5a5977" } # comet
"ui.linenr.selected" = { fg = "#dbbfef" } # lilac "ui.linenr.selected" = { fg = "#dbbfef" } # lilac
"ui.statusline" = { bg = "#281733" } # revolver "ui.statusline" = { fg = "#dbbfef", bg = "#281733" } # revolver
"ui.statusline.inactive" = { fg = "#a4a0e8", bg = "#281733" } # revolver
"ui.popup" = { bg = "#281733" } # revolver "ui.popup" = { bg = "#281733" } # revolver
"ui.window" = { bg = "#452859" } # bossa nova "ui.window" = { bg = "#452859" } # bossa nova
"ui.window" = { bg = "#452859" } # bossa nova "ui.window" = { bg = "#452859" } # bossa nova

Loading…
Cancel
Save