Restructure KeyMap file, make it easy to edit in Zed

Add a JSON schema for this file so that autocomplete can be used for the actions.
This commit is contained in:
Max Brunsfeld 2022-04-21 13:33:39 -07:00
parent f52050a9ec
commit 066b4faf61
6 changed files with 610 additions and 466 deletions

View file

@ -1,5 +1,6 @@
{
"*": {
[
{
"bindings": {
"ctrl-alt-cmd-f": "workspace::FollowNextCollaborator",
"cmd-s": "workspace::Save",
"cmd-alt-i": "zed::DebugElements",
@ -7,9 +8,13 @@
"cmd-k cmd-right": "workspace::ActivateNextPane",
"cmd-=": "zed::IncreaseBufferFontSize",
"cmd--": "zed::DecreaseBufferFontSize",
"cmd-,": "zed::OpenSettings"
"cmd-,": "zed::OpenSettings",
"alt-cmd-,": "zed::OpenKeymap"
}
},
"menu": {
{
"context": "menu",
"bindings": {
"up": "menu::SelectPrev",
"ctrl-p": "menu::SelectPrev",
"down": "menu::SelectNext",
@ -17,9 +22,13 @@
"cmd-up": "menu::SelectFirst",
"cmd-down": "menu::SelectLast",
"enter": "menu::Confirm",
"escape": "menu::Cancel"
"escape": "menu::Cancel",
"ctrl-c": "menu::Cancel"
}
},
"Pane": {
{
"context": "Pane",
"bindings": {
"shift-cmd-{": "pane::ActivatePrevItem",
"shift-cmd-}": "pane::ActivateNextItem",
"cmd-w": "pane::CloseActiveItem",
@ -46,8 +55,11 @@
"cmd-f": "project_search::ToggleFocus",
"cmd-g": "search::SelectNextMatch",
"cmd-shift-G": "search::SelectPrevMatch"
}
},
"Workspace": {
{
"context": "Workspace",
"bindings": {
"cmd-shift-F": "project_search::Deploy",
"cmd-k cmd-t": "theme_selector::Toggle",
"cmd-k t": "theme_selector::Reload",
@ -70,18 +82,27 @@
"item_index": 0
}
]
}
},
"ProjectSearchBar": {
{
"context": "ProjectSearchBar",
"bindings": {
"enter": "project_search::Search",
"cmd-enter": "project_search::SearchInNew"
}
},
"BufferSearchBar": {
{
"context": "BufferSearchBar",
"bindings": {
"escape": "buffer_search::Dismiss",
"cmd-f": "buffer_search::FocusEditor",
"enter": "search::SelectNextMatch",
"shift-enter": "search::SelectPrevMatch"
}
},
"Editor": {
{
"context": "Editor",
"bindings": {
"escape": "editor::Cancel",
"backspace": "editor::Backspace",
"ctrl-h": "editor::Backspace",
@ -216,18 +237,11 @@
"cmd-.": "editor::ToggleCodeActions",
"alt-enter": "editor::OpenExcerpts",
"cmd-f10": "editor::RestartLanguageServer"
}
},
"Editor && renaming": {
"enter": "editor::ConfirmRename"
},
"Editor && showing_completions": {
"enter": "editor::ConfirmCompletion",
"tab": "editor::ConfirmCompletion"
},
"Editor && showing_code_actions": {
"enter": "editor::ConfirmCodeAction"
},
"Editor && mode == full": {
{
"context": "Editor && mode == full",
"bindings": {
"enter": "editor::Newline",
"cmd-f": [
"buffer_search::Deploy",
@ -243,22 +257,54 @@
],
"cmd-shift-O": "outline::Toggle",
"ctrl-g": "go_to_line::Toggle"
}
},
"Editor && mode == auto_height": {
{
"context": "Editor && renaming",
"bindings": {
"enter": "editor::ConfirmRename"
}
},
{
"context": "Editor && showing_completions",
"bindings": {
"enter": "editor::ConfirmCompletion",
"tab": "editor::ConfirmCompletion"
}
},
{
"context": "Editor && showing_code_actions",
"bindings": {
"enter": "editor::ConfirmCodeAction"
}
},
{
"context": "Editor && mode == auto_height",
"bindings": {
"alt-enter": [
"editor::Input",
"\n"
]
}
},
"GoToLine": {
{
"context": "GoToLine",
"bindings": {
"escape": "go_to_line::Toggle",
"enter": "go_to_line::Confirm"
}
},
"ChatPanel": {
{
"context": "ChatPanel",
"bindings": {
"enter": "chat_panel::Send"
}
},
"ProjectPanel": {
{
"context": "ProjectPanel",
"bindings": {
"left": "project_panel::CollapseSelectedEntry",
"right": "project_panel::ExpandSelectedEntry"
}
}
}
]

View file

@ -1,5 +1,7 @@
{
"Editor && VimControl": {
[
{
"context": "Editor && VimControl",
"bindings": {
"i": [
"vim::SwitchMode",
"Insert"
@ -42,15 +44,24 @@
"vim::SwitchMode",
"Normal"
]
}
},
"Editor && vim_operator == g": {
{
"context": "Editor && vim_operator == g",
"bindings": {
"g": "vim::StartOfDocument"
}
},
"Editor && vim_mode == insert": {
{
"context": "Editor && vim_mode == insert",
"bindings": {
"escape": "vim::NormalBefore",
"ctrl-c": "vim::NormalBefore"
}
},
"Editor && vim_mode == normal": {
{
"context": "Editor && vim_mode == normal",
"bindings": {
"c": [
"vim::PushOperator",
"Change"
@ -59,8 +70,11 @@
"vim::PushOperator",
"Delete"
]
}
},
"Editor && vim_operator == c": {
{
"context": "Editor && vim_operator == c",
"bindings": {
"w": [
"vim::NextWordEnd",
{
@ -73,8 +87,11 @@
"ignorePunctuation": true
}
]
}
},
"Editor && vim_operator == d": {
{
"context": "Editor && vim_operator == d",
"bindings": {
"w": [
"vim::NextWordStart",
{
@ -90,4 +107,5 @@
}
]
}
}
}
]

View file

@ -1306,6 +1306,10 @@ impl MutableAppContext {
}
}
pub fn all_action_names<'a>(&'a self) -> impl Iterator<Item = &'static str> + 'a {
self.action_deserializers.keys().copied()
}
pub fn available_actions(
&self,
window_id: usize,

View file

@ -3,14 +3,38 @@ use anyhow::{Context, Result};
use assets::Assets;
use collections::BTreeMap;
use gpui::{keymap::Binding, MutableAppContext};
use schemars::{
gen::{SchemaGenerator, SchemaSettings},
schema::{InstanceType, Schema, SchemaObject, SingleOrVec, SubschemaValidation},
JsonSchema,
};
use serde::Deserialize;
use serde_json::value::RawValue;
use serde_json::{value::RawValue, Value};
#[derive(Deserialize, Default, Clone, JsonSchema)]
#[serde(transparent)]
pub struct KeymapFileContent(Vec<KeymapBlock>);
#[derive(Deserialize, Default, Clone, JsonSchema)]
pub struct KeymapBlock {
#[serde(default)]
context: Option<String>,
bindings: BTreeMap<String, KeymapAction>,
}
#[derive(Deserialize, Default, Clone)]
#[serde(transparent)]
pub struct KeymapFileContent(BTreeMap<String, ActionsByKeystroke>);
pub struct KeymapAction(Box<RawValue>);
type ActionsByKeystroke = BTreeMap<String, Box<RawValue>>;
impl JsonSchema for KeymapAction {
fn schema_name() -> String {
"KeymapAction".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
Schema::Bool(true)
}
}
#[derive(Deserialize)]
struct ActionWithData(Box<str>, Box<RawValue>);
@ -29,13 +53,12 @@ impl KeymapFileContent {
}
pub fn add(self, cx: &mut MutableAppContext) -> Result<()> {
for (context, actions) in self.0 {
let context = if context == "*" { None } else { Some(context) };
for KeymapBlock { context, bindings } in self.0 {
cx.add_bindings(
actions
bindings
.into_iter()
.map(|(keystroke, action)| {
let action = action.get();
let action = action.0.get();
// This is a workaround for a limitation in serde: serde-rs/json#497
// We want to deserialize the action data as a `RawValue` so that we can
@ -61,3 +84,39 @@ impl KeymapFileContent {
Ok(())
}
}
pub fn keymap_file_json_schema(action_names: &[&'static str]) -> serde_json::Value {
let mut root_schema = SchemaSettings::draft07()
.with(|settings| settings.option_add_null_type = false)
.into_generator()
.into_root_schema_for::<KeymapFileContent>();
let action_schema = Schema::Object(SchemaObject {
subschemas: Some(Box::new(SubschemaValidation {
one_of: Some(vec![
Schema::Object(SchemaObject {
instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))),
enum_values: Some(
action_names
.into_iter()
.map(|name| Value::String(name.to_string()))
.collect(),
),
..Default::default()
}),
Schema::Object(SchemaObject {
instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::Array))),
..Default::default()
}),
]),
..Default::default()
})),
..Default::default()
});
root_schema
.definitions
.insert("KeymapAction".to_owned(), action_schema);
serde_json::to_value(root_schema).unwrap()
}

View file

@ -15,7 +15,7 @@ use std::{collections::HashMap, sync::Arc};
use theme::{Theme, ThemeRegistry};
use util::ResultExt as _;
pub use keymap_file::KeymapFileContent;
pub use keymap_file::{keymap_file_json_schema, KeymapFileContent};
#[derive(Clone)]
pub struct Settings {
@ -78,90 +78,6 @@ impl Settings {
})
}
pub fn file_json_schema(
theme_names: Vec<String>,
language_names: Vec<String>,
) -> serde_json::Value {
let settings = SchemaSettings::draft07().with(|settings| {
settings.option_add_null_type = false;
});
let generator = SchemaGenerator::new(settings);
let mut root_schema = generator.into_root_schema_for::<SettingsFileContent>();
// Construct theme names reference type
let theme_names = theme_names
.into_iter()
.map(|name| Value::String(name))
.collect();
let theme_names_schema = Schema::Object(SchemaObject {
instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))),
enum_values: Some(theme_names),
..Default::default()
});
root_schema
.definitions
.insert("ThemeName".to_owned(), theme_names_schema);
// Construct language overrides reference type
let language_override_schema_reference = Schema::Object(SchemaObject {
reference: Some("#/definitions/LanguageOverride".to_owned()),
..Default::default()
});
let language_overrides_properties = language_names
.into_iter()
.map(|name| {
(
name,
Schema::Object(SchemaObject {
subschemas: Some(Box::new(SubschemaValidation {
all_of: Some(vec![language_override_schema_reference.clone()]),
..Default::default()
})),
..Default::default()
}),
)
})
.collect();
let language_overrides_schema = Schema::Object(SchemaObject {
instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::Object))),
object: Some(Box::new(ObjectValidation {
properties: language_overrides_properties,
..Default::default()
})),
..Default::default()
});
root_schema
.definitions
.insert("LanguageOverrides".to_owned(), language_overrides_schema);
// Modify theme property to use new theme reference type
let settings_file_schema = root_schema.schema.object.as_mut().unwrap();
let language_overrides_schema_reference = Schema::Object(SchemaObject {
reference: Some("#/definitions/ThemeName".to_owned()),
..Default::default()
});
settings_file_schema.properties.insert(
"theme".to_owned(),
Schema::Object(SchemaObject {
subschemas: Some(Box::new(SubschemaValidation {
all_of: Some(vec![language_overrides_schema_reference]),
..Default::default()
})),
..Default::default()
}),
);
// Modify language_overrides property to use LanguageOverrides reference
settings_file_schema.properties.insert(
"language_overrides".to_owned(),
Schema::Object(SchemaObject {
reference: Some("#/definitions/LanguageOverrides".to_owned()),
..Default::default()
}),
);
serde_json::to_value(root_schema).unwrap()
}
pub fn with_overrides(
mut self,
language_name: impl Into<Arc<str>>,
@ -249,6 +165,90 @@ impl Settings {
}
}
pub fn settings_file_json_schema(
theme_names: Vec<String>,
language_names: Vec<String>,
) -> serde_json::Value {
let settings = SchemaSettings::draft07().with(|settings| {
settings.option_add_null_type = false;
});
let generator = SchemaGenerator::new(settings);
let mut root_schema = generator.into_root_schema_for::<SettingsFileContent>();
// Construct theme names reference type
let theme_names = theme_names
.into_iter()
.map(|name| Value::String(name))
.collect();
let theme_names_schema = Schema::Object(SchemaObject {
instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))),
enum_values: Some(theme_names),
..Default::default()
});
root_schema
.definitions
.insert("ThemeName".to_owned(), theme_names_schema);
// Construct language overrides reference type
let language_override_schema_reference = Schema::Object(SchemaObject {
reference: Some("#/definitions/LanguageOverride".to_owned()),
..Default::default()
});
let language_overrides_properties = language_names
.into_iter()
.map(|name| {
(
name,
Schema::Object(SchemaObject {
subschemas: Some(Box::new(SubschemaValidation {
all_of: Some(vec![language_override_schema_reference.clone()]),
..Default::default()
})),
..Default::default()
}),
)
})
.collect();
let language_overrides_schema = Schema::Object(SchemaObject {
instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::Object))),
object: Some(Box::new(ObjectValidation {
properties: language_overrides_properties,
..Default::default()
})),
..Default::default()
});
root_schema
.definitions
.insert("LanguageOverrides".to_owned(), language_overrides_schema);
// Modify theme property to use new theme reference type
let settings_file_schema = root_schema.schema.object.as_mut().unwrap();
let language_overrides_schema_reference = Schema::Object(SchemaObject {
reference: Some("#/definitions/ThemeName".to_owned()),
..Default::default()
});
settings_file_schema.properties.insert(
"theme".to_owned(),
Schema::Object(SchemaObject {
subschemas: Some(Box::new(SubschemaValidation {
all_of: Some(vec![language_overrides_schema_reference]),
..Default::default()
})),
..Default::default()
}),
);
// Modify language_overrides property to use LanguageOverrides reference
settings_file_schema.properties.insert(
"language_overrides".to_owned(),
Schema::Object(SchemaObject {
reference: Some("#/definitions/LanguageOverrides".to_owned()),
..Default::default()
}),
);
serde_json::to_value(root_schema).unwrap()
}
fn merge<T: Copy>(target: &mut T, value: Option<T>) {
if let Some(value) = value {
*target = value;

View file

@ -25,7 +25,7 @@ pub use project::{self, fs};
use project_panel::ProjectPanel;
use search::{BufferSearchBar, ProjectSearchBar};
use serde_json::to_string_pretty;
use settings::Settings;
use settings::{keymap_file_json_schema, settings_file_json_schema, Settings};
use std::{
path::{Path, PathBuf},
sync::Arc,
@ -41,6 +41,7 @@ actions!(
Quit,
DebugElements,
OpenSettings,
OpenKeymap,
IncreaseBufferFontSize,
DecreaseBufferFontSize,
InstallCommandLineInterface,
@ -78,39 +79,13 @@ pub fn init(app_state: &Arc<AppState>, cx: &mut gpui::MutableAppContext) {
cx.add_action({
let app_state = app_state.clone();
move |_: &mut Workspace, _: &OpenSettings, cx: &mut ViewContext<Workspace>| {
let app_state = app_state.clone();
cx.spawn(move |workspace, mut cx| async move {
let fs = &app_state.fs;
if !fs.is_file(&SETTINGS_PATH).await {
fs.create_dir(&ROOT_PATH).await?;
fs.create_file(&SETTINGS_PATH, Default::default()).await?;
open_config_file(&SETTINGS_PATH, app_state.clone(), cx);
}
workspace
.update(&mut cx, |workspace, cx| {
if workspace.project().read(cx).is_local() {
workspace.open_paths(&[SETTINGS_PATH.clone()], cx)
} else {
let (_, workspace) =
cx.add_window((app_state.build_window_options)(), |cx| {
let project = Project::local(
app_state.client.clone(),
app_state.user_store.clone(),
app_state.languages.clone(),
app_state.fs.clone(),
cx,
);
(app_state.build_workspace)(project, &app_state, cx)
});
workspace.update(cx, |workspace, cx| {
workspace.open_paths(&[SETTINGS_PATH.clone()], cx)
})
}
})
.await;
Ok::<_, anyhow::Error>(())
})
.detach_and_log_err(cx);
cx.add_action({
let app_state = app_state.clone();
move |_: &mut Workspace, _: &OpenKeymap, cx: &mut ViewContext<Workspace>| {
open_config_file(&KEYMAP_PATH, app_state.clone(), cx);
}
});
cx.add_action(
@ -137,7 +112,6 @@ pub fn init(app_state: &Arc<AppState>, cx: &mut gpui::MutableAppContext) {
);
workspace::lsp_status::init(cx);
settings::KeymapFileContent::load_defaults(cx);
}
@ -179,13 +153,18 @@ pub fn build_workspace(
let theme_names = app_state.themes.list().collect();
let language_names = app_state.languages.language_names();
project.update(cx, |project, _| {
project.update(cx, |project, cx| {
let action_names = cx.all_action_names().collect::<Vec<_>>();
project.set_language_server_settings(serde_json::json!({
"json": {
"schemas": [
{
"fileMatch": "**/.zed/settings.json",
"schema": Settings::file_json_schema(theme_names, language_names),
"fileMatch": [".zed/settings.json"],
"schema": settings_file_json_schema(theme_names, language_names),
},
{
"fileMatch": [".zed/keymap.json"],
"schema": keymap_file_json_schema(&action_names),
}
]
}
@ -289,6 +268,44 @@ async fn install_cli(cx: &AsyncAppContext) -> Result<()> {
}
}
fn open_config_file(
path: &'static Path,
app_state: Arc<AppState>,
cx: &mut ViewContext<Workspace>,
) {
cx.spawn(|workspace, mut cx| async move {
let fs = &app_state.fs;
if !fs.is_file(path).await {
fs.create_dir(&ROOT_PATH).await?;
fs.create_file(path, Default::default()).await?;
}
workspace
.update(&mut cx, |workspace, cx| {
if workspace.project().read(cx).is_local() {
workspace.open_paths(&[path.to_path_buf()], cx)
} else {
let (_, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
let project = Project::local(
app_state.client.clone(),
app_state.user_store.clone(),
app_state.languages.clone(),
app_state.fs.clone(),
cx,
);
(app_state.build_workspace)(project, &app_state, cx)
});
workspace.update(cx, |workspace, cx| {
workspace.open_paths(&[path.to_path_buf()], cx)
})
}
})
.await;
Ok::<_, anyhow::Error>(())
})
.detach_and_log_err(cx)
}
#[cfg(test)]
mod tests {
use super::*;