дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 09:11:10 +02:00
feat(settings): import JetBrains live templates (#6546)
Import Settings now reads templates/*.xml from a JetBrains settings archive or settings folder and, after confirmation, merges the templates (group, abbreviation, description, body, variables and defaults, contexts, deactivated state) into the custom live templates under stable jetbrains.* ids, so importing again updates rather than duplicates. Built-in and unrelated custom templates are kept. Contexts are read as IDEA writes them: the full context id first (JAVA_SCRIPT, SHELL_SCRIPT), then its shorter prefixes down to the language (JAVA_STATEMENT, Python_Class, JS_STATEMENT, KOTLIN_TOPLEVEL), OTHER as everywhere, and comment or string contexts expand outside code. Templates whose contexts don't map to a language are listed as not imported, never made global; expressions OpenIDEA can't evaluate are listed and kept as text. Co-authored-by: muutot <[email protected]>
Цей коміт міститься в:
1 джерело
cbabb5e9b5
коміт
494dd61193
17 files changed
+822
-18
No files matched your search
@@ -522,7 +522,7 @@ impl SettingsStore {
|
||||
pub struct JetBrainsSettings {
|
||||
pub entries: Vec<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/`.
|
||||
pub files: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
@@ -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", "<keymap/>"),
|
||||
("keymaps/nested/ignored.xml", "<keymap/>"),
|
||||
("codestyles/Default.xml", "<code_scheme/>"),
|
||||
("templates/Python.xml", "<templateSet name=\"Python\"/>"),
|
||||
("templates/nested/ignored.xml", "<templateSet/>"),
|
||||
("templates/ignored.txt", "not XML"),
|
||||
("options/mac/keymap.xml", "<application/>"),
|
||||
("options/terminal-font.xml", "<application/>"),
|
||||
],
|
||||
);
|
||||
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::<Vec<_>>(),
|
||||
[
|
||||
@@ -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", "<application/>");
|
||||
put("keymaps/macOS.xml", "<keymap/>");
|
||||
put("codestyles/Default.xml", "<code_scheme/>");
|
||||
put("templates/Python.xml", "<templateSet name=\"Python\"/>");
|
||||
put("templates/nested/ignored.xml", "<templateSet/>");
|
||||
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]
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -37,11 +37,16 @@ OpenIDEA 内置六套快捷键方案:
|
||||
修改生效前会弹出确认框,列出将要导入的内容:
|
||||
|
||||
- 配色方案(`.icls` 文件)以及当前使用的配色方案
|
||||
- 快捷键方案和当前使用的快捷键方案
|
||||
- 编辑器字体:字体、字号、行距(换算为行高)和连字
|
||||
- 去除行尾空格、保存时确保末尾换行、粘性行、显示空白字符、软换行
|
||||
- 当前代码样式方案中的制表符和缩进
|
||||
- `templates/*.xml` 中的实时模板,包括组、缩写、`$VAR$` 正文、变量和映射后的语言上下文
|
||||
- **退出 IDE 前确认**
|
||||
|
||||
快捷键方案、代码样式、实时模板、检查配置和插件不会导入,确认框会列出被跳过的项。导入的值写入全局设置。
|
||||
确认框会在写入前显示实时模板的导入和跳过数量。取消不会产生任何更改。导入的模板会加入按用户保存的自定义模板,不会替换内置模板或无关模板;再次导入会更新相同的 `jetbrains.*` id,而不会重复添加。未知或存在歧义的上下文会列为跳过项,不会改成全局适用。不支持的宏表达式会保留为文本供编辑,但不会执行;仍会应用导入的默认值,否则该字段保持可编辑。
|
||||
|
||||
检查配置、插件以及制表符和缩进以外的代码样式选项不会导入,确认框会将其列为跳过项。导入的设置写入全局设置层。
|
||||
|
||||
### 导入主题
|
||||
|
||||
|
||||
@@ -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$` 的实时模板。**用实时模板包围…** 只显示后者。
|
||||
|
||||
@@ -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 },
|
||||
};
|
||||
|
||||
@@ -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 =
|
||||
'<templateSet name="Python">' +
|
||||
'<template name="iter" value="for $ITEM$ in $ITEMS$: $END$" description="Iterate">' +
|
||||
'<variable name="ITEM" expression="suggestVariableName()" defaultValue=""item"" alwaysStopAt="false" />' +
|
||||
'<variable name="UNKNOWN" expression="groovyScript("1")" defaultValue=""fallback"" />' +
|
||||
'<context><option name="Python" value="true" /></context></template>' +
|
||||
'<template name="brain" value="$END$"><context><option name="Brainfuck" value="true" /></context></template>' +
|
||||
"</templateSet>";
|
||||
const plan = await planJetBrainsImport(
|
||||
{
|
||||
entries: ["templates/Python.xml", "templates/broken.xml"],
|
||||
files: { "templates/Python.xml": xml, "templates/broken.xml": "<templateSet>" },
|
||||
},
|
||||
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"]);
|
||||
});
|
||||
});
|
||||
@@ -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<typeof import("@/platform/ipc")>();
|
||||
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<typeof import("@/workbench/contributions")>()),
|
||||
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$") =>
|
||||
'<templateSet name="Python">' +
|
||||
`<template name="iter" description="Iterate items" value="${body}">` +
|
||||
'<variable name="ITEM" expression="suggestVariableName()" defaultValue=""item"" alwaysStopAt="false" />' +
|
||||
'<variable name="UNSUPPORTED" expression="groovyScript("1")" defaultValue=""fallback"" />' +
|
||||
'<context><option name="Python" value="true" /></context></template>' +
|
||||
'<template name="brain" value="$END$"><context><option name="Brainfuck" value="true" /></context></template>' +
|
||||
"</templateSet>";
|
||||
const bundle = (files: Record<string, string>) => ({ 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<void> }> {
|
||||
let done!: Promise<void>;
|
||||
await act(async () => {
|
||||
done = importJetBrainsSettings(path);
|
||||
});
|
||||
return { done };
|
||||
}
|
||||
|
||||
async function choose(button: "Cancel" | "Import", done: Promise<void>) {
|
||||
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(<MessagesHost />);
|
||||
|
||||
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(<MessagesHost />);
|
||||
|
||||
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": "<templateSet>" }));
|
||||
render(<MessagesHost />);
|
||||
|
||||
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);
|
||||
});
|
||||
@@ -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<JetBrainsImportPlan> {
|
||||
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 (
|
||||
<div className={styles.importSummary}>
|
||||
<div>{tx("These settings will be imported:")}</div>
|
||||
@@ -377,6 +397,7 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) {
|
||||
</div>
|
||||
)}
|
||||
{unknown.length > 0 && <div>{tx`Not available in OpenIDEA (${unknown.length}): ${unknown.join(", ")}.`}</div>}
|
||||
{unsupported && <div>{tx`Unsupported template expressions (kept as text, not evaluated): ${unsupported}.`}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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" });
|
||||
}
|
||||
@@ -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) =>
|
||||
`<template name="${name}" description="${name} description" value="${value}"><context>${contexts}</context></template>`;
|
||||
const context = (name: string, value = "true") => `<option name="${name}" value="${value}" />`;
|
||||
|
||||
describe("JetBrains live-template XML", () => {
|
||||
it("imports Python templates with IDEA bodies, variables and language contexts", () => {
|
||||
const xml =
|
||||
'<templateSet name="Python">' +
|
||||
template(
|
||||
"iter",
|
||||
"for $ITEM$ in $ITEMS$: 	$END$",
|
||||
context("PYTHON") + context("JAVA", "false") + context("Brainfuck", "false"),
|
||||
).replace(
|
||||
"</template>",
|
||||
'<variable name="ITEM" expression="suggestVariableName()" defaultValue=""item"" alwaysStopAt="false" />' +
|
||||
'<variable name="ITEMS" expression="completeSmart()" defaultValue=""items"" alwaysStopAt="true" />' +
|
||||
"</template>",
|
||||
) +
|
||||
template("main", "if __name__ == "__main__":$END$", context("Python")) +
|
||||
"</templateSet>";
|
||||
const parsed = parseJetBrainsTemplates({ "templates/Python.xml": xml }, languages);
|
||||
expect(parsed.invalid).toEqual([]);
|
||||
expect(parsed.skipped).toEqual([]);
|
||||
expect(parsed.unsupported).toEqual([]);
|
||||
expect(parsed.templates).toHaveLength(2);
|
||||
const iter = parsed.templates[0]!;
|
||||
expect(iter).toEqual({
|
||||
id: "jetbrains.Python.iter",
|
||||
group: "Python",
|
||||
abbrev: "iter",
|
||||
description: "iter description",
|
||||
body: "for $ITEM$ in $ITEMS$:\n\t$END$",
|
||||
contexts: ["python"],
|
||||
variables: [
|
||||
{ name: "ITEM", expression: "suggestVariableName()", defaultValue: '"item"', skipIfDefined: true },
|
||||
{ name: "ITEMS", expression: "completeSmart()", defaultValue: '"items"' },
|
||||
],
|
||||
});
|
||||
expect(applicableTemplates(parsed.templates, "python").map((t) => t.abbrev)).toEqual(["iter", "main"]);
|
||||
expect(expandTemplate(iter, { fns: { suggestVariableName: () => "item" } }).preview).toBe("for item in items:\n\t");
|
||||
});
|
||||
|
||||
it("trims template names for stable ids and abbreviations", () => {
|
||||
const parsed = parseJetBrainsTemplates(
|
||||
{
|
||||
"templates/Python.xml":
|
||||
'<templateSet name="Python">' + template(" iter ", "$END$", context("Python")) + "</templateSet>",
|
||||
},
|
||||
languages,
|
||||
);
|
||||
expect(parsed.templates[0]).toMatchObject({ id: "jetbrains.Python.iter", abbrev: "iter" });
|
||||
});
|
||||
|
||||
it("maps common JetBrains context names through the language metadata", () => {
|
||||
const cases: [string, string[]][] = [
|
||||
["C/C++", ["c", "cpp"]],
|
||||
["JavaScript", ["javascript", "javascriptreact"]],
|
||||
["TypeScript", ["typescript", "typescriptreact"]],
|
||||
["JSON", ["json", "jsonc"]],
|
||||
["Text", ["plaintext"]],
|
||||
["JSX", ["javascriptreact"]],
|
||||
["Shell", ["shellscript"]],
|
||||
];
|
||||
const xml =
|
||||
'<templateSet name="Web">' +
|
||||
cases.map(([name], i) => template(`t${i}`, "$END$", context(name))).join("") +
|
||||
"</templateSet>";
|
||||
const parsed = parseJetBrainsTemplates({ "templates/Web.xml": xml }, languages);
|
||||
expect(parsed.skipped).toEqual([]);
|
||||
expect(parsed.templates.map((t) => t.contexts)).toEqual(cases.map(([, ids]) => ids));
|
||||
});
|
||||
|
||||
it("maps the context ids IDEA writes to their languages", () => {
|
||||
const cases: [string, string[]][] = [
|
||||
["JAVA_CODE", ["java"]],
|
||||
["JAVA_STATEMENT", ["java"]],
|
||||
["Python_Class", ["python"]],
|
||||
["JAVA_SCRIPT", ["javascript", "javascriptreact"]],
|
||||
["JS_STATEMENT", ["javascript", "javascriptreact"]],
|
||||
["TS_EXPRESSION", ["typescript", "typescriptreact"]],
|
||||
["SHELL_SCRIPT", ["shellscript"]],
|
||||
["JSON_PROPERTY_KEYS", ["json", "jsonc"]],
|
||||
["OC_STATEMENT", ["c", "cpp"]],
|
||||
["OTHER", ["any"]],
|
||||
];
|
||||
const xml =
|
||||
'<templateSet name="Ids">' +
|
||||
cases.map(([name], i) => template(`t${i}`, "$END$", context(name))).join("") +
|
||||
"</templateSet>";
|
||||
const parsed = parseJetBrainsTemplates({ "templates/Ids.xml": xml }, languages);
|
||||
expect(parsed.skipped).toEqual([]);
|
||||
expect(parsed.templates.map((t) => t.contexts)).toEqual(cases.map(([, ids]) => ids));
|
||||
});
|
||||
|
||||
it("reads the group IDEA writes on templateSet", () => {
|
||||
const parsed = parseJetBrainsTemplates(
|
||||
{
|
||||
"templates/My_Java.xml":
|
||||
'<templateSet group="My Java">' + template("logd", "$END$", context("JAVA_STATEMENT")) + "</templateSet>",
|
||||
},
|
||||
languages,
|
||||
);
|
||||
expect(parsed.templates[0]).toMatchObject({ id: "jetbrains.My_Java.logd", group: "My Java" });
|
||||
});
|
||||
|
||||
it("expands comment and string templates outside code and keeps deactivated ones disabled", () => {
|
||||
const xml =
|
||||
'<templateSet name="Java">' +
|
||||
template("todo", "// TODO $END$", context("JAVA_COMMENT")) +
|
||||
template("code", "$END$", context("JAVA_CODE")) +
|
||||
template("off", "$END$", context("JAVA_CODE")).replace("<template ", '<template deactivated="true" ') +
|
||||
"</templateSet>";
|
||||
const [todo, code, off] = parseJetBrainsTemplates({ "templates/Java.xml": xml }, languages).templates;
|
||||
expect(todo).toMatchObject({ contexts: ["java"], scope: "any" });
|
||||
expect(code!.scope).toBeUndefined();
|
||||
expect(code!.enabled).toBeUndefined();
|
||||
expect(off).toMatchObject({ abbrev: "off", enabled: false });
|
||||
});
|
||||
|
||||
it("reports unknown, absent and disabled contexts instead of making them global", () => {
|
||||
const xml =
|
||||
'<templateSet name="Mixed">' +
|
||||
template("unknown", "$END$", context("Brainfuck")) +
|
||||
template("mixed", "$END$", context("Python") + context("Brainfuck")) +
|
||||
template("maven", "$END$", context("MAVEN")) +
|
||||
'<template name="absent" value="$END$" />' +
|
||||
template("disabled", "$END$", context("Python", "false")) +
|
||||
"</templateSet>";
|
||||
const parsed = parseJetBrainsTemplates({ "templates/Mixed.xml": xml }, languages);
|
||||
expect(parsed.templates).toHaveLength(1);
|
||||
expect(parsed.templates[0]).toMatchObject({ abbrev: "mixed", contexts: ["python"] });
|
||||
expect(parsed.templates[0]!.contexts).not.toContain("any");
|
||||
expect(parsed.skipped).toHaveLength(5);
|
||||
expect(parsed.skipped.join("\n")).toContain("Brainfuck");
|
||||
expect(parsed.skipped.join("\n")).toContain("MAVEN");
|
||||
expect(parsed.skipped.join("\n")).toContain("absent");
|
||||
expect(parsed.skipped.join("\n")).toContain("disabled");
|
||||
});
|
||||
|
||||
it("reports malformed files and updates stable ids without duplicating templates", () => {
|
||||
const first = parseJetBrainsTemplates(
|
||||
{
|
||||
"templates/Python.xml":
|
||||
'<templateSet name="Python">' +
|
||||
template("same", "first $NAME$$END$", context("Python")) +
|
||||
template("same", "second $NAME$$END$", context("Python")) +
|
||||
"</templateSet>",
|
||||
"templates/broken.xml": "<templateSet>",
|
||||
},
|
||||
languages,
|
||||
);
|
||||
expect(first.invalid).toEqual(["templates/broken.xml"]);
|
||||
expect(first.templates).toHaveLength(1);
|
||||
expect(first.templates[0]).toMatchObject({ id: "jetbrains.Python.same", body: "second $NAME$$END$" });
|
||||
|
||||
const again = parseJetBrainsTemplates(
|
||||
{
|
||||
"templates/Python.xml":
|
||||
'<templateSet name="Python">' + template("same", "updated $END$", context("Python")) + "</templateSet>",
|
||||
},
|
||||
languages,
|
||||
);
|
||||
expect(again.templates).toHaveLength(1);
|
||||
expect(again.templates[0]).toMatchObject({ id: first.templates[0]!.id, body: "updated $END$" });
|
||||
});
|
||||
|
||||
it("preserves unsupported macro expressions and defaults, and reports that they cannot run", () => {
|
||||
const xml =
|
||||
'<templateSet name="Python">' +
|
||||
template("macro", "$VALUE$$END$", context("Python")).replace(
|
||||
"</template>",
|
||||
'<variable name="VALUE" expression="groovyScript("return 1")" defaultValue=""fallback"" />' +
|
||||
'<variable name="BROKEN" expression="broken(" />' +
|
||||
"</template>",
|
||||
) +
|
||||
"</templateSet>";
|
||||
const parsed = parseJetBrainsTemplates({ "templates/Python.xml": xml }, languages);
|
||||
expect(parsed.templates[0]!.variables).toEqual([
|
||||
{ name: "VALUE", expression: 'groovyScript("return 1")', defaultValue: '"fallback"' },
|
||||
{ name: "BROKEN", expression: "broken(" },
|
||||
]);
|
||||
expect(parsed.unsupported).toEqual([
|
||||
"templates/Python.xml › Python › macro › VALUE: groovyScript",
|
||||
"templates/Python.xml › Python › macro › BROKEN: broken(",
|
||||
]);
|
||||
expect(expandTemplate(parsed.templates[0]!).preview).toBe("fallback");
|
||||
});
|
||||
});
|
||||
@@ -12,9 +12,10 @@ import {
|
||||
formatDate,
|
||||
parseBody,
|
||||
type LiveTemplate,
|
||||
unsupportedExpressionFunctions,
|
||||
} from "../live/model";
|
||||
import { BUILTIN_TEMPLATES } from "../live/builtins";
|
||||
import { mergeTemplates } from "../live/store";
|
||||
import { mergeImportedTemplates, mergeTemplates } from "../live/store";
|
||||
import { enclosingName, suggestVariableName, templateFunctions } from "../editorContext";
|
||||
|
||||
/** Applies a snippet template to a state and returns the resulting text and selection. */
|
||||
@@ -57,6 +58,13 @@ describe("expressions", () => {
|
||||
expect(evaluateExpression("broken(", {})).toBe("");
|
||||
});
|
||||
|
||||
it("identifies expressions the evaluator cannot run without inventing values", () => {
|
||||
expect(unsupportedExpressionFunctions("capitalize(fileNameWithoutExtension())")).toEqual([]);
|
||||
expect(unsupportedExpressionFunctions("className()")).toEqual([]);
|
||||
expect(unsupportedExpressionFunctions('groovyScript("return 1")')).toEqual(["groovyScript"]);
|
||||
expect(unsupportedExpressionFunctions("broken(")).toEqual(["broken("]);
|
||||
});
|
||||
|
||||
it("formats dates", () => {
|
||||
const d = new Date(2026, 0, 5, 9, 7, 3);
|
||||
expect(formatDate(d)).toBe("2026-01-05");
|
||||
@@ -225,6 +233,40 @@ describe("expansion", () => {
|
||||
expect(merged.some((t) => t.id === BUILTIN_TEMPLATES[1]!.id)).toBe(false);
|
||||
expect(merged.at(-1)).toBe(user);
|
||||
});
|
||||
|
||||
it("merges imports by stable id without touching unrelated templates or built-ins", () => {
|
||||
const builtin = BUILTIN_TEMPLATES[0]!;
|
||||
const edited = { ...builtin, body: "my built-in edit" };
|
||||
const keep: LiveTemplate = {
|
||||
id: "user.keep",
|
||||
group: "User",
|
||||
abbrev: "keep",
|
||||
description: "",
|
||||
body: "keep",
|
||||
contexts: ["python"],
|
||||
};
|
||||
const imported: LiveTemplate = {
|
||||
id: "jetbrains.Python.iter",
|
||||
group: "Python",
|
||||
abbrev: "iter",
|
||||
description: "",
|
||||
body: "for $ITEM$ in $ITEMS$: $END$",
|
||||
contexts: ["python"],
|
||||
};
|
||||
const custom = {
|
||||
templates: { [builtin.id]: edited, [keep.id]: keep, [imported.id]: { ...imported, body: "old" } },
|
||||
deleted: [builtin.id, imported.id, BUILTIN_TEMPLATES[1]!.id],
|
||||
};
|
||||
const merged = mergeImportedTemplates(custom, [imported, { ...builtin, body: "must not replace" }]);
|
||||
expect(merged.templates[builtin.id]).toBe(edited);
|
||||
expect(merged.templates[keep.id]).toBe(keep);
|
||||
expect(merged.templates[imported.id]).toBe(imported);
|
||||
expect(merged.deleted).toEqual([builtin.id, BUILTIN_TEMPLATES[1]!.id]);
|
||||
expect(custom.templates[imported.id]!.body).toBe("old");
|
||||
const again = mergeImportedTemplates(merged, [{ ...imported, body: "updated" }]);
|
||||
expect(Object.keys(again.templates).filter((id) => id === imported.id)).toHaveLength(1);
|
||||
expect(again.templates[imported.id]!.body).toBe("updated");
|
||||
});
|
||||
});
|
||||
|
||||
describe("editor context", () => {
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
import type { LanguageInfo } from "@/bindings";
|
||||
import { unsupportedExpressionFunctions, type LiveTemplate, type TemplateVariable } from "./model";
|
||||
|
||||
export type TemplateLanguage = Pick<LanguageInfo, "id" | "name" | "uiMode">;
|
||||
|
||||
export interface JetBrainsTemplateImport {
|
||||
templates: LiveTemplate[];
|
||||
/** Files or template contexts that could not be mapped, with enough detail to find them. */
|
||||
skipped: string[];
|
||||
/** Malformed XML files; their templates are not imported. */
|
||||
invalid: string[];
|
||||
/** Expressions preserved for editing but not evaluated by OpenIDEA. */
|
||||
unsupported: string[];
|
||||
}
|
||||
|
||||
const TEMPLATE_FILE = /^templates\/([^/]+)\.xml$/;
|
||||
const normalize = (name: string) =>
|
||||
name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[\s_-]+/g, "");
|
||||
|
||||
/** JetBrains context names that cover more than one OpenIDEA file type. */
|
||||
const CONTEXT_ALIASES: Record<string, readonly string[]> = {
|
||||
"c/c++": ["c", "cpp"],
|
||||
"c++": ["cpp"],
|
||||
javascript: ["javascript", "javascriptreact"],
|
||||
typescript: ["typescript", "typescriptreact"],
|
||||
json: ["json", "jsonc"],
|
||||
jsx: ["javascriptreact"],
|
||||
tsx: ["typescriptreact"],
|
||||
text: ["plaintext"],
|
||||
// Context ids IDEA writes into `templates/*.xml` (`JS_STATEMENT`, `TS_EXPRESSION`, CLion's `OC_…`).
|
||||
js: ["javascript", "javascriptreact"],
|
||||
ts: ["typescript", "typescriptreact"],
|
||||
oc: ["c", "cpp"],
|
||||
};
|
||||
|
||||
/** IDEA's Everywhere context (`EverywhereContextType`). */
|
||||
const EVERYWHERE = "OTHER";
|
||||
/** Contexts inside comments and strings, where a `code`-scoped template would never expand. */
|
||||
const NON_CODE_CONTEXT = /(^|[_\s])(COMMENT|STRING)([_\s]|$)/i;
|
||||
|
||||
interface ContextIndex {
|
||||
byId: Map<string, TemplateLanguage>;
|
||||
languages: TemplateLanguage[];
|
||||
}
|
||||
|
||||
/**
|
||||
* IDEA stores context ids such as `JAVA_STATEMENT`, `KOTLIN_TOPLEVEL`, `Python_Class` or
|
||||
* `PHP Statement`: the full id is tried first (`JAVA_SCRIPT`, `SHELL_SCRIPT`), then shorter
|
||||
* prefixes down to the language (`JAVA`, `KOTLIN`, `Python`, `PHP`).
|
||||
*/
|
||||
function contextLanguages(context: string, index: ContextIndex): string[] {
|
||||
if (context === EVERYWHERE) return ["any"];
|
||||
const parts = context.split(/[_\s]+/).filter(Boolean);
|
||||
for (let n = parts.length; n > 0; n--) {
|
||||
const ids = namedLanguages(parts.slice(0, n).join("_"), index);
|
||||
if (ids.length) return ids;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function namedLanguages(context: string, index: ContextIndex): string[] {
|
||||
const key = normalize(context);
|
||||
if (!key) return [];
|
||||
const ids = new Set<string>();
|
||||
for (const language of index.languages) {
|
||||
if (normalize(language.id) === key || normalize(language.name) === key) ids.add(language.id);
|
||||
}
|
||||
for (const id of CONTEXT_ALIASES[key] ?? []) if (index.byId.has(id)) ids.add(id);
|
||||
if (ids.size) return [...ids];
|
||||
|
||||
// A UI mode such as Shell or JSX is a useful fallback, unless several file types share it.
|
||||
const modes = index.languages.filter((language) => language.uiMode && normalize(language.uiMode) === key);
|
||||
return modes.length === 1 ? [modes[0]!.id] : [];
|
||||
}
|
||||
|
||||
function variable(element: Element, label: string, unsupported: string[]): TemplateVariable | null {
|
||||
const name = element.getAttribute("name")?.trim();
|
||||
if (!name) return null;
|
||||
const expression = element.getAttribute("expression") || undefined;
|
||||
const defaultValue = element.getAttribute("defaultValue");
|
||||
const out: TemplateVariable = { name };
|
||||
if (expression !== undefined) out.expression = expression;
|
||||
if (defaultValue !== null) out.defaultValue = defaultValue;
|
||||
// IDEA stops at every variable by default; OpenIDEA's inverse skips a produced value.
|
||||
if (element.getAttribute("alwaysStopAt") === "false") out.skipIfDefined = true;
|
||||
if (expression) {
|
||||
for (const call of unsupportedExpressionFunctions(expression)) unsupported.push(`${label} › ${name}: ${call}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function parseJetBrainsTemplates(
|
||||
files: Record<string, string>,
|
||||
languages: readonly TemplateLanguage[],
|
||||
): JetBrainsTemplateImport {
|
||||
const out: JetBrainsTemplateImport = { templates: [], skipped: [], invalid: [], unsupported: [] };
|
||||
const byId = new Map<string, LiveTemplate>();
|
||||
const index: ContextIndex = {
|
||||
byId: new Map(languages.map((language) => [language.id, language])),
|
||||
languages: [...languages],
|
||||
};
|
||||
const addUnique = (list: string[], value: string) => {
|
||||
if (!list.includes(value)) list.push(value);
|
||||
};
|
||||
|
||||
for (const file of Object.keys(files)
|
||||
.filter((name) => TEMPLATE_FILE.test(name))
|
||||
.sort()) {
|
||||
const stem = TEMPLATE_FILE.exec(file)![1]!;
|
||||
const doc = new DOMParser().parseFromString(files[file]!, "application/xml");
|
||||
const root = doc.documentElement;
|
||||
if (doc.querySelector("parsererror") || root.tagName !== "templateSet") {
|
||||
out.invalid.push(file);
|
||||
continue;
|
||||
}
|
||||
// IDEA writes the group as `group`; `name` is accepted for hand-written sets.
|
||||
const group = (root.getAttribute("group") ?? root.getAttribute("name"))?.trim() || stem;
|
||||
for (const element of Array.from(root.children)) {
|
||||
if (element.tagName !== "template") continue;
|
||||
const name = element.getAttribute("name")?.trim();
|
||||
const body = element.getAttribute("value");
|
||||
const label = `${file} › ${group} › ${name || "(unnamed)"}`;
|
||||
if (!name || body === null) {
|
||||
addUnique(out.skipped, label);
|
||||
continue;
|
||||
}
|
||||
|
||||
const variables: TemplateVariable[] = [];
|
||||
for (const child of Array.from(element.children)) {
|
||||
if (child.tagName !== "variable") continue;
|
||||
const parsed = variable(child, label, out.unsupported);
|
||||
if (parsed) variables.push(parsed);
|
||||
else addUnique(out.skipped, `${label} (variable)`);
|
||||
}
|
||||
|
||||
const contexts: string[] = [];
|
||||
const unmapped: string[] = [];
|
||||
let nonCode = false;
|
||||
const context = Array.from(element.children).find((child) => child.tagName === "context");
|
||||
for (const option of Array.from(context?.children ?? [])) {
|
||||
if (option.tagName !== "option" || option.getAttribute("value")?.toLowerCase() !== "true") continue;
|
||||
const declared = option.getAttribute("name")?.trim();
|
||||
const mapped = declared ? contextLanguages(declared, index) : [];
|
||||
if (mapped.length) {
|
||||
if (NON_CODE_CONTEXT.test(declared!)) nonCode = true;
|
||||
for (const id of mapped) if (!contexts.includes(id)) contexts.push(id);
|
||||
} else {
|
||||
addUnique(unmapped, declared || "(unnamed)");
|
||||
}
|
||||
}
|
||||
// Missing, disabled or unmappable declarations are skipped, never broadened to `any`.
|
||||
if (!contexts.length) {
|
||||
for (const declared of unmapped.length ? unmapped : [""])
|
||||
addUnique(out.skipped, label + (declared ? ` (${declared})` : ""));
|
||||
continue;
|
||||
}
|
||||
if (unmapped.length) addUnique(out.skipped, `${label} (${unmapped.join(", ")})`);
|
||||
|
||||
const template: LiveTemplate = {
|
||||
id: `jetbrains.${stem}.${name}`,
|
||||
group,
|
||||
abbrev: name,
|
||||
description: element.getAttribute("description") ?? "",
|
||||
body,
|
||||
contexts,
|
||||
};
|
||||
if (variables.length) template.variables = variables;
|
||||
if (nonCode) template.scope = "any";
|
||||
if (element.getAttribute("deactivated") === "true") template.enabled = false;
|
||||
byId.set(template.id, template);
|
||||
}
|
||||
}
|
||||
out.templates = [...byId.values()];
|
||||
out.unsupported = [...new Set(out.unsupported)];
|
||||
return out;
|
||||
}
|
||||
@@ -247,6 +247,37 @@ export function evaluateExpression(src: string, fns: TemplateFunctions, values:
|
||||
return ev(e);
|
||||
}
|
||||
|
||||
/** Functions bound to the editor by `templateFunctions` rather than the pure evaluator. */
|
||||
const EDITOR_FUNCTIONS = new Set([
|
||||
"className",
|
||||
"methodName",
|
||||
"functionName",
|
||||
"fileName",
|
||||
"fileNameWithoutExtension",
|
||||
"filePath",
|
||||
"user",
|
||||
"clipboard",
|
||||
"suggestVariableName",
|
||||
"expressionText",
|
||||
"commentStart",
|
||||
"commentEnd",
|
||||
"lineCommentStart",
|
||||
]);
|
||||
|
||||
/** Calls the evaluator cannot run without an editor binding; an invalid expression is returned verbatim. */
|
||||
export function unsupportedExpressionFunctions(src: string): string[] {
|
||||
const expression = parseExpression(src.trim());
|
||||
if (!expression) return [src];
|
||||
const unsupported: string[] = [];
|
||||
const walk = (e: Expr) => {
|
||||
if (e.k !== "call") return;
|
||||
if (!(e.fn in PURE_FUNCTIONS) && !EDITOR_FUNCTIONS.has(e.fn)) unsupported.push(e.fn);
|
||||
e.args.forEach(walk);
|
||||
};
|
||||
walk(expression);
|
||||
return [...new Set(unsupported)];
|
||||
}
|
||||
|
||||
/** Function names an expression calls (to fetch e.g. the clipboard only when needed). */
|
||||
export function calledFunctions(src: string): string[] {
|
||||
const out: string[] = [];
|
||||
|
||||
@@ -56,6 +56,27 @@ export function saveTemplate(t: LiveTemplate) {
|
||||
commit({ ...c, templates: { ...c.templates, [t.id]: t }, deleted: c.deleted.filter((d) => d !== t.id) });
|
||||
}
|
||||
|
||||
/** Adds or updates imported ids in one copy, keeping unrelated templates and built-in edits. */
|
||||
export function mergeImportedTemplates(
|
||||
custom: LiveTemplateCustomizations,
|
||||
imported: readonly LiveTemplate[],
|
||||
): LiveTemplateCustomizations {
|
||||
const templates = { ...custom.templates };
|
||||
const ids = new Set<string>();
|
||||
for (const template of imported) {
|
||||
if (template.pluginOrigin || BUILTIN_IDS.has(template.id)) continue;
|
||||
templates[template.id] = template;
|
||||
ids.add(template.id);
|
||||
}
|
||||
return { templates, deleted: custom.deleted.filter((id) => !ids.has(id)) };
|
||||
}
|
||||
|
||||
/** Commits an import once, after confirmation; re-importing updates the same ids. */
|
||||
export function saveImportedTemplates(imported: readonly LiveTemplate[]) {
|
||||
if (!imported.length) return;
|
||||
commit(mergeImportedTemplates(useLiveTemplates.getState().custom, imported));
|
||||
}
|
||||
|
||||
export function removeTemplate(id: string) {
|
||||
if (id.startsWith("plugin-snippet:")) return;
|
||||
const c = useLiveTemplates.getState().custom;
|
||||
|
||||
@@ -1123,6 +1123,9 @@
|
||||
"Not imported:": "Not imported:",
|
||||
"Current color scheme": "Current color scheme",
|
||||
"Current keymap": "Current keymap",
|
||||
"Live templates": "Live templates",
|
||||
"{imported} imported, {skipped} skipped": "{imported} imported, {skipped} skipped",
|
||||
"Unsupported template expressions (kept as text, not evaluated): {unsupported}.": "Unsupported template expressions (kept as text, not evaluated): {unsupported}.",
|
||||
"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",
|
||||
|
||||
@@ -3757,6 +3757,8 @@
|
||||
"Not imported:": "不匯入:",
|
||||
"Current color scheme": "目前配色方案",
|
||||
"Current keymap": "目前按鍵對映",
|
||||
"{imported} imported, {skipped} skipped": "已匯入 {imported} 個,略過 {skipped} 個",
|
||||
"Unsupported template expressions (kept as text, not evaluated): {unsupported}.": "不支援的範本運算式(保留為文字,不執行):{unsupported}。",
|
||||
"Code Style options other than Tabs and Indents": "製表符和縮排以外的程式碼樣式選項",
|
||||
"No settings OpenIDEA can import were found": "沒有找到 OpenIDEA 可以匯入的設定",
|
||||
"Rename Project": "重新命名專案",
|
||||
|
||||
@@ -4350,6 +4350,8 @@
|
||||
"Not imported:": "不导入:",
|
||||
"Current color scheme": "当前配色方案",
|
||||
"Current keymap": "当前按键映射",
|
||||
"{imported} imported, {skipped} skipped": "已导入 {imported} 个,跳过 {skipped} 个",
|
||||
"Unsupported template expressions (kept as text, not evaluated): {unsupported}.": "不支持的模板表达式(保留为文本,不执行):{unsupported}。",
|
||||
"Code Style options other than Tabs and Indents": "制表符和缩进以外的代码样式选项",
|
||||
"No settings OpenIDEA can import were found": "没有找到 OpenIDEA 可以导入的设置",
|
||||
"Rename Project": "重命名项目",
|
||||
|
||||
Reference in new issue
Заблокувати користувача