mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-19 00:10:00 +00:00
feat(settings): import keymaps, terminal font, tabs and indents and more editor options from JetBrains (#3650)
Import Settings from a JetBrains IDE now also brings over the keymaps (the IDE's active one becomes current), the terminal font, Tabs and Indents of the current code style scheme, console soft wrap and about 45 more EditorSettings / CodeInsightSettings options. The IDEA keymap parser moves to src/platform so the import can use it, and now accepts the lower-case key names IDEA writes in user keymaps (every non-letter shortcut of a user keymap was dropped before, also in Settings › Keymap › Import). Closes #3649 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com>
This commit is contained in:
co-authored by
wildcatDownstairs
parent
8ca2e089a3
commit
07afe43d0d
@@ -441,13 +441,26 @@ impl SettingsStore {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JetBrainsSettings {
|
||||
pub entries: Vec<String>,
|
||||
/// Entry name → text, for `colors/*.icls` and the `options/*.xml` files OpenIDEA reads.
|
||||
/// Entry name → text, for the files OpenIDEA reads: `colors/*.icls`, `keymaps/*.xml`,
|
||||
/// `codestyles/*.xml` and some of `options/`.
|
||||
pub files: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
const JETBRAINS_MARKER: &str = "IntelliJ IDEA Global Settings";
|
||||
const JETBRAINS_OPTIONS: [&str; 4] =
|
||||
["options/editor-font.xml", "options/colors.scheme.xml", "options/editor.xml", "options/ide.general.xml"];
|
||||
const JETBRAINS_OPTIONS: [&str; 9] = [
|
||||
"options/editor-font.xml",
|
||||
"options/terminal-font.xml",
|
||||
"options/colors.scheme.xml",
|
||||
"options/code.style.schemes.xml",
|
||||
"options/editor.xml",
|
||||
"options/ide.general.xml",
|
||||
// The active keymap is stored per operating system.
|
||||
"options/mac/keymap.xml",
|
||||
"options/windows/keymap.xml",
|
||||
"options/linux/keymap.xml",
|
||||
];
|
||||
/// Folders whose files are all read: (folder, extension).
|
||||
const JETBRAINS_READ_DIRS: [(&str, &str); 3] = [("colors/", ".icls"), ("keymaps/", ".xml"), ("codestyles/", ".xml")];
|
||||
const JETBRAINS_MAX_TEXT: u64 = 4 << 20;
|
||||
|
||||
/// The settings of a JetBrains IDE: an exported `settings.zip`, or the IDE's own settings folder
|
||||
@@ -458,11 +471,23 @@ pub fn read_jetbrains_settings(path: &Path) -> IdeResult<JetBrainsSettings> {
|
||||
|
||||
fn is_mapped_jetbrains_file(name: &str) -> bool {
|
||||
JETBRAINS_OPTIONS.contains(&name)
|
||||
|| name.strip_prefix("colors/").is_some_and(|n| !n.contains('/') && n.ends_with(".icls"))
|
||||
|| JETBRAINS_READ_DIRS
|
||||
.iter()
|
||||
.any(|(dir, ext)| name.strip_prefix(dir).is_some_and(|n| !n.contains('/') && n.ends_with(ext)))
|
||||
}
|
||||
|
||||
/// Folders of the settings folder whose files are listed (their names say what the user customised).
|
||||
const JETBRAINS_LISTED_DIRS: [&str; 6] = ["options", "colors", "keymaps", "codestyles", "templates", "inspection"];
|
||||
const JETBRAINS_LISTED_DIRS: [&str; 9] = [
|
||||
"options",
|
||||
"options/mac",
|
||||
"options/windows",
|
||||
"options/linux",
|
||||
"colors",
|
||||
"keymaps",
|
||||
"codestyles",
|
||||
"templates",
|
||||
"inspection",
|
||||
];
|
||||
|
||||
fn read_jetbrains_folder(dir: &Path) -> IdeResult<JetBrainsSettings> {
|
||||
use std::io::Read;
|
||||
@@ -936,11 +961,25 @@ mod tests {
|
||||
("options/editor-font.xml", "<application/>"),
|
||||
("options/vcs.xml", "<application/>"),
|
||||
("keymaps/macOS.xml", "<keymap/>"),
|
||||
("keymaps/nested/ignored.xml", "<keymap/>"),
|
||||
("codestyles/Default.xml", "<code_scheme/>"),
|
||||
("options/mac/keymap.xml", "<application/>"),
|
||||
("options/terminal-font.xml", "<application/>"),
|
||||
],
|
||||
);
|
||||
let read = read_jetbrains_settings(&ok).unwrap();
|
||||
assert_eq!(read.entries.len(), 5);
|
||||
assert_eq!(read.files.keys().collect::<Vec<_>>(), ["colors/_@user_Darcula.icls", "options/editor-font.xml"]);
|
||||
assert_eq!(read.entries.len(), 9);
|
||||
assert_eq!(
|
||||
read.files.keys().collect::<Vec<_>>(),
|
||||
[
|
||||
"codestyles/Default.xml",
|
||||
"colors/_@user_Darcula.icls",
|
||||
"keymaps/macOS.xml",
|
||||
"options/editor-font.xml",
|
||||
"options/mac/keymap.xml",
|
||||
"options/terminal-font.xml"
|
||||
]
|
||||
);
|
||||
assert!(read_jetbrains_settings(&write("other.zip", &[("options/editor.xml", "")])).is_err());
|
||||
std::fs::write(tmp.path().join("plain.zip"), "not a zip").unwrap();
|
||||
assert!(read_jetbrains_settings(&tmp.path().join("plain.zip")).is_err());
|
||||
@@ -959,18 +998,31 @@ mod tests {
|
||||
put("colors/nested/ignored.icls", "<scheme/>");
|
||||
put("options/editor-font.xml", "<application/>");
|
||||
put("options/vcs.xml", "<application/>");
|
||||
put("options/mac/keymap.xml", "<application/>");
|
||||
put("keymaps/macOS.xml", "<keymap/>");
|
||||
put("codestyles/Default.xml", "<code_scheme/>");
|
||||
put("plugins/Tools/lib/tools.jar", "jar");
|
||||
|
||||
let read = read_jetbrains_settings(&config).unwrap();
|
||||
assert_eq!(read.files.keys().collect::<Vec<_>>(), ["colors/_@user_Darcula.icls", "options/editor-font.xml"]);
|
||||
assert_eq!(
|
||||
read.files.keys().collect::<Vec<_>>(),
|
||||
[
|
||||
"codestyles/Default.xml",
|
||||
"colors/_@user_Darcula.icls",
|
||||
"keymaps/macOS.xml",
|
||||
"options/editor-font.xml",
|
||||
"options/mac/keymap.xml"
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
read.entries,
|
||||
[
|
||||
"options/editor-font.xml",
|
||||
"options/vcs.xml",
|
||||
"options/mac/keymap.xml",
|
||||
"colors/_@user_Darcula.icls",
|
||||
"keymaps/macOS.xml",
|
||||
"codestyles/Default.xml",
|
||||
"installed.txt"
|
||||
]
|
||||
);
|
||||
|
||||
+4
-1
@@ -6773,7 +6773,10 @@ export type JdkVendor = {
|
||||
*/
|
||||
export type JetBrainsSettings = {
|
||||
entries: string[],
|
||||
/** Entry name → text, for `colors/*.icls` and the `options/*.xml` files OpenIDEA reads. */
|
||||
/**
|
||||
* Entry name → text, for the files OpenIDEA reads: `colors/*.icls`, `keymaps/*.xml`,
|
||||
* `codestyles/*.xml` and some of `options/`.
|
||||
*/
|
||||
files: { [key in string]: string },
|
||||
};
|
||||
|
||||
|
||||
@@ -11,7 +11,10 @@ const component = (name: string, options: Record<string, string>) =>
|
||||
.map(([k, v]) => `<option name="${k}" value="${v}" />`)
|
||||
.join("")}</component></application>`;
|
||||
|
||||
const editor = { fontFamily: "JetBrains Mono", fontSize: 13, customSchemes: {}, colorOverrides: {} };
|
||||
const settings = {
|
||||
editor: { fontFamily: "JetBrains Mono", fontSize: 13, customSchemes: {}, colorOverrides: {} },
|
||||
customKeymaps: {},
|
||||
};
|
||||
|
||||
/** JetBrains Maple Mono's metrics (ascent 1.02em, descent 0.3em), for any family. */
|
||||
const fontHeight = (_family: string, size: number) => Math.ceil(size * 1.02) + Math.ceil(size * 0.3);
|
||||
@@ -55,7 +58,7 @@ const webstorm = {
|
||||
|
||||
describe("planJetBrainsImport", () => {
|
||||
it("maps a WebStorm export to the settings it has, and lists what is left out", async () => {
|
||||
const plan = await planJetBrainsImport(webstorm, editor, fontHeight);
|
||||
const plan = await planJetBrainsImport(webstorm, settings, fontHeight);
|
||||
const writes = Object.fromEntries(plan.writes);
|
||||
const schemes = writes["editor.customSchemes"] as Record<string, { name: string; parent: string }>;
|
||||
const [id, scheme] = Object.entries(schemes)[0]!;
|
||||
@@ -73,6 +76,7 @@ describe("planJetBrainsImport", () => {
|
||||
"files.ensureFinalNewline": true,
|
||||
"editor.stickyScroll": false,
|
||||
"editor.softWrap": false,
|
||||
"console.softWrap": true,
|
||||
"general.confirmExit": false,
|
||||
});
|
||||
expect(plan.rows).toContainEqual({
|
||||
@@ -84,7 +88,7 @@ describe("planJetBrainsImport", () => {
|
||||
label: "Remove trailing spaces on:",
|
||||
value: "All lines",
|
||||
});
|
||||
expect(plan.skipped).toEqual(["Keymap", "Code Style", "Inspections", "Plugins"]);
|
||||
expect(plan.skipped).toEqual(["Code Style options other than Tabs and Indents", "Inspections", "Plugins"]);
|
||||
expect(plan.invalid).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -102,7 +106,7 @@ describe("planJetBrainsImport", () => {
|
||||
}),
|
||||
},
|
||||
},
|
||||
editor,
|
||||
settings,
|
||||
fontHeight,
|
||||
);
|
||||
expect(plan.writes).toEqual([
|
||||
@@ -110,20 +114,24 @@ describe("planJetBrainsImport", () => {
|
||||
["editor.lineHeight", 27],
|
||||
["files.trimTrailingWhitespace", false],
|
||||
["editor.softWrap", true],
|
||||
["console.softWrap", true],
|
||||
]);
|
||||
expect(plan.skipped).toEqual([]);
|
||||
});
|
||||
|
||||
it("re-importing replaces the earlier copy of a scheme and drops its edits", async () => {
|
||||
const first = Object.fromEntries((await planJetBrainsImport(webstorm, editor, fontHeight)).writes);
|
||||
const customs = first["editor.customSchemes"] as typeof editor.customSchemes;
|
||||
const first = Object.fromEntries((await planJetBrainsImport(webstorm, settings, fontHeight)).writes);
|
||||
const customs = first["editor.customSchemes"] as typeof settings.editor.customSchemes;
|
||||
const [id] = Object.keys(customs);
|
||||
const again = await planJetBrainsImport(
|
||||
webstorm,
|
||||
{
|
||||
...editor,
|
||||
customSchemes: customs,
|
||||
colorOverrides: { [id!]: { keyword: { bold: true } }, other: {} },
|
||||
...settings,
|
||||
editor: {
|
||||
...settings.editor,
|
||||
customSchemes: customs,
|
||||
colorOverrides: { [id!]: { keyword: { bold: true } }, other: {} },
|
||||
},
|
||||
},
|
||||
fontHeight,
|
||||
);
|
||||
@@ -136,7 +144,7 @@ describe("planJetBrainsImport", () => {
|
||||
it("falls back to the font size when the font cannot be measured", async () => {
|
||||
const plan = await planJetBrainsImport(
|
||||
{ entries: [], files: { "options/editor-font.xml": component("DefaultFont", { FONT_SIZE: "20" }) } },
|
||||
editor,
|
||||
settings,
|
||||
() => undefined,
|
||||
);
|
||||
expect(plan.writes).toEqual([
|
||||
@@ -145,8 +153,166 @@ describe("planJetBrainsImport", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("imports the keymaps and makes the active one current", async () => {
|
||||
const keymap =
|
||||
'<keymap version="1" name="macOS copy" parent="Mac OS X 10.5+">' +
|
||||
'<action id="NextTab"><keyboard-shortcut first-keystroke="ctrl right" /></action>' +
|
||||
'<action id="GotoSuperMethod" /><action id="RunAnything" /></keymap>';
|
||||
const active =
|
||||
'<application><component name="KeymapManager"><active_keymap name="macOS copy" /></component></application>';
|
||||
const bundle = {
|
||||
entries: ["keymaps/macOS copy.xml", "keymaps/broken.xml"],
|
||||
files: {
|
||||
"keymaps/macOS copy.xml": keymap,
|
||||
"keymaps/broken.xml": "<nope",
|
||||
// The active keymap is stored per operating system; the host picks its own.
|
||||
"options/mac/keymap.xml": active,
|
||||
"options/windows/keymap.xml": active,
|
||||
"options/linux/keymap.xml": active,
|
||||
},
|
||||
};
|
||||
const plan = await planJetBrainsImport(bundle, settings);
|
||||
const expected = {
|
||||
name: "macOS copy",
|
||||
parent: "intellij-macos",
|
||||
overrides: { "editor.nextTab": ["Ctrl+Right"], "navigate.superMethod": [] },
|
||||
};
|
||||
expect(plan.writes).toEqual([
|
||||
["customKeymaps", { "custom.macos-copy": expected }],
|
||||
["keymap", "custom.macos-copy"],
|
||||
]);
|
||||
expect(plan.rows).toEqual([
|
||||
{ label: "Keymap", value: "macOS copy" },
|
||||
{ label: "Current keymap", value: "macOS copy" },
|
||||
]);
|
||||
expect(plan.unknownActions).toEqual(["RunAnything"]);
|
||||
expect(plan.invalid).toEqual(["broken.xml"]);
|
||||
|
||||
// Importing again replaces the earlier copy and keeps the user's other keymaps.
|
||||
const mine = { name: "Mine", parent: "vscode-macos", overrides: {} };
|
||||
const again = await planJetBrainsImport(bundle, {
|
||||
...settings,
|
||||
customKeymaps: { "custom.macos-copy": { ...expected, overrides: {} }, "custom.mine": mine },
|
||||
});
|
||||
expect(again.writes[0]).toEqual(["customKeymaps", { "custom.macos-copy": expected, "custom.mine": mine }]);
|
||||
});
|
||||
|
||||
it("imports the terminal font", async () => {
|
||||
const plan = await planJetBrainsImport(
|
||||
{
|
||||
entries: [],
|
||||
files: {
|
||||
"options/terminal-font.xml": component("TerminalFontOptions", {
|
||||
VERSION: "1",
|
||||
FONT_SIZE: "17",
|
||||
FONT_SIZE_2D: "17.0",
|
||||
FONT_FAMILY: "MesloLGS NF",
|
||||
LINE_SPACING: "1.1",
|
||||
}),
|
||||
},
|
||||
},
|
||||
settings,
|
||||
);
|
||||
expect(plan.writes).toEqual([
|
||||
["terminal.useEditorFont", false],
|
||||
["terminal.fontFamily", "MesloLGS NF"],
|
||||
["terminal.fontSize", 17],
|
||||
["terminal.lineHeight", 1.1],
|
||||
]);
|
||||
});
|
||||
|
||||
it("imports tabs and indents of the current code style scheme onto the languages' own styles", async () => {
|
||||
const scheme = (name: string, body: string) => `<code_scheme name="${name}" version="173">${body}</code_scheme>`;
|
||||
const plan = await planJetBrainsImport(
|
||||
{
|
||||
entries: ["codestyles/Default.xml", "codestyles/Team.xml"],
|
||||
files: {
|
||||
"options/code.style.schemes.xml": component("CodeStyleSchemeSettings", { CURRENT_SCHEME_NAME: "Team" }),
|
||||
"codestyles/Default.xml": scheme(
|
||||
"Default",
|
||||
'<codeStyleSettings language="Python"><indentOptions><option name="INDENT_SIZE" value="8" /></indentOptions></codeStyleSettings>',
|
||||
),
|
||||
"codestyles/Team.xml": scheme(
|
||||
"Team",
|
||||
'<option name="RIGHT_MARGIN" value="100" />' +
|
||||
'<option name="OTHER_INDENT_OPTIONS"><value><option name="TAB_SIZE" value="8" />' +
|
||||
'<option name="USE_TAB_CHARACTER" value="true" /></value></option>' +
|
||||
'<JSCodeStyleSettings version="0"><option name="USE_SEMICOLON_AFTER_STATEMENT" value="false" /></JSCodeStyleSettings>' +
|
||||
'<codeStyleSettings language="TypeScript"><option name="SPACE_WITHIN_BRACKETS" value="true" />' +
|
||||
'<indentOptions><option name="INDENT_SIZE" value="2" /><option name="CONTINUATION_INDENT_SIZE" value="2" />' +
|
||||
'<option name="TAB_SIZE" value="2" /></indentOptions></codeStyleSettings>' +
|
||||
'<codeStyleSettings language="HTML"><option name="LINE_COMMENT_AT_FIRST_COLUMN" value="false" />' +
|
||||
'<indentOptions><option name="USE_TAB_CHARACTER" value="true" /></indentOptions></codeStyleSettings>' +
|
||||
'<codeStyleSettings language="Brainfuck"><indentOptions><option name="INDENT_SIZE" value="3" /></indentOptions></codeStyleSettings>',
|
||||
),
|
||||
},
|
||||
},
|
||||
{
|
||||
...settings,
|
||||
editor: {
|
||||
...settings.editor,
|
||||
codeStyle: { languages: { typescript: { hardWrapAt: 90 }, go: { tabSize: 8 } } },
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(plan.writes).toEqual([
|
||||
["editor.codeStyle.hardWrapAt", 100],
|
||||
["editor.tabSize", 8],
|
||||
["editor.insertSpaces", false],
|
||||
[
|
||||
"editor.codeStyle.languages",
|
||||
{
|
||||
typescript: { hardWrapAt: 90, indent: 2, tabSize: 2 },
|
||||
typescriptreact: { indent: 2, tabSize: 2 },
|
||||
html: { useTab: true, lineCommentAtFirstColumn: false },
|
||||
go: { tabSize: 8 },
|
||||
},
|
||||
],
|
||||
]);
|
||||
expect(plan.rows).toContainEqual({ label: "Code Style › TypeScript", value: "Indent 2, Tab size 2" });
|
||||
expect(plan.rows).toContainEqual({ label: "Use tab character", value: "On" });
|
||||
expect(plan.skipped).toEqual(["Code Style options other than Tabs and Indents"]);
|
||||
});
|
||||
|
||||
it("imports the editor options that have a setting here", async () => {
|
||||
const xml =
|
||||
"<application>" +
|
||||
component("EditorSettings", {
|
||||
IS_SMOOTH_CARET_BLINKING: "true",
|
||||
IS_BLOCK_CURSOR: "true",
|
||||
ARE_LINE_NUMBERS_SHOWN: "false",
|
||||
LINE_NUMERATION: "HYBRID",
|
||||
SHOW_BREADCRUMBS_ABOVE: "true",
|
||||
CARET_BLINKING_PERIOD: "700",
|
||||
IS_ANIMATED_SCROLLING: "false",
|
||||
}).replace(/<\/?application>/g, "") +
|
||||
component("CodeInsightSettings", {
|
||||
AUTOINSERT_PAIR_QUOTE: "false",
|
||||
REFORMAT_ON_PASTE: "2",
|
||||
SMART_BACKSPACE: "1",
|
||||
PARAMETER_INFO_DELAY: "500",
|
||||
COMPLETION_CASE_SENSITIVE: "2",
|
||||
}).replace(/<\/?application>/g, "") +
|
||||
"</application>";
|
||||
const plan = await planJetBrainsImport({ entries: [], files: { "options/editor.xml": xml } }, settings);
|
||||
expect(Object.fromEntries(plan.writes)).toEqual({
|
||||
"editor.appearance.lineNumberMode": "hybrid",
|
||||
"editor.breadcrumbs.placement": "top",
|
||||
"editor.appearance.smoothCaretBlinking": true,
|
||||
"editor.appearance.blockCaret": true,
|
||||
"editor.appearance.lineNumbers": false,
|
||||
"editor.appearance.caretBlinkPeriod": 700,
|
||||
"editor.smartKeys.pairQuotes": false,
|
||||
"editor.completion.parameterInfoDelay": 500,
|
||||
"editor.smartKeys.reformatOnPaste": "indentBlock",
|
||||
"editor.smartKeys.backspaceUnindent": "nearest",
|
||||
});
|
||||
expect(plan.rows).toContainEqual({ label: "Unindent", value: "To nearest indent position" });
|
||||
expect(plan.rows).toContainEqual({ label: "Show line numbers", value: "Hybrid" });
|
||||
});
|
||||
|
||||
it("skips colour schemes that cannot be read", async () => {
|
||||
const plan = await planJetBrainsImport({ entries: [], files: { "colors/broken.icls": "<nope" } }, editor);
|
||||
const plan = await planJetBrainsImport({ entries: [], files: { "colors/broken.icls": "<nope" } }, settings);
|
||||
expect(plan.invalid).toEqual(["broken.icls"]);
|
||||
expect(plan.writes).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -58,7 +58,7 @@ it.each(["Cancel", "Import"])("confirms folder settings before applying them: %s
|
||||
expect(screen.getByText("Monaco")).toBeInTheDocument();
|
||||
expect(screen.getByText("17")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("Custom")).toHaveLength(2);
|
||||
expect(screen.getByText(/Not imported:/)).toHaveTextContent("Keymap, Plugins");
|
||||
expect(screen.getByText(/Not imported:/)).toHaveTextContent("Plugins");
|
||||
expect(set).not.toHaveBeenCalled();
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: button }));
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* JetBrains option names (as the IDE writes them to `options/editor.xml` and
|
||||
* `codestyles/*.xml`) and the OpenIDEA settings of the same meaning. Each entry
|
||||
* carries the label the option has in Settings, for the import confirmation.
|
||||
*/
|
||||
|
||||
type Mapped = readonly [key: string, label: string];
|
||||
|
||||
/** `<component name="EditorSettings">`: on/off options. */
|
||||
export const EDITOR_FLAGS: Record<string, Mapped> = {
|
||||
IS_WHEEL_FONTCHANGE_ENABLED: ["editor.general.wheelZoom", "Change font size with Ctrl/Command+Mouse Wheel"],
|
||||
IS_DND_ENABLED: ["editor.general.dragAndDrop", "Enable drag-and-drop functionality in editor"],
|
||||
USE_CUSTOM_SOFT_WRAP_INDENT: ["editor.general.softWrapIndent", "Use original line's indent for wrapped parts"],
|
||||
ADDITIONAL_PAGE_AT_BOTTOM: ["editor.general.scrollPastEnd", "Show virtual space at file bottom"],
|
||||
KEEP_TRAILING_SPACE_ON_CARET_LINE: ["editor.general.keepTrailingOnCaretLine", "Keep trailing spaces on caret line"],
|
||||
REMOVE_TRAILING_BLANK_LINES: [
|
||||
"editor.general.removeTrailingBlankLines",
|
||||
"Remove trailing blank lines at the end of saved files",
|
||||
],
|
||||
IS_CARET_BLINKING: ["editor.appearance.caretBlinking", "Caret blinking (ms):"],
|
||||
IS_SMOOTH_CARET_BLINKING: ["editor.appearance.smoothCaretBlinking", "Use smooth caret blinking"],
|
||||
IS_BLOCK_CURSOR: ["editor.appearance.blockCaret", "Use block caret"],
|
||||
IS_SMOOTH_CARET_MOVEMENT: ["editor.appearance.smoothCaretMovement", "Use smooth caret movement"],
|
||||
IS_RIGHT_MARGIN_SHOWN: [
|
||||
"editor.appearance.hardWrapGuides",
|
||||
"Show hard wrap and visual guides (configured in Code Style options)",
|
||||
],
|
||||
ARE_LINE_NUMBERS_SHOWN: ["editor.appearance.lineNumbers", "Show line numbers"],
|
||||
IS_LEADING_WHITESPACES_SHOWN: ["editor.appearance.whitespaceLeading", "Leading"],
|
||||
IS_INNER_WHITESPACES_SHOWN: ["editor.appearance.whitespaceInner", "Inner"],
|
||||
IS_TRAILING_WHITESPACES_SHOWN: ["editor.appearance.whitespaceTrailing", "Trailing"],
|
||||
IS_INDENT_GUIDES_SHOWN: ["editor.appearance.indentGuides", "Show indent guides"],
|
||||
SHOW_INTENTION_BULB: ["editor.appearance.intentionBulb", "Show intention bulb"],
|
||||
ENABLE_RENDERED_DOC: ["editor.appearance.renderDocComments", "Render documentation comments"],
|
||||
SHOW_BREADCRUMBS: ["editor.breadcrumbs.show", "Show breadcrumbs:"],
|
||||
IS_FOLDING_OUTLINE_SHOWN: ["editor.folding.showOutline", "Show code folding outline"],
|
||||
SMART_HOME: ["editor.smartKeys.smartHome", "Home moves caret to first non-whitespace character"],
|
||||
IS_CAMEL_WORDS: ["editor.smartKeys.camelHumps", 'Use "CamelHumps" words'],
|
||||
IS_HIGHLIGHT_SELECTION_OCCURRENCES: ["editor.codeEditing.highlightSelection", "Occurrences of selected text"],
|
||||
SHOW_QUICK_DOC_ON_MOUSE_OVER_ELEMENT: ["editor.codeEditing.quickDocOnHover", "Show quick documentation on hover"],
|
||||
INSERT_PARENTHESES_AUTOMATICALLY: [
|
||||
"editor.completion.insertParentheses",
|
||||
"Insert parentheses automatically when applicable",
|
||||
],
|
||||
};
|
||||
|
||||
/** `<component name="EditorSettings">`: numbers. */
|
||||
export const EDITOR_NUMBERS: Record<string, Mapped> = {
|
||||
CARET_BLINKING_PERIOD: ["editor.appearance.caretBlinkPeriod", "Caret blinking (ms):"],
|
||||
STICKY_LINES_LIMIT: ["editor.codeEditing.stickyLinesMax", "Maximum number of lines"],
|
||||
TOOLTIPS_DELAY_MS: ["editor.codeEditing.quickDocDelay", "Tooltip delay"],
|
||||
};
|
||||
|
||||
/** `<component name="CodeInsightSettings">`: on/off options. */
|
||||
export const CODE_INSIGHT_FLAGS: Record<string, Mapped> = {
|
||||
AUTOINSERT_PAIR_BRACKET: ["editor.smartKeys.pairBrackets", "Insert paired brackets (), [], {}"],
|
||||
AUTOINSERT_PAIR_QUOTE: ["editor.smartKeys.pairQuotes", "Insert pair quote"],
|
||||
SURROUND_SELECTION_ON_QUOTE_TYPED: [
|
||||
"editor.smartKeys.surroundSelection",
|
||||
"Surround selection on typing quote or brace",
|
||||
],
|
||||
TAB_EXITS_BRACKETS_AND_QUOTES: ["editor.smartKeys.tabOutOfPair", "Jump outside closing bracket/quote with Tab"],
|
||||
SMART_INDENT_ON_ENTER: ["editor.smartKeys.smartIndent", "Smart indent"],
|
||||
JAVADOC_STUB_ON_ENTER: ["editor.smartKeys.insertDocStub", "Insert documentation comment stub"],
|
||||
HIGHLIGHT_IDENTIFIER_UNDER_CARET: ["editor.codeEditing.highlightUsages", "Usages of element at caret"],
|
||||
HIGHLIGHT_BRACES: ["editor.codeEditing.highlightBraces", "Matched brace"],
|
||||
AUTO_POPUP_COMPLETION_LOOKUP: ["editor.completion.autoPopup", "Show suggestions as you type"],
|
||||
AUTOCOMPLETE_ON_CODE_COMPLETION: ["editor.completion.autoInsertSingle", "Automatically insert single suggestions"],
|
||||
AUTO_POPUP_JAVADOC_INFO: ["editor.completion.showDocumentation", "Show the documentation popup in"],
|
||||
AUTO_POPUP_PARAMETER_INFO: ["editor.completion.parameterInfo", "Show the parameter info popup in"],
|
||||
};
|
||||
|
||||
/** `<component name="CodeInsightSettings">`: numbers. */
|
||||
export const CODE_INSIGHT_NUMBERS: Record<string, Mapped> = {
|
||||
JAVADOC_INFO_DELAY: ["editor.completion.documentationDelay", "Show the documentation popup in"],
|
||||
PARAMETER_INFO_DELAY: ["editor.completion.parameterInfoDelay", "Show the parameter info popup in"],
|
||||
};
|
||||
|
||||
/** `REFORMAT_ON_PASTE` (IDEA's `CodeInsightSettings` constants) → `editor.smartKeys.reformatOnPaste`, its label. */
|
||||
export const REFORMAT_ON_PASTE: Record<string, Mapped> = {
|
||||
"1": ["none", "None"],
|
||||
"2": ["indentBlock", "Indent Block"],
|
||||
"3": ["indentEachLine", "Indent Each Line"],
|
||||
};
|
||||
|
||||
/** `SMART_BACKSPACE` (IDEA's `SmartBackspaceMode` ordinals) → `editor.smartKeys.backspaceUnindent`, its label. */
|
||||
export const SMART_BACKSPACE: Record<string, Mapped> = {
|
||||
"0": ["none", "Disabled"],
|
||||
"1": ["nearest", "To nearest indent position"],
|
||||
"2": ["autoindent", "To proper indent position"],
|
||||
};
|
||||
|
||||
/** `<codeStyleSettings language=…>` → the language ids that share that code style here. */
|
||||
export const CODE_STYLE_LANGUAGES: Record<string, readonly string[]> = {
|
||||
JAVA: ["java"],
|
||||
kotlin: ["kotlin"],
|
||||
Groovy: ["groovy"],
|
||||
Scala: ["scala"],
|
||||
JavaScript: ["javascript", "javascriptreact"],
|
||||
TypeScript: ["typescript", "typescriptreact"],
|
||||
Vue: ["vue"],
|
||||
HTML: ["html"],
|
||||
XML: ["xml"],
|
||||
CSS: ["css"],
|
||||
SCSS: ["scss"],
|
||||
SASS: ["sass"],
|
||||
LESS: ["less"],
|
||||
JSON: ["json", "jsonc"],
|
||||
yaml: ["yaml"],
|
||||
TOML: ["toml"],
|
||||
Markdown: ["markdown"],
|
||||
Python: ["python"],
|
||||
go: ["go"],
|
||||
Rust: ["rust"],
|
||||
PHP: ["php"],
|
||||
ruby: ["ruby"],
|
||||
Dart: ["dart"],
|
||||
Swift: ["swift"],
|
||||
"C#": ["csharp"],
|
||||
Lua: ["lua"],
|
||||
SQL: ["sql"],
|
||||
"Shell Script": ["shellscript"],
|
||||
};
|
||||
@@ -1,21 +1,32 @@
|
||||
/**
|
||||
* Import Settings… with a JetBrains `settings.zip`: maps the archive's colour
|
||||
* schemes and the editor / general options OpenIDEA has to settings writes, after
|
||||
* a confirmation listing them. Only keys present in the archive are written
|
||||
* (JetBrains leaves defaults out). Keymaps, code styles and the rest are listed
|
||||
* as not imported.
|
||||
* schemes, keymaps, fonts, tabs and indents, and the editor / general options
|
||||
* OpenIDEA has to settings writes, after a confirmation listing them. Only keys
|
||||
* present in the archive are written (JetBrains leaves defaults out). The rest
|
||||
* is listed as not imported.
|
||||
*/
|
||||
import { Fragment } from "react";
|
||||
import type { JetBrainsSettings } from "@/bindings";
|
||||
import type { CustomKeymap, JetBrainsSettings, LanguageCodeStyle } from "@/bindings";
|
||||
import { customSchemes } from "@/platform/colorScheme";
|
||||
import { createFontProbeCanvas, fontsLoaded, monoFontFamily } from "@/platform/fonts";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { importScheme, parseIcls } from "@/platform/icls";
|
||||
import { addIdeaKeymap, parseIdeaKeymap } from "@/platform/ideaKeymap";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { guessOs } from "@/platform/platformInfo";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import styles from "./app.module.css";
|
||||
import {
|
||||
CODE_INSIGHT_FLAGS,
|
||||
CODE_INSIGHT_NUMBERS,
|
||||
CODE_STYLE_LANGUAGES,
|
||||
EDITOR_FLAGS,
|
||||
EDITOR_NUMBERS,
|
||||
REFORMAT_ON_PASTE,
|
||||
SMART_BACKSPACE,
|
||||
} from "./jetbrainsOptions";
|
||||
|
||||
export interface JetBrainsImportPlan {
|
||||
/** Settings writes, in order: `settingsSet("global", key, JSON.stringify(value))`. */
|
||||
@@ -24,15 +35,22 @@ export interface JetBrainsImportPlan {
|
||||
rows: { label: string; value: string }[];
|
||||
/** Categories present in the archive that are not imported (translated). */
|
||||
skipped: string[];
|
||||
/** `.icls` files that could not be read. */
|
||||
/** Colour scheme and keymap files that could not be read. */
|
||||
invalid: string[];
|
||||
/** IDEA action ids the imported keymaps bind that have no counterpart here. */
|
||||
unknownActions: string[];
|
||||
}
|
||||
|
||||
interface EditorState {
|
||||
fontFamily: string;
|
||||
fontSize: number | null;
|
||||
customSchemes: unknown;
|
||||
colorOverrides: Record<string, unknown>;
|
||||
/** The settings the import builds on (`settingsGetGlobal`). */
|
||||
interface CurrentSettings {
|
||||
editor: {
|
||||
fontFamily: string;
|
||||
fontSize: number | null;
|
||||
customSchemes: unknown;
|
||||
colorOverrides: Record<string, unknown>;
|
||||
codeStyle?: { languages?: Record<string, LanguageCodeStyle> };
|
||||
};
|
||||
customKeymaps?: Record<string, CustomKeymap>;
|
||||
}
|
||||
|
||||
const USER_PREFIX = "_@user_";
|
||||
@@ -93,12 +111,39 @@ async function measuredFontHeight(family: string, size: number): Promise<number
|
||||
}
|
||||
}
|
||||
|
||||
/** `<option name value>` children of `parent`. */
|
||||
function optionValues(parent: Element | null | undefined): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
for (const o of Array.from(parent?.children ?? [])) {
|
||||
const name = o.getAttribute("name");
|
||||
const value = o.getAttribute("value");
|
||||
if (o.tagName === "option" && name && value !== null) out.set(name, value);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const childOf = (parent: Element, tag: string, name?: string) =>
|
||||
Array.from(parent.children).find((c) => c.tagName === tag && (name === undefined || c.getAttribute("name") === name));
|
||||
|
||||
/** The code style scheme called `name` among `codestyles/*.xml`. */
|
||||
function codeScheme(files: Record<string, string>, name: string): Element | undefined {
|
||||
for (const [file, text] of Object.entries(files)) {
|
||||
if (!file.startsWith("codestyles/")) continue;
|
||||
const doc = new DOMParser().parseFromString(text, "application/xml");
|
||||
const root = doc.documentElement;
|
||||
if (!doc.querySelector("parsererror") && root.tagName === "code_scheme" && root.getAttribute("name") === name)
|
||||
return root;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export async function planJetBrainsImport(
|
||||
bundle: JetBrainsSettings,
|
||||
editor: EditorState,
|
||||
current: CurrentSettings,
|
||||
fontHeight: FontHeight = measuredFontHeight,
|
||||
): Promise<JetBrainsImportPlan> {
|
||||
const plan: JetBrainsImportPlan = { writes: [], rows: [], skipped: [], invalid: [] };
|
||||
const { editor } = current;
|
||||
const plan: JetBrainsImportPlan = { writes: [], rows: [], skipped: [], invalid: [], unknownActions: [] };
|
||||
const add = (key: string, value: string | number | boolean | undefined, label: string, shown?: string) => {
|
||||
if (value === undefined) return;
|
||||
plan.writes.push([key, value]);
|
||||
@@ -134,6 +179,33 @@ export async function planJetBrainsImport(
|
||||
if (id) add("editor.colorScheme", id, tx("Current color scheme"), customs[id]?.name);
|
||||
}
|
||||
|
||||
let keymaps = current.customKeymaps ?? {};
|
||||
const importedKeymaps = new Map<string, string>(); // name in the keymap file → keymap id
|
||||
for (const [file, text] of Object.entries(bundle.files)) {
|
||||
if (!file.startsWith("keymaps/")) continue;
|
||||
let parsed;
|
||||
try {
|
||||
parsed = parseIdeaKeymap(text);
|
||||
} catch {
|
||||
plan.invalid.push(file.slice("keymaps/".length));
|
||||
continue;
|
||||
}
|
||||
// Overwrites an earlier import of the same keymap, as colour schemes do.
|
||||
const next = addIdeaKeymap(keymaps, parsed);
|
||||
keymaps = next.customs;
|
||||
importedKeymaps.set(parsed.name, next.id);
|
||||
plan.unknownActions.push(...parsed.unknownActions.filter((id) => !plan.unknownActions.includes(id)));
|
||||
plan.rows.push({ label: tx("Keymap"), value: keymaps[next.id]?.name ?? parsed.name });
|
||||
}
|
||||
if (importedKeymaps.size) {
|
||||
plan.writes.push(["customKeymaps", keymaps]);
|
||||
// The active keymap is stored per operating system; a bundled one keeps OpenIDEA's choice.
|
||||
const os = { macos: "mac", windows: "windows", linux: "linux", web: "" }[guessOs()];
|
||||
const active = options(bundle.files[`options/${os}/keymap.xml`], "KeymapManager", "active_keymap").get("");
|
||||
const id = importedKeymaps.get(active ?? "");
|
||||
if (id) add("keymap", id, tx("Current keymap"), keymaps[id]?.name);
|
||||
}
|
||||
|
||||
const font = options(bundle.files["options/editor-font.xml"], "DefaultFont");
|
||||
const family = font.get("FONT_FAMILY")?.trim() || undefined;
|
||||
add("editor.fontFamily", family, tx("Font"));
|
||||
@@ -149,6 +221,21 @@ export async function planJetBrainsImport(
|
||||
}
|
||||
add("editor.ligatures", bool(font.get("USE_LIGATURES")), tx("Enable ligatures"));
|
||||
|
||||
const terminal = options(bundle.files["options/terminal-font.xml"], "TerminalFontOptions");
|
||||
const terminalFamily = terminal.get("FONT_FAMILY")?.trim() || undefined;
|
||||
const terminalSize = num(terminal.get("FONT_SIZE"));
|
||||
// A terminal font of its own: stop following the editor font (the font rows below say so).
|
||||
if (terminalFamily || terminalSize) plan.writes.push(["terminal.useEditorFont", false]);
|
||||
add("terminal.fontFamily", terminalFamily, tx("Terminal font"));
|
||||
add("terminal.fontSize", terminalSize, tx("Terminal font size"));
|
||||
add("terminal.lineHeight", num(terminal.get("LINE_SPACING")), tx("Terminal line height"));
|
||||
add("terminal.columnWidth", num(terminal.get("COLUMN_SPACING")), tx("Terminal column width"));
|
||||
add(
|
||||
"terminal.fallbackFontFamily",
|
||||
terminal.get("SECONDARY_FONT_FAMILY")?.trim() || undefined,
|
||||
tx("Terminal fallback font"),
|
||||
);
|
||||
|
||||
const ed = options(bundle.files["options/editor.xml"], "EditorSettings");
|
||||
const strip = ed.get("STRIP_TRAILING_SPACES"); // None | Changed | Whole
|
||||
if (strip === "Changed" || strip === "Whole") {
|
||||
@@ -175,13 +262,95 @@ export async function planJetBrainsImport(
|
||||
wraps === undefined ? undefined : wraps.split(",").includes("MAIN_EDITOR"),
|
||||
tx("Soft-wrap files"),
|
||||
);
|
||||
add(
|
||||
"console.softWrap",
|
||||
wraps === undefined ? undefined : wraps.split(",").includes("CONSOLE"),
|
||||
tx("Use soft wraps in console"),
|
||||
);
|
||||
add("editor.general.softWrapFiles", ed.get("SOFT_WRAP_FILE_MASKS")?.trim() || undefined, tx("File patterns"));
|
||||
const numeration = { ABSOLUTE: "Absolute", RELATIVE: "Relative", HYBRID: "Hybrid" }[ed.get("LINE_NUMERATION") ?? ""];
|
||||
add("editor.appearance.lineNumberMode", numeration?.toLowerCase(), tx("Show line numbers"), tx(numeration ?? ""));
|
||||
const above = bool(ed.get("SHOW_BREADCRUMBS_ABOVE"));
|
||||
add(
|
||||
"editor.breadcrumbs.placement",
|
||||
above === undefined ? undefined : above ? "top" : "bottom",
|
||||
tx("Show breadcrumbs:"),
|
||||
tx(above ? "Top" : "Bottom"),
|
||||
);
|
||||
const insight = options(bundle.files["options/editor.xml"], "CodeInsightSettings");
|
||||
for (const [source, flags, numbers] of [
|
||||
[ed, EDITOR_FLAGS, EDITOR_NUMBERS],
|
||||
[insight, CODE_INSIGHT_FLAGS, CODE_INSIGHT_NUMBERS],
|
||||
] as const) {
|
||||
for (const [name, [key, label]] of Object.entries(flags)) add(key, bool(source.get(name)), tx(label));
|
||||
for (const [name, [key, label]] of Object.entries(numbers)) add(key, num(source.get(name)), tx(label));
|
||||
}
|
||||
const paste = REFORMAT_ON_PASTE[insight.get("REFORMAT_ON_PASTE") ?? ""];
|
||||
add("editor.smartKeys.reformatOnPaste", paste?.[0], tx("Reformat on paste"), tx(paste?.[1] ?? ""));
|
||||
const backspace = SMART_BACKSPACE[insight.get("SMART_BACKSPACE") ?? ""];
|
||||
add("editor.smartKeys.backspaceUnindent", backspace?.[0], tx("Unindent"), tx(backspace?.[1] ?? ""));
|
||||
|
||||
// Tabs and Indents of the current code style scheme; its other formatting options have no setting here.
|
||||
const schemeName =
|
||||
options(bundle.files["options/code.style.schemes.xml"], "CodeStyleSchemeSettings").get("CURRENT_SCHEME_NAME") ??
|
||||
"Default";
|
||||
const scheme = codeScheme(bundle.files, schemeName);
|
||||
if (scheme) {
|
||||
const root = optionValues(scheme);
|
||||
add("editor.codeStyle.hardWrapAt", num(root.get("RIGHT_MARGIN")), tx("Hard wrap at"));
|
||||
add(
|
||||
"editor.codeStyle.detectIndents",
|
||||
bool(root.get("AUTODETECT_INDENTS")),
|
||||
tx("Detect and use existing file indents for editing"),
|
||||
);
|
||||
// "Other File Types": the indent of languages without a code style of their own.
|
||||
const other = optionValues(childOf(childOf(scheme, "option", "OTHER_INDENT_OPTIONS") ?? scheme, "value"));
|
||||
add("editor.tabSize", num(other.get("TAB_SIZE")), tx("Tab size"));
|
||||
const otherTabs = bool(other.get("USE_TAB_CHARACTER"));
|
||||
add(
|
||||
"editor.insertSpaces",
|
||||
otherTabs === undefined ? undefined : !otherTabs,
|
||||
tx("Use tab character"),
|
||||
otherTabs === undefined ? undefined : onOff(otherTabs),
|
||||
);
|
||||
|
||||
const languages = { ...editor.codeStyle?.languages };
|
||||
let changed = false;
|
||||
for (const block of Array.from(scheme.children)) {
|
||||
const ids = CODE_STYLE_LANGUAGES[block.getAttribute("language") ?? ""];
|
||||
if (block.tagName !== "codeStyleSettings" || !ids) continue;
|
||||
const own = optionValues(block);
|
||||
const indent = optionValues(childOf(block, "indentOptions"));
|
||||
const style: Partial<LanguageCodeStyle> = {};
|
||||
const shown: string[] = [];
|
||||
const set = <K extends keyof LanguageCodeStyle>(
|
||||
key: K,
|
||||
value: LanguageCodeStyle[K] | undefined,
|
||||
label: string,
|
||||
) => {
|
||||
if (value === undefined) return;
|
||||
style[key] = value;
|
||||
shown.push(`${tx(label)} ${typeof value === "boolean" ? onOff(value) : value}`);
|
||||
};
|
||||
set("indent", num(indent.get("INDENT_SIZE")), "Indent");
|
||||
set("tabSize", num(indent.get("TAB_SIZE")), "Tab size");
|
||||
set("useTab", bool(indent.get("USE_TAB_CHARACTER")), "Use tab character");
|
||||
set("hardWrapAt", num(own.get("RIGHT_MARGIN")), "Hard wrap at");
|
||||
set("lineCommentAtFirstColumn", bool(own.get("LINE_COMMENT_AT_FIRST_COLUMN")), "Line comment at first column");
|
||||
set("lineCommentAddSpace", bool(own.get("LINE_COMMENT_ADD_SPACE")), "Add a space at line comment start");
|
||||
if (!shown.length) continue;
|
||||
for (const id of ids) languages[id] = { ...languages[id], ...style } as LanguageCodeStyle;
|
||||
changed = true;
|
||||
plan.rows.push({ label: `${tx("Code Style")} › ${block.getAttribute("language")}`, value: shown.join(", ") });
|
||||
}
|
||||
if (changed) plan.writes.push(["editor.codeStyle.languages", languages]);
|
||||
}
|
||||
|
||||
const general = options(bundle.files["options/ide.general.xml"], "GeneralSettings");
|
||||
add("general.confirmExit", bool(general.get("confirmExit")), tx("Confirm before exiting the IDE"));
|
||||
|
||||
const has = (prefix: string) => bundle.entries.some((e) => e.startsWith(prefix));
|
||||
if (has("keymaps/")) plan.skipped.push(tx("Keymap"));
|
||||
if (has("codestyles/")) plan.skipped.push(tx("Code Style"));
|
||||
if (has("codestyles/")) plan.skipped.push(tx("Code Style options other than Tabs and Indents"));
|
||||
if (has("templates/")) plan.skipped.push(tx("Live templates"));
|
||||
if (has("inspection/")) plan.skipped.push(tx("Inspections"));
|
||||
if (has("installed.txt")) plan.skipped.push(tx("Plugins"));
|
||||
@@ -190,6 +359,7 @@ export async function planJetBrainsImport(
|
||||
|
||||
function Summary({ plan }: { plan: JetBrainsImportPlan }) {
|
||||
const left = [...plan.skipped, ...plan.invalid];
|
||||
const unknown = plan.unknownActions;
|
||||
return (
|
||||
<div className={styles.importSummary}>
|
||||
<div>{tx("These settings will be imported:")}</div>
|
||||
@@ -206,6 +376,7 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) {
|
||||
{tx("Not imported:")} {left.join(", ")}
|
||||
</div>
|
||||
)}
|
||||
{unknown.length > 0 && <div>{tx`Not available in OpenIDEA (${unknown.length}): ${unknown.join(", ")}.`}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -213,8 +384,7 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) {
|
||||
/** Reads `path`, asks, then writes the mapped settings to the global layer. */
|
||||
export async function importJetBrainsSettings(path: string) {
|
||||
const bundle = await call(commands.settingsReadJetbrains(path));
|
||||
const { editor } = await commands.settingsGetGlobal();
|
||||
const plan = await planJetBrainsImport(bundle, editor);
|
||||
const plan = await planJetBrainsImport(bundle, await commands.settingsGetGlobal());
|
||||
if (!plan.writes.length) {
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
|
||||
@@ -53,7 +53,7 @@ import {
|
||||
} from "./model";
|
||||
import { groupIcon, groupPath, groupRank } from "./groups";
|
||||
import { KeymapNameDialog } from "./KeymapDialogs";
|
||||
import { parseIdeaKeymap } from "./ideaKeymapImport";
|
||||
import { parseIdeaKeymap } from "@/platform/ideaKeymap";
|
||||
import { RecordShortcutDialog } from "./RecordShortcutDialog";
|
||||
import { StrokeRecorder } from "./StrokeRecorder";
|
||||
import styles from "./Keymap.module.css";
|
||||
|
||||
@@ -5,23 +5,19 @@
|
||||
*/
|
||||
import type { Action } from "@/platform/actions";
|
||||
import { evaluateWhen, type ContextKeys } from "@/platform/context";
|
||||
import { defaultPreset, normalizeBinding, PRESET_TITLES, PRESETS, useKeymap, type Keymap } from "@/platform/keymap";
|
||||
import {
|
||||
customKeymapId,
|
||||
defaultPreset,
|
||||
normalizeBinding,
|
||||
presetBindings,
|
||||
PRESET_TITLES,
|
||||
PRESETS,
|
||||
withBindings,
|
||||
type Keymap,
|
||||
type KeymapDraft,
|
||||
} from "@/platform/keymap";
|
||||
|
||||
export interface KeymapDraft {
|
||||
preset: string;
|
||||
overrides: Keymap;
|
||||
}
|
||||
|
||||
/**
|
||||
* The defaults of `id`: the preset's, or for an action the preset leaves out,
|
||||
* the shortcut its plugin declares (`keymaps`). Removing or changing one is an
|
||||
* override like any other.
|
||||
*/
|
||||
export function presetBindings(preset: string, id: string): string[] {
|
||||
const own = PRESETS[preset];
|
||||
const keys = own && id in own ? own[id] : useKeymap.getState().extensions?.[id];
|
||||
return (keys ?? []).map(normalizeBinding);
|
||||
}
|
||||
export { presetBindings, withBindings, type KeymapDraft };
|
||||
|
||||
export function resolveBindings(draft: KeymapDraft, id: string): string[] {
|
||||
return draft.overrides[id]?.map(normalizeBinding) ?? presetBindings(draft.preset, id);
|
||||
@@ -41,17 +37,6 @@ export function isModified(draft: KeymapDraft, id: string): boolean {
|
||||
return id in draft.overrides;
|
||||
}
|
||||
|
||||
const sameList = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((x, i) => x === b[i]);
|
||||
|
||||
/** Sets the full binding list of `id`; drops the override when it equals the preset. */
|
||||
export function withBindings(draft: KeymapDraft, id: string, bindings: readonly string[]): Keymap {
|
||||
const list = [...new Set(bindings.map(normalizeBinding))];
|
||||
const overrides = { ...draft.overrides };
|
||||
if (sameList(list, presetBindings(draft.preset, id))) delete overrides[id];
|
||||
else overrides[id] = list;
|
||||
return overrides;
|
||||
}
|
||||
|
||||
export function addBinding(draft: KeymapDraft, id: string, binding: string): Keymap {
|
||||
return withBindings(draft, id, [...resolveBindings(draft, id), binding]);
|
||||
}
|
||||
@@ -235,24 +220,13 @@ export function validateKeymapName(name: string, customs: CustomKeymaps, ownId?:
|
||||
return clash ? `Keymap '${n}' already exists` : null;
|
||||
}
|
||||
|
||||
function newKeymapId(name: string, customs: CustomKeymaps): string {
|
||||
const slug =
|
||||
name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "") || "keymap";
|
||||
let id = `custom.${slug}`;
|
||||
for (let i = 2; customs[id] || PRESETS[id]; i++) id = `custom.${slug}-${i}`;
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Copies the selected keymap (its effective overrides) under `name`; returns the new id. */
|
||||
export function duplicateKeymap(
|
||||
draft: KeymapDraft,
|
||||
customs: CustomKeymaps,
|
||||
name: string,
|
||||
): { id: string; customs: CustomKeymaps } {
|
||||
const id = newKeymapId(name, customs);
|
||||
const id = customKeymapId(name, customs);
|
||||
return {
|
||||
id,
|
||||
customs: { ...customs, [id]: { name: name.trim(), parent: draft.preset, overrides: { ...draft.overrides } } },
|
||||
|
||||
+5
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { normalizeBinding } from "@/platform/keymap";
|
||||
import { fromSwingStroke, parseIdeaKeymap } from "../keymap/ideaKeymapImport";
|
||||
import { fromSwingStroke, parseIdeaKeymap } from "./ideaKeymap";
|
||||
|
||||
describe("IntelliJ IDEA keymap import", () => {
|
||||
it("converts Swing keystrokes", () => {
|
||||
@@ -8,6 +8,10 @@ describe("IntelliJ IDEA keymap import", () => {
|
||||
expect(fromSwingStroke("ctrl pressed OPEN_BRACKET")).toBe("Ctrl+[");
|
||||
expect(fromSwingStroke("F12")).toBe("F12");
|
||||
expect(fromSwingStroke("alt BACK_SPACE")).toBe("Alt+Backspace");
|
||||
// As IDEA saves a user's keymap.
|
||||
expect(fromSwingStroke("ctrl right")).toBe("Ctrl+Right");
|
||||
expect(fromSwingStroke("shift ctrl alt s")).toBe("Shift+Ctrl+Alt+S");
|
||||
expect(fromSwingStroke("meta back_slash")).toBe("Meta+\\");
|
||||
expect(fromSwingStroke("meta NUMPAD5")).toBeNull();
|
||||
expect(fromSwingStroke("hyper A")).toBeNull();
|
||||
});
|
||||
@@ -4,8 +4,16 @@
|
||||
* parent; each listed action's shortcuts replace the parent's.
|
||||
*/
|
||||
import { IDEA_ACTIONS } from "@/platform/ideaActions";
|
||||
import { defaultPreset, isValidBinding, normalizeBinding, type Keymap } from "@/platform/keymap";
|
||||
import { withBindings } from "./model";
|
||||
import type { CustomKeymap } from "@/bindings";
|
||||
import {
|
||||
customKeymapId,
|
||||
defaultPreset,
|
||||
isValidBinding,
|
||||
normalizeBinding,
|
||||
PRESET_TITLES,
|
||||
withBindings,
|
||||
type Keymap,
|
||||
} from "@/platform/keymap";
|
||||
|
||||
export interface ImportedIdeaKeymap {
|
||||
name: string;
|
||||
@@ -67,13 +75,16 @@ const SWING_KEYS: Record<string, string> = {
|
||||
|
||||
const SWING_MODS: Record<string, string> = { shift: "Shift", ctrl: "Ctrl", control: "Ctrl", alt: "Alt", meta: "Meta" };
|
||||
|
||||
/** `"shift meta O"` / `"ctrl pressed OPEN_BRACKET"` → `"Meta+Shift+O"`, or null when not expressible. */
|
||||
/**
|
||||
* `"shift meta O"` / `"ctrl pressed OPEN_BRACKET"` → `"Meta+Shift+O"`, or null when not expressible.
|
||||
* Bundled keymaps name keys in upper case; the keymaps IDEA saves for the user are all lower case (`"ctrl right"`).
|
||||
*/
|
||||
export function fromSwingStroke(stroke: string): string | null {
|
||||
const words = stroke
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter((w) => !/^(pressed|released|typed)$/i.test(w));
|
||||
const key = words.pop();
|
||||
const key = words.pop()?.toUpperCase();
|
||||
if (!key || words.some((w) => !SWING_MODS[w.toLowerCase()])) return null;
|
||||
const name = /^([A-Z0-9]|F\d{1,2})$/.test(key) ? key : SWING_KEYS[key];
|
||||
return name ? [...words.map((w) => SWING_MODS[w.toLowerCase()]), name].join("+") : null;
|
||||
@@ -134,3 +145,16 @@ export function parseIdeaKeymap(xml: string): ImportedIdeaKeymap {
|
||||
skippedShortcuts,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a parsed keymap to the user keymaps under its own name, replacing an
|
||||
* earlier import of the same name (a name a bundled keymap has gets a suffix).
|
||||
*/
|
||||
export function addIdeaKeymap(
|
||||
customs: Record<string, CustomKeymap>,
|
||||
parsed: ImportedIdeaKeymap,
|
||||
): { id: string; customs: Record<string, CustomKeymap> } {
|
||||
const name = Object.values(PRESET_TITLES).includes(parsed.name) ? `${parsed.name} (JetBrains)` : parsed.name;
|
||||
const id = Object.keys(customs).find((k) => customs[k]?.name === name) ?? customKeymapId(name, customs);
|
||||
return { id, customs: { ...customs, [id]: { name, parent: parsed.parent, overrides: parsed.overrides } } };
|
||||
}
|
||||
@@ -730,3 +730,43 @@ export function installKeyboardDispatcher(
|
||||
target.removeEventListener("blur", onBlur);
|
||||
};
|
||||
}
|
||||
|
||||
/** A keymap being edited: a bundled preset and the overrides on top of it. */
|
||||
export interface KeymapDraft {
|
||||
preset: string;
|
||||
overrides: Keymap;
|
||||
}
|
||||
|
||||
/**
|
||||
* The defaults of `id`: the preset's, or for an action the preset leaves out,
|
||||
* the shortcut its plugin declares (`keymaps`). Removing or changing one is an
|
||||
* override like any other.
|
||||
*/
|
||||
export function presetBindings(preset: string, id: string): string[] {
|
||||
const own = PRESETS[preset];
|
||||
const keys = own && id in own ? own[id] : useKeymap.getState().extensions?.[id];
|
||||
return (keys ?? []).map(normalizeBinding);
|
||||
}
|
||||
|
||||
const sameList = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((x, i) => x === b[i]);
|
||||
|
||||
/** Sets the full binding list of `id`; drops the override when it equals the preset. */
|
||||
export function withBindings(draft: KeymapDraft, id: string, bindings: readonly string[]): Keymap {
|
||||
const list = [...new Set(bindings.map(normalizeBinding))];
|
||||
const overrides = { ...draft.overrides };
|
||||
if (sameList(list, presetBindings(draft.preset, id))) delete overrides[id];
|
||||
else overrides[id] = list;
|
||||
return overrides;
|
||||
}
|
||||
|
||||
/** A free id for a user keymap called `name`. */
|
||||
export function customKeymapId(name: string, customs: Record<string, unknown>): string {
|
||||
const slug =
|
||||
name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "") || "keymap";
|
||||
let id = `custom.${slug}`;
|
||||
for (let i = 2; customs[id] || PRESETS[id]; i++) id = `custom.${slug}-${i}`;
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -465,6 +465,8 @@
|
||||
"These settings will be imported:": "These settings will be imported:",
|
||||
"Not imported:": "Not imported:",
|
||||
"Current color scheme": "Current color scheme",
|
||||
"Current keymap": "Current keymap",
|
||||
"Code Style options other than Tabs and Indents": "Code Style options other than Tabs and Indents",
|
||||
"No settings OpenIDEA can import were found": "No settings OpenIDEA can import were found",
|
||||
"Overwrite existing branch": "Overwrite existing branch",
|
||||
"Unset upstream branch": "Unset upstream branch",
|
||||
|
||||
@@ -3512,6 +3512,8 @@
|
||||
"These settings will be imported:": "将导入以下设置:",
|
||||
"Not imported:": "不导入:",
|
||||
"Current color scheme": "当前配色方案",
|
||||
"Current keymap": "当前按键映射",
|
||||
"Code Style options other than Tabs and Indents": "制表符和缩进以外的代码样式选项",
|
||||
"No settings OpenIDEA can import were found": "没有找到 OpenIDEA 可以导入的设置",
|
||||
"Rename Project": "重命名项目",
|
||||
"Rename Project…": "重命名项目…",
|
||||
|
||||
Reference in New Issue
Block a user