Skip to content

Commit

Permalink
Add runtime language configuration (#1794)
Browse files Browse the repository at this point in the history
* Add set-language typable command to change the language of current buffer.
* Add completer for available language options.
  • Loading branch information
zen3ger committed Mar 25, 2022
1 parent bee05dd commit f42320a
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
4 changes: 4 additions & 0 deletions helix-core/src/syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,10 @@ impl Loader {
None
}

pub fn language_configs(&self) -> impl Iterator<Item = &Arc<LanguageConfiguration>> {
self.language_configs.iter()
}

pub fn set_scopes(&self, scopes: Vec<String>) {
self.scopes.store(Arc::new(scopes));

Expand Down
30 changes: 30 additions & 0 deletions helix-term/src/commands/typed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -913,6 +913,29 @@ fn setting(
Ok(())
}

/// Change the language of the current buffer at runtime.
fn language(
cx: &mut compositor::Context,
args: &[Cow<str>],
_event: PromptEvent,
) -> anyhow::Result<()> {
if args.len() != 1 {
anyhow::bail!("Bad arguments. Usage: `:set-language language`");
}

let doc = doc_mut!(cx.editor);
let loader = Some(cx.editor.syn_loader.clone());
let config = cx.editor.syn_loader.language_configs().find_map(|config| {
if &config.language_id == &args[0] {
Some(config.clone())
} else {
None
}
});
doc.set_language(config, loader);
Ok(())
}

fn sort(
cx: &mut compositor::Context,
args: &[Cow<str>],
Expand Down Expand Up @@ -1376,6 +1399,13 @@ pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[
fun: goto_line_number,
completer: None,
},
TypableCommand {
name: "set-language",
aliases: &["lang"],
doc: "Set the language of current buffer.",
fun: language,
completer: Some(completers::language),
},
TypableCommand {
name: "set-option",
aliases: &["set"],
Expand Down
21 changes: 21 additions & 0 deletions helix-term/src/ui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,27 @@ pub mod completers {
})
}

pub fn language(editor: &Editor, input: &str) -> Vec<Completion> {
let matcher = Matcher::default();

let mut matches: Vec<_> = editor
.syn_loader
.language_configs()
.filter_map(|config| {
matcher
.fuzzy_match(&config.language_id, input)
.map(|score| (config.language_id.clone(), score))
})
.collect();

matches.sort_unstable_by_key(|(_language, score)| Reverse(*score));

matches
.into_iter()
.map(|(language, _score)| ((0..), language.into()))
.collect()
}

pub fn directory(_editor: &Editor, input: &str) -> Vec<Completion> {
filename_impl(input, |entry| {
let is_dir = entry.file_type().map_or(false, |entry| entry.is_dir());
Expand Down

0 comments on commit f42320a

Please sign in to comment.