diff --git a/src/editor/core/actions.ts b/src/editor/core/actions.ts
index 107328d654..e2c36438ac 100644
--- a/src/editor/core/actions.ts
+++ b/src/editor/core/actions.ts
@@ -15,6 +15,7 @@ import {
commentBlock,
commentLine,
completeStatement,
+ cycleCase,
deleteLine,
duplicateEntireLines,
duplicateLineOrSelection,
@@ -973,6 +974,9 @@ export function registerEditorActions(): () => void {
}),
edit("code.joinLines", "Join Lines", (v) => joinLines(v)),
edit("code.toggleCase", "Toggle Case", (v) => toggleCase(v), { keywords: ["upper", "lower"] }),
+ edit("code.cycleCase", "Cycle Identifier Case", (v) => cycleCase(v), {
+ keywords: ["camel", "snake", "kebab", "pascal", "screaming"],
+ }),
caret("code.addCaretsToLineEnds", "Add Carets to Ends of Selected Lines", (v) => addCaretsToLineEnds(v), {
category: "Edit",
}),
diff --git a/src/editor/core/cm/editing.test.ts b/src/editor/core/cm/editing.test.ts
index 3aa351787a..174028eec8 100644
--- a/src/editor/core/cm/editing.test.ts
+++ b/src/editor/core/cm/editing.test.ts
@@ -7,6 +7,7 @@ import {
addCaretsToLineEnds,
commentLine,
completeStatement,
+ cycleCase,
deleteLine,
duplicateEntireLines,
joinLines,
@@ -201,6 +202,58 @@ describe("toggle case", () => {
});
});
+describe("cycle case", () => {
+ it("cycles the identifier at the caret and keeps it selected", () => {
+ const v = make("int myVar|Name = 1;");
+ cycleCase(v);
+ expect(show(v)).toBe("int [MyVarName] = 1;");
+ cycleCase(v);
+ expect(show(v)).toBe("int [my_var_name] = 1;");
+ });
+
+ it("cycles the identifier the caret just left", () => {
+ const v = make("let my_var| = 1;");
+ cycleCase(v);
+ expect(show(v)).toBe("let [MY_VAR] = 1;");
+ });
+
+ it("converts the selection", () => {
+ const v = make("const [SOME_VALUE] = 1;");
+ cycleCase(v);
+ expect(show(v)).toBe("const [some-value] = 1;");
+ });
+
+ it("takes a kebab-case name at the caret whole", () => {
+ const v = make("
");
+ cycleCase(v);
+ expect(show(v)).toBe("
");
+ });
+
+ it("leaves a subtraction alone", () => {
+ const v = make("let n = a - b|;");
+ cycleCase(v);
+ expect(show(v)).toBe("let n = a - [B];");
+ });
+
+ it("moves each caret to the next style", () => {
+ const v = make("[fooBar] [foo_bar]");
+ cycleCase(v);
+ expect(show(v)).toBe("[FooBar] [FOO_BAR]");
+ });
+
+ it("keeps what surrounds a converted selection", () => {
+ const v = make("x = [ user name ] + 1;");
+ cycleCase(v);
+ expect(show(v)).toBe("x = [ userName ] + 1;");
+ });
+
+ it("does nothing where there is no identifier to convert", () => {
+ const v = make("let a = 2|0;");
+ expect(cycleCase(v)).toBe(false);
+ expect(show(v)).toBe("let a = 2|0;");
+ });
+});
+
describe("multiple carets", () => {
it("adds carets at the ends of the selected lines", () => {
const v = make("[ab\ncd\nef]\ngh");
diff --git a/src/editor/core/cm/editing.ts b/src/editor/core/cm/editing.ts
index 2ea80c4034..3d2ccc26ac 100644
--- a/src/editor/core/cm/editing.ts
+++ b/src/editor/core/cm/editing.ts
@@ -31,6 +31,7 @@ import {
} from "@codemirror/commands";
import { SearchCursor } from "@codemirror/search";
import { humpLeft, humpRight, wordStartLeft } from "../model/camelHumps";
+import { cycleIdentifierCase, wordSpan } from "../model/identifierCase";
type Node = ReturnType["resolveInner"]>;
@@ -1057,6 +1058,49 @@ export const toggleCase: Command = (view) => {
return true;
};
+const NAME_CHAR = /[\p{L}\p{N}_$-]/u;
+
+/**
+ * ⇧⌥U: Cycle the Case of the identifier at each caret (which stays selected)
+ * or of each selection, from the style it is written in: snake_case →
+ * SCREAMING_SNAKE_CASE → kebab-case → camelCase → PascalCase.
+ */
+export const cycleCase: Command = (view) => {
+ const { state } = view;
+ if (state.readOnly) return false;
+ /** The `-`-joined name at or right before `pos`. */
+ const nameAt = (pos: number): { from: number; to: number } | null => {
+ const char = (at: number) => at >= 0 && at < state.doc.length && NAME_CHAR.test(state.sliceDoc(at, at + 1));
+ if (!char(pos) && !char(pos - 1)) return null;
+ let from = pos;
+ let to = pos;
+ while (char(from - 1)) from--;
+ while (char(to)) to++;
+ return { from, to };
+ };
+ let changed = false;
+ const tr = state.changeByRange((r) => {
+ const name = r.empty ? nameAt(r.head) : r;
+ if (!name) return { range: r };
+ const span = wordSpan(state.sliceDoc(name.from, name.to));
+ if (!span) return { range: r };
+ const from = name.from + span.from;
+ const insert = cycleIdentifierCase(state.sliceDoc(from, name.from + span.to));
+ if (insert === null) return { range: r };
+ changed = true;
+ const set = state.changes({ from, to: name.from + span.to, insert });
+ return {
+ changes: set,
+ range: r.empty
+ ? EditorSelection.range(from, from + insert.length)
+ : EditorSelection.range(set.mapPos(r.anchor), set.mapPos(r.head)),
+ };
+ });
+ if (!changed) return false;
+ view.dispatch(state.update(tr, { userEvent: "input.case" }));
+ return true;
+};
+
/** ⌥⇧G: Add Carets to Ends of Selected Lines. */
export const addCaretsToLineEnds: Command = (view) => {
const { state } = view;
diff --git a/src/editor/core/model/identifierCase.test.ts b/src/editor/core/model/identifierCase.test.ts
new file mode 100644
index 0000000000..40761cc3b7
--- /dev/null
+++ b/src/editor/core/model/identifierCase.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from "vitest";
+import { cycleIdentifierCase, identifierCase, identifierWords, wordSpan } from "./identifierCase";
+
+describe("identifier case", () => {
+ it("reads the style an identifier is written in", () => {
+ expect(identifierCase("my_var_name")).toBe("snake");
+ expect(identifierCase("MY_VAR_NAME")).toBe("screaming");
+ expect(identifierCase("my-var-name")).toBe("kebab");
+ expect(identifierCase("myVarName")).toBe("camel");
+ expect(identifierCase("MyVarName")).toBe("pascal");
+ expect(identifierCase("user name")).toBe("kebab");
+ expect(identifierCase("FOO_1")).toBe("screaming");
+ });
+
+ it("splits a name into words at separators, case changes and the end of an acronym", () => {
+ expect(identifierWords("myHTTPServer2_v2")).toEqual(["my", "HTTP", "Server2", "v2"]);
+ expect(identifierWords("user name.is_mine-here")).toEqual(["user", "name", "is", "mine", "here"]);
+ expect(identifierWords("--")).toEqual([]);
+ });
+
+ it("spans a selection from its first to its last word character", () => {
+ expect(wordSpan(" user name \n")).toEqual({ from: 2, to: 11 });
+ expect(wordSpan(" -- ")).toBeNull();
+ });
+
+ it("has no style without a cased letter", () => {
+ expect(identifierCase("2024")).toBeNull();
+ expect(identifierCase("")).toBeNull();
+ expect(identifierCase("变量")).toBeNull();
+ });
+});
+
+describe("cycle identifier case", () => {
+ it("goes snake_case → SCREAMING_SNAKE_CASE → kebab-case → camelCase → PascalCase", () => {
+ expect(cycleIdentifierCase("my_var_name")).toBe("MY_VAR_NAME");
+ expect(cycleIdentifierCase("MY_VAR_NAME")).toBe("my-var-name");
+ expect(cycleIdentifierCase("my-var-name")).toBe("myVarName");
+ expect(cycleIdentifierCase("myVarName")).toBe("MyVarName");
+ expect(cycleIdentifierCase("MyVarName")).toBe("my_var_name");
+ });
+
+ it("gives one word its three spellings: name → Name → NAME", () => {
+ expect(cycleIdentifierCase("name")).toBe("Name");
+ expect(cycleIdentifierCase("Name")).toBe("NAME");
+ expect(cycleIdentifierCase("NAME")).toBe("name");
+ });
+
+ it("skips a style that writes the name the same way", () => {
+ // A word that starts with a digit looks the same in camelCase and PascalCase.
+ expect(cycleIdentifierCase("2nd place")).toBe("2ndPlace");
+ expect(cycleIdentifierCase("2ndPlace")).toBe("2nd_place");
+ });
+
+ it("reads a selected phrase as words and converts it", () => {
+ expect(cycleIdentifierCase("user name")).toBe("userName");
+ expect(cycleIdentifierCase("user.name")).toBe("userName");
+ expect(cycleIdentifierCase("User Name")).toBe("userName");
+ });
+
+ it("splits acronyms and keeps digits with their word", () => {
+ expect(cycleIdentifierCase("parseHTTPResponse")).toBe("ParseHTTPResponse");
+ expect(cycleIdentifierCase("ParseHTTPResponse")).toBe("parse_http_response");
+ expect(cycleIdentifierCase("v2Api")).toBe("V2Api");
+ expect(cycleIdentifierCase("XMLHttpRequest")).toBe("xml_http_request");
+ });
+
+ it("follows the lower and upper case of letters, not of the whole string", () => {
+ expect(cycleIdentifierCase("a_b")).toBe("A_B");
+ expect(cycleIdentifierCase("a-b")).toBe("aB");
+ expect(cycleIdentifierCase("ab")).toBe("Ab");
+ expect(cycleIdentifierCase("grüße")).toBe("Grüße");
+ expect(cycleIdentifierCase("Grüße")).toBe("GRÜSSE");
+ });
+
+ it("leaves text without a cased letter alone", () => {
+ expect(cycleIdentifierCase("2024")).toBeNull();
+ expect(cycleIdentifierCase("")).toBeNull();
+ expect(cycleIdentifierCase("变量")).toBeNull();
+ });
+});
diff --git a/src/editor/core/model/identifierCase.ts b/src/editor/core/model/identifierCase.ts
new file mode 100644
index 0000000000..c35d0a536c
--- /dev/null
+++ b/src/editor/core/model/identifierCase.ts
@@ -0,0 +1,98 @@
+/**
+ * Identifier case styles. `cycleIdentifierCase` walks through them in this
+ * order, starting after the style a name is written in.
+ */
+export const identifierCases = ["snake", "screaming", "kebab", "camel", "pascal"] as const;
+export type IdentifierCase = (typeof identifierCases)[number];
+
+const WORD = /[\p{L}\p{N}]/u;
+const SEPARATOR = /[^\p{L}\p{N}]/u;
+const LOWER = /\p{Ll}/u;
+const UPPER = /\p{Lu}/u;
+const DIGIT = /\p{N}/u;
+
+/**
+ * The words of a name or a selected phrase: split at `_`, `-`, spaces and the
+ * like, before an upper-case letter that follows a lower-case one or a digit,
+ * and where an acronym ends (`HTTPServer`).
+ */
+export function identifierWords(text: string): string[] {
+ const out: string[] = [];
+ let word: string[] = [];
+ const chars = Array.from(text);
+ for (const [i, c] of chars.entries()) {
+ if (SEPARATOR.test(c)) {
+ if (word.length) out.push(word.join(""));
+ word = [];
+ continue;
+ }
+ const prev = word.at(-1) ?? "";
+ const next = chars[i + 1];
+ if (UPPER.test(c) && (LOWER.test(prev) || DIGIT.test(prev) || (UPPER.test(prev) && !!next && LOWER.test(next)))) {
+ out.push(word.join(""));
+ word = [];
+ }
+ word.push(c);
+ }
+ if (word.length) out.push(word.join(""));
+ return out;
+}
+
+/** `text` between its first and last word character; null when it has none. */
+export function wordSpan(text: string): { from: number; to: number } | null {
+ const from = text.search(WORD);
+ if (from < 0) return null;
+ const last = text.search(/[\p{L}\p{N}](?![\s\S]*[\p{L}\p{N}])/u);
+ return { from, to: last + (text.codePointAt(last)! > 0xffff ? 2 : 1) };
+}
+
+/** The style `text` is written in; null when it has no letter with a case. */
+export function identifierCase(text: string): IdentifierCase | null {
+ if (text === text.toLowerCase() && text === text.toUpperCase()) return null;
+ const span = wordSpan(text);
+ if (!span) return null;
+ const inner = text.slice(span.from, span.to);
+ if (inner.includes("_")) return inner === inner.toUpperCase() ? "screaming" : "snake";
+ if (SEPARATOR.test(inner)) return "kebab";
+ return UPPER.test(Array.from(inner)[0]!) ? "pascal" : "camel";
+}
+
+/** `text` written in `style`. */
+export function toIdentifierCase(text: string, style: IdentifierCase): string {
+ const lower = (c: string) => c.toLowerCase();
+ const upper = (c: string) => c.toUpperCase();
+ const words = identifierWords(text).map((w) => Array.from(w));
+ const every = (c: (ch: string) => string) => words.map((cs) => cs.map(c).join(""));
+ /** The first letter in the case of `c`, the rest as written. */
+ const lead = (cs: string[], c: (ch: string) => string) => (cs.length ? c(cs[0]!) + cs.slice(1).join("") : "");
+ switch (style) {
+ case "snake":
+ return every(lower).join("_");
+ case "screaming":
+ return every(upper).join("_");
+ case "kebab":
+ return every(lower).join("-");
+ case "camel":
+ return words.map((cs, i) => lead(cs, i ? upper : lower)).join("");
+ case "pascal":
+ return words.map((cs) => lead(cs, upper)).join("");
+ }
+}
+
+/**
+ * `text` in the next style of the cycle, skipping the styles that write it the
+ * same way; null when none writes it differently.
+ */
+export function cycleIdentifierCase(text: string): string | null {
+ const current = identifierCase(text);
+ if (!current) return null;
+ // One word has three spellings, not five: name → Name → NAME.
+ const single = identifierWords(text).length === 1 && !SEPARATOR.test(text);
+ const order: readonly IdentifierCase[] = single ? ["camel", "pascal", "screaming", "snake"] : identifierCases;
+ const start = Math.max(0, order.indexOf(current));
+ for (let step = 1; step <= order.length; step++) {
+ const next = toIdentifierCase(text, order[(start + step) % order.length]!);
+ if (next !== text) return next;
+ }
+ return null;
+}
diff --git a/src/features/settings/__tests__/keymap.test.ts b/src/features/settings/__tests__/keymap.test.ts
index dc9d19fb80..00fde8eff9 100644
--- a/src/features/settings/__tests__/keymap.test.ts
+++ b/src/features/settings/__tests__/keymap.test.ts
@@ -258,6 +258,19 @@ describe("shortcut search", () => {
}
});
+ it("finds the identifier case action by name and by each style it converts between", () => {
+ const dispose = registerEditorActions();
+ try {
+ for (const query of ["Cycle Identifier Case", "camel", "snake", "kebab", "pascal"]) {
+ expect(matchActions(allActions(), query, { isEnabled: () => true, recent: [] }).map((a) => a.id)).toContain(
+ "code.cycleCase",
+ );
+ }
+ } finally {
+ dispose();
+ }
+ });
+
it("matches exact bindings and chord first strokes", () => {
expect(bindingMatches(["Meta+K Meta+C"], "Meta+K")).toBe(true);
expect(bindingMatches(["Shift+Meta+O"], "Meta+Shift+O")).toBe(true);
diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts
index 55a14422b3..36c7229622 100644
--- a/src/platform/keymaps/intellij-macos.ts
+++ b/src/platform/keymaps/intellij-macos.ts
@@ -154,6 +154,7 @@ export const intellijMacos: Record = {
"editor.toggleInsertState": ["Insert"],
"code.joinLines": ["Ctrl+Shift+J"],
"code.toggleCase": ["Meta+Shift+U"],
+ "code.cycleCase": ["Alt+Shift+U"],
"code.pasteFromHistory": ["Meta+Shift+V"],
"code.sortLines": [],
"code.reverseLines": [],
diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts
index 763ca8a7b7..7c627d90e0 100644
--- a/src/platform/keymaps/intellij-windows.ts
+++ b/src/platform/keymaps/intellij-windows.ts
@@ -156,6 +156,7 @@ export const intellijWindows: Record = {
"editor.toggleInsertState": ["Insert"],
"code.joinLines": ["Ctrl+Shift+J"],
"code.toggleCase": ["Ctrl+Shift+U"],
+ "code.cycleCase": ["Alt+Shift+U"],
"code.pasteFromHistory": ["Ctrl+Shift+V"],
"code.sortLines": [],
"code.reverseLines": [],
diff --git a/src/platform/keymaps/vscode-macos.ts b/src/platform/keymaps/vscode-macos.ts
index 4dc9c94554..2168acc9ad 100644
--- a/src/platform/keymaps/vscode-macos.ts
+++ b/src/platform/keymaps/vscode-macos.ts
@@ -173,6 +173,7 @@ export const vscodeMacos: Record = {
"code.startNewLineBefore": ["Meta+Shift+Enter"],
"code.joinLines": ["Ctrl+J"],
"code.toggleCase": [],
+ "code.cycleCase": [],
"code.pasteFromHistory": [],
"code.sortLines": [],
"code.reverseLines": [],
diff --git a/src/platform/keymaps/windows.test.ts b/src/platform/keymaps/windows.test.ts
index ee603d83dc..13c76b324c 100644
--- a/src/platform/keymaps/windows.test.ts
+++ b/src/platform/keymaps/windows.test.ts
@@ -28,6 +28,11 @@ describe("Windows keymaps", () => {
["code.commentLine", "Ctrl+/"],
])("IDEA %s → %s", (id, key) => expect(intellijWindows[id]).toEqual([key]));
+ it("cycles the case of an identifier with ⇧⌥U in both IDEA presets", () => {
+ expect(intellijWindows["code.cycleCase"]).toEqual(["Alt+Shift+U"]);
+ expect(intellijMacos["code.cycleCase"]).toEqual(["Alt+Shift+U"]);
+ });
+
it("VS Code reads ⌘ as Ctrl", () => {
expect(vscodeWindows["navigate.gotoFile"]).toEqual(["Ctrl+P"]);
expect(vscodeWindows["code.quickDocumentation"]).toEqual(["Ctrl+K Ctrl+I"]);
diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json
index d9f240946f..756cdd75c9 100644
--- a/src/platform/locales/text/es.json
+++ b/src/platform/locales/text/es.json
@@ -112,6 +112,7 @@
"Clone Caret Below": "Clonar cursor abajo",
"Join Lines": "Unir líneas",
"Toggle Case": "Alternar mayúsculas y minúsculas",
+ "Cycle Identifier Case": "Alternar el caso del identificador",
"Add Carets to Ends of Selected Lines": "Agregar cursores al final de las líneas seleccionadas",
"Unselect Occurrence": "Deseleccionar coincidencia",
"Paste from History…": "Pegar desde el historial…",
diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json
index e026b023a1..d675bbbf18 100644
--- a/src/platform/locales/text/fr.json
+++ b/src/platform/locales/text/fr.json
@@ -67,6 +67,7 @@
"Clone Caret Below": "Dupliquer le curseur en dessous",
"Join Lines": "Joindre les lignes",
"Toggle Case": "Changer la casse",
+ "Cycle Identifier Case": "Alterner la casse de l'identifiant",
"Add Carets to Ends of Selected Lines": "Ajouter des curseurs à la fin des lignes sélectionnées",
"Unselect Occurrence": "Désélectionner l'occurrence",
"Paste from History…": "Coller depuis l'historique…",
diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json
index f04b5886ac..5657f0c686 100644
--- a/src/platform/locales/text/ko.json
+++ b/src/platform/locales/text/ko.json
@@ -143,6 +143,7 @@
"Clone Caret Below": "캐럿을 아래에 복제",
"Join Lines": "줄 결합",
"Toggle Case": "대/소문자 전환",
+ "Cycle Identifier Case": "식별자 대/소문자 순환",
"Add Carets to Ends of Selected Lines": "선택한 줄 끝에 캐럿 추가",
"Unselect Occurrence": "찾은 항목 선택 해제",
"Paste from History…": "기록에서 붙여넣기…",
diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json
index e2beaab44b..24dae7ea01 100644
--- a/src/platform/locales/text/pl.json
+++ b/src/platform/locales/text/pl.json
@@ -104,6 +104,7 @@
"Clone Caret Below": "Klonuj kursor poniżej",
"Join Lines": "Połącz wiersze",
"Toggle Case": "Przełącz wielkość liter",
+ "Cycle Identifier Case": "Przełączaj wielkość liter identyfikatora",
"Add Carets to Ends of Selected Lines": "Dodaj kursory na końcach zaznaczonych wierszy",
"Unselect Occurrence": "Odznacz wystąpienie",
"Paste from History…": "Wklej z historii…",
diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json
index 1d290d8137..41d2a03749 100644
--- a/src/platform/locales/text/pt.json
+++ b/src/platform/locales/text/pt.json
@@ -104,6 +104,7 @@
"Clone Caret Below": "Clonar cursor abaixo",
"Join Lines": "Juntar linhas",
"Toggle Case": "Alternar maiúsculas/minúsculas",
+ "Cycle Identifier Case": "Alternar o caso do identificador",
"Add Carets to Ends of Selected Lines": "Adicionar cursores ao final das linhas selecionadas",
"Unselect Occurrence": "Desmarcar ocorrência",
"Paste from History…": "Colar do histórico…",
diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json
index a05b152f38..5c26b81e00 100644
--- a/src/platform/locales/text/tr.json
+++ b/src/platform/locales/text/tr.json
@@ -2943,6 +2943,7 @@
"Clone Caret Below": "İmleci Alta Çoğalt",
"Join Lines": "Satırları Birleştir",
"Toggle Case": "Büyük/Küçük Harfi Değiştir",
+ "Cycle Identifier Case": "Tanımlayıcı Büyük/Küçük Harflerini Döndür",
"Add Carets to Ends of Selected Lines": "Seçili Satırların Sonuna İmleç Ekle",
"Unselect Occurrence": "Eşleşmenin Seçimini Kaldır",
"Paste from History…": "Geçmişten Yapıştır…",
diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json
index bc30b4afab..bc60891cce 100644
--- a/src/platform/locales/text/zh-TW.json
+++ b/src/platform/locales/text/zh-TW.json
@@ -695,6 +695,7 @@
"Clone Caret Below": "在下方新增游標",
"Join Lines": "合併行",
"Toggle Case": "切換大小寫",
+ "Cycle Identifier Case": "循環切換識別字大小寫",
"Add or Remove Caret": "新增或移除插入點",
"Create Rectangular Selection on Mouse Drag": "拖動滑鼠建立矩形選取範圍",
"Middle Click": "滑鼠中鍵",
diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json
index 48b96c86a4..7043391794 100644
--- a/src/platform/locales/text/zh.json
+++ b/src/platform/locales/text/zh.json
@@ -1000,6 +1000,7 @@
"Clone Caret Below": "在下方添加光标",
"Join Lines": "合并行",
"Toggle Case": "切换大小写",
+ "Cycle Identifier Case": "循环切换标识符大小写",
"Add or Remove Caret": "添加或移除插入点",
"Create Rectangular Selection on Mouse Drag": "拖动鼠标创建矩形选区",
"Middle Click": "鼠标中键",