diff --git a/docs/en/guide/vim.mdx b/docs/en/guide/vim.mdx index a3e00701b..f38a82f14 100644 --- a/docs/en/guide/vim.mdx +++ b/docs/en/guide/vim.mdx @@ -47,6 +47,8 @@ Supported lines: `set clipboard+=unnamedplus` (or `unnamed`) also copies yanks, deletes and changes without a register to the system clipboard. The `"+` register always reads and writes the system clipboard. +`set number` (`nu`) and `set relativenumber` (`rnu`) switch the line numbers of every editor, as in IdeaVim: both together show hybrid numbers, `relativenumber` alone shows 0 on the caret line, and `nonumber norelativenumber` hides them. An option the file does not set follows **Settings › Editor › General › Appearance › Show line numbers**, and nothing is written to Settings. + `u` on the right-hand side of an Insert-mode mapping breaks the undo sequence, as in Vim. Anything else (functions, `if`, `autocmd`, plugin commands) is reported as ignored and never executed. diff --git a/docs/zh/guide/vim.mdx b/docs/zh/guide/vim.mdx index 76fbe9fea..46c72f126 100644 --- a/docs/zh/guide/vim.mdx +++ b/docs/zh/guide/vim.mdx @@ -47,6 +47,8 @@ Vim 模式开启时(如果上次是开启状态,启动时也会),OpenIDE `set clipboard+=unnamedplus`(或 `unnamed`)让不指定寄存器的复制、删除和修改也写入系统剪贴板。`"+` 寄存器始终读写系统剪贴板。 +`set number`(`nu`)和 `set relativenumber`(`rnu`)与 IdeaVim 一样切换所有编辑器的行号:两者同时开启显示混合行号,只开 `relativenumber` 时光标行显示 0,`nonumber norelativenumber` 隐藏行号。文件里没有设置的选项跟随 **设置 › 编辑器 › 常规 › 外观 › 显示行号**,不会写回设置。 + 在插入模式映射的右侧,`u` 会像 Vim 一样断开撤销序列。 其他内容(函数、`if`、`autocmd`、插件命令等)都会被标记为已忽略,不会执行。 diff --git a/e2e/vimLineNumbers.spec.ts b/e2e/vimLineNumbers.spec.ts new file mode 100644 index 000000000..9639b4156 --- /dev/null +++ b/e2e/vimLineNumbers.spec.ts @@ -0,0 +1,58 @@ +import { expect, stubDesktop, test } from "./fixtures"; + +const FILE = "/dev/acme-api/line-numbers.txt"; + +/** Applies rc file lines through the same parser and engine the app uses. */ +async function applyRc(page: import("@playwright/test").Page, rc: string) { + await page.evaluate(async (text) => { + // Load the app modules in the browser's Vite realm; the variables keep knip from resolving the URLs. + const enginePath = "/src/features/vim/engine.ts"; + const rcPath = "/src/features/vim/rc.ts"; + const { applyRcCommands } = await import(enginePath); + const { parseVimrc } = await import(rcPath); + applyRcCommands(parseVimrc(text).commands); + }, rc); +} + +test("set relativenumber in the rc file switches the editor's line numbers (#7341)", async ({ page }) => { + test.setTimeout(180_000); + await page.addInitScript(() => + localStorage.setItem("openidea.vim.v1", JSON.stringify({ enabled: true, handlers: {} })), + ); + await page.goto("/"); + await expect(page.getByRole("tree", { name: "Project" })).toBeVisible(); + await stubDesktop(page); + await page.evaluate(async (path) => { + const backendPath = "/src/editor/core/backend.ts"; + const contributionsPath = "/src/workbench/contributions.ts"; + const { docBackend } = await import(backendPath); + const { editorService } = await import(contributionsPath); + docBackend().files.set(path, "a\nb\nc\nd\ne\n"); + await editorService().openFile(path); + }, FILE); + const editor = page.locator(".cm-editor").first(); + await expect(editor).toHaveAttribute("data-openidea-vim", "true"); + const numbers = editor.locator(".cm-lineNumbers .cm-gutterElement:not([style*='visibility: hidden'])"); + await editor.locator(".cm-content").click(); + await page.keyboard.press("g"); + await page.keyboard.press("g"); + await page.keyboard.press("j"); + await page.keyboard.press("j"); + await expect(numbers.filter({ hasText: /^\d+$/ }).first()).toBeVisible(); + + // `number` follows Settings (absolute numbers on): hybrid, the caret line keeps its number. + await applyRc(page, "set relativenumber"); + await expect(numbers.nth(0)).toHaveText("2"); + await expect(numbers.nth(2)).toHaveText("3"); + await expect(numbers.nth(3)).toHaveText("1"); + + await applyRc(page, "set nonumber relativenumber"); + await expect(numbers.nth(2)).toHaveText("0"); + + await applyRc(page, "set nonu nornu"); + await expect(editor.locator(".cm-lineNumbers")).toHaveCount(0); + + await applyRc(page, ""); + await expect(numbers.nth(0)).toHaveText("1"); + await expect(numbers.nth(2)).toHaveText("3"); +}); diff --git a/src/editor/api.ts b/src/editor/api.ts index daec15af5..7fe40acd7 100644 --- a/src/editor/api.ts +++ b/src/editor/api.ts @@ -42,6 +42,7 @@ import { rootOfPath } from "@/platform/projectRoots"; import { isVirtualUri } from "@/platform/virtualDocs"; import { cornerInset } from "@/editor/core/cm/cornerInset"; export { iconAreaSource, mapLineStart, type IconAreaSource } from "@/editor/core/cm/iconArea"; +export { lineNumberOption, setLineNumberOptions, type LineNumberOptions } from "@/editor/core/cm/lineNumberOptions"; export { invalidateNavigationProviders, navigationEpoch, diff --git a/src/editor/core/cm/lineNumberOptions.ts b/src/editor/core/cm/lineNumberOptions.ts new file mode 100644 index 000000000..11cb5cc29 --- /dev/null +++ b/src/editor/core/cm/lineNumberOptions.ts @@ -0,0 +1,42 @@ +/** + * Vim's `number` / `relativenumber` over Settings › Editor › General › Appearance › + * Show line numbers, as IdeaVim maps them onto every editor: an option the rc file + * (or `:set`) leaves alone keeps following Settings, and nothing is written back to + * Settings. Vim mode publishes the options it set here; null while it is off. + */ +import { create } from "zustand"; + +export interface LineNumberOptions { + number?: boolean; + relativenumber?: boolean; +} + +export const useLineNumberOptions = create<{ options: LineNumberOptions | null }>(() => ({ options: null })); + +export function setLineNumberOptions(options: LineNumberOptions | null) { + const empty = !options || (options.number === undefined && options.relativenumber === undefined); + useLineNumberOptions.setState({ options: empty ? null : { ...options } }); +} + +interface ShownLineNumbers { + lineNumbers: boolean; + lineNumberMode: string; +} + +/** Vim's view of Settings: `number` is on for absolute and hybrid numbers, `relativenumber` for relative and hybrid. */ +export function lineNumberOption(name: keyof LineNumberOptions, settings: ShownLineNumbers): boolean { + const set = useLineNumberOptions.getState().options?.[name]; + if (set !== undefined) return set; + return settings.lineNumbers && settings.lineNumberMode !== (name === "number" ? "relative" : "absolute"); +} + +/** The line numbers editors show: Settings, unless Vim set `number` or `relativenumber` (both on: hybrid, as in Vim). */ +export function shownLineNumbers(settings: ShownLineNumbers): ShownLineNumbers { + if (!useLineNumberOptions.getState().options) return settings; + const number = lineNumberOption("number", settings); + const relative = lineNumberOption("relativenumber", settings); + return { + lineNumbers: number || relative, + lineNumberMode: number && relative ? "hybrid" : relative ? "relative" : "absolute", + }; +} diff --git a/src/editor/core/cm/prefs.ts b/src/editor/core/cm/prefs.ts index b9af97fb5..35ae30293 100644 --- a/src/editor/core/cm/prefs.ts +++ b/src/editor/core/cm/prefs.ts @@ -81,6 +81,7 @@ export { type LocalAppearanceOverride, } from "./localAppearance"; import { GUTTER_ICON_GROUPS, type EffectiveAppearance, type LocalAppearanceOverride } from "./localAppearance"; +import { shownLineNumbers } from "./lineNumberOptions"; // --- soft wraps --------------------------------------------------------------- @@ -619,7 +620,7 @@ export function effectiveAppearance( override?: LocalAppearanceOverride | null, ): EffectiveAppearance { return { - lineNumbers: override?.lineNumbers ?? prefs.appearance.lineNumbers, + lineNumbers: override?.lineNumbers ?? shownLineNumbers(prefs.appearance).lineNumbers, whitespaces: override?.whitespaces ?? !!showWhitespace, gutterIcons: override?.gutterIcons ?? prefs.showGutterIcons, indentGuides: override?.indentGuides ?? prefs.appearance.indentGuides, diff --git a/src/editor/core/cm/setup.ts b/src/editor/core/cm/setup.ts index d552a031b..6952fe430 100644 --- a/src/editor/core/cm/setup.ts +++ b/src/editor/core/cm/setup.ts @@ -68,6 +68,7 @@ import { overwriteField } from "./overwrite"; import { imeSyllableSpaces } from "./imeCommit"; import { stickySelectionField } from "./stickySelection"; import { horizontalScrollHold } from "./horizontalScrollHold"; +import { shownLineNumbers } from "./lineNumberOptions"; import { relativeLineNumbers } from "./relativeLineNumbers"; import { clipboardDocumentPath, clipboardFilesExtension } from "./clipboard"; import { primarySelectionYield } from "./primarySelection"; @@ -281,7 +282,7 @@ export function heavyExtension( } export function lineNumbersExtension(settings: EditorSettings | undefined, override?: boolean | null): Extension { - const a = prefsOf(settings).appearance; + const a = shownLineNumbers(prefsOf(settings).appearance); if (!(override ?? a.lineNumbers) || isDistractionFree()) return []; return a.lineNumberMode === "relative" || a.lineNumberMode === "hybrid" ? relativeLineNumbers(a.lineNumberMode === "hybrid") diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index 1fdf8b16f..2c40f9232 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -52,6 +52,7 @@ import { type TextEditorWrapperContribution, } from "@/workbench/contributions"; import { useDistractionFree } from "@/workbench/distractionFree"; +import { useLineNumberOptions } from "./cm/lineNumberOptions"; import { restoreMaximizedToolWindow } from "@/workbench/toolwindows/store"; import { ask, confirm } from "@/workbench/messages"; import { t, tx } from "@/platform/i18n"; @@ -507,6 +508,8 @@ export class EditorController implements SlotHost { ); // Gutter, centred column and sticky lines follow Distraction Free Mode. this.disposers.push(useDistractionFree.subscribe(() => this.manager.applySettings())); + // Vim's `number` / `relativenumber` change every editor's line numbers. + this.disposers.push(useLineNumberOptions.subscribe(() => this.manager.applySettings())); this.disposers.push( useTextEditorWrappers.subscribe(({ wrappers }) => { this.upgradeWrappedImageTabs(wrappers); diff --git a/src/features/vim/__tests__/lineNumbers.test.ts b/src/features/vim/__tests__/lineNumbers.test.ts new file mode 100644 index 000000000..ab2f08e5a --- /dev/null +++ b/src/features/vim/__tests__/lineNumbers.test.ts @@ -0,0 +1,61 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { Vim } from "@replit/codemirror-vim"; +import { useLineNumberOptions, shownLineNumbers } from "@/editor/core/cm/lineNumberOptions"; +import { applyRcCommands, setLineNumberOptionsActive } from "../engine"; +import { parseVimrc } from "../rc"; + +const apply = (rc: string) => applyRcCommands(parseVimrc(rc).commands); +const absolute = { lineNumbers: true, lineNumberMode: "absolute" }; + +afterEach(() => { + apply(""); + setLineNumberOptionsActive(false); +}); + +describe("Vim number / relativenumber (#7341)", () => { + it("reads both options from an rc file instead of reporting them as ignored", () => { + const rc = parseVimrc("set number relativenumber\nset nonu\nset rnu"); + expect(rc.ignored).toEqual([]); + expect(rc.commands.map((c) => c.kind === "set" && [c.name, c.value])).toEqual([ + ["number", true], + ["relativenumber", true], + ["nu", false], + ["rnu", true], + ]); + }); + + it("sets every editor's line numbers over Settings while Vim mode is on", () => { + setLineNumberOptionsActive(true); + expect(apply("set relativenumber")).toEqual([]); + // `number` is unset and follows Settings (absolute numbers on): hybrid, as in IdeaVim. + expect(shownLineNumbers(absolute)).toEqual({ lineNumbers: true, lineNumberMode: "hybrid" }); + apply("set nonumber relativenumber"); + expect(shownLineNumbers(absolute)).toEqual({ lineNumbers: true, lineNumberMode: "relative" }); + apply("set nonu nornu"); + expect(shownLineNumbers(absolute).lineNumbers).toBe(false); + apply("set rnu"); + expect(shownLineNumbers({ lineNumbers: false, lineNumberMode: "absolute" }).lineNumberMode).toBe("relative"); + }); + + it("follows Settings again when the rc file no longer sets them or Vim mode turns off", () => { + setLineNumberOptionsActive(true); + apply("set rnu"); + expect(useLineNumberOptions.getState().options).toEqual({ relativenumber: true }); + apply("set tw=80"); + expect(useLineNumberOptions.getState().options).toBeNull(); + apply("set rnu"); + setLineNumberOptionsActive(false); + expect(useLineNumberOptions.getState().options).toBeNull(); + expect(shownLineNumbers(absolute)).toBe(absolute); + setLineNumberOptionsActive(true); + expect(useLineNumberOptions.getState().options).toEqual({ relativenumber: true }); + }); + + it("reads an unset option from Settings", () => { + setLineNumberOptionsActive(true); + expect(Vim.getOption("number")).toBe(true); + expect(Vim.getOption("relativenumber")).toBe(false); + apply("set nu rnu"); + expect(Vim.getOption("rnu")).toBe(true); + }); +}); diff --git a/src/features/vim/__tests__/rc.test.ts b/src/features/vim/__tests__/rc.test.ts index e5827ab0d..3202ddd59 100644 --- a/src/features/vim/__tests__/rc.test.ts +++ b/src/features/vim/__tests__/rc.test.ts @@ -215,7 +215,7 @@ describe(":action ids", () => { describe("source", () => { it("applies the sourced file in place, sharing the leader", () => { - const sources = new Map([["~/.vimrc", 'let mapleader = ","\nset textwidth=80\nset number\nnmap a b']]); + const sources = new Map([["~/.vimrc", 'let mapleader = ","\nset textwidth=80\nset hlsearch\nnmap a b']]); const { commands, ignored } = parseVimrc("nmap x y\nsource ~/.vimrc\nnmap c d", sources); expect(commands).toEqual([ { kind: "map", mode: "normal", noremap: false, lhs: "x", rhs: "y" }, @@ -224,7 +224,7 @@ describe("source", () => { { kind: "map", mode: "normal", noremap: false, lhs: ",c", rhs: "d" }, ]); expect(ignored).toEqual([ - { file: "~/.vimrc", line: 3, text: "set number", reason: "option not supported: number" }, + { file: "~/.vimrc", line: 3, text: "set hlsearch", reason: "option not supported: hlsearch" }, ]); }); diff --git a/src/features/vim/engine.ts b/src/features/vim/engine.ts index 5fdd75cd8..87bc2f93a 100644 --- a/src/features/vim/engine.ts +++ b/src/features/vim/engine.ts @@ -26,6 +26,8 @@ import { useVimMode, type VimModeState } from "./mode"; import { resolveActionId, type RcCommand, type SetOp } from "./rc"; import { useVimSettings } from "./settings"; import { mapFunctionTextObjects } from "./textObjects"; +import { resetLineNumberOptions } from "./lineNumbers"; +export { setLineNumberOptionsActive } from "./lineNumbers"; /** Insert/Replace state as seen by transactions (mode changes are queued). */ // Vim's `u` / `Ctrl-R` call CodeMirror's history; an editor that keeps its history elsewhere @@ -604,6 +606,7 @@ function adjustedOption(name: string, op: SetOp, value: string): string | number export function applyRcCommands(commands: readonly RcCommand[]): string[] { defineExCommands(); Vim.mapclear(); + resetLineNumberOptions(); shadowLeaderBuiltins(commands); // `mapclear` drops them with the user mappings; before those, which may remap them. mapFunctionTextObjects(); diff --git a/src/features/vim/index.ts b/src/features/vim/index.ts index 1c1ee203a..85b0b76f6 100644 --- a/src/features/vim/index.ts +++ b/src/features/vim/index.ts @@ -43,11 +43,13 @@ export function activate(): () => void { setContext("vim.mode", ""); contribution?.(); contribution = null; + void engine?.then((e) => e.setLineNumberOptionsActive(false)); return; } const e = await loadEngine(); if (!rcApplied) await reloadRc(true).catch((err) => console.error("vimrc failed", err)); if (gen !== generation || contribution) return; + e.setLineNumberOptionsActive(true); contribution = registerEditorContribution({ id: "vim", order: 0, diff --git a/src/features/vim/lineNumbers.ts b/src/features/vim/lineNumbers.ts new file mode 100644 index 000000000..2867260bf --- /dev/null +++ b/src/features/vim/lineNumbers.ts @@ -0,0 +1,39 @@ +/** + * `number` (`nu`) and `relativenumber` (`rnu`): as in IdeaVim they set every editor's + * line numbers over Settings › Editor › General › Appearance › Show line numbers, and + * one the rc file leaves alone reads and follows that setting. Both on is hybrid + * (the caret line keeps its own number), `relativenumber` alone shows 0 there. + */ +import { Vim } from "@replit/codemirror-vim"; +import { lineNumberOption, setLineNumberOptions, type LineNumberOptions } from "@/editor/api"; +import { editorPrefs } from "@/platform/editorSettings"; + +let options: LineNumberOptions = {}; +let active = false; + +const publish = () => setLineNumberOptions(active ? options : null); + +for (const [name, alias] of [ + ["number", "nu"], + ["relativenumber", "rnu"], +] as const) { + // A callback option: called with a value to set it, without one to read it. + Vim.defineOption(name, undefined, "boolean", [alias], ((value?: boolean) => { + if (value === undefined) return lineNumberOption(name, editorPrefs().appearance); + options = { ...options, [name]: value }; + publish(); + return undefined; + }) as never); +} + +/** Forgets what the previous rc file set, before it is applied again. */ +export function resetLineNumberOptions() { + options = {}; + publish(); +} + +/** Vim mode on: its options apply; off: Settings alone. */ +export function setLineNumberOptionsActive(on: boolean) { + active = on; + publish(); +} diff --git a/src/features/vim/rc.ts b/src/features/vim/rc.ts index e6d3d6289..785fd4a3b 100644 --- a/src/features/vim/rc.ts +++ b/src/features/vim/rc.ts @@ -116,6 +116,10 @@ const SUPPORTED_OPTIONS = new Set([ "lmap", "clipboard", "cb", + "number", + "nu", + "relativenumber", + "rnu", ]); const MAP_FLAGS = /^<(silent|unique|nowait|buffer|expr|script)>$/i;