Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions book/src/install.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,9 @@ RUSTFLAGS="-C target-feature=-crt-static"


Helix also needs its runtime files so make sure to copy/symlink the `runtime/` directory into the
config directory (for example `~/.config/helix/runtime` on Linux/macOS). This location can be overridden
via the `HELIX_RUNTIME` environment variable.
config directory (for example `~/.config/helix/runtime` on Linux/macOS). An alternative runtime directory can
be used by setting the `HELIX_RUNTIME` environment variable. Both runtime directories can be used at the same
time, with the files residing under the config runtime directory given priority.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can be expanded a bit, ideally we would have bullet points here that exactly lists what directories are searched in what order (and where grammars are installed by the cli)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. I've also moved it down slightly in the document to try and make the flow make a bit more sense.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There was a conflict with master. I've now merged in latest master and resolved the conflict.

BTW, what is the preferred process to keep these PRs up to date / conflict free with master? Should we be periodically rebasing and force pushing to our PR branch, or doing a regular merge? I was doing the former to try and keep things cleaner but then I see archseer at some point decided to do a regular merge.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rebase is preferred but if it's a small PR that we'll squash then it'll result in a single commit anyway


| OS | Command |
| -------------------- | ------------------------------------------------ |
Expand All @@ -134,11 +135,6 @@ cd %appdata%\helix
mklink /D runtime "<helix-repo>\runtime"
```

The runtime location can be overridden via the `HELIX_RUNTIME` environment variable.

> NOTE: if `HELIX_RUNTIME` is set prior to calling `cargo install --path helix-term --locked`,
> tree-sitter grammars will be built in `$HELIX_RUNTIME/grammars`.

If you plan on keeping the repo locally, an alternative to copying/symlinking
runtime files is to set `HELIX_RUNTIME=/path/to/helix/runtime`
(`HELIX_RUNTIME=$PWD/runtime` if you're in the helix repo directory).
Expand Down
23 changes: 14 additions & 9 deletions helix-loader/src/grammar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,9 @@ pub fn get_language(name: &str) -> Result<Language> {
#[cfg(not(target_arch = "wasm32"))]
pub fn get_language(name: &str) -> Result<Language> {
use libloading::{Library, Symbol};
let mut library_path = crate::runtime_dir().join("grammars").join(name);
library_path.set_extension(DYLIB_EXTENSION);
let mut rel_library_path = PathBuf::new().join("grammars").join(name);
rel_library_path.set_extension(DYLIB_EXTENSION);
let library_path = crate::runtime_file(&rel_library_path);

let library = unsafe { Library::new(&library_path) }
.with_context(|| format!("Error opening dynamic library {:?}", library_path))?;
Expand Down Expand Up @@ -252,7 +253,9 @@ fn fetch_grammar(grammar: GrammarConfiguration) -> Result<FetchStatus> {
remote, revision, ..
} = grammar.source
{
let grammar_dir = crate::runtime_dir()
let grammar_dir = crate::runtime_dirs()
.first()
.expect("No runtime directories provided") // guaranteed by post-condition
.join("grammars")
.join("sources")
.join(&grammar.grammar_id);
Expand Down Expand Up @@ -350,7 +353,9 @@ fn build_grammar(grammar: GrammarConfiguration, target: Option<&str>) -> Result<
let grammar_dir = if let GrammarSource::Local { path } = &grammar.source {
PathBuf::from(&path)
} else {
crate::runtime_dir()
crate::runtime_dirs()
.first()
.expect("No runtime directories provided") // guaranteed by post-condition
.join("grammars")
.join("sources")
.join(&grammar.grammar_id)
Expand Down Expand Up @@ -401,7 +406,10 @@ fn build_tree_sitter_library(
None
}
};
let parser_lib_path = crate::runtime_dir().join("grammars");
let parser_lib_path = crate::runtime_dirs()
.first()
.expect("No runtime directories provided") // guaranteed by post-condition
.join("grammars");
let mut library_path = parser_lib_path.join(&grammar.grammar_id);
library_path.set_extension(DYLIB_EXTENSION);

Expand Down Expand Up @@ -511,9 +519,6 @@ fn mtime(path: &Path) -> Result<SystemTime> {
/// Gives the contents of a file from a language's `runtime/queries/<lang>`
/// directory
pub fn load_runtime_file(language: &str, filename: &str) -> Result<String, std::io::Error> {
let path = crate::RUNTIME_DIR
.join("queries")
.join(language)
.join(filename);
let path = crate::runtime_file(&PathBuf::new().join("queries").join(language).join(filename));
std::fs::read_to_string(path)
}
81 changes: 67 additions & 14 deletions helix-loader/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ pub mod config;
pub mod grammar;

use etcetera::base_strategy::{choose_base_strategy, BaseStrategy};
use std::path::PathBuf;
use std::path::{Path, PathBuf};

pub const VERSION_AND_GIT_HASH: &str = env!("VERSION_AND_GIT_HASH");

pub static RUNTIME_DIR: once_cell::sync::Lazy<PathBuf> = once_cell::sync::Lazy::new(runtime_dir);
static RUNTIME_DIRS: once_cell::sync::Lazy<Vec<PathBuf>> =
once_cell::sync::Lazy::new(prioritize_runtime_dirs);

static CONFIG_FILE: once_cell::sync::OnceCell<PathBuf> = once_cell::sync::OnceCell::new();

Expand All @@ -25,31 +26,83 @@ pub fn initialize_config_file(specified_file: Option<PathBuf>) {
CONFIG_FILE.set(config_file).ok();
}

pub fn runtime_dir() -> PathBuf {
if let Ok(dir) = std::env::var("HELIX_RUNTIME") {
return dir.into();
}

/// A list of runtime directories from highest to lowest priority
///
/// The priority is:
///
/// 1. sibling directory to `CARGO_MANIFEST_DIR` (if environment variable is set)
/// 2. subdirectory of user config directory (always included)
/// 3. `HELIX_RUNTIME` (if environment variable is set)
/// 4. subdirectory of path to helix executable (always included)
///
/// Postcondition: returns at least two paths (they might not exist).
fn prioritize_runtime_dirs() -> Vec<PathBuf> {
const RT_DIR: &str = "runtime";
// Adding higher priority first
let mut rt_dirs = Vec::new();
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);
log::debug!("runtime dir: {}", path.to_string_lossy());
return path;
rt_dirs.push(path);
}

const RT_DIR: &str = "runtime";
let conf_dir = config_dir().join(RT_DIR);
if conf_dir.exists() {
return conf_dir;
let conf_rt_dir = config_dir().join(RT_DIR);
rt_dirs.push(conf_rt_dir);

if let Ok(dir) = std::env::var("HELIX_RUNTIME") {
rt_dirs.push(dir.into());
}

// fallback to location of the executable being run
// canonicalize the path in case the executable is symlinked
std::env::current_exe()
let exe_rt_dir = std::env::current_exe()
.ok()
.and_then(|path| std::fs::canonicalize(path).ok())
.and_then(|path| path.parent().map(|path| path.to_path_buf().join(RT_DIR)))
.unwrap()
.unwrap();
rt_dirs.push(exe_rt_dir);
rt_dirs
}

/// Runtime directories ordered from highest to lowest priority
///
/// All directories should be checked when looking for files.
///
/// Postcondition: returns at least one path (it might not exist).
pub fn runtime_dirs() -> &'static [PathBuf] {
&RUNTIME_DIRS
}

/// Find file with path relative to runtime directory
///
/// `rel_path` should be the relative path from within the `runtime/` directory.
/// The valid runtime directories are searched in priority order and the first
/// file found to exist is returned, otherwise None.
fn find_runtime_file(rel_path: &Path) -> Option<PathBuf> {
RUNTIME_DIRS.iter().find_map(|rt_dir| {
let path = rt_dir.join(rel_path);
if path.exists() {
Some(path)
} else {
None
}
})
}

/// Find file with path relative to runtime directory
///
/// `rel_path` should be the relative path from within the `runtime/` directory.
/// The valid runtime directories are searched in priority order and the first
/// file found to exist is returned, otherwise the path to the final attempt
/// that failed.
pub fn runtime_file(rel_path: &Path) -> PathBuf {
find_runtime_file(rel_path).unwrap_or_else(|| {
RUNTIME_DIRS
.last()
.map(|dir| dir.join(rel_path))
.unwrap_or_default()
})
}

pub fn config_dir() -> PathBuf {
Expand Down
10 changes: 5 additions & 5 deletions helix-term/src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ use crate::{
use log::{debug, error, warn};
use std::{
io::{stdin, stdout, Write},
path::Path,
sync::Arc,
time::{Duration, Instant},
};
Expand Down Expand Up @@ -135,10 +136,9 @@ impl Application {

use helix_view::editor::Action;

let theme_loader = std::sync::Arc::new(theme::Loader::new(
&helix_loader::config_dir(),
&helix_loader::runtime_dir(),
));
let mut theme_parent_dirs = vec![helix_loader::config_dir()];
theme_parent_dirs.extend(helix_loader::runtime_dirs().iter().cloned());
let theme_loader = std::sync::Arc::new(theme::Loader::new(&theme_parent_dirs));

let true_color = config.editor.true_color || crate::true_color();
let theme = config
Expand Down Expand Up @@ -184,7 +184,7 @@ impl Application {
compositor.push(editor_view);

if args.load_tutor {
let path = helix_loader::runtime_dir().join("tutor");
let path = helix_loader::runtime_file(Path::new("tutor"));
editor.open(&path, Action::VerticalSplit)?;
// Unset path to prevent accidentally saving to the original tutor file.
doc_mut!(editor).set_path(None)?;
Expand Down
2 changes: 1 addition & 1 deletion helix-term/src/commands/typed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1534,7 +1534,7 @@ fn tutor(
return Ok(());
}

let path = helix_loader::runtime_dir().join("tutor");
let path = helix_loader::runtime_file(Path::new("tutor"));
cx.editor.open(&path, Action::Replace)?;
// Unset path to prevent accidentally saving to the original tutor file.
doc_mut!(cx.editor).set_path(None)?;
Expand Down
34 changes: 22 additions & 12 deletions helix-term/src/health.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub fn general() -> std::io::Result<()> {
let config_file = helix_loader::config_file();
let lang_file = helix_loader::lang_config_file();
let log_file = helix_loader::log_file();
let rt_dir = helix_loader::runtime_dir();
let rt_dirs = helix_loader::runtime_dirs();
let clipboard_provider = get_clipboard_provider();

if config_file.exists() {
Expand All @@ -66,17 +66,27 @@ pub fn general() -> std::io::Result<()> {
writeln!(stdout, "Language file: default")?;
}
writeln!(stdout, "Log file: {}", log_file.display())?;
writeln!(stdout, "Runtime directory: {}", rt_dir.display())?;

if let Ok(path) = std::fs::read_link(&rt_dir) {
let msg = format!("Runtime directory is symlinked to {}", path.display());
writeln!(stdout, "{}", msg.yellow())?;
}
if !rt_dir.exists() {
writeln!(stdout, "{}", "Runtime directory does not exist.".red())?;
}
if rt_dir.read_dir().ok().map(|it| it.count()) == Some(0) {
writeln!(stdout, "{}", "Runtime directory is empty.".red())?;
writeln!(
stdout,
"Runtime directories: {}",
rt_dirs
.iter()
.map(|d| d.to_string_lossy())
.collect::<Vec<_>>()
.join(";")
)?;
for rt_dir in rt_dirs.iter() {
if let Ok(path) = std::fs::read_link(&rt_dir) {
let msg = format!("Runtime directory is symlinked to: {}", path.display());
writeln!(stdout, "{}", msg.yellow())?;
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: this should show what runtime directory is symlinked, this may not always be obvious when multiple runtime dirs are symlinked.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have added both paths to output.

if !rt_dir.exists() {
let msg = format!("Runtime directory does not exist: {}", rt_dir.display());
writeln!(stdout, "{}", msg.yellow())?;
} else if rt_dir.read_dir().ok().map(|it| it.count()) == Some(0) {
let msg = format!("Runtime directory is empty: {}", rt_dir.display());
writeln!(stdout, "{}", msg.yellow())?;
}
}
writeln!(stdout, "Clipboard provider: {}", clipboard_provider.name())?;

Expand Down
8 changes: 4 additions & 4 deletions helix-term/src/ui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,10 +280,10 @@ pub mod completers {
}

pub fn theme(_editor: &Editor, input: &str) -> Vec<Completion> {
let mut names = theme::Loader::read_names(&helix_loader::runtime_dir().join("themes"));
names.extend(theme::Loader::read_names(
&helix_loader::config_dir().join("themes"),
));
let mut names = theme::Loader::read_names(&helix_loader::config_dir().join("themes"));
for rt_dir in helix_loader::runtime_dirs() {
Copy link
Member

@pascalkuthe pascalkuthe Mar 7, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the function I commented in earlier has been inlined here (maybe by the merge from master?). This function has the same issue where we might ensup with the same theme name multiple times. I think an (unstable) sort and deadup would be a good solution

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Look down a couple of lines to 289 and 290 and it looks like this being done already.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah you are right, sorry about that 😅

names.extend(theme::Loader::read_names(&rt_dir.join("themes")));
}
names.push("default".into());
names.push("base16_default".into());
names.sort();
Expand Down
Loading