Skip to content

Latest commit

 

History

History
225 lines (194 loc) · 74.4 KB

README.md

File metadata and controls

225 lines (194 loc) · 74.4 KB

claudecode

Overview

claudecode is the core package of claudecode.nvim. It makes Neovim an IDE peer for the Claude Code CLI. It does six jobs:

  1. It starts a localhost MCP WebSocket server (./server/README.md).
  2. It writes a discovery lock file that holds an auth token.
  3. It launches the CLI in a terminal provider (./terminal/README.md) with env vars that point the CLI at the server.
  4. It serves MCP tool calls (./tools/README.md).
  5. It streams selection and @-mention notifications to the CLI.
  6. It shows blocking accept/reject diffs for the edits that Claude proposes.

Module map (direct files):

File Role
init.lua Entry point: setup, start/stop, user commands, @-mention queue
config.lua Defaults, legacy-option mapping, and assert-based validation
lockfile.lua <port>.lock discovery file and auth token
terminal.lua Provider dispatcher: command, env, cwd, send_to_terminal
diff.lua Native side-by-side blocking diff and the diff lifecycle
diff_inline.lua Unified (layout = "unified") inline diff renderer
selection.lua Visual and cursor selection tracking and the selection_changed broadcast
integrations.lua File-explorer selection readers (nvim-tree, neo-tree, oil, mini.files, netrw, snacks picker)
visual_commands.lua Visual-mode command wrapper and tree-explorer line-to-path mapping
cwd.lua Terminal working-directory resolution and git root lookup
utils.lua Argv parsing, tilde expansion, a mode's selection type, UTF-8 repair, the window-change gate
logger.lua Level-filtered logging to vim.notify and nvim_echo
health.lua :checkhealth claudecode
types.lua LuaLS @class and @alias declarations. Its only runtime code is return {}

Interface

Subdirectories

  • ./server/README.md: WebSocket (RFC 6455) and JSON-RPC 2.0 MCP server. API: start(config, auth_token), stop(), send, send_response, broadcast, and get_status().
  • ./terminal/README.md: the native, snacks, external, and none providers, plus paste_fix for streamed pastes.
  • ./tools/README.md: the MCP tool registry. It exposes 10 tools and the hidden close_tab.

Entry point (init.lua)

  • M.setup(opts) -> M: applies config, sets up the logger, terminal, and diff modules, and creates commands and the shutdown autocmd. It starts the server when auto_start is set [init.lua:M.setup]
  • M.start(show_startup_notification?) -> ok, port|err and M.stop() -> ok, err? [init.lua:M.start]
  • M.state: config, server, port, auth_token, initialized, mention_queue, mention_timer, and connection_timer [init.lua:M.state]
  • M.is_claude_connected(): false when the server is not running. When get_status().clients is non-empty, true only when a client is in state connected with handshake_complete, so a closing client does not count. When it is empty, true when client_count > 0, with no handshake check [init.lua:M.is_claude_connected]
  • M.send_at_mention(file_path, start_line?, end_line?, context?) -> ok, err?: line numbers are 0-indexed [init.lua:M.send_at_mention]
  • M.process_mention_queue(from_new_connection?): the server's on_open callback calls it with true once a client completed its WebSocket handshake. Without the argument it flushes the queue now. A flush sends the oldest mention only once some connected client has been connected for connection_wait_delay ms, and otherwise waits for that moment [init.lua:M.process_mention_queue]
  • M.open_with_model(args), M.get_version(), and M.version, read from the first line of the repository's VERSION file at load. Without a readable, well-formed VERSION file the version is 0.0.0-unknown [init.lua:M.version]
  • Internal API: M._create_commands, M._broadcast_at_mention, M._add_paths_to_claude (default max_files 100, batch_size 10), M._format_path_for_at_mention, M._ensure_terminal_visible_if_connected, and M._maybe_warn_unfocusable_provider [init.lua:M._add_paths_to_claude]. Nothing outside tests/ calls M._add_paths_to_claude or M._ensure_terminal_visible_if_connected. The user commands call M.send_at_mention for each path, with no file cap and no batches. :ClaudeCodeSend does it through a local add_paths_to_claude [init.lua:M._create_commands]

User commands [init.lua:M._create_commands]

  • Server: :ClaudeCodeStart, :ClaudeCodeStop, and :ClaudeCodeStatus.
  • Context: :ClaudeCodeSend (range, tree-aware), :ClaudeCodeTreeAdd, and :ClaudeCodeAdd <path> [start] [end].
  • :ClaudeCodeAdd reads Neovim's split arguments (opts.fargs), so a path with escaped spaces, such as the expansion of % for a buffer named my file.lua, stays one argument. It needs a running server and at most 3 arguments. Only a path that starts with %, #, or < goes through vim.fn.expand. Other paths expand only a bare ~ or a leading ~/, so $VAR stays literal. The path must be a readable file or a directory. Line numbers must be at least 1, and start must not be past end.
  • :ClaudeCodeTreeAdd refuses without a running server. The tree handlers detect a tree buffer by filetype only, and the visual :ClaudeCodeSend handler does not accept snacks_picker_list, which the normal handler accepts.
  • Terminal: :ClaudeCode [args], :ClaudeCodeFocus [args], :ClaudeCodeOpen [args], :ClaudeCodeClose, and :ClaudeCodeSendText[!] <text>. These commands exist only when claudecode.terminal loads. :ClaudeCodeSendText! inserts the text without submitting it.
  • Diff: :ClaudeCodeDiffAccept, :ClaudeCodeDiffDeny, and :ClaudeCodeCloseAllDiffs.
  • Model: :ClaudeCodeSelectModel [args]. It exists even when claudecode.terminal does not load, and its choice runs :ClaudeCode --model <value> [args] [init.lua:M.open_with_model]

User autocmd events

  • User ClaudeCodeSendComplete with data = { file_path, start_line, end_line, context } [init.lua:fire_send_complete]
  • User ClaudeCodeDiffOpened with data = { tab_name, file_path, new_file_path, is_new_file, diff_window, target_window, terminal_window, tab_number }, fired after the diff is registered [diff.lua:M._setup_blocking_diff]
  • User ClaudeCodeDiffClosed with data = { tab_name, file_path, reason }, for example replaced by new diff, diff tab closed after save, diff tab closed after reject, setup failed, or shutdown [diff.lua:M._cleanup_diff_state]
  • fire_diff_event runs the autocmds in pcall with modeline = false, so an error in a handler never reaches the diff code [diff.lua:fire_diff_event]

Configuration (config.lua)

  • M.defaults, M.apply(user_config) -> config, and M.validate(config) -> true [config.lua:M.apply]
  • Defaults: port_range = { min = 10000, max = 65535 }, auto_start = true, log_level = "info", track_selection = true, focus_after_send = false, visual_demotion_delay_ms = 50, connection_wait_delay = 600, connection_timeout = 10000, queue_timeout = 5000, terminal.provider = "auto", and six models entries [config.lua:M.defaults]
  • diff_opts defaults: layout = "vertical", open_in_new_tab = false, keep_terminal_focus = false, hide_terminal_in_new_tab = false, on_new_file_reject = "keep_empty", and auto_resize_terminal = true [config.lua:M.defaults]

Other modules

  • terminal.lua: setup, open, close, simple_toggle, focus_toggle, toggle, toggle_open_no_focus, ensure_visible, hide_float, get_active_terminal_bufnr, and send_to_terminal(text, { submit = true, focus = false }) [terminal.lua:M.send_to_terminal]
  • terminal.lua: open, simple_toggle, and focus_toggle take (opts_override, cmd_args) and call the provider method of the same name with (cmd_string, env_table, effective_config). M.toggle calls M.simple_toggle, not the provider's toggle. toggle_open_no_focus and ensure_visible call the provider's ensure_visible when it has one, else open the terminal without focus when it is not visible [terminal.lua:M.toggle] [terminal.lua:ensure_terminal_visible_no_focus]
  • terminal.lua test hook: _get_managed_terminal_for_test() returns the provider's _get_terminal_for_test() result, or nil [terminal.lua:M._get_managed_terminal_for_test]
  • terminal.lua defaults: split_side = "right", split_width_percentage = 0.30, diff_split_width_percentage = nil, provider = "auto", show_native_term_exit_tip = true, auto_close = true, auto_insert = true, env = {}, snacks_win_opts = {}, fix_streamed_paste = "auto", cwd = nil, git_repo_cwd = false, and cwd_provider = nil [terminal.lua:M.defaults]
  • diff.lua: setup, open_diff(old_file_path, new_file_path, new_file_contents, tab_name) (wraps _open_native_diff, a legacy path that nothing in the plugin calls. It never checks the tab for a user's diff. It opens the old file in the main editor window, current tab first, which is never itself a diff window, and runs :diffthis there, so it joins a vimdiff in that tab. With no main editor window, it uses the window right of the top-left one, which can be one of the user's diff windows, and splits it when it shows a terminal or nofile buffer. When it is the preview window, it splits the Claude terminal's window instead when that window is tiled in the same tab), open_diff_blocking(old_file_path, new_file_path, new_file_contents, tab_name, client_id), close_diff_by_tab_name, close_all_diffs, close_pending_diffs, close_rejected_diffs, close_saved_diffs, close_diffs_for_client, accept_current_diff, deny_current_diff, and reload_file_buffers_manual [diff.lua:M.open_diff_blocking]
  • diff.lua internals that diff_inline.lua depends on: _register_diff_state, _get_active_diffs, _cleanup_diff_state, _resolve_diff_as_rejected, _write_proposal, _register_reject_when_hidden, _close_proposal_window, _save_window_sizes, _restore_window_sizes, _restore_cursor, _resize_terminal_for_diff, _find_main_editor_window, _find_claudecode_terminal_window, _leave_preview_window, _is_buffer_dirty, _detect_filetype, _get_autocmd_group, and _display_terminal_in_new_tab [diff.lua:M._register_diff_state] [diff.lua:M._get_active_diffs]
  • diff.lua internals exposed for testing: _resolve_split_width_percentage, _auto_resize_enabled, _tabpage_has_diff_window, and _register_diff_autocmds. _setup_blocking_diff calls _create_diff_view_from_window through M, so tests can replace it [diff.lua:M._register_diff_autocmds] [diff.lua:M._create_diff_view_from_window]
  • diff_inline.lua: setup_inline_diff, compute_inline_diff, extract_new_content, render_diff_buffer, resolve_inline_as_saved, resolve_inline_as_rejected, and cleanup_inline_diff [diff_inline.lua:M.setup_inline_diff]
  • selection.lua: enable(server, visual_demotion_delay_ms), disable, get_latest_selection, get_visual_selection, get_cursor_position(winid?), is_claude_terminal_buffer, send_current_selection, get_range_selection, send_at_mention_for_visual_selection, and the autocmd handlers on_cursor_moved, on_mode_changed, and on_text_changed [selection.lua:M.enable]
  • selection.lua internals: state, server (set by enable, cleared by disable), debounce_update, update_selection, handle_selection_demotion, get_visual_selection_from_marks, flush_visual_selection, has_selection_changed, send_selection_update, _cancel_debounce_timer, _cancel_demotion_timer, _create_autocommands, and _clear_autocommands [selection.lua:M.update_selection] [selection.lua:M.enable]
  • lockfile.lua: lock_dir, generate_auth_token, create(port, auth_token?) -> ok, path, token, remove, get_auth_token, and get_workspace_folders [lockfile.lua:M.create]
  • lockfile.get_workspace_folders() returns getcwd() first, then each LSP client's workspace folder with file:// removed (no percent-decoding), without duplicates [lockfile.lua:M.get_workspace_folders]
  • integrations.lua: get_selected_files_from_tree() picks a reader by filetype: NvimTree (_get_nvim_tree_selection), neo-tree (_get_neotree_selection), oil (_get_oil_selection), minifiles (_get_mini_files_selection), netrw (_get_netrw_selection), and snacks_picker_list (_get_snacks_picker_selection). For any other filetype it returns nil and an error, not {} [integrations.lua:M.get_selected_files_from_tree]
  • integrations._get_mini_files_selection_with_range(start_line, end_line) is not a dispatch target. The visual :ClaudeCodeSend handler calls it in a minifiles buffer [integrations.lua:M._get_mini_files_selection_with_range] [init.lua:M._create_commands]
  • The tree readers keep these paths: nvim-tree drops a root-level file (^/[^/]*$), oil skips . and .. and adds / to a directory, and mini.files, netrw, and the snacks picker keep only paths that exist [integrations.lua:M._get_nvim_tree_selection] [integrations.lua:M._get_oil_selection]
  • visual_commands.lua: create_visual_command_wrapper, exit_visual_and_schedule, validate_visual_mode, get_visual_range, get_tree_state, capture_visual_selection_data, and get_files_from_visual_selection [visual_commands.lua:M.create_visual_command_wrapper]
  • visual_commands.get_tree_state() knows only neo-tree (when its window is current), nvim-tree, oil, and netrw. It returns nil for minifiles and snacks_picker_list [visual_commands.lua:M.get_tree_state]
  • cwd.lua: resolve(term_cfg, ctx) and git_root(start_dir) [cwd.lua:M.resolve]. Nothing in lua/ calls cwd.resolve. terminal.lua:build_config has its own copy of the cwd order and calls only cwd.git_root, so a change to resolve does not change the terminal [terminal.lua:build_config]
  • utils.lua: shell_split, parse_command, expand_tilde, normalize_focus, selection_type, utf8_sequence_length, valid_utf8, map_terminal_suspend, win_set_buf_in_split, close_tabpage_without_entering, without_autocmds, when_windows_allowed, and resume_tool_coroutine [utils.lua:M.parse_command] [utils.lua:M.valid_utf8] [utils.lua:M.map_terminal_suspend] [utils.lua:M.win_set_buf_in_split] [utils.lua:M.close_tabpage_without_entering] [utils.lua:M.without_autocmds] [utils.lua:M.when_windows_allowed] [utils.lua:M.resume_tool_coroutine]
  • logger.lua: levels, setup, error, warn, info, one_line, debug, trace, and is_level_enabled [logger.lua:M.setup]
  • health.lua: check(). It checks, in order: Neovim 0.8.0 or later, require("claudecode"), that setup() ran, the CLI (the first word of terminal_cmd, or claude) and its --version, the terminal provider, then the server, its lock file (present, missing, or there but not readable), and a connected client. It stops after a failed load, a missing setup(), or a stopped server [health.lua:M.check] [health.lua:check_cli] [health.lua:check_server]

Invariants

Lifecycle and auth

  • setup runs config.apply before logger, terminal, and diff setup. The auto-start runs only after diff.setup, and the user commands are created after the auto-start [init.lua:M.setup]
  • setup writes the top-level git_repo_cwd, cwd, and cwd_provider options into the caller's opts.terminal table, and passes that table, not config.terminal, to terminal.setup. Before setup, M.state.config is the config.defaults table itself [init.lua:M.setup] [init.lua:M.state]
  • setup warns when focus_after_send = true and the provider is none, or external with a usable external_terminal_cmd, because those providers cannot take the focus [init.lua:M._maybe_warn_unfocusable_provider]
  • start refuses with "Already running". The auth token must be a string of length 10 or more. If server.start fails, start returns the error at once. If the lock file fails, start stops the server and clears its state [init.lua:M.start]
  • start requires the token returned by lockfile.create to equal the generated token. Otherwise it removes the lock file, stops the server, and clears its state. When lockfile.remove returns an error, it only logs that error as a warning and still returns the mismatch error [init.lua:M.start]
  • stop returns "Not running" without a server. When lockfile.remove returns an error, stop only logs that error as a warning. lockfile.remove returns that error when vim.loop.fs_unlink fails, also when it fails without raising (for example in a read-only directory), so the lock file stays and the failure is logged. lockfile.remove looks for the name with vim.loop.fs_lstat and deletes it with fs_unlink, which refuses a folder. So a lock file that exists but cannot be read (mode 000) is still deleted, a link at the path is removed as a link (a link that points nowhere too) and never its target, and a folder is never deleted, also when another process replaces the file with one after the check. It returns "Lock file does not exist" when fs_lstat finds nothing at that path (nothing has that name, or the lock folder cannot be searched) or finds a folder (a folder stays) [init.lua:M.stop] [lockfile.lua:M.remove]
  • stop tries to remove the lock file and disables selection tracking when track_selection is set, then stops the server. When server.stop fails, stop returns the error and keeps state.server, although the removal and the disable already ran [init.lua:M.stop]
  • The auth token is 32 lowercase hex characters from vim.loop.random or /dev/urandom. It never comes from math.random [lockfile.lua:get_random_bytes]
  • The lock directory is $CLAUDE_CONFIG_DIR/ide when that variable is set and not empty, else ~/.claude/ide. It is resolved once when the module loads [lockfile.lua:M.lock_dir]
  • health.check builds the lock-file path lock_dir/<port>.lock itself, so a change to the lock-file name must change health.lua too [health.lua:check_server]
  • lockfile.create requires a port in 1..65535 and a caller token of 10..500 characters. It writes JSON { pid, workspaceFolders, ideName = "Neovim", transport = "ws", authToken } [lockfile.lua:M.create]
  • lockfile.get_auth_token(port) returns false, nil, error when it cannot give the token. The error is "Lock file does not exist" when vim.loop.fs_stat finds nothing at that path (nothing has that name, a link points nowhere, or the lock folder cannot be searched) or finds a folder, and "Lock file exists but cannot be read" with the system message when fs_stat finds the file and io.open fails (mode 000, or a socket, for example) [lockfile.lua:M.get_auth_token]

Configuration and terminal

  • config.validate asserts most top-level fields. It does not assert disable_broadcast_debouncing or enable_broadcast_debouncing_in_tests. Examples: 0 < port_range.min <= max <= 65535, log_level in trace|debug|info|warn|error, env values are strings, models is a non-empty list of { name, value }, and diff_opts.layout is vertical|horizontal|unified. For terminal it asserts only that it is a table and checks provider_opts. It does not assert terminal.provider or other terminal.* keys [config.lua:M.validate]
  • config.validate also asserts visual_demotion_delay_ms >= 0, connection_wait_delay >= 0, connection_timeout > 0, queue_timeout > 0, boolean auto_start and track_selection, and a nil or string terminal_cmd. It checks focus_after_send and each diff_opts key only when set. external_terminal_cmd must be a string or a function, and a non-empty string must contain %s. types.lua also allows a table there, which validate rejects [config.lua:M.validate] [types.lua:ClaudeCodeTerminalProviderOptions]
  • config.apply deep-copies the defaults. It maps the legacy vertical_split option to layout, and legacy open_in_current_tab to open_in_new_tab. A legacy option set as a boolean overwrites the new option [config.lua:M.apply]
  • config.lua requires no other module, so apply never loads claudecode.terminal [config.lua:M.defaults]
  • Provider selection: auto uses snacks if available, else native. external requires external_terminal_cmd as a function or as a string containing %s. Every other failure falls back to native [terminal.lua:get_provider]
  • get_provider picks the provider again on every call. Only the provider modules are cached [terminal.lua:get_provider]. When a snacks, external, none, or custom table provider fails, each call logs a warning that it falls back to native. terminal.setup calls it too [terminal.lua:M.setup]
  • terminal.setup changes M.defaults in place. It always sets terminal_cmd and env from its own arguments and ignores a terminal_cmd key in the terminal options. An invalid provider value keeps the previous value (default auto), and the warning names it: Keeping 'auto', or Keeping the custom provider table when the previous value is a table [terminal.lua:M.setup]
  • terminal.setup warns about its options through vim.notify directly, not through the logger. So its warnings show at once, and log_level does not filter them. It warns on a terminal config that is not a table, an invalid terminal_cmd or env, an invalid value for a known key, and an unknown key [terminal.lua:M.setup]
  • A per-call opts_override changes only a key that has a validator (split_side, split_width_percentage, snacks_win_opts, cwd, git_repo_cwd, cwd_provider) and a non-nil current value. So a per-call cwd or cwd_provider is ignored unless setup set one. Providers get only split_side, split_width_percentage, auto_close, auto_insert, snacks_win_opts, and the resolved cwd [terminal.lua:build_config]
  • The Claude command is terminal_cmd, or claude when it is unset. no_proxy and NO_PROXY always include localhost, 127.0.0.1, and ::1 [terminal.lua:get_claude_command_and_env]
  • Terminal cwd precedence: cwd_provider, then static cwd, then the git root when git_repo_cwd is set. A cwd_provider result or a static cwd goes through cwd.expand_leading, which expands only a leading ~, ~/, $VAR or ${VAR}, without a shell, so ~ and $VAR work even when Neovim's current folder holds a folder with that literal name. The rest of the text is used as written, so $, \, [, { and backticks in the folder name stay. No cwd path reaches vim.fn.expand, which runs text between backticks as a shell command, and a buffer name (a term:// or zipfile:// buffer, say) can put such text in ctx.file_dir [terminal.lua:build_config] [cwd.lua:M.expand_leading]
  • cwd.git_root and cwd.resolve take a directory path as written: a folder name with [, {, *, ?, $, \, a space or a comma stays that folder. A leading ~, ~/, $VAR or ${VAR} is expanded first by expand_leading, without a shell, even when Neovim's current folder holds a folder with that literal name, and a string that then names no directory gives nil. Neither the start folder nor the root git prints reaches vim.fn.expand. The terminal does not call cwd.resolve, but terminal.lua:build_config applies the same as-written rule to a static cwd and a cwd_provider result, so $ or \ past the start of the text stays. Unlike normalize_dir, it passes text that names no folder on to the terminal instead of dropping it. When git rev-parse cannot run or finds no repository, git_root walks up from start_dir made absolute with :p, with its .. parts simplified, to the nearest folder that holds a .git folder. A relative start_dir that begins with ~ is not made absolute, because Vim reads ~ as the home folder and ~name as a user's home folder, so the walk starts from there [cwd.lua:M.git_root] [cwd.lua:normalize_dir] [terminal.lua:build_config]
  • send_to_terminal never starts a terminal: without a valid terminal buffer it returns false. With focus = true it calls M.open() after a successful send, which can show a hidden terminal. It refuses the none and external providers, because they have no buffer. It turns CRLF and CR into LF and wraps multi-line text in bracketed-paste markers. It returns false when the buffer has no job channel or chansend fails [terminal.lua:M.send_to_terminal]
  • utils.parse_command does no globbing or variable expansion, so model aliases such as opus[1m] stay intact [utils.lua:M.parse_command]

@-mentions and selection

  • Line numbers sent to Claude are 0-indexed. :ClaudeCodeAdd converts the 1-indexed input [init.lua:M._create_commands]
  • A mention sent while disconnected goes to the queue with the same absolute path as a connected send, and the terminal opens. A connected send goes to the queue too, unless broadcast debouncing is off, the queue is empty, and some connected client completed its handshake connection_wait_delay ms ago [init.lua:M._broadcast_at_mention]
  • The queue sends each mention once, oldest first: 50 ms after a send, connection_wait_delay ms after a client completed its handshake, and 25 ms apart. A mention goes out only once some connected client completed its handshake connection_wait_delay ms ago, so another client's handshake does not postpone it [init.lua:ms_until_a_client_is_ready]. The broadcast then reaches every connected client, also one that connected later and is still in its own wait. A mention leaves the queue only when a connected client took it. When the write of that frame then fails on every client, the error "Claude's connection failed while the @ mention was sent" appears, and the mention is not sent again. Each mention has a deadline, connection_timeout + connection_wait_delay ms after its send, and no handshake or disconnect moves it. At its deadline, a mention still in the queue is cleared with the error "Connection timeout - clearing N queued @ mentions", or with "Send timeout - clearing N queued @ mentions that the connected Claude did not take in time" while a client that is not ready yet is connected [init.lua:expire_mentions]. While a ready client is connected, no deadline clears a mention: the queue drains to it, 25 ms apart. When that client leaves, the next flush clears the mentions whose deadline passed meanwhile [init.lua:flush_mention_queue]. A client that completes its handshake less than connection_timeout ms after the send, and stays connected, is ready before the deadline and gets every queued mention. queue_timeout is accepted but unused [init.lua:schedule_mention_flush]
  • M.stop clears the queue and stops its timers. A queue timer's callback does nothing once its timer was stopped or replaced, so nothing queued before a stop reaches Claude [init.lua:start_timer]
  • A mention sent while disconnected is formatted before it is queued, as a connected send is, so it carries the absolute path and a later :cd does not change the file it names. A directory mention loses its line numbers. When _format_path_for_at_mention raises, send_at_mention returns false and the error, queues nothing, and opens no terminal. A mention sent while disconnected fires no ClaudeCodeSendComplete [init.lua:M.send_at_mention] [init.lua:queue_mention]
  • A connected send that succeeds calls terminal.open() when focus_after_send is set, else terminal.ensure_visible(), then fires ClaudeCodeSendComplete with the formatted path. Success means the mention was accepted, not delivered [init.lua:M.send_at_mention]
  • Broadcast debouncing is off when disable_broadcast_debouncing is set, or when busted is loaded and enable_broadcast_debouncing_in_tests is not set [init.lua:M._broadcast_at_mention]
  • _format_path_for_at_mention raises on an empty path. When busted is not loaded, it also raises on a path that is neither readable nor a directory. It returns the absolute path from fnamemodify(path, ":p") and cuts no cwd prefix, so with cwd /a/proj the path /a/proj2/x stays /a/proj2/x. It resolves a relative path against the cwd at the call. It puts ./ before a path that starts with ~, so ~foo names a file in the cwd, not a home directory. A directory, the cwd included, ends in a path separator (/ outside Windows). Outside Windows it asserts that the result starts with / [init.lua:M._format_path_for_at_mention]
  • Selection tracking is a no-op unless it is enabled. Updates are debounced by 100 ms, except that leaving visual mode, editing or consuming the held text and moving the cursor away from a held selection report at once [selection.lua:M.flush_visual_selection] [selection.lua:reconcile_held_selection]. The held text can also change while you are in the Claude terminal (a reload, a plugin's edit), where TextChanged does not fire for its buffer: a listener from nvim_buf_attach on that buffer sends the file's cursor then [selection.lua:watch_selection_buffer]. Entering another file waits for the debounce. Claude terminal buffers are skipped [selection.lua:M.update_selection]
  • Tracking listens to CursorMoved, CursorMovedI, BufEnter, ModeChanged, TextChanged, TextChangedI, and TextChangedP [selection.lua:M._create_autocommands]
  • After Visual mode ends, the visual selection stays the latest selection until the cursor leaves the position it had at the exit, the held text changes, or a buffer other than the Claude terminal is entered. The cursor position then replaces it, at once for a cursor move or a text change, and after the 100 ms debounce for another buffer. A move to the Claude terminal keeps the visual selection [selection.lua:reconcile_held_selection] [selection.lua:M.update_selection]
  • The automatic paths send selection_changed only when the selection differs from the last one sent [selection.lua:M.update_selection] [selection.lua:M.flush_visual_selection]. send_current_selection sends with no change check. It runs update_selection first, so a changed selection goes out twice [selection.lua:M.send_current_selection]
  • has_selection_changed compares only filePath, text, and the start and end positions [selection.lua:M.has_selection_changed]
  • Select mode (gh, or v, V and CTRL-V when 'selectmode' contains cmd) is tracked like Visual mode [selection.lua:is_visual_mode], and a command such as a <cmd>ClaudeCodeSend<CR> mapping takes the visual path there [visual_commands.lua:M.create_visual_command_wrapper]. The visual path ends Select mode. For a mapping made with mode = "v" (:vmap), Neovim queues a key that restores Select mode after the mapping, and the visual path cancels it with gV [visual_commands.lua:M.exit_visual_and_schedule]
  • A visual selection is flushed on visual exit. The flush is skipped when an operator (d, c, >, gU...) changed the buffer's text in visual mode, because the marks then point at text you never selected. A plugin's edit in visual mode and a :write do not skip it, although both move the changedtick: Neovim ends visual mode before an operator edits, a plugin's edit runs in visual mode, and a :write fires no buffer callback. A reload counts as an operator. Neovim 0.8 and 0.9 end visual mode for the length of an nvim_buf_set_lines or nvim_buf_set_text call, so the on_lines callback only counts the edit and a check reads the mode after the call: in vim.schedule, or in a vim.on_key listener at the next key when a mapping runs that key first (<Cmd>lua edit()<CR><Esc>), whichever comes first. The flush skips a selection with an edit that is not checked yet, which is what an operator leaves, because its flush comes first [selection.lua:M.flush_visual_selection] [selection.lua:note_visual_edit] [selection.lua:check_visual_edits]
  • selection_changed positions are 0-based lines and 0-based UTF-8 byte offsets into the buffer line, not VS Code's UTF-16 code units. end is exclusive. A position inside a multibyte code point, such as a stale mark after an edit and gv, moves back to the code point's first byte [selection.lua:code_point_start]. A charwise or blockwise selection ends after the character that starts at its end position. That character is what y takes as one (vim.fn.byteidx): it includes its composing characters, and on Neovim 0.11+ the rest of its grapheme cluster. On Neovim 0.11+ a control, such as a TAB, U+0085 or U+200B, is a character of its own, without the composing characters after it. So is an invalid byte on every version, although before 0.11 the cursor can skip the composing characters after it. With 'selection' set to exclusive, a selection of more than one position ends after the character before that position instead. Before 0.11, with 'selection' set to exclusive, y can leave out composing characters that follow an invalid byte before that position, and the selection keeps them [selection.lua:selection_end_byte]
  • A charwise selection that includes a line break (v$) ends at the start of the next line, and its text ends with that line break, as Neovim yanks it. On the buffer's last line, for a blockwise selection, and with 'virtualedit' containing all (where the end is a virtual space), the end stays at the end of the line. On an empty line, and for a block whose last row is empty, that end is character 1, because Claude Code counts an end at character 0 as the line before. With all, the text has none of the virtual spaces that Neovim's y adds. A blockwise selection sends the contiguous span between its first and last positions, not the rectangle [selection.lua:end_past_line]
  • A linewise selection ends on its last line at that line's byte length. When that line is empty and another line follows, it ends at the start of the next line, and its text ends with the empty line's line break, because Claude Code counts an end at character 0 as the line before. An empty last line of the buffer ends at character 1 [selection.lua:extract_linewise_text]
  • A mention sent without a range from a tracked selection that ends at character 0 of a line ends on the line before [selection.lua:M.send_at_mention_for_visual_selection]
  • send_at_mention_for_visual_selection needs tracking enabled, a running server, a non-empty selection, and a selection in the current buffer. Otherwise it logs and returns false [selection.lua:M.send_at_mention_for_visual_selection]
  • get_range_selection(line1, line2) does not follow the linewise end rules above. Its end is the byte length of the last line, so an empty last line ends at character 0, and its text is not repaired with valid_utf8 [selection.lua:M.get_range_selection]
  • Selection text sent to Claude is always valid UTF-8. Each invalid byte sequence in the buffer becomes U+FFFD, so the text can be longer than the byte range of its positions [utils.lua:M.valid_utf8]

Diffs

  • open_diff_blocking must run inside a non-main coroutine. Otherwise it raises -32000 [diff.lua:M.open_diff_blocking]
  • open_diff_blocking makes old_file_path absolute against the cwd at the call, so a later :cd does not change the file a diff points at [diff.lua:M.open_diff_blocking]
  • A diff whose status is saved and whose client_id is set and differs from the caller's holds edits for another Claude client. open_diff_blocking then refuses the tab name with -32000 "Diff tab in use", and close_diff_by_tab_name with a client_id keeps that diff and returns false [diff.lua:holds_edits_for_other_client] [diff.lua:M.close_diff_by_tab_name]
  • A diff opens in a new tab when diff_opts.open_in_new_tab is set, or when the current tab or the tab of the window it would use already has a diff window. close_tab then goes back to the tab the user was in. Otherwise it starts from a window that shows the old file or from the main editor window, neither of which is a diff window, the preview window, or a floating window. The main editor window also never shows a terminal or prompt buffer, or a buffer whose filetype is neo-tree, neo-tree-popup, NvimTree, oil, minifiles, netrw, aerial, tagbar, snacks_picker_list, or snacks_layout_box. Other sidebars count as editor windows. When neither exists, it splits the current window [diff.lua:M._setup_blocking_diff] [diff.lua:find_main_editor_window]
  • The current tab comes first, as VS Code opens a diff in the active editor group: the current tab's window that shows the old file, then the current tab's main editor window, then the same two in the other tabs. A unified diff skips the window that shows the old file and opens next to the main editor window, current tab first. It is not a Neovim diff, so a user's diff in the current tab does not give it a new tab. Only when the current tab has neither does the diff go to another tab, and Neovim then switches to that tab. For example, with only the preview window in the current tab and the Claude terminal next to an empty window in another tab, the diff opens in that other tab. A vertical or horizontal diff of an existing file that starts from a window with an empty, unnamed buffer opens the file there, and that window keeps showing the file after close_tab [diff.lua:windows_current_tab_first] [diff.lua:choose_original_window]
  • A diff in a new tab shows the Claude terminal in a split of that tab, then puts the cursor in the proposal, in Normal mode. The terminal buffer goes into the split with utils.win_set_buf_in_split and BufEnter in 'eventignore', so an auto-insert handler of that buffer, such as the Snacks auto_insert autocmd or the diff's own BufEnter handler from an earlier diff, cannot queue a startinsert that would start in the proposal. Entering that terminal window later still starts terminal mode, because with terminal.auto_insert on the diff gives the terminal buffer a BufEnter handler for it. A WinClosed autocmd for that window deletes the handler when that window closes. That happens when close_tab or the user closes the diff tab, and also when the user closes that split alone (:q) while the diff is still open. Until then the handler stays, even if that window now shows another buffer, and it starts terminal mode on every entry of the terminal buffer, in any window. After the window closes, a later entry of the terminal buffer, such as a restored float, queues no insert. When a BufLeave autocmd of the user's closes that split while the terminal is put into it, the new tab has no terminal, and the diff is still built in the new tab: the code enters the new tab again when the autocmd entered a window in another tab and the new tab still exists. Closing the diff closes its tab from the tab the user was in, without entering it first (utils.close_tabpage_without_entering). Entering it runs the BufEnter handlers of the buffer in its current window. When that window shows the terminal (the user focused it, then left it with <C-\><C-N> or went to another tab), a handler queues a startinsert, and the insert would start in the user's file once the tab is gone. Events at close depend on where the user is. With the user in the original tab, the tab the diff was opened from, closing the diff fires WinClosed, BufWinLeave, BufHidden and TabClosed, and no BufLeave, WinLeave, TabLeave, BufEnter, WinEnter or TabEnter. With the user in the diff tab or in a third tab, close_tab goes back to the original tab first, as before: it fires BufLeave, WinLeave and TabLeave for the window the user is in, then WinEnter, TabEnter and BufEnter for the original tab's window, so a BufLeave autocmd on the user's file in the third tab runs. When the original tab no longer exists, close_tab goes to no tab first: a user in a third tab stays there, and a user in the diff tab goes to the neighbouring tab as :tabclose does, which fires TabLeave and TabEnter. When the close leaves no window that shows the Claude terminal (the user hid it in the original tab, or the original tab is gone), the close shows it again (terminal.ensure_visible), which fires WinLeave, WinEnter, BufLeave and BufEnter for the user's window and enter and leave events for the terminal, as when the user opens the terminal, so a BufLeave autocmd, such as an autosave, can run then. When :tabclose cannot close the diff tab, because it is the last tab page (E784) or because 'nohidden' and a modified buffer of the user's in that tab stop it (E37), the tab stays. The cleanup then drops the terminal's BufEnter handler, and runs the rest with every autocmd blocked (:noautocmd, utils.without_autocmds): it gives the proposal window of a unified diff an empty buffer, turns diff mode off in the windows of that tab that show the file, moves a cursor that was in a window of the diff to the window the diff stored for the file (the proposal window, with its empty buffer, in a unified diff), and closes the proposal window of a split diff and the terminal window the diff added, unless that is the only window that shows the Claude terminal and the cleanup shows the terminal again afterwards. The window the diff stored for the file can show a file of the user's own by then, and nothing in it changes. No autocmd of the user's can run while a window of the diff is still open, so none can switch one to a file of their own, enter the terminal, or close the tab. Then, if the cursor ended in another window, it fires WinEnter and BufEnter for that window, and if only its buffer changed (the empty buffer under a cursor that stayed in the proposal window of a unified diff), BufEnter alone. It fires no leave event, no BufNew, BufAdd, BufWinLeave, BufHidden, WinClosed or OptionSet event for these steps, and with the cursor in a window of the user's own it fires no event at all. The diff's terminal window and proposal window are only touched while they still show the buffer the diff put there: a window the user switched to a file of their own stays as it is, with the cursor in it too, and the terminal's handler goes either way. When :tabclose leaves the diff's terminal window open, a terminal that was visible before the diff and that no other window shows, a float parked with hide aside, stays in that window. Closing it would make terminal.ensure_visible open another window, which fires the events of a new terminal window (an autocmd BufEnter term://* startinsert of the user's then starts an insert in their file). :tabclose closes the windows of the tab one after the other and stops at the one it cannot close (E37), so a terminal window that it reaches before that one is already closed, as on main, and the provider shows the terminal again. diff_opts.keep_terminal_focus = true still moves the cursor to the terminal [diff.lua:display_terminal_in_new_tab] [utils.lua:M.win_set_buf_in_split] [diff.lua:M._cleanup_diff_state] [diff.lua:release_surviving_diff_tab] [diff_inline.lua:M.cleanup_inline_diff] [utils.lua:M.close_tabpage_without_entering] [utils.lua:M.without_autocmds]
  • When it does not open a new tab, a unified diff opens in a new split right of the main editor window. With no main editor window anywhere, it first splits the current window into an empty scratch window, so the diff adds two windows, and cleanup closes both. In a new tab, it reuses the empty window that :tabnew made while that window is untouched, so the tab holds no blank pane. It splits beside that window when a TabNew handler filled it or when the tab holds only the terminal [diff_inline.lua:M.setup_inline_diff] [diff_inline.lua:create_fallback_editor_window] [diff_inline.lua:shows_untouched_tabnew_buffer]
  • A unified diff needs vim.text.diff or vim.diff and raises -32000 without one. Neovim 0.8.0 has vim.diff, so the layout runs on every Neovim the plugin supports. Its proposal buffer, <tab_name> (unified diff), has 'modifiable' off, and accepting sends the proposal lines that setup computed, not the buffer's text. [diff_inline.lua:M.setup_inline_diff] [diff_inline.lua:M.resolve_inline_as_saved]
  • A new diff with an existing tab name first rejects the old diff (if pending), then cleans it up. This runs before the coroutine check, so a call outside a coroutine still removes the old diff. A ClaudeCodeDiffClosed handler that runs the event loop during that cleanup lets a queued openDiff register a diff for the same tab name. The replace step repeats until no diff is registered for the tab name, so that diff is rejected and answered too if it is pending [diff.lua:M.open_diff_blocking]
  • Every active_diffs entry gets an open_order from _register_diff_state. The bulk closes sort by it [diff.lua:M._register_diff_state] [diff.lua:close_active_diffs]
  • The native proposal buffer is an unlisted acwrite scratch buffer named <tab_name> (proposed), or <tab_name> (NEW FILE - proposed). A new file's original side is a read-only nofile placeholder named <old_file_path> (NEW FILE). The proposal buffer carries b:claudecode_diff_tab_name, which :ClaudeCodeDiffAccept and :ClaudeCodeDiffDeny read [diff.lua:M._setup_blocking_diff] [diff.lua:load_original_buffer] [diff.lua:M.accept_current_diff]
  • A diff that resolves before open_diff_blocking yields, for example from a ClaudeCodeDiffOpened handler that runs :ClaudeCodeDiffDeny, is returned at once as the openDiff reply instead of a deferred one [diff.lua:M.open_diff_blocking]
  • A diff never splits the preview window while the Claude terminal is a tiled window in the same tab. It splits the terminal's window instead, because the preview window keeps its 'previewheight' lines when it is split, and a vertical split gives the new window that height too. A vertical or unified diff then opens right of the terminal, so with the preview window left of the terminal, the terminal sits between the preview window and the diff. A horizontal diff opens below the terminal. With a floating or hidden Claude terminal, a diff in a tab with only the preview window splits the preview window. The legacy open_diff never opens the old file in the preview window either [diff.lua:leave_preview_window] [diff_inline.lua:create_fallback_editor_window] [diff.lua:M._open_native_diff]
  • A unified diff keeps the Claude terminal's width, with two exceptions: the terminal in a new tab, and a terminal whose window it splits (the old width includes the columns the diff took). It sizes those as the other layouts do: terminal.diff_split_width_percentage of the columns, else split_width_percentage, and not at all with diff_opts.auto_resize_terminal = false [diff_inline.lua:M.setup_inline_diff] [diff.lua:resize_terminal_for_diff]
  • A width percentage counts only when it is a number between 0 and 1, both excluded. An invalid diff_split_width_percentage falls back to split_width_percentage, and an invalid split_width_percentage to 0.30. A floating terminal is never resized [diff.lua:resolve_split_width_percentage] [diff.lua:resize_terminal_for_diff]
  • Closing a diff gives the windows of the tab it split back the sizes they had before the diff, because the diff's wincmd = and the closing of its windows resize them. When two diffs split one tab, the sizes are those from before the first, and the last diff to close gives them back. Nothing is resized when the tab's window layout, or the space its windows fill (screen size, tab line), changed during the diff [diff.lua:restore_window_sizes]
  • The restored sizes include a Claude terminal in that tab, so a width the user gave it stays. A diff never resizes a Claude terminal outside its own tab, so that one keeps its width too. Only when the sizes cannot come back does a vertical or horizontal diff set the Claude terminal, in any tab, to split_width_percentage of the columns, and not at all with diff_opts.auto_resize_terminal = false. A diff in its own tab sets no width when it closes: its terminal window closes with its tab, and a Claude terminal the close has to show again opens at split_width_percentage [diff.lua:M._cleanup_diff_state]. A unified diff differs: its cleanup sets the Claude terminal back to the width it had before setup, also after it shows the terminal again for a diff in its own tab, and it does not check auto_resize_terminal [diff_inline.lua:M.cleanup_inline_diff]
  • Without diff_opts.keep_terminal_focus, a diff that opens in the tab of a floating Claude terminal hides the float, because a float cannot make room for a diff and would cover it. This is true for both layouts. The diff decides from the windows at that moment: it calls hide_float(tab) with the diff's tab when any window of the terminal in the diff's tab is a float, hidden or not, and it keeps no state. Of the built-in providers, only snacks hides a float, through hide_float, and it hides the float it tracks only when that float is visible and in that tab. A custom provider can implement it, and one that ignores tab hides its float in any tab. With snacks, a float in another tab, a float the user hid, and a terminal that is a split are left alone. A float of the terminal in the diff's tab that the provider does not track stays, and it covers the diff. Nothing shows the float again when the diff closes: the user brings it back with :ClaudeCodeFocus. The one exception is a diff in its own tab: when it closes, it calls ensure_visible if a window of the terminal was visible in any tab when it opened (had_terminal_in_original, set at open from find_claudecode_terminal_window, so a terminal split in another diff's new tab counts), and the call shows the terminal when none is visible then (a provider's own ensure_visible decides, when it has one). It does not check for other open diffs, so it can show the float over a diff that is still open: diff A hides the float, diff B opens in a new tab, diff C opens in another new tab while B's tab shows the terminal, and the close of C after the close of B shows the float over A. The same call shows a float that the user or another diff hid while this diff was open. A diff that opens in the tab hides the float again when the user brought it back, but a split diff does not open in a tab that already shows a diff: it opens in a new tab and leaves the float alone. The cursor restore on close never goes back into a window hidden with hide, so with a float that a diff hid, the cursor goes to the window it was in when the first diff opened, or stays where Neovim put it. find_claudecode_terminal_window skips a window hidden with hide, so with a hidden float keep_terminal_focus leaves the cursor in the diff, and a diff in its own tab shows nothing on close when no window of the terminal was visible in any tab when it opened [diff.lua:hide_terminal_float_for_diff] [diff.lua:M._cleanup_diff_state] [diff_inline.lua:M.cleanup_inline_diff] [diff.lua:find_claudecode_terminal_window] [diff.lua:restore_cursor] [terminal/snacks.lua:M.hide_float]
  • When closing a diff closes the window the cursor is in, the cursor goes back to the window it was in when the diff opened, in another tab too. A cursor the user moved to another window during the diff stays there. A diff in its own tab goes back to the tab the user was in instead. With diff_opts.keep_terminal_focus = true the cursor is in the Claude terminal during the diff, so it stays there. When no Claude terminal is shown, the cursor stays in the diff, so it goes back to the window it was in, as without the option [diff.lua:restore_cursor]
  • When the target buffer is dirty, diff setup raises -32000 with message "Diff setup failed". Its data holds the inner error, which contains "Cannot create diff: file has unsaved changes" [diff.lua:M._setup_blocking_diff]
  • A diff resolves only from status pending. Save returns FILE_SAVED and the content. In the unified layout the content is the proposal's lines with a final line break exactly when the proposal ends with one, so every blank line at its end stays. Reject returns DIFF_REJECTED and the tab name [diff.lua:M._resolve_diff_as_saved] [diff_inline.lua:M.resolve_inline_as_saved]
  • A write of the proposal buffer (:w, :wq, :x, ZZ, which run BufWriteCmd) never writes the file. It accepts a pending diff and does nothing else. :w leaves the windows open until close_tab, and :wq, :x and ZZ also close the proposal window. A write after the diff has its answer sends nothing and does not fail (the handler never returns true, which would delete the autocmd and make the next :w fail with E676). It warns when the buffer holds edits that Claude never gets [diff.lua:M._write_proposal]
  • In the vertical and horizontal layouts the saved content is the lines of the proposal buffer, joined with the line break of the buffer's 'fileformat' (LF, CRLF for dos, CR for mac), plus a final line break only when the buffer's 'eol' is on and the buffer has a line. When 'fileformats' includes dos, a proposal that has a line break and only CRLF line breaks gets 'fileformat' dos and lines without their CRs, as the same text read from a file does, so a line that the user types or joins is saved with CRLF, as :w writes it. Any other proposal gets 'fileformat' unix whatever the first entry of 'fileformats' is, with its CRs inside its lines, which :w writes back unchanged. The unified layout's buffer is read-only, so its text is the proposal itself. The diff sets 'eol' from the proposal when it creates the buffer, so a proposal without a final line break is saved without one, and the user's edits keep that ending. A buffer with no lines at all (an empty proposal, or a buffer the user emptied with ggdG or :%delete) is saved as an empty string, because :w writes no bytes for it whatever 'eol' says. A buffer with one empty line is saved as one line break of the buffer's 'fileformat' when 'eol' is on and as "" when it is off. The save tells the two apart with wordcount().bytes, because nvim_buf_get_lines returns one empty string for both [diff.lua:M._setup_blocking_diff] [diff.lua:M._resolve_diff_as_saved]
  • A pending diff rejects at once when its proposal buffer is shown in no window, in the split and the unified layout: its last window closes (:q, :close, <C-w>c, :tabclose), or that window switches to another buffer (:edit, :buffer, :enew, which only hide it). A copy of the proposal in another window or tab defers the reject until that copy leaves too. The switch path rejects on the next loop turn, and only when the diff is still the same one and still hidden. Both layouts keep the proposal buffer's 'bufhidden' at hide: the buffer is modified, and wipe would make :q fail with E37 [diff.lua:M._register_reject_when_hidden] [diff_inline.lua:M.setup_inline_diff]
  • A diff that has its answer, by either one, clears 'modified' on its proposal buffer. While the flag stayed set, :wq left the window open, and :qa stopped with E37 or E162 and moved a window onto the hidden buffer until close_tab deleted it [diff.lua:mark_proposal_unmodified]
  • At exit, Neovim fires BufUnload for each loaded buffer before VimLeavePre, and a proposal's BufUnload autocmd rejects its diff, but that loop stops as soon as an autocmd deletes the buffer it fired for. The reject of a new-file diff with on_new_file_reject = "keep_empty", in a tab that the diff did not open, deletes its proposal buffer, and another plugin's buffer can delete itself in its own BufUnload. The diffs after either get no BufUnload (probed on Neovim 0.8.0, 0.9.5, 0.10.4, 0.11.5 and 0.12.3). SIGTERM and SIGHUP run VimLeavePre without that loop. A quit from inside an autocmd that is not nested, :noautocmd qa!, a Lua os.exit(), SIGKILL and a crash run no VimLeavePre, and a quit or a signal that Neovim handles while such an autocmd is still running can skip it too (for example one that waits in vim.wait). The VimLeavePre autocmd of ClaudeCodeMCPDiff therefore runs cleanup_at_exit, which first rejects each diff with the status pending, oldest first, each under pcall, and skips a diff with another status. A reject can remove its own diff (the keep_empty case above), so a diff can be gone before the next one is rejected. The reject of a diff whose openDiff setup has not finished stays in setup_result, because the call has no response sender yet, so the server's stop sends that call's response. The README at the repository root, under Global Invariants, lists what Claude receives for each kind of call [diff.lua:cleanup_at_exit] [diff.lua:M.open_diff_blocking] [server/init.lua:M.stop]
  • The cleanup of a diff closes the proposal window, and the window that the split layout opened for the file's old text, only while each still shows its buffer. A window that the user switched to another buffer stays with that buffer. Neovim saves a window's options, 'diff' included, for each buffer that leaves it, and sets them again when that buffer enters the window. The plugin splits the window before it runs :diffthis, so the proposal window saves no diff mode for the file, and :edit <file> back in that window leaves diff mode off. The original-side window does save it when the user leaves the file there (:edit third.txt), so :edit #, or :edit <file>, back there turns diff mode on again, after the diff has ended. A window that never showed the buffer can take diff mode on in two ways. It can copy the current options of a window that shows the buffer: :split <file> copies the window that it splits, while a window in a new tab page, from :tabnew <file>, from :tabnew and :buffer <file>, or from :tab sbuffer, gets no diff mode from the windows of the diff. Or it can take a set that another window saved when the buffer left it: while no window shows the buffer, a set with diff mode on reaches a window of the same tab page, and does not reach a window of another tab page or a window that closed. The split layout's cleanup does one thing about that. After it closes its windows and deletes its buffers, and before it fires ClaudeCodeDiffClosed, it runs :diffoff in a kept window that shows the file's own buffer, and in each other window of the original side's tab page that shows the file and is the only window of that tab page with 'diff' on, so nothing that a handler of that event starts is looked at. A diff needs a partner window, so the plugin takes a window that is the only one with 'diff' on in its tab page for the leftover of the ended diff, and a diff of the user's own over two or more windows stays. The 'diff' check leaves an option that the user set after turning diff mode off. :diffoff also puts back the options that diff mode set ('scrollbind', 'cursorbind', 'foldmethod', 'foldcolumn', 'wrap'). The cleanup runs only while Neovim allows window changes, so it never meets the E11 and E565 refusals of :diffoff in the command-line window and under textlock: it waits for the window gate and runs afterwards [diff.lua:M._cleanup_diff_state] [diff.lua:end_diff_mode_in_windows_that_show_the_file]. The cleanup looks only at the tab page of the original side and only once, so a file that comes back later gets the options that Neovim saved or copies, diff mode included, as on main. That covers :edit # or :edit <file> in the original-side window that left the file, a new window for it such as :split <file>, and a ClaudeCodeDiffClosed handler that brings the file back into a window. One limit comes from Neovim: the default closeoff in 'diffopt' turns diff mode off in the last window that has it when another diff window closes. That ends a user's diff mode in a kept original-side window when the proposal window closes, and in a kept proposal window when the cleanup closes the window that the plugin opened for the file. It also ends it in a window that the diff never used, when the user joined that window to the diff with :diffthis and it is the last diff window left after the cleanup closes the plugin's window for the file. A user's diff mode over two or more windows stays. The unified layout needs no cleanup there: it sets 'signcolumn' to yes with local scope, for the proposal buffer only, so once the user switches the window, 'signcolumn' is what Neovim gives the new buffer in that window: the value of a window that shows or showed that buffer, a :setlocal value of the editor window included, or, for a buffer that no window showed, the window default (what :set gives, which a new split copies from the window it splits). The window keeps a value that the user sets afterwards. Two cases still close the window: a diff in its own tab (open_in_new_tab, or a tab that already has a diff) closes the whole tab, and the fallback window that the plugin opens in a tab that holds only the Claude terminal always closes [diff.lua:M._close_proposal_window] [diff.lua:M._cleanup_diff_state] [diff_inline.lua:M.cleanup_inline_diff] [diff_inline.lua:M.setup_inline_diff]
  • Rejecting a new-file diff that is not in its own tab cleans it up at once when diff_opts.on_new_file_reject is "keep_empty" (the default), before close_tab. A unified diff gets no such cleanup [diff.lua:M._resolve_diff_as_rejected] [diff_inline.lua:M.resolve_inline_as_rejected]
  • BufDelete, BufUnload, and BufWipeout on the proposal buffer reject a pending diff. WinClosed rejects it only when no other window in any tab shows the proposal buffer. The original file's buffer is not watched. The unified layout registers the same autocmds [diff.lua:register_diff_autocmds] [diff_inline.lua:M.setup_inline_diff]
  • close_pending_diffs and close_diffs_for_client close only pending diffs. close_rejected_diffs closes only rejected diffs. close_all_diffs closes every diff, except a saved diff that another client owns when it gets a client_id. Of the bulk closes, only close_all_diffs passes a client_id to close_diff_by_tab_name. The other bulk closes do not, so the owner check never keeps one of their diffs [diff.lua:M.close_pending_diffs] [diff.lua:M.close_all_diffs] [diff.lua:close_active_diffs]
  • A bulk close lists its diffs first, and each close fires ClaudeCodeDiffClosed. Before each close it reads the entry again: a diff a handler accepted since the list was made stays open when the close selects by status, and one a handler rejected closes as listed. close_all_diffs selects no status, so it also closes a diff accepted in the meantime. It closes the newest diff first, not in pairs() order, so when each close puts the cursor back, the cursor ends where it was before the oldest of them opened. :ClaudeCodeCloseAllDiffs runs three bulk closes, for pending, then rejected, then accepted diffs, so it closes newest first only within each status. With diffs of more than one status, the cursor can end in another window [diff.lua:close_active_diffs]
  • While Neovim refuses window changes (the command-line window q: raises E11, and text lock raises E565, for example inside an <expr> mapping that lets the event loop run), _cleanup_diff_state hands the teardown to utils.when_windows_allowed: it runs at once when the gate allows window changes, and else the diff stays registered until the gate's 50 ms timer sees that Neovim allows them. One timer serves every held function. The teardown runs only while active_diffs still holds that entry, so a diff that took the tab name keeps its windows. The answer to each waiting call goes out before the teardown, so a bulk close, close_tab, closeAllDiffTabs and the server stop answer every call at once, and ClaudeCodeDiffClosed fires when the diff closes, not when the cleanup was first asked for. A replacing openDiff in those states holds the old diff the same way, and the new call fails with an error answer before it sets anything up, so it leaves no window or buffer behind [diff.lua:M._cleanup_diff_state]
  • :ClaudeCodeCloseAllDiffs runs close_pending_diffs, close_rejected_diffs, then close_saved_diffs [init.lua:M._create_commands]
  • close_saved_diffs closes a saved diff only once its file or the file's buffer holds the accepted text. When the file does not hold it, and the file's buffer has no unsaved changes and an empty 'buftype', it first loads the file into its buffer and sets the accepted lines there, unsaved. It never writes the file. The lines follow the buffer's format: in a dos buffer it drops a CR before each line break, so :w writes every line break as CRLF, LF-only lines of the proposal included. In a 'bomb' buffer it drops a leading BOM. A text without a final line break turns 'fixeol' off until the buffer's next write or read. Once the lines are set, it makes the buffer listed and durable: a 'bufhidden' of wipe, delete, or unload becomes hide. When loading the file or setting the lines fails, it wipes a buffer it created, or unloads one it loaded. It checks the unsaved changes and 'buftype' after it loads the buffer, so a buffer it then refuses stays loaded. It returns the count, each file whose buffer got the text with the command that writes it (:w, :checktime, then :w! for a 'readonly' buffer (the ! also skips the changed-since-reading check, so :checktime runs first), or when the file's folder does not exist :w ++p, which Neovim 0.8 lacks, so there :call mkdir(expand('%:p:h'), 'p') | w) and a 'fileencoding' that cannot hold the text, and each saved diff it kept with the reason (for E325, the next step: open the file with :split <file>, answering the swap file prompt if Neovim shows one) [diff.lua:M.close_saved_diffs]
  • active_diffs is module state. A reload that clears package.loaded["claudecode.diff"] forgets the open diffs, and the new module's ClaudeCodeMCPDiff augroup (created with clear = true) deletes their autocmds. Their windows and proposal buffers stay, so an accepted diff's text is then only in its proposal buffer [diff.lua:get_autocmd_group]

Side Effects

  • :ClaudeCodeCloseAllDiffs can load an accepted diff's file into a listed buffer and replace its lines with the accepted text, leaving the buffer modified. For a text without a final line break it adds a buffer-local BufWritePost/BufReadPost autocmd that restores 'fixeol' once [diff.lua:M.close_saved_diffs]
  • start binds a 127.0.0.1 TCP port and writes the lock file. It enables selection tracking only when track_selection is true. stop removes the lock file, or logs a warning when it cannot, and stops the server [init.lua:M.start]
  • lockfile.create creates the lock directory with mode 0700. It then tries to chmod an existing directory to 0700 through pcall and ignores the result, so on platforms without fs_chmod the old mode stays. It writes a temp file opened wx with mode 0600, then renames it to <port>.lock [lockfile.lua:M.create]
  • The terminal env gets ENABLE_IDE_INTEGRATION=true, FORCE_CODE_TERMINAL=true, CLAUDE_CODE_SSE_PORT=<port> only while the server runs, then the user env (merged after these, so it can override them), then no_proxy/NO_PROXY. The last step merges the shell's and the user's no_proxy and NO_PROXY values, so a user value is merged, not used as it is [terminal.lua:get_claude_command_and_env] [terminal.lua:no_proxy_with_loopback]
  • terminal.setup can replace the global vim.paste through paste_fix.apply [terminal.lua:M.setup]
  • The plugin broadcasts at_mentioned (filePath, lineStart, lineEnd) [init.lua:M._broadcast_at_mention] and selection_changed [selection.lua:M.send_selection_update] to every connected client
  • While Claude holds a visual selection, and while you select in a buffer (from entering visual mode until the flush), selection.lua attaches an nvim_buf_attach listener (on_lines, on_reload, on_detach) to that buffer, once per buffer. It does not attach to the Claude terminal buffer, whose output is a stream of edits. It detaches itself at the next on_lines after Claude holds no selection of that buffer and you do not select in it, and a reload with :edit or :edit! detaches it, so it attaches again when the buffer still holds the selection [selection.lua:watch_selection_buffer]
  • init.lua feeds <Esc> after a successful :ClaudeCodeSend that does not take the visual path, outside a tree buffer. It also feeds <Esc> when :ClaudeCode or :ClaudeCodeFocus runs in Visual mode [init.lua:M._create_commands]
  • Augroups: ClaudeCodeShutdown, which holds the VimLeavePre autocmd that stops on exit [init.lua:M.setup], ClaudeCodeSelection [selection.lua:M._create_autocommands], ClaudeCodeMCPDiff [diff.lua:get_autocmd_group], ClaudeCodeDiffCleanup [diff.lua:M._open_native_diff], ClaudeCodeNativeAdopted [terminal/native.lua:adopt_existing_terminal], ClaudeCodeOpenFileNewFiles [tools/open_file.lua:new_file_buffers], snacks_win_<id>, one per Snacks terminal whose split the plugin re-creates [terminal/snacks.lua:register_window_events], and a module-level VimLeavePre autocmd in diff.lua whose callback rejects each pending diff and then calls M._cleanup_all_active_diffs("shutdown") [diff.lua:cleanup_at_exit]
  • Each diff that opens in a new tab adds a buffer-local BufEnter autocmd (startinsert) to the Claude terminal buffer in ClaudeCodeMCPDiff, unless terminal.auto_insert is false, diff_opts.hide_terminal_in_new_tab is true, or no valid Claude terminal buffer exists. A WinClosed autocmd deletes it when the terminal window it was made for closes [diff.lua:display_terminal_in_new_tab]
  • Diffs create scratch buffers, splits, and tabs. They resize the terminal window and fire User events. Cleanup closes these and reloads unchanged file buffers 100 ms after a save [diff.lua:M.close_diff_by_tab_name]
  • When a blocking diff resolves, open_diff_blocking sends the reply through the global _G.claude_deferred_responses[tostring(co)], then sets that entry to nil. Without an entry, it logs an error [diff.lua:M.open_diff_blocking]
  • The native diff writes each temp file into its own session folder under stdpath("cache")/claudecode_diffs, or claudecode_diffs_fallback when it cannot create a directory in the first. The folder name includes the Neovim PID, so two running Neovim processes never share one. If both fail, open_diff returns success = false with an error that names both directories [diff.lua:create_temp_file]. A BufDelete/BufWipeout autocmd on the proposal buffer cleans up once, even when a wipe fires both events. It deletes the file and then its empty folder with vim.fn.delete, and warns once for each delete that fails. When the file delete fails, the folder is not empty, so its delete fails too and both warnings show [diff.lua:cleanup_temp_file]. _cleanup_diff_state does not [diff.lua:M._open_native_diff]
  • When a step of the legacy open_diff raises after its temp file was written (a buffer that already has the proposal's name raises E95, a swap file for the original raises E325, an autocmd errors), _open_native_diff removes the temp file and its folder, and wipes the buffer that has the temp file's name, unless a window shows that buffer or it has unsaved changes. It finds the buffer by the name or by the real path, because Neovim resolves a link in a buffer's name. It then raises the same error. It closes no window, moves no focus and turns no diff mode off, so the windows that the failed call had already split stay, as they did before, and so does a proposal buffer that a window shows, or that was already renamed to <path> (New). When a window still shows the proposal, the temp file behind it is gone, so the next :checktime prints E211 once (no text is lost). Nothing in the plugin calls this path [diff.lua:remove_failed_proposal] [diff.lua:M._open_native_diff]
  • diff_inline.lua creates the claudecode_inline_diff namespace when the module loads. It defines the four ClaudeCodeInlineDiff* highlight groups (with default = true) [diff_inline.lua:setup_highlights] and sets extmarks [diff_inline.lua:M.render_diff_buffer]
  • The plugin runs git rev-parse --show-toplevel at most once for each git root lookup [cwd.lua:M.git_root], and health.check runs <claude> --version [health.lua:check_cli]
  • logger defers each log line through vim.schedule. ERROR and WARN go to vim.notify. Other levels go to nvim_echo [logger.lua:log]. The level is INFO until setup runs. logger.setup warns at once, not deferred, when log_level is missing or invalid, and uses INFO [logger.lua:M.setup]. The plugin's setup never reaches that warning: config.apply fills in info and raises on an invalid log_level first [config.lua:M.validate]
  • one_line accepts only error, warn, and info, and asserts on any other level [logger.lua:M.one_line]
  • Below log_level debug, one_line replaces each run of whitespace with one space. A line wider than v:echospace cells drops its component tag and puts ERROR: or WARN: in place of its level tag (an info line gets none), so the level shows without colors. It drops the [ClaudeCode] name too when that would take more than half the width. Then it is cut to the width, ending in ... when v:echospace is at least 3. Below debug, only that line reaches :messages: Neovim adds a line to the message history only by showing it, and showing a line wider than the command line stops at "Press ENTER" (always before Neovim 0.11, and from 0.11 on while 'messagesopt' contains its default hit-enter), so the whole line shows only at log_level debug [logger.lua:M.one_line]
  • M.start logs the reason a server did not start through one_line, for example No free port in 10000-65535 (EADDRINUSE), because auto_start runs it while Neovim starts. That line, [ClaudeCode] [init] [ERROR] No free port in 10000-65535 (EADDRINUSE), is 68 cells wide. At 80 columns it fits with Neovim's default 'laststatus' of 2, and with 'ruler' and 'showcmd' off. With 'laststatus' set to 0, or to 1 with one window, and 'ruler' and 'showcmd' on, v:echospace is 51, and one_line shows [ClaudeCode] ERROR: No free port in 10000-65535 ... [logger.lua:fit_command_line]. M.start returns Server not started: <reason>. When the reason contains auth, the message ends with (authentication related) [init.lua:M.start]

Verification

  • Run: mise run test
  • Targeted: busted -v tests/unit/init_spec.lua, busted -v tests/unit/config_spec.lua, busted -v tests/unit/diff_spec.lua, busted -v tests/unit/diff_inline_spec.lua, busted -v tests/unit/terminal_spec.lua, busted -v tests/unit/utils_spec.lua, busted -v tests/unit/health_spec.lua, busted -v tests/unit/logger_spec.lua, busted -v tests/unit/version_spec.lua, busted -v tests/unit/at_mention_spec.lua, busted -v tests/unit/claudecode_add_command_spec.lua, busted -v tests/unit/diff_inline_new_tab_spec.lua, busted -v tests/integration/basic_spec.lua
  • Real Neovim: scripts/run_integration_tests_individually.sh runs each tests/integration/*_spec.lua file in headless Neovim with plenary.nvim, command_args_spec.lua included. It runs tests/integration/diff_window_choice_spec.lua, which busted only marks as pending