Skip to content

Commit

Permalink
add workspace config and manual LSP root management
Browse files Browse the repository at this point in the history
  • Loading branch information
pascalkuthe committed Jan 31, 2023
1 parent 4dcf1fe commit ee0e2b2
Show file tree
Hide file tree
Showing 15 changed files with 286 additions and 193 deletions.
4 changes: 4 additions & 0 deletions book/src/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ hidden = false
You may also specify a file to use for configuration with the `-c` or
`--config` CLI argument: `hx -c path/to/custom-config.toml`.

Finally, you can have a `config.toml` local to a project by putting it under a `.helix` directory in your repository.
Its settings will be merged with the configuration directory `config.toml` and the built-in configuration.

It is also possible to trigger configuration file reloading by sending the `USR1`
signal to the helix process, e.g. via `pkill -USR1 hx`. This is only supported
on unix operating systems.
Expand Down Expand Up @@ -57,6 +60,7 @@ on unix operating systems.
| `rulers` | List of column positions at which to display the rulers. Can be overridden by language specific `rulers` in `languages.toml` file. | `[]` |
| `bufferline` | Renders a line at the top of the editor displaying open buffers. Can be `always`, `never` or `multiple` (only shown if more than one buffer is in use) | `never` |
| `color-modes` | Whether to color the mode indicator with different colors depending on the mode itself | `false` |
| `workspace-roots` | Directories relative to the workspace root that are treated as LSP roots. Should only be set in `.helix/config.toml` | `[]` |

### `[editor.statusline]` Section

Expand Down
1 change: 1 addition & 0 deletions book/src/generated/typable-cmd.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
| `:tree-sitter-subtree`, `:ts-subtree` | Display tree sitter subtree under cursor, primarily for debugging queries. |
| `:config-reload` | Refresh user config. |
| `:config-open` | Open the user config.toml file. |
| `:config-open-workspace` | Open the workspace config.toml file. |
| `:log-open` | Open the helix log file. |
| `:insert-output` | Run shell command, inserting output before each selection. |
| `:append-output` | Run shell command, appending output after each selection. |
Expand Down
1 change: 1 addition & 0 deletions book/src/languages.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ These configuration keys are available:
| `grammar` | The tree-sitter grammar to use (defaults to the value of `name`) |
| `formatter` | The formatter for the language, it will take precedence over the lsp when defined. The formatter must be able to take the original file as input from stdin and write the formatted file to stdout |
| `max-line-length` | Maximum line length. Used for the `:reflow` command and soft-wrapping |
| `workspace-roots` | Directories relative to the workspace root that are treated as LSP roots. Should only be set in `.helix/config.toml`. Overwrites the setting of the same name in `config.toml` if set. | `` |

### File-type detection and the `file-types` key

Expand Down
47 changes: 2 additions & 45 deletions helix-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,55 +36,12 @@ pub mod unicode {
pub use unicode_width as width;
}

pub use helix_loader::find_root;

pub fn find_first_non_whitespace_char(line: RopeSlice) -> Option<usize> {
line.chars().position(|ch| !ch.is_whitespace())
}

/// Find project root.
///
/// Order of detection:
/// * Top-most folder containing a root marker in current git repository
/// * Git repository root if no marker detected
/// * Top-most folder containing a root marker if not git repository detected
/// * Current working directory as fallback
pub fn find_root(root: Option<&str>, root_markers: &[String]) -> std::path::PathBuf {
let current_dir = std::env::current_dir().expect("unable to determine current directory");

let root = match root {
Some(root) => {
let root = std::path::Path::new(root);
if root.is_absolute() {
root.to_path_buf()
} else {
current_dir.join(root)
}
}
None => current_dir.clone(),
};

let mut top_marker = None;
for ancestor in root.ancestors() {
if root_markers
.iter()
.any(|marker| ancestor.join(marker).exists())
{
top_marker = Some(ancestor);
}

if ancestor.join(".git").exists() {
// Top marker is repo root if not root marker was detected yet
if top_marker.is_none() {
top_marker = Some(ancestor);
}
// Don't go higher than repo if we're in one
break;
}
}

// Return the found top marker or the current_dir as fallback
top_marker.map_or(current_dir, |a| a.to_path_buf())
}

pub use ropey::{self, str_utils, Rope, RopeBuilder, RopeSlice};

// pub use tendril::StrTendril as Tendril;
Expand Down
5 changes: 4 additions & 1 deletion helix-core/src/syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use std::{
fmt,
hash::{Hash, Hasher},
mem::{replace, transmute},
path::Path,
path::{Path, PathBuf},
str::FromStr,
sync::Arc,
};
Expand Down Expand Up @@ -126,6 +126,9 @@ pub struct LanguageConfiguration {
pub auto_pairs: Option<AutoPairs>,

pub rulers: Option<Vec<u16>>, // if set, override editor's rulers

/// Hardcoded LSP root direcotries relative to the workspace root like `examples` or `tools/fuzz`
pub workspace_roots: Option<Vec<PathBuf>>,
}

#[derive(Debug, PartialEq, Eq, Hash)]
Expand Down
63 changes: 32 additions & 31 deletions helix-loader/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,37 +9,38 @@ pub fn default_lang_config() -> toml::Value {

/// User configured languages.toml file, merged with the default config.
pub fn user_lang_config() -> Result<toml::Value, toml::de::Error> {
let config = crate::local_config_dirs()
.into_iter()
.chain([crate::config_dir()].into_iter())
.map(|path| path.join("languages.toml"))
.filter_map(|file| {
std::fs::read_to_string(file)
.map(|config| toml::from_str(&config))
.ok()
})
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.chain([default_lang_config()].into_iter())
.fold(toml::Value::Table(toml::value::Table::default()), |a, b| {
// combines for example
// b:
// [[language]]
// name = "toml"
// language-server = { command = "taplo", args = ["lsp", "stdio"] }
//
// a:
// [[language]]
// language-server = { command = "/usr/bin/taplo" }
//
// into:
// [[language]]
// name = "toml"
// language-server = { command = "/usr/bin/taplo" }
//
// thus it overrides the third depth-level of b with values of a if they exist, but otherwise merges their values
crate::merge_toml_values(b, a, 3)
});
let config = [
crate::config_dir(),
crate::find_root(None, &[], &[]).join(".helix"),
]
.into_iter()
.map(|path| path.join("languages.toml"))
.filter_map(|file| {
std::fs::read_to_string(file)
.map(|config| toml::from_str(&config))
.ok()
})
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.fold(default_lang_config(), |a, b| {
// combines for example
// b:
// [[language]]
// name = "toml"
// language-server = { command = "taplo", args = ["lsp", "stdio"] }
//
// a:
// [[language]]
// language-server = { command = "/usr/bin/taplo" }
//
// into:
// [[language]]
// name = "toml"
// language-server = { command = "/usr/bin/taplo" }
//
// thus it overrides the third depth-level of b with values of a if they exist, but otherwise merges their values
crate::merge_toml_values(a, b, 3)
});

Ok(config)
}
69 changes: 43 additions & 26 deletions helix-loader/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub fn runtime_dir() -> PathBuf {

if let Ok(dir) = std::env::var("CARGO_MANIFEST_DIR") {
// this is the directory of the crate being run by cargo, we need the workspace path so we take the parent
let path = std::path::PathBuf::from(dir).parent().unwrap().join(RT_DIR);
let path = PathBuf::from(dir).parent().unwrap().join(RT_DIR);
log::debug!("runtime dir: {}", path.to_string_lossy());
return path;
}
Expand Down Expand Up @@ -60,15 +60,6 @@ pub fn config_dir() -> PathBuf {
path
}

pub fn local_config_dirs() -> Vec<PathBuf> {
let directories = find_local_config_dirs()
.into_iter()
.map(|path| path.join(".helix"))
.collect();
log::debug!("Located configuration folders: {:?}", directories);
directories
}

pub fn cache_dir() -> PathBuf {
// TODO: allow env var override
let strategy = choose_base_strategy().expect("Unable to find the config directory!");
Expand All @@ -84,6 +75,10 @@ pub fn config_file() -> PathBuf {
.unwrap_or_else(|| config_dir().join("config.toml"))
}

pub fn workspace_config_file() -> PathBuf {
find_root(None, &[], &[]).join(".helix").join("config.toml")
}

pub fn lang_config_file() -> PathBuf {
config_dir().join("languages.toml")
}
Expand All @@ -92,22 +87,6 @@ pub fn log_file() -> PathBuf {
cache_dir().join("helix.log")
}

pub fn find_local_config_dirs() -> Vec<PathBuf> {
let current_dir = std::env::current_dir().expect("unable to determine current directory");
let mut directories = Vec::new();

for ancestor in current_dir.ancestors() {
if ancestor.join(".git").exists() {
directories.push(ancestor.to_path_buf());
// Don't go higher than repo if we're in one
break;
} else if ancestor.join(".helix").is_dir() {
directories.push(ancestor.to_path_buf());
}
}
directories
}

/// Merge two TOML documents, merging values from `right` onto `left`
///
/// When an array exists in both `left` and `right`, `right`'s array is
Expand Down Expand Up @@ -249,3 +228,41 @@ mod merge_toml_tests {
)
}
}

pub fn find_root(root: Option<&str>, root_markers: &[String], root_dirs: &[PathBuf]) -> PathBuf {
let current_dir = std::env::current_dir().expect("unable to determine current directory");

let root = match root {
Some(root) => {
let root = std::path::Path::new(root);
if root.is_absolute() {
root.to_path_buf()
} else {
current_dir.join(root)
}
}
None => current_dir.clone(),
};

let mut top_marker = None;
for ancestor in root.ancestors() {
if root_markers
.iter()
.any(|marker| ancestor.join(marker).exists())
{
top_marker = Some(ancestor);
}

if ancestor.join(".git").is_dir() || root_dirs.iter().any(|dir| ancestor.ends_with(dir)) {
// Top marker is repo root if not root marker was detected yet
if top_marker.is_none() {
top_marker = Some(ancestor);
}
// Don't go higher than repo if we're in one
break;
}
}

// Return the found top marker or the current_dir as fallback
top_marker.map_or(current_dir, |a| a.to_path_buf())
}
4 changes: 3 additions & 1 deletion helix-lsp/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ use helix_loader::{self, VERSION_AND_GIT_HASH};
use lsp_types as lsp;
use serde::Deserialize;
use serde_json::Value;
use std::collections::HashMap;
use std::future::Future;
use std::process::Stdio;
use std::sync::{
atomic::{AtomicU64, Ordering},
Arc,
};
use std::{collections::HashMap, path::PathBuf};
use tokio::{
io::{BufReader, BufWriter},
process::{Child, Command},
Expand Down Expand Up @@ -49,6 +49,7 @@ impl Client {
config: Option<Value>,
server_environment: HashMap<String, String>,
root_markers: &[String],
manual_roots: &[PathBuf],
id: usize,
req_timeout: u64,
doc_path: Option<&std::path::PathBuf>,
Expand Down Expand Up @@ -79,6 +80,7 @@ impl Client {
let root_path = find_root(
doc_path.and_then(|x| x.parent().and_then(|x| x.to_str())),
root_markers,
manual_roots,
);

let root_uri = lsp::Url::from_file_path(root_path.clone()).ok();
Expand Down
9 changes: 7 additions & 2 deletions helix-lsp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use tokio::sync::mpsc::UnboundedReceiver;

use std::{
collections::{hash_map::Entry, HashMap},
path::PathBuf,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
Expand Down Expand Up @@ -398,6 +399,7 @@ impl Registry {
&mut self,
language_config: &LanguageConfiguration,
doc_path: Option<&std::path::PathBuf>,
root_dirs: &[PathBuf],
) -> Result<Option<Arc<Client>>> {
let config = match &language_config.language_server {
Some(config) => config,
Expand All @@ -413,7 +415,7 @@ impl Registry {
let id = self.counter.fetch_add(1, Ordering::Relaxed);

let NewClientResult(client, incoming) =
start_client(id, language_config, config, doc_path)?;
start_client(id, language_config, config, doc_path, root_dirs)?;
self.incoming.push(UnboundedReceiverStream::new(incoming));

let (_, old_client) = entry.insert((id, client.clone()));
Expand All @@ -431,6 +433,7 @@ impl Registry {
&mut self,
language_config: &LanguageConfiguration,
doc_path: Option<&std::path::PathBuf>,
root_dirs: &[PathBuf],
) -> Result<Option<Arc<Client>>> {
let config = match &language_config.language_server {
Some(config) => config,
Expand All @@ -444,7 +447,7 @@ impl Registry {
let id = self.counter.fetch_add(1, Ordering::Relaxed);

let NewClientResult(client, incoming) =
start_client(id, language_config, config, doc_path)?;
start_client(id, language_config, config, doc_path, root_dirs)?;
self.incoming.push(UnboundedReceiverStream::new(incoming));

entry.insert((id, client.clone()));
Expand Down Expand Up @@ -545,13 +548,15 @@ fn start_client(
config: &LanguageConfiguration,
ls_config: &LanguageServerConfiguration,
doc_path: Option<&std::path::PathBuf>,
root_dirs: &[PathBuf],
) -> Result<NewClientResult> {
let (client, incoming, initialize_notify) = Client::start(
&ls_config.command,
&ls_config.args,
config.config.clone(),
ls_config.environment.clone(),
&config.roots,
config.workspace_roots.as_deref().unwrap_or(root_dirs),
id,
ls_config.timeout,
doc_path,
Expand Down
2 changes: 1 addition & 1 deletion helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2391,7 +2391,7 @@ fn append_mode(cx: &mut Context) {
fn file_picker(cx: &mut Context) {
// We don't specify language markers, root will be the root of the current
// git repo or the current dir if we're not in a repo
let root = find_root(None, &[]);
let root = find_root(None, &[], &[]);
let picker = ui::file_picker(root, &cx.editor.config());
cx.push_layer(Box::new(overlayed(picker)));
}
Expand Down
Loading

0 comments on commit ee0e2b2

Please sign in to comment.