claudecode is the core package of claudecode.nvim. It makes Neovim an IDE peer for the Claude Code CLI. It does six jobs:
- It starts a localhost MCP WebSocket server (
./server/README.md). - It writes a discovery lock file that holds an auth token.
- It launches the CLI in a terminal provider (
./terminal/README.md) with env vars that point the CLI at the server. - It serves MCP tool calls (
./tools/README.md). - It streams selection and @-mention notifications to the CLI.
- 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 {} |
./server/README.md: WebSocket (RFC 6455) and JSON-RPC 2.0 MCP server. API:start(config, auth_token),stop(),send,send_response,broadcast, andget_status()../terminal/README.md: thenative,snacks,external, andnoneproviders, pluspaste_fixfor streamed pastes../tools/README.md: the MCP tool registry. It exposes 10 tools and the hiddenclose_tab.
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 whenauto_startis set [init.lua:M.setup]M.start(show_startup_notification?) -> ok, port|errandM.stop() -> ok, err?[init.lua:M.start]M.state:config,server,port,auth_token,initialized,mention_queue,mention_timer, andconnection_timer[init.lua:M.state]M.is_claude_connected(): false when the server is not running. Whenget_status().clientsis non-empty, true only when a client is in stateconnectedwithhandshake_complete, so aclosingclient does not count. When it is empty, true whenclient_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'son_opencallback calls it withtrueonce 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 forconnection_wait_delayms, and otherwise waits for that moment [init.lua:M.process_mention_queue]M.open_with_model(args),M.get_version(), andM.version, read from the first line of the repository'sVERSIONfile at load. Without a readable, well-formedVERSIONfile the version is0.0.0-unknown[init.lua:M.version]- Internal API:
M._create_commands,M._broadcast_at_mention,M._add_paths_to_claude(defaultmax_files100,batch_size10),M._format_path_for_at_mention,M._ensure_terminal_visible_if_connected, andM._maybe_warn_unfocusable_provider[init.lua:M._add_paths_to_claude]. Nothing outsidetests/callsM._add_paths_to_claudeorM._ensure_terminal_visible_if_connected. The user commands callM.send_at_mentionfor each path, with no file cap and no batches.:ClaudeCodeSenddoes it through a localadd_paths_to_claude[init.lua:M._create_commands]
- Server:
:ClaudeCodeStart,:ClaudeCodeStop, and:ClaudeCodeStatus. - Context:
:ClaudeCodeSend(range, tree-aware),:ClaudeCodeTreeAdd, and:ClaudeCodeAdd <path> [start] [end]. :ClaudeCodeAddreads Neovim's split arguments (opts.fargs), so a path with escaped spaces, such as the expansion of%for a buffer namedmy file.lua, stays one argument. It needs a running server and at most 3 arguments. Only a path that starts with%,#, or<goes throughvim.fn.expand. Other paths expand only a bare~or a leading~/, so$VARstays 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.:ClaudeCodeTreeAddrefuses without a running server. The tree handlers detect a tree buffer by filetype only, and the visual:ClaudeCodeSendhandler does not acceptsnacks_picker_list, which the normal handler accepts.- Terminal:
:ClaudeCode [args],:ClaudeCodeFocus [args],:ClaudeCodeOpen [args],:ClaudeCodeClose, and:ClaudeCodeSendText[!] <text>. These commands exist only whenclaudecode.terminalloads.:ClaudeCodeSendText!inserts the text without submitting it. - Diff:
:ClaudeCodeDiffAccept,:ClaudeCodeDiffDeny, and:ClaudeCodeCloseAllDiffs. - Model:
:ClaudeCodeSelectModel [args]. It exists even whenclaudecode.terminaldoes not load, and its choice runs:ClaudeCode --model <value> [args][init.lua:M.open_with_model]
User ClaudeCodeSendCompletewithdata = { file_path, start_line, end_line, context }[init.lua:fire_send_complete]User ClaudeCodeDiffOpenedwithdata = { 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 ClaudeCodeDiffClosedwithdata = { tab_name, file_path, reason }, for examplereplaced by new diff,diff tab closed after save,diff tab closed after reject,setup failed, orshutdown[diff.lua:M._cleanup_diff_state]fire_diff_eventruns the autocmds inpcallwithmodeline = false, so an error in a handler never reaches the diff code [diff.lua:fire_diff_event]
M.defaults,M.apply(user_config) -> config, andM.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 sixmodelsentries [config.lua:M.defaults] diff_optsdefaults:layout = "vertical",open_in_new_tab = false,keep_terminal_focus = false,hide_terminal_in_new_tab = false,on_new_file_reject = "keep_empty", andauto_resize_terminal = true[config.lua:M.defaults]
terminal.lua:setup,open,close,simple_toggle,focus_toggle,toggle,toggle_open_no_focus,ensure_visible,hide_float,get_active_terminal_bufnr, andsend_to_terminal(text, { submit = true, focus = false })[terminal.lua:M.send_to_terminal]terminal.lua:open,simple_toggle, andfocus_toggletake(opts_override, cmd_args)and call the provider method of the same name with(cmd_string, env_table, effective_config).M.togglecallsM.simple_toggle, not the provider'stoggle.toggle_open_no_focusandensure_visiblecall the provider'sensure_visiblewhen 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.luatest 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.luadefaults: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, andcwd_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:diffthisthere, 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 ornofilebuffer. 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, andreload_file_buffers_manual[diff.lua:M.open_diff_blocking]diff.luainternals thatdiff_inline.luadepends 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.luainternals exposed for testing:_resolve_split_width_percentage,_auto_resize_enabled,_tabpage_has_diff_window, and_register_diff_autocmds._setup_blocking_diffcalls_create_diff_view_from_windowthroughM, 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, andcleanup_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 handlerson_cursor_moved,on_mode_changed, andon_text_changed[selection.lua:M.enable]selection.luainternals:state,server(set byenable, cleared bydisable),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, andget_workspace_folders[lockfile.lua:M.create]lockfile.get_workspace_folders()returnsgetcwd()first, then each LSP client's workspace folder withfile://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), andsnacks_picker_list(_get_snacks_picker_selection). For any other filetype it returnsniland 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:ClaudeCodeSendhandler calls it in aminifilesbuffer [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, andget_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 returnsnilforminifilesandsnacks_picker_list[visual_commands.lua:M.get_tree_state]cwd.lua:resolve(term_cfg, ctx)andgit_root(start_dir)[cwd.lua:M.resolve]. Nothing inlua/callscwd.resolve.terminal.lua:build_confighas its own copy of the cwd order and calls onlycwd.git_root, so a change toresolvedoes 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, andresume_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, andis_level_enabled[logger.lua:M.setup]health.lua:check(). It checks, in order: Neovim 0.8.0 or later,require("claudecode"), thatsetup()ran, the CLI (the first word ofterminal_cmd, orclaude) 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 missingsetup(), or a stopped server [health.lua:M.check] [health.lua:check_cli] [health.lua:check_server]
setuprunsconfig.applybefore logger, terminal, and diff setup. The auto-start runs only afterdiff.setup, and the user commands are created after the auto-start [init.lua:M.setup]setupwrites the top-levelgit_repo_cwd,cwd, andcwd_provideroptions into the caller'sopts.terminaltable, and passes that table, notconfig.terminal, toterminal.setup. Beforesetup,M.state.configis theconfig.defaultstable itself [init.lua:M.setup] [init.lua:M.state]setupwarns whenfocus_after_send = trueand the provider isnone, orexternalwith a usableexternal_terminal_cmd, because those providers cannot take the focus [init.lua:M._maybe_warn_unfocusable_provider]startrefuses with "Already running". The auth token must be a string of length 10 or more. Ifserver.startfails,startreturns the error at once. If the lock file fails,startstops the server and clears its state [init.lua:M.start]startrequires the token returned bylockfile.createto equal the generated token. Otherwise it removes the lock file, stops the server, and clears its state. Whenlockfile.removereturns an error, it only logs that error as a warning and still returns the mismatch error [init.lua:M.start]stopreturns "Not running" without a server. Whenlockfile.removereturns an error,stoponly logs that error as a warning.lockfile.removereturns that error whenvim.loop.fs_unlinkfails, also when it fails without raising (for example in a read-only directory), so the lock file stays and the failure is logged.lockfile.removelooks for the name withvim.loop.fs_lstatand deletes it withfs_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" whenfs_lstatfinds 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]stoptries to remove the lock file and disables selection tracking whentrack_selectionis set, then stops the server. Whenserver.stopfails,stopreturns the error and keepsstate.server, although the removal and the disable already ran [init.lua:M.stop]- The auth token is 32 lowercase hex characters from
vim.loop.randomor/dev/urandom. It never comes frommath.random[lockfile.lua:get_random_bytes] - The lock directory is
$CLAUDE_CONFIG_DIR/idewhen that variable is set and not empty, else~/.claude/ide. It is resolved once when the module loads [lockfile.lua:M.lock_dir] health.checkbuilds the lock-file pathlock_dir/<port>.lockitself, so a change to the lock-file name must changehealth.luatoo [health.lua:check_server]lockfile.createrequires 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)returnsfalse, nil, errorwhen it cannot give the token. The error is "Lock file does not exist" whenvim.loop.fs_statfinds 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 whenfs_statfinds the file andio.openfails (mode 000, or a socket, for example) [lockfile.lua:M.get_auth_token]
config.validateasserts most top-level fields. It does not assertdisable_broadcast_debouncingorenable_broadcast_debouncing_in_tests. Examples:0 < port_range.min <= max <= 65535,log_levelintrace|debug|info|warn|error,envvalues are strings,modelsis a non-empty list of{ name, value }, anddiff_opts.layoutisvertical|horizontal|unified. Forterminalit asserts only that it is a table and checksprovider_opts. It does not assertterminal.provideror otherterminal.*keys [config.lua:M.validate]config.validatealso assertsvisual_demotion_delay_ms >= 0,connection_wait_delay >= 0,connection_timeout > 0,queue_timeout > 0, booleanauto_startandtrack_selection, and a nil or stringterminal_cmd. It checksfocus_after_sendand eachdiff_optskey only when set.external_terminal_cmdmust be a string or a function, and a non-empty string must contain%s.types.luaalso allows a table there, whichvalidaterejects [config.lua:M.validate] [types.lua:ClaudeCodeTerminalProviderOptions]config.applydeep-copies the defaults. It maps the legacyvertical_splitoption tolayout, and legacyopen_in_current_tabtoopen_in_new_tab. A legacy option set as a boolean overwrites the new option [config.lua:M.apply]config.luarequires no other module, soapplynever loadsclaudecode.terminal[config.lua:M.defaults]- Provider selection:
autouses snacks if available, else native.externalrequiresexternal_terminal_cmdas a function or as a string containing%s. Every other failure falls back tonative[terminal.lua:get_provider] get_providerpicks the provider again on every call. Only the provider modules are cached [terminal.lua:get_provider]. When asnacks,external,none, or custom table provider fails, each call logs a warning that it falls back tonative.terminal.setupcalls it too [terminal.lua:M.setup]terminal.setupchangesM.defaultsin place. It always setsterminal_cmdandenvfrom its own arguments and ignores aterminal_cmdkey in the terminal options. An invalidprovidervalue keeps the previous value (defaultauto), and the warning names it:Keeping 'auto', orKeeping the custom provider tablewhen the previous value is a table [terminal.lua:M.setup]terminal.setupwarns about its options throughvim.notifydirectly, not through the logger. So its warnings show at once, andlog_leveldoes not filter them. It warns on a terminal config that is not a table, an invalidterminal_cmdorenv, an invalid value for a known key, and an unknown key [terminal.lua:M.setup]- A per-call
opts_overridechanges 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-callcwdorcwd_provideris ignored unlesssetupset one. Providers get onlysplit_side,split_width_percentage,auto_close,auto_insert,snacks_win_opts, and the resolvedcwd[terminal.lua:build_config] - The Claude command is
terminal_cmd, orclaudewhen it is unset.no_proxyandNO_PROXYalways includelocalhost,127.0.0.1, and::1[terminal.lua:get_claude_command_and_env] - Terminal cwd precedence:
cwd_provider, then staticcwd, then the git root whengit_repo_cwdis set. Acwd_providerresult or a staticcwdgoes throughcwd.expand_leading, which expands only a leading~,~/,$VARor${VAR}, without a shell, so~and$VARwork 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 reachesvim.fn.expand, which runs text between backticks as a shell command, and a buffer name (aterm://orzipfile://buffer, say) can put such text inctx.file_dir[terminal.lua:build_config] [cwd.lua:M.expand_leading] cwd.git_rootandcwd.resolvetake a directory path as written: a folder name with[,{,*,?,$,\, a space or a comma stays that folder. A leading~,~/,$VARor${VAR}is expanded first byexpand_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 reachesvim.fn.expand. The terminal does not callcwd.resolve, butterminal.lua:build_configapplies the same as-written rule to a staticcwdand acwd_providerresult, so$or\past the start of the text stays. Unlikenormalize_dir, it passes text that names no folder on to the terminal instead of dropping it. Whengit rev-parsecannot run or finds no repository,git_rootwalks up fromstart_dirmade absolute with:p, with its..parts simplified, to the nearest folder that holds a.gitfolder. A relativestart_dirthat begins with~is not made absolute, because Vim reads~as the home folder and~nameas 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_terminalnever starts a terminal: without a valid terminal buffer it returnsfalse. Withfocus = trueit callsM.open()after a successful send, which can show a hidden terminal. It refuses thenoneandexternalproviders, because they have no buffer. It turns CRLF and CR into LF and wraps multi-line text in bracketed-paste markers. It returnsfalsewhen the buffer has no job channel orchansendfails [terminal.lua:M.send_to_terminal]utils.parse_commanddoes no globbing or variable expansion, so model aliases such asopus[1m]stay intact [utils.lua:M.parse_command]
- Line numbers sent to Claude are 0-indexed.
:ClaudeCodeAddconverts 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_delayms ago [init.lua:M._broadcast_at_mention] - The queue sends each mention once, oldest first: 50 ms after a send,
connection_wait_delayms after a client completed its handshake, and 25 ms apart. A mention goes out only once some connected client completed its handshakeconnection_wait_delayms 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_delayms 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 thanconnection_timeoutms after the send, and stays connected, is ready before the deadline and gets every queued mention.queue_timeoutis accepted but unused [init.lua:schedule_mention_flush] M.stopclears 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
:cddoes not change the file it names. A directory mention loses its line numbers. When_format_path_for_at_mentionraises,send_at_mentionreturnsfalseand the error, queues nothing, and opens no terminal. A mention sent while disconnected fires noClaudeCodeSendComplete[init.lua:M.send_at_mention] [init.lua:queue_mention] - A connected send that succeeds calls
terminal.open()whenfocus_after_sendis set, elseterminal.ensure_visible(), then firesClaudeCodeSendCompletewith the formatted path. Success means the mention was accepted, not delivered [init.lua:M.send_at_mention] - Broadcast debouncing is off when
disable_broadcast_debouncingis set, or when busted is loaded andenable_broadcast_debouncing_in_testsis not set [init.lua:M._broadcast_at_mention] _format_path_for_at_mentionraises 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 fromfnamemodify(path, ":p")and cuts no cwd prefix, so with cwd/a/projthe path/a/proj2/xstays/a/proj2/x. It resolves a relative path against the cwd at the call. It puts./before a path that starts with~, so~foonames 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
TextChangeddoes not fire for its buffer: a listener fromnvim_buf_attachon 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, andTextChangedP[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_changedonly when the selection differs from the last one sent [selection.lua:M.update_selection] [selection.lua:M.flush_visual_selection].send_current_selectionsends with no change check. It runsupdate_selectionfirst, so a changed selection goes out twice [selection.lua:M.send_current_selection] has_selection_changedcompares onlyfilePath,text, and the start and end positions [selection.lua:M.has_selection_changed]- Select mode (
gh, orv,Vand CTRL-V when'selectmode'containscmd) 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 withmode = "v"(:vmap), Neovim queues a key that restores Select mode after the mapping, and the visual path cancels it withgV[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:writedo 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:writefires no buffer callback. A reload counts as an operator. Neovim 0.8 and 0.9 end visual mode for the length of annvim_buf_set_linesornvim_buf_set_textcall, so theon_linescallback only counts the edit and a check reads the mode after the call: invim.schedule, or in avim.on_keylistener 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_changedpositions are 0-based lines and 0-based UTF-8 byte offsets into the buffer line, not VS Code's UTF-16 code units.endis exclusive. A position inside a multibyte code point, such as a stale mark after an edit andgv, 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 whatytakes 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 toexclusive, a selection of more than one position ends after the character before that position instead. Before 0.11, with'selection'set toexclusive,ycan 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'containingall(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 ischaracter1, because Claude Code counts an end atcharacter0 as the line before. Withall, the text has none of the virtual spaces that Neovim'syadds. 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
character0 as the line before. An empty last line of the buffer ends atcharacter1 [selection.lua:extract_linewise_text] - A mention sent without a range from a tracked selection that ends at
character0 of a line ends on the line before [selection.lua:M.send_at_mention_for_visual_selection] send_at_mention_for_visual_selectionneeds tracking enabled, a running server, a non-empty selection, and a selection in the current buffer. Otherwise it logs and returnsfalse[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 atcharacter0, and its text is not repaired withvalid_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]
open_diff_blockingmust run inside a non-main coroutine. Otherwise it raises-32000[diff.lua:M.open_diff_blocking]open_diff_blockingmakesold_file_pathabsolute against the cwd at the call, so a later:cddoes not change the file a diff points at [diff.lua:M.open_diff_blocking]- A diff whose status is
savedand whoseclient_idis set and differs from the caller's holds edits for another Claude client.open_diff_blockingthen refuses the tab name with-32000"Diff tab in use", andclose_diff_by_tab_namewith aclient_idkeeps that diff and returnsfalse[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_tabis set, or when the current tab or the tab of the window it would use already has a diff window.close_tabthen 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 aterminalorpromptbuffer, or a buffer whose filetype isneo-tree,neo-tree-popup,NvimTree,oil,minifiles,netrw,aerial,tagbar,snacks_picker_list, orsnacks_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
unifieddiff 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. Averticalorhorizontaldiff 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 afterclose_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_splitandBufEnterin'eventignore', so an auto-insert handler of that buffer, such as the Snacksauto_insertautocmd or the diff's ownBufEnterhandler from an earlier diff, cannot queue astartinsertthat would start in the proposal. Entering that terminal window later still starts terminal mode, because withterminal.auto_inserton the diff gives the terminal buffer aBufEnterhandler for it. AWinClosedautocmd for that window deletes the handler when that window closes. That happens whenclose_tabor 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 aBufLeaveautocmd 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 theBufEnterhandlers 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 astartinsert, 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 firesWinClosed,BufWinLeave,BufHiddenandTabClosed, and noBufLeave,WinLeave,TabLeave,BufEnter,WinEnterorTabEnter. With the user in the diff tab or in a third tab,close_tabgoes back to the original tab first, as before: it firesBufLeave,WinLeaveandTabLeavefor the window the user is in, thenWinEnter,TabEnterandBufEnterfor the original tab's window, so aBufLeaveautocmd on the user's file in the third tab runs. When the original tab no longer exists,close_tabgoes 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:tabclosedoes, which firesTabLeaveandTabEnter. 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 firesWinLeave,WinEnter,BufLeaveandBufEnterfor the user's window and enter and leave events for the terminal, as when the user opens the terminal, so aBufLeaveautocmd, such as an autosave, can run then. When:tabclosecannot 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'sBufEnterhandler, and runs the rest with every autocmd blocked (:noautocmd,utils.without_autocmds): it gives the proposal window of aunifieddiff 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 aunifieddiff), 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 firesWinEnterandBufEnterfor that window, and if only its buffer changed (the empty buffer under a cursor that stayed in the proposal window of aunifieddiff),BufEnteralone. It fires no leave event, noBufNew,BufAdd,BufWinLeave,BufHidden,WinClosedorOptionSetevent 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:tabcloseleaves the diff's terminal window open, a terminal that was visible before the diff and that no other window shows, a float parked withhideaside, stays in that window. Closing it would maketerminal.ensure_visibleopen another window, which fires the events of a new terminal window (an autocmdBufEnter term://* startinsertof the user's then starts an insert in their file).:tabclosecloses 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 = truestill 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
unifieddiff 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:tabnewmade while that window is untouched, so the tab holds no blank pane. It splits beside that window when aTabNewhandler 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
unifieddiff needsvim.text.difforvim.diffand raises-32000without one. Neovim 0.8.0 hasvim.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
ClaudeCodeDiffClosedhandler that runs the event loop during that cleanup lets a queuedopenDiffregister 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_diffsentry gets anopen_orderfrom_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
acwritescratch buffer named<tab_name> (proposed), or<tab_name> (NEW FILE - proposed). A new file's original side is a read-onlynofileplaceholder named<old_file_path> (NEW FILE). The proposal buffer carriesb:claudecode_diff_tab_name, which:ClaudeCodeDiffAcceptand:ClaudeCodeDiffDenyread [diff.lua:M._setup_blocking_diff] [diff.lua:load_original_buffer] [diff.lua:M.accept_current_diff] - A diff that resolves before
open_diff_blockingyields, for example from aClaudeCodeDiffOpenedhandler 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. Averticalorunifieddiff 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. Ahorizontaldiff 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 legacyopen_diffnever 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
unifieddiff 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_percentageof the columns, elsesplit_width_percentage, and not at all withdiff_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_percentagefalls back tosplit_width_percentage, and an invalidsplit_width_percentageto 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
verticalorhorizontaldiff set the Claude terminal, in any tab, tosplit_width_percentageof the columns, and not at all withdiff_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 atsplit_width_percentage[diff.lua:M._cleanup_diff_state]. Aunifieddiff 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 checkauto_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 callshide_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, onlysnackshides a float, throughhide_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 ignorestabhides its float in any tab. Withsnacks, 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 callsensure_visibleif a window of the terminal was visible in any tab when it opened (had_terminal_in_original, set at open fromfind_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 ownensure_visibledecides, 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 withhide, 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_windowskips a window hidden withhide, so with a hidden floatkeep_terminal_focusleaves 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 = truethe 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
-32000with message "Diff setup failed". Itsdataholds 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 returnsFILE_SAVEDand the content. In theunifiedlayout 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 returnsDIFF_REJECTEDand 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 runBufWriteCmd) never writes the file. It accepts a pending diff and does nothing else.:wleaves the windows open untilclose_tab, and:wq,:xandZZalso close the proposal window. A write after the diff has its answer sends nothing and does not fail (the handler never returnstrue, which would delete the autocmd and make the next:wfail with E676). It warns when the buffer holds edits that Claude never gets [diff.lua:M._write_proposal] - In the
verticalandhorizontallayouts the saved content is the lines of the proposal buffer, joined with the line break of the buffer's'fileformat'(LF, CRLF fordos, CR formac), plus a final line break only when the buffer's'eol'is on and the buffer has a line. When'fileformats'includesdos, a proposal that has a line break and only CRLF line breaks gets'fileformat'dosand 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:wwrites it. Any other proposal gets'fileformat'unixwhatever the first entry of'fileformats'is, with its CRs inside its lines, which:wwrites back unchanged. Theunifiedlayout'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 withggdGor:%delete) is saved as an empty string, because:wwrites 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 withwordcount().bytes, becausenvim_buf_get_linesreturns 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'athide: the buffer is modified, andwipewould make:qfail 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,:wqleft the window open, and:qastopped with E37 or E162 and moved a window onto the hidden buffer untilclose_tabdeleted it [diff.lua:mark_proposal_unmodified] - At exit, Neovim fires
BufUnloadfor each loaded buffer beforeVimLeavePre, and a proposal'sBufUnloadautocmd 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 withon_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 ownBufUnload. The diffs after either get noBufUnload(probed on Neovim 0.8.0, 0.9.5, 0.10.4, 0.11.5 and 0.12.3). SIGTERM and SIGHUP runVimLeavePrewithout that loop. A quit from inside an autocmd that is notnested,:noautocmd qa!, a Luaos.exit(), SIGKILL and a crash run noVimLeavePre, 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 invim.wait). TheVimLeavePreautocmd ofClaudeCodeMCPDifftherefore runscleanup_at_exit, which first rejects each diff with the statuspending, oldest first, each underpcall, and skips a diff with another status. A reject can remove its own diff (thekeep_emptycase above), so a diff can be gone before the next one is rejected. The reject of a diff whoseopenDiffsetup has not finished stays insetup_result, because the call has no response sender yet, so the server'sstopsends 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:tabnewand: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 firesClaudeCodeDiffClosed, it runs:diffoffin 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.:diffoffalso 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:diffoffin 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 aClaudeCodeDiffClosedhandler that brings the file back into a window. One limit comes from Neovim: the defaultcloseoffin'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:diffthisand 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'toyeswith 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:setlocalvalue of the editor window included, or, for a buffer that no window showed, the window default (what:setgives, 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_rejectis"keep_empty"(the default), beforeclose_tab. Aunifieddiff gets no such cleanup [diff.lua:M._resolve_diff_as_rejected] [diff_inline.lua:M.resolve_inline_as_rejected] BufDelete,BufUnload, andBufWipeouton the proposal buffer reject a pending diff.WinClosedrejects 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_diffsandclose_diffs_for_clientclose onlypendingdiffs.close_rejected_diffscloses onlyrejecteddiffs.close_all_diffscloses every diff, except a saved diff that another client owns when it gets aclient_id. Of the bulk closes, onlyclose_all_diffspasses aclient_idtoclose_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_diffsselects no status, so it also closes a diff accepted in the meantime. It closes the newest diff first, not inpairs()order, so when each close puts the cursor back, the cursor ends where it was before the oldest of them opened.:ClaudeCodeCloseAllDiffsruns 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_statehands the teardown toutils.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 whileactive_diffsstill 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,closeAllDiffTabsand the server stop answer every call at once, andClaudeCodeDiffClosedfires 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] :ClaudeCodeCloseAllDiffsrunsclose_pending_diffs,close_rejected_diffs, thenclose_saved_diffs[init.lua:M._create_commands]close_saved_diffscloses asaveddiff 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 adosbuffer it drops a CR before each line break, so:wwrites 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'ofwipe,delete, orunloadbecomeshide. 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:checktimeruns 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 (forE325, 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_diffsis module state. A reload that clearspackage.loaded["claudecode.diff"]forgets the open diffs, and the new module'sClaudeCodeMCPDiffaugroup (created withclear = 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]
:ClaudeCodeCloseAllDiffscan 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-localBufWritePost/BufReadPostautocmd that restores'fixeol'once [diff.lua:M.close_saved_diffs]startbinds a127.0.0.1TCP port and writes the lock file. It enables selection tracking only whentrack_selectionis true.stopremoves the lock file, or logs a warning when it cannot, and stops the server [init.lua:M.start]lockfile.createcreates the lock directory with mode 0700. It then tries to chmod an existing directory to 0700 throughpcalland ignores the result, so on platforms withoutfs_chmodthe old mode stays. It writes a temp file openedwxwith 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 userenv(merged after these, so it can override them), thenno_proxy/NO_PROXY. The last step merges the shell's and the user'sno_proxyandNO_PROXYvalues, 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.setupcan replace the globalvim.pastethroughpaste_fix.apply[terminal.lua:M.setup]- The plugin broadcasts
at_mentioned(filePath,lineStart,lineEnd) [init.lua:M._broadcast_at_mention] andselection_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.luaattaches annvim_buf_attachlistener (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 nexton_linesafter Claude holds no selection of that buffer and you do not select in it, and a reload with:editor:edit!detaches it, so it attaches again when the buffer still holds the selection [selection.lua:watch_selection_buffer] init.luafeeds<Esc>after a successful:ClaudeCodeSendthat does not take the visual path, outside a tree buffer. It also feeds<Esc>when:ClaudeCodeor:ClaudeCodeFocusruns in Visual mode [init.lua:M._create_commands]- Augroups:
ClaudeCodeShutdown, which holds theVimLeavePreautocmd 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-levelVimLeavePreautocmd indiff.luawhose callback rejects each pending diff and then callsM._cleanup_all_active_diffs("shutdown")[diff.lua:cleanup_at_exit] - Each diff that opens in a new tab adds a buffer-local
BufEnterautocmd (startinsert) to the Claude terminal buffer inClaudeCodeMCPDiff, unlessterminal.auto_insertisfalse,diff_opts.hide_terminal_in_new_tabistrue, or no valid Claude terminal buffer exists. AWinClosedautocmd 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
Userevents. 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_blockingsends 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, orclaudecode_diffs_fallbackwhen 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_diffreturnssuccess = falsewith an error that names both directories [diff.lua:create_temp_file]. ABufDelete/BufWipeoutautocmd on the proposal buffer cleans up once, even when a wipe fires both events. It deletes the file and then its empty folder withvim.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_statedoes not [diff.lua:M._open_native_diff] - When a step of the legacy
open_diffraises after its temp file was written (a buffer that already has the proposal's name raisesE95, a swap file for the original raisesE325, an autocmd errors),_open_native_diffremoves 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:checktimeprintsE211once (no text is lost). Nothing in the plugin calls this path [diff.lua:remove_failed_proposal] [diff.lua:M._open_native_diff] diff_inline.luacreates theclaudecode_inline_diffnamespace when the module loads. It defines the fourClaudeCodeInlineDiff*highlight groups (withdefault = true) [diff_inline.lua:setup_highlights] and sets extmarks [diff_inline.lua:M.render_diff_buffer]- The plugin runs
git rev-parse --show-toplevelat most once for each git root lookup [cwd.lua:M.git_root], andhealth.checkruns<claude> --version[health.lua:check_cli] loggerdefers each log line throughvim.schedule. ERROR and WARN go tovim.notify. Other levels go tonvim_echo[logger.lua:log]. The level is INFO untilsetupruns.logger.setupwarns at once, not deferred, whenlog_levelis missing or invalid, and uses INFO [logger.lua:M.setup]. The plugin'ssetupnever reaches that warning:config.applyfills ininfoand raises on an invalidlog_levelfirst [config.lua:M.validate]one_lineaccepts onlyerror,warn, andinfo, and asserts on any other level [logger.lua:M.one_line]- Below log_level debug,
one_linereplaces each run of whitespace with one space. A line wider thanv:echospacecells drops its component tag and putsERROR:orWARN: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...whenv:echospaceis 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 defaulthit-enter), so the whole line shows only at log_level debug [logger.lua:M.one_line] M.startlogs the reason a server did not start throughone_line, for exampleNo free port in 10000-65535 (EADDRINUSE), becauseauto_startruns 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:echospaceis 51, andone_lineshows[ClaudeCode] ERROR: No free port in 10000-65535 ...[logger.lua:fit_command_line].M.startreturnsServer not started: <reason>. When the reason containsauth, the message ends with(authentication related)[init.lua:M.start]
- 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.shruns eachtests/integration/*_spec.luafile in headless Neovim with plenary.nvim,command_args_spec.luaincluded. It runstests/integration/diff_window_choice_spec.lua, whichbustedonly marks as pending