diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rs index 185ec0bc9..66a8b5266 100644 --- a/crates/ide-workspace/src/settings.rs +++ b/crates/ide-workspace/src/settings.rs @@ -441,13 +441,26 @@ impl SettingsStore { #[serde(rename_all = "camelCase")] pub struct JetBrainsSettings { pub entries: Vec, - /// 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, } 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 { 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 { use std::io::Read; @@ -936,11 +961,25 @@ mod tests { ("options/editor-font.xml", ""), ("options/vcs.xml", ""), ("keymaps/macOS.xml", ""), + ("keymaps/nested/ignored.xml", ""), + ("codestyles/Default.xml", ""), + ("options/mac/keymap.xml", ""), + ("options/terminal-font.xml", ""), ], ); let read = read_jetbrains_settings(&ok).unwrap(); - assert_eq!(read.entries.len(), 5); - assert_eq!(read.files.keys().collect::>(), ["colors/_@user_Darcula.icls", "options/editor-font.xml"]); + assert_eq!(read.entries.len(), 9); + assert_eq!( + read.files.keys().collect::>(), + [ + "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", ""); put("options/editor-font.xml", ""); put("options/vcs.xml", ""); + put("options/mac/keymap.xml", ""); put("keymaps/macOS.xml", ""); + put("codestyles/Default.xml", ""); put("plugins/Tools/lib/tools.jar", "jar"); let read = read_jetbrains_settings(&config).unwrap(); - assert_eq!(read.files.keys().collect::>(), ["colors/_@user_Darcula.icls", "options/editor-font.xml"]); + assert_eq!( + read.files.keys().collect::>(), + [ + "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" ] ); diff --git a/src/bindings.ts b/src/bindings.ts index 75047ad6a..6ba08d8dd 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -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 }, }; diff --git a/src/features/app/__tests__/jetbrainsSettings.test.ts b/src/features/app/__tests__/jetbrainsSettings.test.ts index 6c9b5ee0c..04f5e2535 100644 --- a/src/features/app/__tests__/jetbrainsSettings.test.ts +++ b/src/features/app/__tests__/jetbrainsSettings.test.ts @@ -11,7 +11,10 @@ const component = (name: string, options: Record) => .map(([k, v]) => ``; -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; 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 = + '' + + '' + + ''; + const active = + ''; + const bundle = { + entries: ["keymaps/macOS copy.xml", "keymaps/broken.xml"], + files: { + "keymaps/macOS copy.xml": keymap, + "keymaps/broken.xml": " { + 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) => `${body}`; + 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", + '', + ), + "codestyles/Team.xml": scheme( + "Team", + '' + + '' + + '' + + '' + + '', + ), + }, + }, + { + ...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 = + "" + + 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, "") + + ""; + 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": " { fireEvent.click(screen.getByRole("button", { name: button })); diff --git a/src/features/app/jetbrainsOptions.ts b/src/features/app/jetbrainsOptions.ts new file mode 100644 index 000000000..16ed38032 --- /dev/null +++ b/src/features/app/jetbrainsOptions.ts @@ -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]; + +/** ``: on/off options. */ +export const EDITOR_FLAGS: Record = { + 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", + ], +}; + +/** ``: numbers. */ +export const EDITOR_NUMBERS: Record = { + 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"], +}; + +/** ``: on/off options. */ +export const CODE_INSIGHT_FLAGS: Record = { + 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"], +}; + +/** ``: numbers. */ +export const CODE_INSIGHT_NUMBERS: Record = { + 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 = { + "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 = { + "0": ["none", "Disabled"], + "1": ["nearest", "To nearest indent position"], + "2": ["autoindent", "To proper indent position"], +}; + +/** `` → the language ids that share that code style here. */ +export const CODE_STYLE_LANGUAGES: Record = { + 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"], +}; diff --git a/src/features/app/jetbrainsSettings.tsx b/src/features/app/jetbrainsSettings.tsx index 79a568c69..c57d20786 100644 --- a/src/features/app/jetbrainsSettings.tsx +++ b/src/features/app/jetbrainsSettings.tsx @@ -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; +/** The settings the import builds on (`settingsGetGlobal`). */ +interface CurrentSettings { + editor: { + fontFamily: string; + fontSize: number | null; + customSchemes: unknown; + colorOverrides: Record; + codeStyle?: { languages?: Record }; + }; + customKeymaps?: Record; } const USER_PREFIX = "_@user_"; @@ -93,12 +111,39 @@ async function measuredFontHeight(family: string, size: number): Promise` children of `parent`. */ +function optionValues(parent: Element | null | undefined): Map { + const out = new Map(); + 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, 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 { - 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(); // 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 = {}; + const shown: string[] = []; + const set = ( + 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 (
{tx("These settings will be imported:")}
@@ -206,6 +376,7 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) { {tx("Not imported:")} {left.join(", ")}
)} + {unknown.length > 0 &&
{tx`Not available in OpenIDEA (${unknown.length}): ${unknown.join(", ")}.`}
} ); } @@ -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", diff --git a/src/features/settings/keymap/KeymapPage.tsx b/src/features/settings/keymap/KeymapPage.tsx index 7c31ca179..cadd59f99 100644 --- a/src/features/settings/keymap/KeymapPage.tsx +++ b/src/features/settings/keymap/KeymapPage.tsx @@ -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"; diff --git a/src/features/settings/keymap/model.ts b/src/features/settings/keymap/model.ts index 3a030470f..b777bcd59 100644 --- a/src/features/settings/keymap/model.ts +++ b/src/features/settings/keymap/model.ts @@ -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 } } }, diff --git a/src/features/settings/__tests__/ideaKeymapImport.test.ts b/src/platform/ideaKeymap.test.ts similarity index 87% rename from src/features/settings/__tests__/ideaKeymapImport.test.ts rename to src/platform/ideaKeymap.test.ts index b99b6a169..484b1d906 100644 --- a/src/features/settings/__tests__/ideaKeymapImport.test.ts +++ b/src/platform/ideaKeymap.test.ts @@ -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(); }); diff --git a/src/features/settings/keymap/ideaKeymapImport.ts b/src/platform/ideaKeymap.ts similarity index 80% rename from src/features/settings/keymap/ideaKeymapImport.ts rename to src/platform/ideaKeymap.ts index ff3dea970..cd29c2474 100644 --- a/src/features/settings/keymap/ideaKeymapImport.ts +++ b/src/platform/ideaKeymap.ts @@ -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 = { const SWING_MODS: Record = { 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, + parsed: ImportedIdeaKeymap, +): { id: string; customs: Record } { + 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 } } }; +} diff --git a/src/platform/keymap.ts b/src/platform/keymap.ts index cd50d16fb..6fdab49b4 100644 --- a/src/platform/keymap.ts +++ b/src/platform/keymap.ts @@ -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 { + 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; +} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 8ea0b0a10..414fbde1f 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -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", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 547bf23e9..51c7adbf3 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -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…": "重命名项目…",