diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rs index c601b560a4..ba2a6d9f8f 100644 --- a/crates/ide-workspace/src/settings.rs +++ b/crates/ide-workspace/src/settings.rs @@ -522,7 +522,7 @@ impl SettingsStore { pub struct JetBrainsSettings { pub entries: Vec, /// Entry name → text, for the files OpenIDEA reads: `colors/*.icls`, `keymaps/*.xml`, - /// `codestyles/*.xml` and some of `options/`. + /// `codestyles/*.xml`, `templates/*.xml` and some of `options/`. pub files: BTreeMap, } @@ -540,7 +540,8 @@ const JETBRAINS_OPTIONS: [&str; 9] = [ "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_READ_DIRS: [(&str, &str); 4] = + [("colors/", ".icls"), ("keymaps/", ".xml"), ("codestyles/", ".xml"), ("templates/", ".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 @@ -1146,12 +1147,15 @@ mod tests { ("keymaps/macOS.xml", ""), ("keymaps/nested/ignored.xml", ""), ("codestyles/Default.xml", ""), + ("templates/Python.xml", ""), + ("templates/nested/ignored.xml", ""), + ("templates/ignored.txt", "not XML"), ("options/mac/keymap.xml", ""), ("options/terminal-font.xml", ""), ], ); let read = read_jetbrains_settings(&ok).unwrap(); - assert_eq!(read.entries.len(), 9); + assert_eq!(read.entries.len(), 12); assert_eq!( read.files.keys().collect::>(), [ @@ -1160,7 +1164,8 @@ mod tests { "keymaps/macOS.xml", "options/editor-font.xml", "options/mac/keymap.xml", - "options/terminal-font.xml" + "options/terminal-font.xml", + "templates/Python.xml" ] ); assert!(read_jetbrains_settings(&write("other.zip", &[("options/editor.xml", "")])).is_err()); @@ -1184,6 +1189,8 @@ mod tests { put("options/mac/keymap.xml", ""); put("keymaps/macOS.xml", ""); put("codestyles/Default.xml", ""); + put("templates/Python.xml", ""); + put("templates/nested/ignored.xml", ""); put("plugins/Tools/lib/tools.jar", "jar"); let read = read_jetbrains_settings(&config).unwrap(); @@ -1194,7 +1201,8 @@ mod tests { "colors/_@user_Darcula.icls", "keymaps/macOS.xml", "options/editor-font.xml", - "options/mac/keymap.xml" + "options/mac/keymap.xml", + "templates/Python.xml" ] ); assert_eq!( @@ -1206,6 +1214,7 @@ mod tests { "colors/_@user_Darcula.icls", "keymaps/macOS.xml", "codestyles/Default.xml", + "templates/Python.xml", "installed.txt" ] ); @@ -1243,13 +1252,28 @@ mod tests { } #[test] - fn jetbrains_folder_bounds_mapped_text_like_an_archive() { + fn jetbrains_folder_and_archive_bound_mapped_template_text() { + use std::io::Write; + let tmp = tempfile::tempdir().unwrap(); std::fs::create_dir(tmp.path().join("options")).unwrap(); + std::fs::create_dir(tmp.path().join("templates")).unwrap(); std::fs::write(tmp.path().join("options/editor-font.xml"), vec![b'x'; JETBRAINS_MAX_TEXT as usize + 1]) .unwrap(); + let large = vec![b'x'; JETBRAINS_MAX_TEXT as usize + 1]; + std::fs::write(tmp.path().join("templates/Python.xml"), &large).unwrap(); let read = read_jetbrains_settings(tmp.path()).unwrap(); assert_eq!(read.files["options/editor-font.xml"].len(), JETBRAINS_MAX_TEXT as usize); + assert_eq!(read.files["templates/Python.xml"].len(), JETBRAINS_MAX_TEXT as usize); + + let archive = tmp.path().join("settings.zip"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&archive).unwrap()); + zip.start_file(JETBRAINS_MARKER, zip::write::SimpleFileOptions::default()).unwrap(); + zip.start_file("templates/Python.xml", zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(&large).unwrap(); + zip.finish().unwrap(); + let read = read_jetbrains_settings(&archive).unwrap(); + assert_eq!(read.files["templates/Python.xml"].len(), JETBRAINS_MAX_TEXT as usize); } #[test] diff --git a/docs/en/guide/migrate.mdx b/docs/en/guide/migrate.mdx index 8ff787c95c..7ba98bcce6 100644 --- a/docs/en/guide/migrate.mdx +++ b/docs/en/guide/migrate.mdx @@ -37,11 +37,16 @@ Use **File › Manage IDE Settings › Import Settings from JetBrains IDE…** a A confirmation lists what will be imported before anything changes: - Color schemes (the `.icls` files) and the color scheme in use +- Keymaps and the active keymap - Editor font: family, size, line spacing (as line height) and ligatures - Trailing-space stripping, final newline on save, sticky lines, whitespace display, soft wraps +- Tabs and indents from the current code style scheme +- Live templates from `templates/*.xml`, including their groups, abbreviations, `$VAR$` bodies, variables and mapped language contexts - **Confirm before exiting the IDE** -Keymaps, code styles, live templates, inspection profiles and plugins are not imported; the confirmation lists the ones it skipped. Imported values go to the global settings. +The confirmation shows imported and skipped live-template counts before anything is written. Cancelling changes nothing. Imported templates join the per-user custom templates without replacing built-ins or unrelated templates; importing again updates the same `jetbrains.*` ids instead of adding duplicates. Unknown or ambiguous contexts are listed as skipped rather than made global. Unsupported macro expressions are preserved as text for editing but are not evaluated; imported defaults still apply, otherwise the field remains editable. + +Inspection profiles, plugins and code style options other than Tabs and Indents are not imported; the confirmation lists them as skipped. Imported settings go to the global settings layer. ### Import a theme diff --git a/docs/en/guide/templates.mdx b/docs/en/guide/templates.mdx index afb5b7b806..d0ef1fb141 100644 --- a/docs/en/guide/templates.mdx +++ b/docs/en/guide/templates.mdx @@ -17,6 +17,14 @@ After expansion, the caret is in the first field. `⇥` / `Tab` moves to the nex Built-in templates exist for Rust, JavaScript / TypeScript, Python, Go, Java, Kotlin, PHP and SQL, plus a few general ones (`todo`, `fixme`, `hack`, `date`). **Insert Live Template…** lists the templates that apply at the caret. By default templates expand only in code, not in comments or strings. +### Import from JetBrains + +Choose **File › Manage IDE Settings › Import Settings from JetBrains IDE…** to use an IDE's settings directory on this computer, or **Import Settings…** to select an exported `settings.zip`. The importer reads `templates/*.xml` and lists the imported and skipped counts before writing. Cancel leaves existing templates unchanged. + +Template groups, abbreviations, descriptions, `$VAR$` bodies, variable expressions/defaults and language contexts are preserved. JetBrains `alwaysStopAt="false"` becomes **Skip if defined**. Imports use stable `jetbrains.*` ids, so importing again updates the same templates without replacing built-ins or unrelated custom templates. + +Unknown or ambiguous contexts are skipped, not treated as global. Macro expressions OpenIDEA cannot evaluate are preserved as expression text and listed in the confirmation; imported defaults still apply, otherwise the field stays editable. Malformed XML is reported and none of that file's templates are imported. + ### Surround With Select code and press `⌥⌘T` / `Ctrl+Alt+T`. The list starts with the language's wrappers (`if`, `while`, `try` and so on), followed by live templates that use `$SELECTION$`. **Surround with Live Template…** shows only the latter. diff --git a/docs/zh/guide/migrate.mdx b/docs/zh/guide/migrate.mdx index 6e78f23cf2..16ac5de8d6 100644 --- a/docs/zh/guide/migrate.mdx +++ b/docs/zh/guide/migrate.mdx @@ -37,11 +37,16 @@ OpenIDEA 内置六套快捷键方案: 修改生效前会弹出确认框,列出将要导入的内容: - 配色方案(`.icls` 文件)以及当前使用的配色方案 +- 快捷键方案和当前使用的快捷键方案 - 编辑器字体:字体、字号、行距(换算为行高)和连字 - 去除行尾空格、保存时确保末尾换行、粘性行、显示空白字符、软换行 +- 当前代码样式方案中的制表符和缩进 +- `templates/*.xml` 中的实时模板,包括组、缩写、`$VAR$` 正文、变量和映射后的语言上下文 - **退出 IDE 前确认** -快捷键方案、代码样式、实时模板、检查配置和插件不会导入,确认框会列出被跳过的项。导入的值写入全局设置。 +确认框会在写入前显示实时模板的导入和跳过数量。取消不会产生任何更改。导入的模板会加入按用户保存的自定义模板,不会替换内置模板或无关模板;再次导入会更新相同的 `jetbrains.*` id,而不会重复添加。未知或存在歧义的上下文会列为跳过项,不会改成全局适用。不支持的宏表达式会保留为文本供编辑,但不会执行;仍会应用导入的默认值,否则该字段保持可编辑。 + +检查配置、插件以及制表符和缩进以外的代码样式选项不会导入,确认框会将其列为跳过项。导入的设置写入全局设置层。 ### 导入主题 diff --git a/docs/zh/guide/templates.mdx b/docs/zh/guide/templates.mdx index d33e05d029..ff13a6c207 100644 --- a/docs/zh/guide/templates.mdx +++ b/docs/zh/guide/templates.mdx @@ -17,6 +17,14 @@ description: "展开缩写、包围代码、使用后缀补全和 Emmet、编写 内置模板覆盖 Rust、JavaScript / TypeScript、Python、Go、Java、Kotlin、PHP 和 SQL,另有几个通用模板(`todo`、`fixme`、`hack`、`date`)。**插入实时模板…** 列出在光标处适用的模板。默认情况下模板只在代码中展开,在注释和字符串中不会展开。 +### 从 JetBrains 导入 + +选择 **文件 › 管理 IDE 设置 › 从 JetBrains IDE 导入设置…** 使用本机某个 IDE 的设置目录,或选择 **导入设置…** 选中导出的 `settings.zip`。导入器会读取 `templates/*.xml`,并在写入前显示导入和跳过的数量。取消不会更改现有模板。 + +模板组、缩写、描述、`$VAR$` 正文、变量表达式/默认值和语言上下文都会保留。JetBrains 的 `alwaysStopAt="false"` 对应 **已定义时跳过**。导入使用稳定的 `jetbrains.*` id,再次导入会更新相同模板,不会替换内置模板或无关的自定义模板。 + +未知或存在歧义的上下文会被跳过,不会当作全局上下文。OpenIDEA 无法计算的宏表达式会保留为表达式文本,并在确认框中列出;导入的默认值仍会应用,否则该字段保持可编辑。XML 格式错误时会给出报告,并且不会导入该文件中的任何模板。 + ### 包围 选中代码后按 `⌥⌘T` / `Ctrl+Alt+T`。列表最前面是该语言的包围结构(`if`、`while`、`try` 等),后面是使用了 `$SELECTION$` 的实时模板。**用实时模板包围…** 只显示后者。 diff --git a/src/bindings.ts b/src/bindings.ts index 60b6c36345..264f995a4a 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -9212,7 +9212,7 @@ export type JetBrainsSettings = { entries: string[], /** * Entry name → text, for the files OpenIDEA reads: `colors/*.icls`, `keymaps/*.xml`, - * `codestyles/*.xml` and some of `options/`. + * `codestyles/*.xml`, `templates/*.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 04f5e25357..c8dd3d8a54 100644 --- a/src/features/app/__tests__/jetbrainsSettings.test.ts +++ b/src/features/app/__tests__/jetbrainsSettings.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import type { LanguageInfo } from "@/bindings"; import { planJetBrainsImport } from "../jetbrainsSettings"; const icls = (name: string) => @@ -316,4 +317,53 @@ describe("planJetBrainsImport", () => { expect(plan.invalid).toEqual(["broken.icls"]); expect(plan.writes).toEqual([]); }); + + it("plans live templates separately and reports imported, skipped and unsupported items", async () => { + const python: LanguageInfo = { + id: "python", + name: "Python", + extensions: ["py"], + uiMode: "Python", + lineComment: "#", + blockComment: null, + indent: null, + }; + const xml = + '' + + '' + + '' + + ""; + const plan = await planJetBrainsImport( + { + entries: ["templates/Python.xml", "templates/broken.xml"], + files: { "templates/Python.xml": xml, "templates/broken.xml": "" }, + }, + settings, + fontHeight, + [python], + ); + expect(plan.writes).toEqual([]); + expect(plan.skipped).toEqual([]); + expect(plan.invalid).toEqual(["templates/broken.xml"]); + expect(plan.rows).toEqual([{ label: "Live templates", value: "1 imported, 2 skipped" }]); + expect(plan.liveTemplates?.templates).toEqual([ + { + id: "jetbrains.Python.iter", + group: "Python", + abbrev: "iter", + description: "Iterate", + body: "for $ITEM$ in $ITEMS$: $END$", + contexts: ["python"], + variables: [ + { name: "ITEM", expression: "suggestVariableName()", defaultValue: '"item"', skipIfDefined: true }, + { name: "UNKNOWN", expression: 'groovyScript("1")', defaultValue: '"fallback"' }, + ], + }, + ]); + expect(plan.liveTemplates?.skipped).toEqual(["templates/Python.xml › Python › brain (Brainfuck)"]); + expect(plan.liveTemplates?.unsupported).toEqual(["templates/Python.xml › Python › iter › UNKNOWN: groovyScript"]); + }); }); diff --git a/src/features/app/__tests__/jetbrainsTemplatesImport.test.tsx b/src/features/app/__tests__/jetbrainsTemplatesImport.test.tsx new file mode 100644 index 0000000000..f6413bbedf --- /dev/null +++ b/src/features/app/__tests__/jetbrainsTemplatesImport.test.tsx @@ -0,0 +1,191 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { act, fireEvent, render, screen } from "@testing-library/react"; +import type { LanguageInfo } from "@/bindings"; +import { applicableTemplates, type LiveTemplate } from "@/features/templates/live/model"; + +const read = vi.fn(); +const set = vi.fn(); +const notify = vi.fn(); +const editor = { fontFamily: "JetBrains Mono", fontSize: 13, customSchemes: {}, colorOverrides: {} }; +const python: LanguageInfo = { + id: "python", + name: "Python", + extensions: ["py"], + uiMode: "Python", + lineComment: "#", + blockComment: null, + indent: null, +}; + +vi.mock("@/platform/ipc", async (original) => { + const actual = await original(); + return { + ...actual, + commands: { + ...actual.commands, + settingsReadJetbrains: (path: string) => read(path), + settingsGetGlobal: async () => ({ editor }), + settingsSet: (scope: string, key: string, value: string) => set(scope, key, value), + languages: async () => [python], + }, + }; +}); +vi.mock("@/workbench/contributions", async (original) => ({ + ...(await original()), + notifications: () => ({ notify }), +})); + +const { importJetBrainsSettings } = await import("../jetbrainsSettings"); +const { MessagesHost } = await import("@/workbench/messages"); +const { BUILTIN_TEMPLATES } = await import("@/features/templates/live/builtins"); +const { LIVE_TEMPLATES_KEY, mergeTemplates, saveTemplate, useLiveTemplates } = + await import("@/features/templates/live/store"); + +const empty = { templates: {}, deleted: [] }; +const xml = (body = "for $ITEM$ in $ITEMS$: $END$") => + '' + + `' + + '' + + ""; +const bundle = (files: Record) => ({ status: "ok", data: { entries: Object.keys(files), files } }); + +beforeEach(() => { + vi.clearAllMocks(); + localStorage.removeItem(LIVE_TEMPLATES_KEY); + useLiveTemplates.setState({ custom: empty, templates: mergeTemplates(BUILTIN_TEMPLATES, empty) }); + read.mockResolvedValue(bundle({ "templates/Python.xml": xml() })); + set.mockResolvedValue({ status: "ok", data: { editor } }); + // jsdom has no canvas: settings without templates still fall back to the font size. + vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null); +}); + +afterEach(() => vi.restoreAllMocks()); + +async function start(path: string): Promise<{ done: Promise }> { + let done!: Promise; + await act(async () => { + done = importJetBrainsSettings(path); + }); + return { done }; +} + +async function choose(button: "Cancel" | "Import", done: Promise) { + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: button })); + await done; + }); +} + +it("cancelling writes neither settings nor live templates", async () => { + const keep: LiveTemplate = { + id: "user.keep", + group: "User", + abbrev: "keep", + description: "", + body: "keep", + contexts: ["python"], + }; + saveTemplate(keep); + saveTemplate({ ...BUILTIN_TEMPLATES[0]!, body: "my built-in edit" }); + const before = useLiveTemplates.getState().custom; + const stored = localStorage.getItem(LIVE_TEMPLATES_KEY); + render(); + + const { done } = await start("/settings/PyCharm2026.1"); + expect(screen.getByText("1 imported, 1 skipped")).toBeInTheDocument(); + expect(screen.getByText(/Not imported:/)).toHaveTextContent("Brainfuck"); + expect(screen.getByText(/Unsupported template expressions/)).toHaveTextContent("groovyScript"); + expect(set).not.toHaveBeenCalled(); + expect(useLiveTemplates.getState().custom).toBe(before); + await choose("Cancel", done); + expect(set).not.toHaveBeenCalled(); + expect(useLiveTemplates.getState().custom).toBe(before); + expect(localStorage.getItem(LIVE_TEMPLATES_KEY)).toBe(stored); + expect(notify).not.toHaveBeenCalled(); +}); + +it.each(["/settings/settings.zip", "/settings/PyCharm2026.1"])( + "confirms and atomically imports visible Python templates from %s, then updates the same ids", + async (path) => { + const keep: LiveTemplate = { + id: "user.keep", + group: "User", + abbrev: "keep", + description: "", + body: "keep", + contexts: ["rust"], + }; + saveTemplate(keep); + saveTemplate({ ...BUILTIN_TEMPLATES[0]!, body: "my built-in edit" }); + const write = vi.spyOn(Storage.prototype, "setItem"); + render(); + + const { done } = await start(path); + await choose("Import", done); + expect(read).toHaveBeenCalledExactlyOnceWith(path); + expect(set).not.toHaveBeenCalled(); + expect(write).toHaveBeenCalledTimes(1); + const imported = applicableTemplates(useLiveTemplates.getState().templates, "python").find( + (template) => template.id === "jetbrains.Python.iter", + ); + expect(imported).toMatchObject({ + group: "Python", + abbrev: "iter", + description: "Iterate items", + body: "for $ITEM$ in $ITEMS$: $END$", + contexts: ["python"], + variables: [ + { name: "ITEM", expression: "suggestVariableName()", defaultValue: '"item"', skipIfDefined: true }, + { name: "UNSUPPORTED", expression: 'groovyScript("1")', defaultValue: '"fallback"' }, + ], + }); + expect(useLiveTemplates.getState().custom.templates[keep.id]).toBe(keep); + expect(useLiveTemplates.getState().custom.templates[BUILTIN_TEMPLATES[0]!.id]!.body).toBe("my built-in edit"); + expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "Settings imported", body: path })); + + read.mockResolvedValue(bundle({ "templates/Python.xml": xml("updated $END$") })); + const { done: again } = await start(path); + await choose("Import", again); + expect(write).toHaveBeenCalledTimes(2); + expect( + useLiveTemplates.getState().templates.filter((template) => template.id === "jetbrains.Python.iter"), + ).toHaveLength(1); + expect(useLiveTemplates.getState().custom.templates["jetbrains.Python.iter"]!.body).toBe("updated $END$"); + expect(useLiveTemplates.getState().custom.templates[keep.id]).toBe(keep); + }, +); + +it("reports malformed template XML without losing existing templates", async () => { + const existing: LiveTemplate = { + id: "jetbrains.Python.iter", + group: "Python", + abbrev: "iter", + description: "Existing", + body: "existing $END$", + contexts: ["python"], + }; + saveTemplate(existing); + const before = useLiveTemplates.getState().custom; + const write = vi.spyOn(Storage.prototype, "setItem"); + read.mockResolvedValue(bundle({ "templates/Python.xml": "" })); + render(); + + await act(async () => { + await importJetBrainsSettings("/settings/settings.zip"); + }); + expect(screen.queryByRole("button", { name: "Import" })).not.toBeInTheDocument(); + expect(notify).toHaveBeenCalledWith( + expect.objectContaining({ + level: "warning", + title: "No settings OpenIDEA can import were found", + body: "templates/Python.xml", + }), + ); + expect(set).not.toHaveBeenCalled(); + expect(write).not.toHaveBeenCalled(); + expect(useLiveTemplates.getState().custom).toBe(before); + expect(useLiveTemplates.getState().custom.templates[existing.id]).toBe(existing); +}); diff --git a/src/features/app/jetbrainsSettings.tsx b/src/features/app/jetbrainsSettings.tsx index bfefade561..e281534e3c 100644 --- a/src/features/app/jetbrainsSettings.tsx +++ b/src/features/app/jetbrainsSettings.tsx @@ -1,12 +1,12 @@ /** * Import Settings… with a JetBrains `settings.zip`: maps the archive's colour - * 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. + * schemes, keymaps, fonts, tabs and indents, live templates, 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 { CustomKeymap, JetBrainsSettings, LanguageCodeStyle } from "@/bindings"; +import type { CustomKeymap, JetBrainsSettings, LanguageCodeStyle, LanguageInfo } from "@/bindings"; import { customSchemes } from "@/platform/colorScheme"; import { createFontProbeCanvas, fontsLoaded, monoFontFamily } from "@/platform/fonts"; import { tx } from "@/platform/i18n"; @@ -17,6 +17,8 @@ import { guessOs } from "@/platform/platformInfo"; import { useProject } from "@/platform/project"; import { notifications } from "@/workbench/contributions"; import { ask } from "@/workbench/messages"; +import { parseJetBrainsTemplates, type JetBrainsTemplateImport } from "@/features/templates/live/jetbrains"; +import { saveImportedTemplates } from "@/features/templates/live/store"; import styles from "./app.module.css"; import { CODE_INSIGHT_FLAGS, @@ -39,6 +41,8 @@ export interface JetBrainsImportPlan { invalid: string[]; /** IDEA action ids the imported keymaps bind that have no counterpart here. */ unknownActions: string[]; + /** Custom live templates are committed once after confirmation, not through settings writes. */ + liveTemplates?: JetBrainsTemplateImport; } /** The settings the import builds on (`settingsGetGlobal`). */ @@ -141,6 +145,7 @@ export async function planJetBrainsImport( bundle: JetBrainsSettings, current: CurrentSettings, fontHeight: FontHeight = measuredFontHeight, + languages?: readonly LanguageInfo[], ): Promise { const { editor } = current; const plan: JetBrainsImportPlan = { writes: [], rows: [], skipped: [], invalid: [], unknownActions: [] }; @@ -349,17 +354,32 @@ export async function planJetBrainsImport( const general = options(bundle.files["options/ide.general.xml"], "GeneralSettings"); add("general.confirmExit", bool(general.get("confirmExit")), tx("Confirm before exiting the IDE")); + const templateFiles = Object.fromEntries( + Object.entries(bundle.files).filter(([file]) => /^templates\/[^/]+\.xml$/.test(file)), + ); + if (Object.keys(templateFiles).length) { + const catalog = languages ?? (await commands.languages().catch(() => [])); + const parsed = parseJetBrainsTemplates(templateFiles, catalog); + if (parsed.templates.length || parsed.skipped.length || parsed.invalid.length) { + plan.liveTemplates = parsed; + const imported = parsed.templates.length; + const skipped = parsed.skipped.length + parsed.invalid.length; + plan.rows.push({ label: tx("Live templates"), value: tx`${imported} imported, ${skipped} skipped` }); + for (const file of parsed.invalid) if (!plan.invalid.includes(file)) plan.invalid.push(file); + } + } + const has = (prefix: string) => bundle.entries.some((e) => e.startsWith(prefix)); 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")); return plan; } function Summary({ plan }: { plan: JetBrainsImportPlan }) { - const left = [...plan.skipped, ...plan.invalid]; + const left = [...plan.skipped, ...(plan.liveTemplates?.skipped ?? []), ...plan.invalid]; const unknown = plan.unknownActions; + const unsupported = plan.liveTemplates?.unsupported.join(", ") ?? ""; return (
{tx("These settings will be imported:")}
@@ -377,6 +397,7 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) {
)} {unknown.length > 0 &&
{tx`Not available in OpenIDEA (${unknown.length}): ${unknown.join(", ")}.`}
} + {unsupported &&
{tx`Unsupported template expressions (kept as text, not evaluated): ${unsupported}.`}
} ); } @@ -385,10 +406,12 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) { export async function importJetBrainsSettings(path: string) { const bundle = await call(commands.settingsReadJetbrains(path)); const plan = await planJetBrainsImport(bundle, await commands.settingsGetGlobal()); - if (!plan.writes.length) { + if (!plan.writes.length && !plan.liveTemplates?.templates.length) { + const details = [...plan.invalid, ...(plan.liveTemplates?.skipped ?? [])].join(", "); notifications().notify({ level: "warning", title: "No settings OpenIDEA can import were found", + body: details || undefined, key: "app.settingsImport", }); return; @@ -404,6 +427,7 @@ export async function importJetBrainsSettings(path: string) { for (const [key, value] of plan.writes) // oxlint-disable-next-line no-await-in-loop -- each write updates the settings value stored once at the end settings = await call(commands.settingsSet("global", key, JSON.stringify(value))); + if (plan.liveTemplates?.templates.length) saveImportedTemplates(plan.liveTemplates.templates); useProject.setState({ settings }); notifications().notify({ level: "info", title: "Settings imported", body: path, key: "app.settingsImport" }); } diff --git a/src/features/templates/__tests__/jetbrainsTemplates.test.ts b/src/features/templates/__tests__/jetbrainsTemplates.test.ts new file mode 100644 index 0000000000..5095c6f4d8 --- /dev/null +++ b/src/features/templates/__tests__/jetbrainsTemplates.test.ts @@ -0,0 +1,209 @@ +import { describe, expect, it } from "vitest"; +import { applicableTemplates, expandTemplate } from "../live/model"; +import { parseJetBrainsTemplates, type TemplateLanguage } from "../live/jetbrains"; + +const languages: TemplateLanguage[] = [ + { id: "python", name: "Python", uiMode: "Python" }, + { id: "java", name: "Java", uiMode: "Java" }, + { id: "c", name: "C", uiMode: "C" }, + { id: "cpp", name: "C++", uiMode: "C++" }, + { id: "javascript", name: "JavaScript", uiMode: "JavaScript" }, + { id: "javascriptreact", name: "JavaScript JSX", uiMode: "JSX" }, + { id: "typescript", name: "TypeScript", uiMode: "TypeScript" }, + { id: "typescriptreact", name: "TypeScript JSX", uiMode: "TSX" }, + { id: "shellscript", name: "Shell Script", uiMode: "Shell" }, + { id: "json", name: "JSON", uiMode: "JSON" }, + { id: "jsonc", name: "JSON with Comments", uiMode: "JSON" }, + { id: "plaintext", name: "Plain Text", uiMode: null }, + { id: "properties", name: "Properties", uiMode: "Properties files" }, + { id: "ini", name: "INI", uiMode: "Properties files" }, +]; + +const template = (name: string, value: string, contexts: string) => + ``; +const context = (name: string, value = "true") => `