{"repo_name": "claudecode.nvim", "file_name": "/claudecode.nvim/lua/claudecode/terminal.lua", "inference_info": {"prefix_code": "--- Module to manage a dedicated vertical split terminal for Claude Code.\n-- Supports Snacks.nvim or a native Neovim terminal fallback.\n-- @module claudecode.terminal\n\n--- @class TerminalProvider\n--- @field setup function\n--- @field open function\n--- @field close function\n--- @field toggle function\n--- @field simple_toggle function\n--- @field focus_toggle function\n--- @field get_active_bufnr function\n--- @field is_available function\n--- @field _get_terminal_for_test function\n\nlocal M = {}\n\nlocal claudecode_server_module = require(\"claudecode.server.init\")\n\nlocal config = {\n split_side = \"right\",\n split_width_percentage = 0.30,\n provider = \"auto\",\n show_native_term_exit_tip = true,\n terminal_cmd = nil,\n auto_close = true,\n}\n\n-- Lazy load providers\nlocal providers = {}\n\n--- Loads a terminal provider module\n--- @param provider_name string The name of the provider to load\n--- @return TerminalProvider|nil provider The provider module, or nil if loading failed\nlocal function load_provider(provider_name)\n if not providers[provider_name] then\n local ok, provider = pcall(require, \"claudecode.terminal.\" .. provider_name)\n if ok then\n providers[provider_name] = provider\n else\n return nil\n end\n end\n return providers[provider_name]\nend\n\n--- Gets the effective terminal provider, guaranteed to return a valid provider\n--- Falls back to native provider if configured provider is unavailable\n--- @return TerminalProvider provider The terminal provider module (never nil)\nlocal function get_provider()\n local logger = require(\"claudecode.logger\")\n\n if config.provider == \"auto\" then\n -- Try snacks first, then fallback to native silently\n local snacks_provider = load_provider(\"snacks\")\n if snacks_provider and snacks_provider.is_available() then\n return snacks_provider\n end\n -- Fall through to native provider\n elseif config.provider == \"snacks\" then\n local snacks_provider = load_provider(\"snacks\")\n if snacks_provider and snacks_provider.is_available() then\n return snacks_provider\n else\n logger.warn(\"terminal\", \"'snacks' provider configured, but Snacks.nvim not available. Falling back to 'native'.\")\n end\n elseif config.provider == \"native\" then\n -- noop, will use native provider as default below\n logger.debug(\"terminal\", \"Using native terminal provider\")\n else\n logger.warn(\"terminal\", \"Invalid provider configured: \" .. tostring(config.provider) .. \". Defaulting to 'native'.\")\n end\n\n local native_provider = load_provider(\"native\")\n if not native_provider then\n error(\"ClaudeCode: Critical error - native terminal provider failed to load\")\n end\n return native_provider\nend\n\n--- Builds the effective terminal configuration by merging defaults with overrides\n--- @param opts_override table|nil Optional overrides for terminal appearance\n--- @return table The effective terminal configuration\nlocal function build_config(opts_override)\n local effective_config = vim.deepcopy(config)\n if type(opts_override) == \"table\" then\n local validators = {\n split_side = function(val)\n return val == \"left\" or val == \"right\"\n end,\n split_width_percentage = function(val)\n return type(val) == \"number\" and val > 0 and val < 1\n end,\n }\n for key, val in pairs(opts_override) do\n if effective_config[key] ~= nil and validators[key] and validators[key](val) then\n effective_config[key] = val\n end\n end\n end\n return {\n split_side = effective_config.split_side,\n split_width_percentage = effective_config.split_width_percentage,\n auto_close = effective_config.auto_close,\n }\nend\n\n--- Checks if a terminal buffer is currently visible in any window\n--- @param bufnr number|nil The buffer number to check\n--- @return boolean True if the buffer is visible in any window, false otherwise\nlocal function is_terminal_visible(bufnr)\n if not bufnr then\n return false\n end\n\n local bufinfo = vim.fn.getbufinfo(bufnr)\n return bufinfo and #bufinfo > 0 and #bufinfo[1].windows > 0\nend\n\n--- Gets the claude command string and necessary environment variables\n--- @param cmd_args string|nil Optional arguments to append to the command\n--- @return string cmd_string The command string\n--- @return table env_table The environment variables table\n", "suffix_code": "\n\n--- Common helper to open terminal without focus if not already visible\n--- @param opts_override table|nil Optional config overrides\n--- @param cmd_args string|nil Optional command arguments\n--- @return boolean True if terminal was opened or already visible\nlocal function ensure_terminal_visible_no_focus(opts_override, cmd_args)\n local provider = get_provider()\n local active_bufnr = provider.get_active_bufnr()\n\n if is_terminal_visible(active_bufnr) then\n -- Terminal is already visible, do nothing\n return true\n end\n\n -- Terminal is not visible, open it without focus\n local effective_config = build_config(opts_override)\n local cmd_string, claude_env_table = get_claude_command_and_env(cmd_args)\n\n provider.open(cmd_string, claude_env_table, effective_config, false) -- false = don't focus\n return true\nend\n\n--- Configures the terminal module.\n-- Merges user-provided terminal configuration with defaults and sets the terminal command.\n-- @param user_term_config table (optional) Configuration options for the terminal.\n-- @field user_term_config.split_side string 'left' or 'right' (default: 'right').\n-- @field user_term_config.split_width_percentage number Percentage of screen width (0.0 to 1.0, default: 0.30).\n-- @field user_term_config.provider string 'snacks' or 'native' (default: 'snacks').\n-- @field user_term_config.show_native_term_exit_tip boolean Show tip for exiting native terminal (default: true).\n-- @param p_terminal_cmd string|nil The command to run in the terminal (from main config).\nfunction M.setup(user_term_config, p_terminal_cmd)\n if user_term_config == nil then -- Allow nil, default to empty table silently\n user_term_config = {}\n elseif type(user_term_config) ~= \"table\" then -- Warn if it's not nil AND not a table\n vim.notify(\"claudecode.terminal.setup expects a table or nil for user_term_config\", vim.log.levels.WARN)\n user_term_config = {}\n end\n\n if p_terminal_cmd == nil or type(p_terminal_cmd) == \"string\" then\n config.terminal_cmd = p_terminal_cmd\n else\n vim.notify(\n \"claudecode.terminal.setup: Invalid terminal_cmd provided: \" .. tostring(p_terminal_cmd) .. \". Using default.\",\n vim.log.levels.WARN\n )\n config.terminal_cmd = nil -- Fallback to default behavior\n end\n\n for k, v in pairs(user_term_config) do\n if config[k] ~= nil and k ~= \"terminal_cmd\" then -- terminal_cmd is handled above\n if k == \"split_side\" and (v == \"left\" or v == \"right\") then\n config[k] = v\n elseif k == \"split_width_percentage\" and type(v) == \"number\" and v > 0 and v < 1 then\n config[k] = v\n elseif k == \"provider\" and (v == \"snacks\" or v == \"native\") then\n config[k] = v\n elseif k == \"show_native_term_exit_tip\" and type(v) == \"boolean\" then\n config[k] = v\n elseif k == \"auto_close\" and type(v) == \"boolean\" then\n config[k] = v\n else\n vim.notify(\"claudecode.terminal.setup: Invalid value for \" .. k .. \": \" .. tostring(v), vim.log.levels.WARN)\n end\n elseif k ~= \"terminal_cmd\" then -- Avoid warning for terminal_cmd if passed in user_term_config\n vim.notify(\"claudecode.terminal.setup: Unknown configuration key: \" .. k, vim.log.levels.WARN)\n end\n end\n\n -- Setup providers with config\n get_provider().setup(config)\nend\n\n--- Opens or focuses the Claude terminal.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.open(opts_override, cmd_args)\n local effective_config = build_config(opts_override)\n local cmd_string, claude_env_table = get_claude_command_and_env(cmd_args)\n\n get_provider().open(cmd_string, claude_env_table, effective_config)\nend\n\n--- Closes the managed Claude terminal if it's open and valid.\nfunction M.close()\n get_provider().close()\nend\n\n--- Simple toggle: always show/hide the Claude terminal regardless of focus.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.simple_toggle(opts_override, cmd_args)\n local effective_config = build_config(opts_override)\n local cmd_string, claude_env_table = get_claude_command_and_env(cmd_args)\n\n get_provider().simple_toggle(cmd_string, claude_env_table, effective_config)\nend\n\n--- Smart focus toggle: switches to terminal if not focused, hides if currently focused.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.focus_toggle(opts_override, cmd_args)\n local effective_config = build_config(opts_override)\n local cmd_string, claude_env_table = get_claude_command_and_env(cmd_args)\n\n get_provider().focus_toggle(cmd_string, claude_env_table, effective_config)\nend\n\n--- Toggle open terminal without focus if not already visible, otherwise do nothing.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.toggle_open_no_focus(opts_override, cmd_args)\n ensure_terminal_visible_no_focus(opts_override, cmd_args)\nend\n\n--- Ensures terminal is visible without changing focus. Creates if necessary, shows if hidden.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.ensure_visible(opts_override, cmd_args)\n ensure_terminal_visible_no_focus(opts_override, cmd_args)\nend\n\n--- Toggles the Claude terminal open or closed (legacy function - use simple_toggle or focus_toggle).\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.toggle(opts_override, cmd_args)\n -- Default to simple toggle for backward compatibility\n M.simple_toggle(opts_override, cmd_args)\nend\n\n--- Gets the buffer number of the currently active Claude Code terminal.\n-- This checks both Snacks and native fallback terminals.\n-- @return number|nil The buffer number if an active terminal is found, otherwise nil.\nfunction M.get_active_terminal_bufnr()\n return get_provider().get_active_bufnr()\nend\n\n--- Gets the managed terminal instance for testing purposes.\n-- NOTE: This function is intended for use in tests to inspect internal state.\n-- The underscore prefix indicates it's not part of the public API for regular use.\n-- @return snacks.terminal|nil The managed Snacks terminal instance, or nil.\nfunction M._get_managed_terminal_for_test()\n local snacks_provider = load_provider(\"snacks\")\n if snacks_provider and snacks_provider._get_terminal_for_test then\n return snacks_provider._get_terminal_for_test()\n end\n return nil\nend\n\nreturn M\n", "middle_code": "local function get_claude_command_and_env(cmd_args)\n local cmd_from_config = config.terminal_cmd\n local base_cmd\n if not cmd_from_config or cmd_from_config == \"\" then\n base_cmd = \"claude\" \n else\n base_cmd = cmd_from_config\n end\n local cmd_string\n if cmd_args and cmd_args ~= \"\" then\n cmd_string = base_cmd .. \" \" .. cmd_args\n else\n cmd_string = base_cmd\n end\n local sse_port_value = claudecode_server_module.state.port\n local env_table = {\n ENABLE_IDE_INTEGRATION = \"true\",\n FORCE_CODE_TERMINAL = \"true\",\n }\n if sse_port_value then\n env_table[\"CLAUDE_CODE_SSE_PORT\"] = tostring(sse_port_value)\n end\n return cmd_string, env_table\nend", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "lua", "sub_task_type": null}, "context_code": [["/claudecode.nvim/lua/claudecode/terminal/native.lua", "--- Native Neovim terminal provider for Claude Code.\n-- @module claudecode.terminal.native\n\n--- @type TerminalProvider\nlocal M = {}\n\nlocal logger = require(\"claudecode.logger\")\nlocal utils = require(\"claudecode.utils\")\n\nlocal bufnr = nil\nlocal winid = nil\nlocal jobid = nil\nlocal tip_shown = false\nlocal config = {}\n\nlocal function cleanup_state()\n bufnr = nil\n winid = nil\n jobid = nil\nend\n\nlocal function is_valid()\n -- First check if we have a valid buffer\n if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then\n cleanup_state()\n return false\n end\n\n -- If buffer is valid but window is invalid, try to find a window displaying this buffer\n if not winid or not vim.api.nvim_win_is_valid(winid) then\n -- Search all windows for our terminal buffer\n local windows = vim.api.nvim_list_wins()\n for _, win in ipairs(windows) do\n if vim.api.nvim_win_get_buf(win) == bufnr then\n -- Found a window displaying our terminal buffer, update the tracked window ID\n winid = win\n logger.debug(\"terminal\", \"Recovered terminal window ID:\", win)\n return true\n end\n end\n -- Buffer exists but no window displays it - this is normal for hidden terminals\n return true -- Buffer is valid even though not visible\n end\n\n -- Both buffer and window are valid\n return true\nend\n\nlocal function open_terminal(cmd_string, env_table, effective_config, focus)\n focus = utils.normalize_focus(focus)\n\n if is_valid() then -- Should not happen if called correctly, but as a safeguard\n if focus then\n -- Focus existing terminal: switch to terminal window and enter insert mode\n vim.api.nvim_set_current_win(winid)\n vim.cmd(\"startinsert\")\n end\n -- If focus=false, preserve user context by staying in current window\n return true\n end\n\n local original_win = vim.api.nvim_get_current_win()\n local width = math.floor(vim.o.columns * effective_config.split_width_percentage)\n local full_height = vim.o.lines\n local placement_modifier\n\n if effective_config.split_side == \"left\" then\n placement_modifier = \"topleft \"\n else\n placement_modifier = \"botright \"\n end\n\n vim.cmd(placement_modifier .. width .. \"vsplit\")\n local new_winid = vim.api.nvim_get_current_win()\n vim.api.nvim_win_set_height(new_winid, full_height)\n\n vim.api.nvim_win_call(new_winid, function()\n vim.cmd(\"enew\")\n end)\n\n local term_cmd_arg\n if cmd_string:find(\" \", 1, true) then\n term_cmd_arg = vim.split(cmd_string, \" \", { plain = true, trimempty = false })\n else\n term_cmd_arg = { cmd_string }\n end\n\n jobid = vim.fn.termopen(term_cmd_arg, {\n env = env_table,\n on_exit = function(job_id, _, _)\n vim.schedule(function()\n if job_id == jobid then\n logger.debug(\"terminal\", \"Terminal process exited, cleaning up\")\n\n -- Ensure we are operating on the correct window and buffer before closing\n local current_winid_for_job = winid\n local current_bufnr_for_job = bufnr\n\n cleanup_state() -- Clear our managed state first\n\n if current_winid_for_job and vim.api.nvim_win_is_valid(current_winid_for_job) then\n if current_bufnr_for_job and vim.api.nvim_buf_is_valid(current_bufnr_for_job) then\n -- Optional: Check if the window still holds the same terminal buffer\n if vim.api.nvim_win_get_buf(current_winid_for_job) == current_bufnr_for_job then\n vim.api.nvim_win_close(current_winid_for_job, true)\n end\n else\n -- Buffer is invalid, but window might still be there (e.g. if user changed buffer in term window)\n -- Still try to close the window we tracked.\n vim.api.nvim_win_close(current_winid_for_job, true)\n end\n end\n end\n end)\n end,\n })\n\n if not jobid or jobid == 0 then\n vim.notify(\"Failed to open native terminal.\", vim.log.levels.ERROR)\n vim.api.nvim_win_close(new_winid, true)\n vim.api.nvim_set_current_win(original_win)\n cleanup_state()\n return false\n end\n\n winid = new_winid\n bufnr = vim.api.nvim_get_current_buf()\n vim.bo[bufnr].bufhidden = \"wipe\" -- Wipe buffer when hidden (e.g., window closed)\n -- buftype=terminal is set by termopen\n\n if focus then\n -- Focus the terminal: switch to terminal window and enter insert mode\n vim.api.nvim_set_current_win(winid)\n vim.cmd(\"startinsert\")\n else\n -- Preserve user context: return to the window they were in before terminal creation\n vim.api.nvim_set_current_win(original_win)\n end\n\n if config.show_native_term_exit_tip and not tip_shown then\n vim.notify(\"Native terminal opened. Press Ctrl-\\\\ Ctrl-N to return to Normal mode.\", vim.log.levels.INFO)\n tip_shown = true\n end\n return true\nend\n\nlocal function close_terminal()\n if is_valid() then\n -- Closing the window should trigger on_exit of the job if the process is still running,\n -- which then calls cleanup_state.\n -- If the job already exited, on_exit would have cleaned up.\n -- This direct close is for user-initiated close.\n vim.api.nvim_win_close(winid, true)\n cleanup_state() -- Cleanup after explicit close\n end\nend\n\nlocal function focus_terminal()\n if is_valid() then\n vim.api.nvim_set_current_win(winid)\n vim.cmd(\"startinsert\")\n end\nend\n\nlocal function is_terminal_visible()\n -- Check if our terminal buffer exists and is displayed in any window\n if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then\n return false\n end\n\n local windows = vim.api.nvim_list_wins()\n for _, win in ipairs(windows) do\n if vim.api.nvim_win_is_valid(win) and vim.api.nvim_win_get_buf(win) == bufnr then\n -- Update our tracked window ID if we find the buffer in a different window\n winid = win\n return true\n end\n end\n\n -- Buffer exists but no window displays it\n winid = nil\n return false\nend\n\nlocal function hide_terminal()\n -- Hide the terminal window but keep the buffer and job alive\n if bufnr and vim.api.nvim_buf_is_valid(bufnr) and winid and vim.api.nvim_win_is_valid(winid) then\n -- Set buffer to hide instead of being wiped when window closes\n vim.api.nvim_buf_set_option(bufnr, \"bufhidden\", \"hide\")\n\n -- Close the window - this preserves the buffer and job\n vim.api.nvim_win_close(winid, false)\n winid = nil -- Clear window reference\n\n logger.debug(\"terminal\", \"Terminal window hidden, process preserved\")\n end\nend\n\nlocal function show_hidden_terminal(effective_config, focus)\n -- Show an existing hidden terminal buffer in a new window\n if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then\n return false\n end\n\n -- Check if it's already visible\n if is_terminal_visible() then\n if focus then\n focus_terminal()\n end\n return true\n end\n\n local original_win = vim.api.nvim_get_current_win()\n\n -- Create a new window for the existing buffer\n local width = math.floor(vim.o.columns * effective_config.split_width_percentage)\n local full_height = vim.o.lines\n local placement_modifier\n\n if effective_config.split_side == \"left\" then\n placement_modifier = \"topleft \"\n else\n placement_modifier = \"botright \"\n end\n\n vim.cmd(placement_modifier .. width .. \"vsplit\")\n local new_winid = vim.api.nvim_get_current_win()\n vim.api.nvim_win_set_height(new_winid, full_height)\n\n -- Set the existing buffer in the new window\n vim.api.nvim_win_set_buf(new_winid, bufnr)\n winid = new_winid\n\n if focus then\n -- Focus the terminal: switch to terminal window and enter insert mode\n vim.api.nvim_set_current_win(winid)\n vim.cmd(\"startinsert\")\n else\n -- Preserve user context: return to the window they were in before showing terminal\n vim.api.nvim_set_current_win(original_win)\n end\n\n logger.debug(\"terminal\", \"Showed hidden terminal in new window\")\n return true\nend\n\nlocal function find_existing_claude_terminal()\n local buffers = vim.api.nvim_list_bufs()\n for _, buf in ipairs(buffers) do\n if vim.api.nvim_buf_is_valid(buf) and vim.api.nvim_buf_get_option(buf, \"buftype\") == \"terminal\" then\n -- Check if this is a Claude Code terminal by examining the buffer name or terminal job\n local buf_name = vim.api.nvim_buf_get_name(buf)\n -- Terminal buffers often have names like \"term://...\" that include the command\n if buf_name:match(\"claude\") then\n -- Additional check: see if there's a window displaying this buffer\n local windows = vim.api.nvim_list_wins()\n for _, win in ipairs(windows) do\n if vim.api.nvim_win_get_buf(win) == buf then\n logger.debug(\"terminal\", \"Found existing Claude terminal in buffer\", buf, \"window\", win)\n return buf, win\n end\n end\n end\n end\n end\n return nil, nil\nend\n\n--- @param term_config table\nfunction M.setup(term_config)\n config = term_config or {}\nend\n\n--- @param cmd_string string\n--- @param env_table table\n--- @param effective_config table\n--- @param focus boolean|nil\nfunction M.open(cmd_string, env_table, effective_config, focus)\n focus = utils.normalize_focus(focus)\n\n if is_valid() then\n -- Check if terminal exists but is hidden (no window)\n if not winid or not vim.api.nvim_win_is_valid(winid) then\n -- Terminal is hidden, show it by calling show_hidden_terminal\n show_hidden_terminal(effective_config, focus)\n else\n -- Terminal is already visible\n if focus then\n focus_terminal()\n end\n end\n else\n -- Check if there's an existing Claude terminal we lost track of\n local existing_buf, existing_win = find_existing_claude_terminal()\n if existing_buf and existing_win then\n -- Recover the existing terminal\n bufnr = existing_buf\n winid = existing_win\n -- Note: We can't recover the job ID easily, but it's less critical\n logger.debug(\"terminal\", \"Recovered existing Claude terminal\")\n if focus then\n focus_terminal() -- Focus recovered terminal\n end\n -- If focus=false, preserve user context by staying in current window\n else\n if not open_terminal(cmd_string, env_table, effective_config, focus) then\n vim.notify(\"Failed to open Claude terminal using native fallback.\", vim.log.levels.ERROR)\n end\n end\n end\nend\n\nfunction M.close()\n close_terminal()\nend\n\n--- Simple toggle: always show/hide terminal regardless of focus\n--- @param cmd_string string\n--- @param env_table table\n--- @param effective_config table\nfunction M.simple_toggle(cmd_string, env_table, effective_config)\n -- Check if we have a valid terminal buffer (process running)\n local has_buffer = bufnr and vim.api.nvim_buf_is_valid(bufnr)\n local is_visible = has_buffer and is_terminal_visible()\n\n if is_visible then\n -- Terminal is visible, hide it (but keep process running)\n hide_terminal()\n else\n -- Terminal is not visible\n if has_buffer then\n -- Terminal process exists but is hidden, show it\n if show_hidden_terminal(effective_config, true) then\n logger.debug(\"terminal\", \"Showing hidden terminal\")\n else\n logger.error(\"terminal\", \"Failed to show hidden terminal\")\n end\n else\n -- No terminal process exists, check if there's an existing one we lost track of\n local existing_buf, existing_win = find_existing_claude_terminal()\n if existing_buf and existing_win then\n -- Recover the existing terminal\n bufnr = existing_buf\n winid = existing_win\n logger.debug(\"terminal\", \"Recovered existing Claude terminal\")\n focus_terminal()\n else\n -- No existing terminal found, create a new one\n if not open_terminal(cmd_string, env_table, effective_config) then\n vim.notify(\"Failed to open Claude terminal using native fallback (simple_toggle).\", vim.log.levels.ERROR)\n end\n end\n end\n end\nend\n\n--- Smart focus toggle: switches to terminal if not focused, hides if currently focused\n--- @param cmd_string string\n--- @param env_table table\n--- @param effective_config table\nfunction M.focus_toggle(cmd_string, env_table, effective_config)\n -- Check if we have a valid terminal buffer (process running)\n local has_buffer = bufnr and vim.api.nvim_buf_is_valid(bufnr)\n local is_visible = has_buffer and is_terminal_visible()\n\n if has_buffer then\n -- Terminal process exists\n if is_visible then\n -- Terminal is visible - check if we're currently in it\n local current_win_id = vim.api.nvim_get_current_win()\n if winid == current_win_id then\n -- We're in the terminal window, hide it (but keep process running)\n hide_terminal()\n else\n -- Terminal is visible but we're not in it, focus it\n focus_terminal()\n end\n else\n -- Terminal process exists but is hidden, show it\n if show_hidden_terminal(effective_config, true) then\n logger.debug(\"terminal\", \"Showing hidden terminal\")\n else\n logger.error(\"terminal\", \"Failed to show hidden terminal\")\n end\n end\n else\n -- No terminal process exists, check if there's an existing one we lost track of\n local existing_buf, existing_win = find_existing_claude_terminal()\n if existing_buf and existing_win then\n -- Recover the existing terminal\n bufnr = existing_buf\n winid = existing_win\n logger.debug(\"terminal\", \"Recovered existing Claude terminal\")\n\n -- Check if we're currently in this recovered terminal\n local current_win_id = vim.api.nvim_get_current_win()\n if existing_win == current_win_id then\n -- We're in the recovered terminal, hide it\n hide_terminal()\n else\n -- Focus the recovered terminal\n focus_terminal()\n end\n else\n -- No existing terminal found, create a new one\n if not open_terminal(cmd_string, env_table, effective_config) then\n vim.notify(\"Failed to open Claude terminal using native fallback (focus_toggle).\", vim.log.levels.ERROR)\n end\n end\n end\nend\n\n--- Legacy toggle function for backward compatibility (defaults to simple_toggle)\n--- @param cmd_string string\n--- @param env_table table\n--- @param effective_config table\nfunction M.toggle(cmd_string, env_table, effective_config)\n M.simple_toggle(cmd_string, env_table, effective_config)\nend\n\n--- @return number|nil\nfunction M.get_active_bufnr()\n if is_valid() then\n return bufnr\n end\n return nil\nend\n\n--- @return boolean\nfunction M.is_available()\n return true -- Native provider is always available\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/terminal/snacks.lua", "--- Snacks.nvim terminal provider for Claude Code.\n-- @module claudecode.terminal.snacks\n\n--- @type TerminalProvider\nlocal M = {}\n\nlocal snacks_available, Snacks = pcall(require, \"snacks\")\nlocal utils = require(\"claudecode.utils\")\nlocal terminal = nil\n\n--- @return boolean\nlocal function is_available()\n return snacks_available and Snacks and Snacks.terminal\nend\n\n--- Setup event handlers for terminal instance\n--- @param term_instance table The Snacks terminal instance\n--- @param config table Configuration options\nlocal function setup_terminal_events(term_instance, config)\n local logger = require(\"claudecode.logger\")\n\n -- Handle command completion/exit - only if auto_close is enabled\n if config.auto_close then\n term_instance:on(\"TermClose\", function()\n if vim.v.event.status ~= 0 then\n logger.error(\"terminal\", \"Claude exited with code \" .. vim.v.event.status .. \".\\nCheck for any errors.\")\n end\n\n -- Clean up\n terminal = nil\n vim.schedule(function()\n term_instance:close({ buf = true })\n vim.cmd.checktime()\n end)\n end, { buf = true })\n end\n\n -- Handle buffer deletion\n term_instance:on(\"BufWipeout\", function()\n logger.debug(\"terminal\", \"Terminal buffer wiped\")\n terminal = nil\n end, { buf = true })\nend\n\n--- Builds Snacks terminal options with focus control\n--- @param config table Terminal configuration (split_side, split_width_percentage, etc.)\n--- @param env_table table Environment variables to set for the terminal process\n--- @param focus boolean|nil Whether to focus the terminal when opened (defaults to true)\n--- @return table Snacks terminal options with start_insert/auto_insert controlled by focus parameter\nlocal function build_opts(config, env_table, focus)\n focus = utils.normalize_focus(focus)\n return {\n env = env_table,\n start_insert = focus,\n auto_insert = focus,\n auto_close = false,\n win = {\n position = config.split_side,\n width = config.split_width_percentage,\n height = 0,\n relative = \"editor\",\n },\n }\nend\n\nfunction M.setup()\n -- No specific setup needed for Snacks provider\nend\n\n--- @param cmd_string string\n--- @param env_table table\n--- @param config table\n--- @param focus boolean|nil\nfunction M.open(cmd_string, env_table, config, focus)\n if not is_available() then\n vim.notify(\"Snacks.nvim terminal provider selected but Snacks.terminal not available.\", vim.log.levels.ERROR)\n return\n end\n\n focus = utils.normalize_focus(focus)\n\n if terminal and terminal:buf_valid() then\n -- Check if terminal exists but is hidden (no window)\n if not terminal.win or not vim.api.nvim_win_is_valid(terminal.win) then\n -- Terminal is hidden, show it using snacks toggle\n terminal:toggle()\n if focus then\n terminal:focus()\n local term_buf_id = terminal.buf\n if term_buf_id and vim.api.nvim_buf_get_option(term_buf_id, \"buftype\") == \"terminal\" then\n if terminal.win and vim.api.nvim_win_is_valid(terminal.win) then\n vim.api.nvim_win_call(terminal.win, function()\n vim.cmd(\"startinsert\")\n end)\n end\n end\n end\n else\n -- Terminal is already visible\n if focus then\n terminal:focus()\n local term_buf_id = terminal.buf\n if term_buf_id and vim.api.nvim_buf_get_option(term_buf_id, \"buftype\") == \"terminal\" then\n -- Check if window is valid before calling nvim_win_call\n if terminal.win and vim.api.nvim_win_is_valid(terminal.win) then\n vim.api.nvim_win_call(terminal.win, function()\n vim.cmd(\"startinsert\")\n end)\n end\n end\n end\n end\n return\n end\n\n local opts = build_opts(config, env_table, focus)\n local term_instance = Snacks.terminal.open(cmd_string, opts)\n if term_instance and term_instance:buf_valid() then\n setup_terminal_events(term_instance, config)\n terminal = term_instance\n else\n terminal = nil\n local logger = require(\"claudecode.logger\")\n local error_details = {}\n if not term_instance then\n table.insert(error_details, \"Snacks.terminal.open() returned nil\")\n elseif not term_instance:buf_valid() then\n table.insert(error_details, \"terminal instance is invalid\")\n if term_instance.buf and not vim.api.nvim_buf_is_valid(term_instance.buf) then\n table.insert(error_details, \"buffer is invalid\")\n end\n if term_instance.win and not vim.api.nvim_win_is_valid(term_instance.win) then\n table.insert(error_details, \"window is invalid\")\n end\n end\n\n local context = string.format(\"cmd='%s', opts=%s\", cmd_string, vim.inspect(opts))\n local error_msg = string.format(\n \"Failed to open Claude terminal using Snacks. Details: %s. Context: %s\",\n table.concat(error_details, \", \"),\n context\n )\n vim.notify(error_msg, vim.log.levels.ERROR)\n logger.debug(\"terminal\", error_msg)\n end\nend\n\nfunction M.close()\n if not is_available() then\n return\n end\n if terminal and terminal:buf_valid() then\n terminal:close()\n end\nend\n\n--- Simple toggle: always show/hide terminal regardless of focus\n--- @param cmd_string string\n--- @param env_table table\n--- @param config table\nfunction M.simple_toggle(cmd_string, env_table, config)\n if not is_available() then\n vim.notify(\"Snacks.nvim terminal provider selected but Snacks.terminal not available.\", vim.log.levels.ERROR)\n return\n end\n\n local logger = require(\"claudecode.logger\")\n\n -- Check if terminal exists and is visible\n if terminal and terminal:buf_valid() and terminal.win then\n -- Terminal is visible, hide it\n logger.debug(\"terminal\", \"Simple toggle: hiding visible terminal\")\n terminal:toggle()\n elseif terminal and terminal:buf_valid() and not terminal.win then\n -- Terminal exists but not visible, show it\n logger.debug(\"terminal\", \"Simple toggle: showing hidden terminal\")\n terminal:toggle()\n else\n -- No terminal exists, create new one\n logger.debug(\"terminal\", \"Simple toggle: creating new terminal\")\n M.open(cmd_string, env_table, config)\n end\nend\n\n--- Smart focus toggle: switches to terminal if not focused, hides if currently focused\n--- @param cmd_string string\n--- @param env_table table\n--- @param config table\nfunction M.focus_toggle(cmd_string, env_table, config)\n if not is_available() then\n vim.notify(\"Snacks.nvim terminal provider selected but Snacks.terminal not available.\", vim.log.levels.ERROR)\n return\n end\n\n local logger = require(\"claudecode.logger\")\n\n -- Terminal exists, is valid, but not visible\n if terminal and terminal:buf_valid() and not terminal.win then\n logger.debug(\"terminal\", \"Focus toggle: showing hidden terminal\")\n terminal:toggle()\n -- Terminal exists, is valid, and is visible\n elseif terminal and terminal:buf_valid() and terminal.win then\n local claude_term_neovim_win_id = terminal.win\n local current_neovim_win_id = vim.api.nvim_get_current_win()\n\n -- you're IN it\n if claude_term_neovim_win_id == current_neovim_win_id then\n logger.debug(\"terminal\", \"Focus toggle: hiding terminal (currently focused)\")\n terminal:toggle()\n -- you're NOT in it\n else\n logger.debug(\"terminal\", \"Focus toggle: focusing terminal\")\n vim.api.nvim_set_current_win(claude_term_neovim_win_id)\n if terminal.buf and vim.api.nvim_buf_is_valid(terminal.buf) then\n if vim.api.nvim_buf_get_option(terminal.buf, \"buftype\") == \"terminal\" then\n vim.api.nvim_win_call(claude_term_neovim_win_id, function()\n vim.cmd(\"startinsert\")\n end)\n end\n end\n end\n -- No terminal exists\n else\n logger.debug(\"terminal\", \"Focus toggle: creating new terminal\")\n M.open(cmd_string, env_table, config)\n end\nend\n\n--- Legacy toggle function for backward compatibility (defaults to simple_toggle)\n--- @param cmd_string string\n--- @param env_table table\n--- @param config table\nfunction M.toggle(cmd_string, env_table, config)\n M.simple_toggle(cmd_string, env_table, config)\nend\n\n--- @return number|nil\nfunction M.get_active_bufnr()\n if terminal and terminal:buf_valid() and terminal.buf then\n if vim.api.nvim_buf_is_valid(terminal.buf) then\n return terminal.buf\n end\n end\n return nil\nend\n\n--- @return boolean\nfunction M.is_available()\n return is_available()\nend\n\n-- For testing purposes\n--- @return table|nil\nfunction M._get_terminal_for_test()\n return terminal\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/init.lua", "---@brief [[\n--- Claude Code Neovim Integration\n--- This plugin integrates Claude Code CLI with Neovim, enabling\n--- seamless AI-assisted coding experiences directly in Neovim.\n---@brief ]]\n\n--- @module 'claudecode'\nlocal M = {}\n\nlocal logger = require(\"claudecode.logger\")\n\n--- @class ClaudeCode.Version\n--- @field major integer Major version number\n--- @field minor integer Minor version number\n--- @field patch integer Patch version number\n--- @field prerelease string|nil Prerelease identifier (e.g., \"alpha\", \"beta\")\n--- @field string fun(self: ClaudeCode.Version):string Returns the formatted version string\n\n--- The current version of the plugin.\n--- @type ClaudeCode.Version\nM.version = {\n major = 0,\n minor = 2,\n patch = 0,\n prerelease = nil,\n string = function(self)\n local version = string.format(\"%d.%d.%d\", self.major, self.minor, self.patch)\n if self.prerelease then\n version = version .. \"-\" .. self.prerelease\n end\n return version\n end,\n}\n\n--- @class ClaudeCode.Config\n--- @field port_range {min: integer, max: integer} Port range for WebSocket server.\n--- @field auto_start boolean Auto-start WebSocket server on Neovim startup.\n--- @field terminal_cmd string|nil Custom terminal command to use when launching Claude.\n--- @field log_level \"trace\"|\"debug\"|\"info\"|\"warn\"|\"error\" Log level.\n--- @field track_selection boolean Enable sending selection updates to Claude.\n--- @field visual_demotion_delay_ms number Milliseconds to wait before demoting a visual selection.\n--- @field connection_wait_delay number Milliseconds to wait after connection before sending queued @ mentions.\n--- @field connection_timeout number Maximum time to wait for Claude Code to connect (milliseconds).\n--- @field queue_timeout number Maximum time to keep @ mentions in queue (milliseconds).\n--- @field diff_opts { auto_close_on_accept: boolean, show_diff_stats: boolean, vertical_split: boolean, open_in_current_tab: boolean } Options for the diff provider.\n\n--- @type ClaudeCode.Config\nlocal default_config = {\n port_range = { min = 10000, max = 65535 },\n auto_start = true,\n terminal_cmd = nil,\n log_level = \"info\",\n track_selection = true,\n visual_demotion_delay_ms = 50, -- Reduced from 200ms for better responsiveness in tree navigation\n connection_wait_delay = 200, -- Milliseconds to wait after connection before sending queued @ mentions\n connection_timeout = 10000, -- Maximum time to wait for Claude Code to connect (milliseconds)\n queue_timeout = 5000, -- Maximum time to keep @ mentions in queue (milliseconds)\n diff_opts = {\n auto_close_on_accept = true,\n show_diff_stats = true,\n vertical_split = true,\n open_in_current_tab = false,\n },\n}\n\n--- @class ClaudeCode.State\n--- @field config ClaudeCode.Config The current plugin configuration.\n--- @field server table|nil The WebSocket server instance.\n--- @field port number|nil The port the server is running on.\n--- @field auth_token string|nil The authentication token for the current session.\n--- @field initialized boolean Whether the plugin has been initialized.\n--- @field queued_mentions table[] Array of queued @ mentions waiting for connection.\n--- @field connection_timer table|nil Timer for connection timeout.\n\n--- @type ClaudeCode.State\nM.state = {\n config = vim.deepcopy(default_config),\n server = nil,\n port = nil,\n auth_token = nil,\n initialized = false,\n queued_mentions = {},\n connection_timer = nil,\n}\n\n---@alias ClaudeCode.TerminalOpts { \\\n--- split_side?: \"left\"|\"right\", \\\n--- split_width_percentage?: number, \\\n--- provider?: \"auto\"|\"snacks\"|\"native\", \\\n--- show_native_term_exit_tip?: boolean }\n---\n---@alias ClaudeCode.SetupOpts { \\\n--- terminal?: ClaudeCode.TerminalOpts }\n\n---@brief Check if Claude Code is connected to WebSocket server\n---@return boolean connected Whether Claude Code has active connections\nfunction M.is_claude_connected()\n if not M.state.server then\n return false\n end\n\n local server_module = require(\"claudecode.server.init\")\n local status = server_module.get_status()\n return status.running and status.client_count > 0\nend\n\n---@brief Clear the @ mention queue and stop timers\nlocal function clear_mention_queue()\n if #M.state.queued_mentions > 0 then\n logger.debug(\"queue\", \"Clearing \" .. #M.state.queued_mentions .. \" queued @ mentions\")\n end\n\n M.state.queued_mentions = {}\n\n if M.state.connection_timer then\n M.state.connection_timer:stop()\n M.state.connection_timer:close()\n M.state.connection_timer = nil\n end\nend\n\n---@brief Add @ mention to queue for later sending\n---@param mention_data table The @ mention data to queue\nlocal function queue_at_mention(mention_data)\n mention_data.timestamp = vim.loop.now()\n table.insert(M.state.queued_mentions, mention_data)\n\n logger.debug(\"queue\", \"Queued @ mention: \" .. vim.inspect(mention_data))\n\n -- Start connection timer if not already running\n if not M.state.connection_timer then\n M.state.connection_timer = vim.loop.new_timer()\n M.state.connection_timer:start(M.state.config.connection_timeout, 0, function()\n vim.schedule(function()\n if #M.state.queued_mentions > 0 then\n logger.error(\"queue\", \"Connection timeout - clearing \" .. #M.state.queued_mentions .. \" queued @ mentions\")\n clear_mention_queue()\n end\n end)\n end)\n end\nend\n\n---@brief Process queued @ mentions after connection established\nfunction M._process_queued_mentions()\n if #M.state.queued_mentions == 0 then\n return\n end\n\n logger.debug(\"queue\", \"Processing \" .. #M.state.queued_mentions .. \" queued @ mentions\")\n\n -- Stop connection timer\n if M.state.connection_timer then\n M.state.connection_timer:stop()\n M.state.connection_timer:close()\n M.state.connection_timer = nil\n end\n\n -- Wait for connection_wait_delay before sending\n vim.defer_fn(function()\n local mentions_to_send = vim.deepcopy(M.state.queued_mentions)\n M.state.queued_mentions = {} -- Clear queue\n\n if #mentions_to_send == 0 then\n return\n end\n\n -- Ensure terminal is visible when processing queued mentions\n local terminal = require(\"claudecode.terminal\")\n terminal.ensure_visible()\n\n local success_count = 0\n local total_count = #mentions_to_send\n local delay = 10 -- Use same delay as existing batch operations\n\n local function send_mentions_sequentially(index)\n if index > total_count then\n if success_count > 0 then\n local message = success_count == 1 and \"Sent 1 queued @ mention to Claude Code\"\n or string.format(\"Sent %d queued @ mentions to Claude Code\", success_count)\n logger.debug(\"queue\", message)\n end\n return\n end\n\n local mention = mentions_to_send[index]\n local now = vim.loop.now()\n\n -- Check if mention hasn't expired\n if (now - mention.timestamp) < M.state.config.queue_timeout then\n local success, error_msg = M._broadcast_at_mention(mention.file_path, mention.start_line, mention.end_line)\n if success then\n success_count = success_count + 1\n else\n logger.error(\"queue\", \"Failed to send queued @ mention: \" .. (error_msg or \"unknown error\"))\n end\n else\n logger.debug(\"queue\", \"Skipped expired @ mention: \" .. mention.file_path)\n end\n\n -- Send next mention with delay\n if index < total_count then\n vim.defer_fn(function()\n send_mentions_sequentially(index + 1)\n end, delay)\n else\n -- Final summary\n if success_count > 0 then\n local message = success_count == 1 and \"Sent 1 queued @ mention to Claude Code\"\n or string.format(\"Sent %d queued @ mentions to Claude Code\", success_count)\n logger.debug(\"queue\", message)\n end\n end\n end\n\n send_mentions_sequentially(1)\n end, M.state.config.connection_wait_delay)\nend\n\n---@brief Show terminal if Claude is connected and it's not already visible\n---@return boolean success Whether terminal was shown or was already visible\nfunction M._ensure_terminal_visible_if_connected()\n if not M.is_claude_connected() then\n return false\n end\n\n local terminal = require(\"claudecode.terminal\")\n local active_bufnr = terminal.get_active_terminal_bufnr and terminal.get_active_terminal_bufnr()\n\n if not active_bufnr then\n return false\n end\n\n local bufinfo = vim.fn.getbufinfo(active_bufnr)[1]\n local is_visible = bufinfo and #bufinfo.windows > 0\n\n if not is_visible then\n terminal.simple_toggle()\n end\n\n return true\nend\n\n---@brief Send @ mention to Claude Code, handling connection state automatically\n---@param file_path string The file path to send\n---@param start_line number|nil Start line (0-indexed for Claude)\n---@param end_line number|nil End line (0-indexed for Claude)\n---@param context string|nil Context for logging\n---@return boolean success Whether the operation was successful\n---@return string|nil error Error message if failed\nfunction M.send_at_mention(file_path, start_line, end_line, context)\n context = context or \"command\"\n\n if not M.state.server then\n logger.error(context, \"Claude Code integration is not running\")\n return false, \"Claude Code integration is not running\"\n end\n\n -- Check if Claude Code is connected\n if M.is_claude_connected() then\n -- Claude is connected, send immediately and ensure terminal is visible\n local success, error_msg = M._broadcast_at_mention(file_path, start_line, end_line)\n if success then\n local terminal = require(\"claudecode.terminal\")\n terminal.ensure_visible()\n end\n return success, error_msg\n else\n -- Claude not connected, queue the mention and launch terminal\n local mention_data = {\n file_path = file_path,\n start_line = start_line,\n end_line = end_line,\n context = context,\n }\n\n queue_at_mention(mention_data)\n\n -- Launch terminal with Claude Code\n local terminal = require(\"claudecode.terminal\")\n terminal.open()\n\n logger.debug(context, \"Queued @ mention and launched Claude Code: \" .. file_path)\n\n return true, nil\n end\nend\n\n---\n--- Set up the plugin with user configuration\n---@param opts ClaudeCode.SetupOpts|nil Optional configuration table to override defaults.\n---@return table The plugin module\nfunction M.setup(opts)\n opts = opts or {}\n\n local terminal_opts = nil\n if opts.terminal then\n terminal_opts = opts.terminal\n opts.terminal = nil -- Remove from main opts to avoid polluting M.state.config\n end\n\n local config = require(\"claudecode.config\")\n M.state.config = config.apply(opts)\n -- vim.g.claudecode_user_config is no longer needed as config values are passed directly.\n\n logger.setup(M.state.config)\n\n -- Setup terminal module: always try to call setup to pass terminal_cmd,\n -- even if terminal_opts (for split_side etc.) are not provided.\n local terminal_setup_ok, terminal_module = pcall(require, \"claudecode.terminal\")\n if terminal_setup_ok then\n -- Guard in case tests or user replace the module with a minimal stub without `setup`.\n if type(terminal_module.setup) == \"function\" then\n -- terminal_opts might be nil, which the setup function should handle gracefully.\n terminal_module.setup(terminal_opts, M.state.config.terminal_cmd)\n end\n else\n logger.error(\"init\", \"Failed to load claudecode.terminal module for setup.\")\n end\n\n local diff = require(\"claudecode.diff\")\n diff.setup(M.state.config)\n\n if M.state.config.auto_start then\n M.start(false) -- Suppress notification on auto-start\n end\n\n M._create_commands()\n\n vim.api.nvim_create_autocmd(\"VimLeavePre\", {\n group = vim.api.nvim_create_augroup(\"ClaudeCodeShutdown\", { clear = true }),\n callback = function()\n if M.state.server then\n M.stop()\n else\n -- Clear queue even if server isn't running\n clear_mention_queue()\n end\n end,\n desc = \"Automatically stop Claude Code integration when exiting Neovim\",\n })\n\n M.state.initialized = true\n return M\nend\n\n--- Start the Claude Code integration\n---@param show_startup_notification? boolean Whether to show a notification upon successful startup (defaults to true)\n---@return boolean success Whether the operation was successful\n---@return number|string port_or_error The WebSocket port if successful, or error message if failed\nfunction M.start(show_startup_notification)\n if show_startup_notification == nil then\n show_startup_notification = true\n end\n if M.state.server then\n local msg = \"Claude Code integration is already running on port \" .. tostring(M.state.port)\n logger.warn(\"init\", msg)\n return false, \"Already running\"\n end\n\n local server = require(\"claudecode.server.init\")\n local lockfile = require(\"claudecode.lockfile\")\n\n -- Generate auth token first so we can pass it to the server\n local auth_token\n local auth_success, auth_result = pcall(function()\n return lockfile.generate_auth_token()\n end)\n\n if not auth_success then\n local error_msg = \"Failed to generate authentication token: \" .. (auth_result or \"unknown error\")\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n auth_token = auth_result\n\n -- Validate the generated auth token\n if not auth_token or type(auth_token) ~= \"string\" or #auth_token < 10 then\n local error_msg = \"Invalid authentication token generated\"\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n local success, result = server.start(M.state.config, auth_token)\n\n if not success then\n local error_msg = \"Failed to start Claude Code server: \" .. (result or \"unknown error\")\n if result and result:find(\"auth\") then\n error_msg = error_msg .. \" (authentication related)\"\n end\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n M.state.server = server\n M.state.port = tonumber(result)\n M.state.auth_token = auth_token\n\n local lock_success, lock_result, returned_auth_token = lockfile.create(M.state.port, auth_token)\n\n if not lock_success then\n server.stop()\n M.state.server = nil\n M.state.port = nil\n M.state.auth_token = nil\n\n local error_msg = \"Failed to create lock file: \" .. (lock_result or \"unknown error\")\n if lock_result and lock_result:find(\"auth\") then\n error_msg = error_msg .. \" (authentication token issue)\"\n end\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n -- Verify that the auth token in the lock file matches what we generated\n if returned_auth_token ~= auth_token then\n server.stop()\n M.state.server = nil\n M.state.port = nil\n M.state.auth_token = nil\n\n local error_msg = \"Authentication token mismatch between server and lock file\"\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n if M.state.config.track_selection then\n local selection = require(\"claudecode.selection\")\n selection.enable(M.state.server, M.state.config.visual_demotion_delay_ms)\n end\n\n if show_startup_notification then\n logger.info(\"init\", \"Claude Code integration started on port \" .. tostring(M.state.port))\n end\n\n return true, M.state.port\nend\n\n--- Stop the Claude Code integration\n---@return boolean success Whether the operation was successful\n---@return string? error Error message if operation failed\nfunction M.stop()\n if not M.state.server then\n logger.warn(\"init\", \"Claude Code integration is not running\")\n return false, \"Not running\"\n end\n\n local lockfile = require(\"claudecode.lockfile\")\n local lock_success, lock_error = lockfile.remove(M.state.port)\n\n if not lock_success then\n logger.warn(\"init\", \"Failed to remove lock file: \" .. lock_error)\n -- Continue with shutdown even if lock file removal fails\n end\n\n if M.state.config.track_selection then\n local selection = require(\"claudecode.selection\")\n selection.disable()\n end\n\n local success, error = M.state.server.stop()\n\n if not success then\n logger.error(\"init\", \"Failed to stop Claude Code integration: \" .. error)\n return false, error\n end\n\n M.state.server = nil\n M.state.port = nil\n M.state.auth_token = nil\n\n -- Clear any queued @ mentions when server stops\n clear_mention_queue()\n\n logger.info(\"init\", \"Claude Code integration stopped\")\n\n return true\nend\n\n--- Set up user commands\n---@private\nfunction M._create_commands()\n vim.api.nvim_create_user_command(\"ClaudeCodeStart\", function()\n M.start()\n end, {\n desc = \"Start Claude Code integration\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeStop\", function()\n M.stop()\n end, {\n desc = \"Stop Claude Code integration\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeStatus\", function()\n if M.state.server and M.state.port then\n logger.info(\"command\", \"Claude Code integration is running on port \" .. tostring(M.state.port))\n else\n logger.info(\"command\", \"Claude Code integration is not running\")\n end\n end, {\n desc = \"Show Claude Code integration status\",\n })\n\n ---@param file_paths table List of file paths to add\n ---@param options table|nil Optional settings: { delay?: number, show_summary?: boolean, context?: string }\n ---@return number success_count Number of successfully added files\n ---@return number total_count Total number of files attempted\n local function add_paths_to_claude(file_paths, options)\n options = options or {}\n local delay = options.delay or 0\n local show_summary = options.show_summary ~= false\n local context = options.context or \"command\"\n\n if not file_paths or #file_paths == 0 then\n return 0, 0\n end\n\n local success_count = 0\n local total_count = #file_paths\n\n if delay > 0 then\n local function send_files_sequentially(index)\n if index > total_count then\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n return\n end\n\n local file_path = file_paths[index]\n local success, error_msg = M.send_at_mention(file_path, nil, nil, context)\n if success then\n success_count = success_count + 1\n else\n logger.error(context, \"Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\"))\n end\n\n if index < total_count then\n vim.defer_fn(function()\n send_files_sequentially(index + 1)\n end, delay)\n else\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n end\n end\n\n send_files_sequentially(1)\n else\n for _, file_path in ipairs(file_paths) do\n local success, error_msg = M.send_at_mention(file_path, nil, nil, context)\n if success then\n success_count = success_count + 1\n else\n logger.error(context, \"Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\"))\n end\n end\n\n if show_summary and success_count > 0 then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n logger.debug(context, message)\n end\n end\n\n return success_count, total_count\n end\n\n local function handle_send_normal(opts)\n local current_ft = (vim.bo and vim.bo.filetype) or \"\"\n local current_bufname = (vim.api and vim.api.nvim_buf_get_name and vim.api.nvim_buf_get_name(0)) or \"\"\n\n local is_tree_buffer = current_ft == \"NvimTree\"\n or current_ft == \"neo-tree\"\n or current_ft == \"oil\"\n or string.match(current_bufname, \"neo%-tree\")\n or string.match(current_bufname, \"NvimTree\")\n\n if is_tree_buffer then\n local integrations = require(\"claudecode.integrations\")\n local files, error = integrations.get_selected_files_from_tree()\n\n if error then\n logger.error(\"command\", \"ClaudeCodeSend->TreeAdd: \" .. error)\n return\n end\n\n if not files or #files == 0 then\n logger.warn(\"command\", \"ClaudeCodeSend->TreeAdd: No files selected\")\n return\n end\n\n add_paths_to_claude(files, { context = \"ClaudeCodeSend->TreeAdd\" })\n\n return\n end\n\n local selection_module_ok, selection_module = pcall(require, \"claudecode.selection\")\n if selection_module_ok then\n -- Pass range information if available (for :'<,'> commands)\n local line1, line2 = nil, nil\n if opts and opts.range and opts.range > 0 then\n line1, line2 = opts.line1, opts.line2\n end\n local sent_successfully = selection_module.send_at_mention_for_visual_selection(line1, line2)\n if sent_successfully then\n -- Exit any potential visual mode (for consistency)\n pcall(function()\n if vim.api and vim.api.nvim_feedkeys then\n local esc = vim.api.nvim_replace_termcodes(\"\", true, false, true)\n vim.api.nvim_feedkeys(esc, \"i\", true)\n end\n end)\n end\n else\n logger.error(\"command\", \"ClaudeCodeSend: Failed to load selection module.\")\n end\n end\n\n local function handle_send_visual(visual_data, _opts)\n -- Try tree file selection first\n if visual_data then\n local visual_commands = require(\"claudecode.visual_commands\")\n local files, error = visual_commands.get_files_from_visual_selection(visual_data)\n\n if not error and files and #files > 0 then\n local success_count = add_paths_to_claude(files, {\n delay = 10,\n context = \"ClaudeCodeSend_visual\",\n show_summary = false,\n })\n if success_count > 0 then\n local message = success_count == 1 and \"Added 1 file to Claude context from visual selection\"\n or string.format(\"Added %d files to Claude context from visual selection\", success_count)\n logger.debug(\"command\", message)\n end\n return\n end\n end\n\n -- Handle regular text selection using range from visual mode\n local selection_module_ok, selection_module = pcall(require, \"claudecode.selection\")\n if not selection_module_ok then\n return\n end\n\n -- Use the marks left by visual mode instead of trying to get current visual selection\n local line1, line2 = vim.fn.line(\"'<\"), vim.fn.line(\"'>\")\n if line1 and line2 and line1 > 0 and line2 > 0 then\n selection_module.send_at_mention_for_visual_selection(line1, line2)\n else\n selection_module.send_at_mention_for_visual_selection()\n end\n end\n\n local visual_commands = require(\"claudecode.visual_commands\")\n local unified_send_handler = visual_commands.create_visual_command_wrapper(handle_send_normal, handle_send_visual)\n\n vim.api.nvim_create_user_command(\"ClaudeCodeSend\", unified_send_handler, {\n desc = \"Send current visual selection as an at_mention to Claude Code (supports tree visual selection)\",\n range = true,\n })\n\n local function handle_tree_add_normal()\n if not M.state.server then\n logger.error(\"command\", \"ClaudeCodeTreeAdd: Claude Code integration is not running.\")\n return\n end\n\n local integrations = require(\"claudecode.integrations\")\n local files, error = integrations.get_selected_files_from_tree()\n\n if error then\n logger.error(\"command\", \"ClaudeCodeTreeAdd: \" .. error)\n return\n end\n\n if not files or #files == 0 then\n logger.warn(\"command\", \"ClaudeCodeTreeAdd: No files selected\")\n return\n end\n\n -- Use connection-aware broadcasting for each file\n local success_count = 0\n local total_count = #files\n\n for _, file_path in ipairs(files) do\n local success, error_msg = M.send_at_mention(file_path, nil, nil, \"ClaudeCodeTreeAdd\")\n if success then\n success_count = success_count + 1\n else\n logger.error(\n \"command\",\n \"ClaudeCodeTreeAdd: Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\")\n )\n end\n end\n\n if success_count == 0 then\n logger.error(\"command\", \"ClaudeCodeTreeAdd: Failed to add any files\")\n elseif success_count < total_count then\n local message = string.format(\"Added %d/%d files to Claude context\", success_count, total_count)\n logger.debug(\"command\", message)\n else\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n logger.debug(\"command\", message)\n end\n end\n\n local function handle_tree_add_visual(visual_data)\n if not M.state.server then\n logger.error(\"command\", \"ClaudeCodeTreeAdd_visual: Claude Code integration is not running.\")\n return\n end\n\n local visual_cmd_module = require(\"claudecode.visual_commands\")\n local files, error = visual_cmd_module.get_files_from_visual_selection(visual_data)\n\n if error then\n logger.error(\"command\", \"ClaudeCodeTreeAdd_visual: \" .. error)\n return\n end\n\n if not files or #files == 0 then\n logger.warn(\"command\", \"ClaudeCodeTreeAdd_visual: No files selected in visual range\")\n return\n end\n\n -- Use connection-aware broadcasting for each file\n local success_count = 0\n local total_count = #files\n\n for _, file_path in ipairs(files) do\n local success, error_msg = M.send_at_mention(file_path, nil, nil, \"ClaudeCodeTreeAdd_visual\")\n if success then\n success_count = success_count + 1\n else\n logger.error(\n \"command\",\n \"ClaudeCodeTreeAdd_visual: Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\")\n )\n end\n end\n\n if success_count > 0 then\n local message = success_count == 1 and \"Added 1 file to Claude context from visual selection\"\n or string.format(\"Added %d files to Claude context from visual selection\", success_count)\n logger.debug(\"command\", message)\n\n if success_count < total_count then\n logger.warn(\"command\", string.format(\"Added %d/%d files from visual selection\", success_count, total_count))\n end\n else\n logger.error(\"command\", \"ClaudeCodeTreeAdd_visual: Failed to add any files from visual selection\")\n end\n end\n\n local unified_tree_add_handler =\n visual_commands.create_visual_command_wrapper(handle_tree_add_normal, handle_tree_add_visual)\n\n vim.api.nvim_create_user_command(\"ClaudeCodeTreeAdd\", unified_tree_add_handler, {\n desc = \"Add selected file(s) from tree explorer to Claude Code context (supports visual selection)\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeAdd\", function(opts)\n if not M.state.server then\n logger.error(\"command\", \"ClaudeCodeAdd: Claude Code integration is not running.\")\n return\n end\n\n if not opts.args or opts.args == \"\" then\n logger.error(\"command\", \"ClaudeCodeAdd: No file path provided\")\n return\n end\n\n local args = vim.split(opts.args, \"%s+\")\n local file_path = args[1]\n local start_line = args[2] and tonumber(args[2]) or nil\n local end_line = args[3] and tonumber(args[3]) or nil\n\n if #args > 3 then\n logger.error(\n \"command\",\n \"ClaudeCodeAdd: Too many arguments. Usage: ClaudeCodeAdd [start-line] [end-line]\"\n )\n return\n end\n\n if args[2] and not start_line then\n logger.error(\"command\", \"ClaudeCodeAdd: Invalid start line number: \" .. args[2])\n return\n end\n\n if args[3] and not end_line then\n logger.error(\"command\", \"ClaudeCodeAdd: Invalid end line number: \" .. args[3])\n return\n end\n\n if start_line and start_line < 1 then\n logger.error(\"command\", \"ClaudeCodeAdd: Start line must be positive: \" .. start_line)\n return\n end\n\n if end_line and end_line < 1 then\n logger.error(\"command\", \"ClaudeCodeAdd: End line must be positive: \" .. end_line)\n return\n end\n\n if start_line and end_line and start_line > end_line then\n logger.error(\n \"command\",\n \"ClaudeCodeAdd: Start line (\" .. start_line .. \") must be <= end line (\" .. end_line .. \")\"\n )\n return\n end\n\n file_path = vim.fn.expand(file_path)\n if vim.fn.filereadable(file_path) == 0 and vim.fn.isdirectory(file_path) == 0 then\n logger.error(\"command\", \"ClaudeCodeAdd: File or directory does not exist: \" .. file_path)\n return\n end\n\n local claude_start_line = start_line and (start_line - 1) or nil\n local claude_end_line = end_line and (end_line - 1) or nil\n\n local success, error_msg = M.send_at_mention(file_path, claude_start_line, claude_end_line, \"ClaudeCodeAdd\")\n if not success then\n logger.error(\"command\", \"ClaudeCodeAdd: \" .. (error_msg or \"Failed to add file\"))\n else\n local message = \"ClaudeCodeAdd: Successfully added \" .. file_path\n if start_line or end_line then\n if start_line and end_line then\n message = message .. \" (lines \" .. start_line .. \"-\" .. end_line .. \")\"\n elseif start_line then\n message = message .. \" (from line \" .. start_line .. \")\"\n end\n end\n logger.debug(\"command\", message)\n end\n end, {\n nargs = \"+\",\n complete = \"file\",\n desc = \"Add specified file or directory to Claude Code context with optional line range\",\n })\n\n local terminal_ok, terminal = pcall(require, \"claudecode.terminal\")\n if terminal_ok then\n vim.api.nvim_create_user_command(\"ClaudeCode\", function(opts)\n local current_mode = vim.fn.mode()\n if current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\22\" then\n vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(\"\", true, false, true), \"n\", false)\n end\n local cmd_args = opts.args and opts.args ~= \"\" and opts.args or nil\n terminal.simple_toggle({}, cmd_args)\n end, {\n nargs = \"*\",\n desc = \"Toggle the Claude Code terminal window (simple show/hide) with optional arguments\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeFocus\", function(opts)\n local current_mode = vim.fn.mode()\n if current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\22\" then\n vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(\"\", true, false, true), \"n\", false)\n end\n local cmd_args = opts.args and opts.args ~= \"\" and opts.args or nil\n terminal.focus_toggle({}, cmd_args)\n end, {\n nargs = \"*\",\n desc = \"Smart focus/toggle Claude Code terminal (switches to terminal if not focused, hides if focused)\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeOpen\", function(opts)\n local cmd_args = opts.args and opts.args ~= \"\" and opts.args or nil\n terminal.open({}, cmd_args)\n end, {\n nargs = \"*\",\n desc = \"Open the Claude Code terminal window with optional arguments\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeClose\", function()\n terminal.close()\n end, {\n desc = \"Close the Claude Code terminal window\",\n })\n else\n logger.error(\n \"init\",\n \"Terminal module not found. Terminal commands (ClaudeCode, ClaudeCodeOpen, ClaudeCodeClose) not registered.\"\n )\n end\n\n -- Diff management commands\n vim.api.nvim_create_user_command(\"ClaudeCodeDiffAccept\", function()\n local diff = require(\"claudecode.diff\")\n diff.accept_current_diff()\n end, {\n desc = \"Accept the current diff changes\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeDiffDeny\", function()\n local diff = require(\"claudecode.diff\")\n diff.deny_current_diff()\n end, {\n desc = \"Deny/reject the current diff changes\",\n })\nend\n\n--- Get version information\n---@return table Version information\nfunction M.get_version()\n return {\n version = M.version:string(),\n major = M.version.major,\n minor = M.version.minor,\n patch = M.version.patch,\n prerelease = M.version.prerelease,\n }\nend\n\n--- Format file path for at mention (exposed for testing)\n---@param file_path string The file path to format\n---@return string formatted_path The formatted path\n---@return boolean is_directory Whether the path is a directory\nfunction M._format_path_for_at_mention(file_path)\n -- Input validation\n if not file_path or type(file_path) ~= \"string\" or file_path == \"\" then\n error(\"format_path_for_at_mention: file_path must be a non-empty string\")\n end\n\n -- Only check path existence in production (not tests)\n -- This allows tests to work with mock paths while still providing validation in real usage\n if not package.loaded[\"busted\"] then\n if vim.fn.filereadable(file_path) == 0 and vim.fn.isdirectory(file_path) == 0 then\n error(\"format_path_for_at_mention: path does not exist: \" .. file_path)\n end\n end\n\n local is_directory = vim.fn.isdirectory(file_path) == 1\n local formatted_path = file_path\n\n if is_directory then\n local cwd = vim.fn.getcwd()\n if string.find(file_path, cwd, 1, true) == 1 then\n local relative_path = string.sub(file_path, #cwd + 2)\n if relative_path ~= \"\" then\n formatted_path = relative_path\n else\n formatted_path = \"./\"\n end\n end\n if not string.match(formatted_path, \"/$\") then\n formatted_path = formatted_path .. \"/\"\n end\n else\n local cwd = vim.fn.getcwd()\n if string.find(file_path, cwd, 1, true) == 1 then\n local relative_path = string.sub(file_path, #cwd + 2)\n if relative_path ~= \"\" then\n formatted_path = relative_path\n end\n end\n end\n\n return formatted_path, is_directory\nend\n\n-- Test helper functions (exposed for testing)\nfunction M._broadcast_at_mention(file_path, start_line, end_line)\n if not M.state.server then\n return false, \"Claude Code integration is not running\"\n end\n\n -- Safely format the path and handle validation errors\n local formatted_path, is_directory\n local format_success, format_result, is_dir_result = pcall(M._format_path_for_at_mention, file_path)\n if not format_success then\n return false, format_result -- format_result contains the error message\n end\n formatted_path, is_directory = format_result, is_dir_result\n\n if is_directory and (start_line or end_line) then\n logger.debug(\"command\", \"Line numbers ignored for directory: \" .. formatted_path)\n start_line = nil\n end_line = nil\n end\n\n local params = {\n filePath = formatted_path,\n lineStart = start_line,\n lineEnd = end_line,\n }\n\n local broadcast_success = M.state.server.broadcast(\"at_mentioned\", params)\n if broadcast_success then\n return true, nil\n else\n local error_msg = \"Failed to broadcast \" .. (is_directory and \"directory\" or \"file\") .. \" \" .. formatted_path\n logger.error(\"command\", error_msg)\n return false, error_msg\n end\nend\n\nfunction M._add_paths_to_claude(file_paths, options)\n options = options or {}\n local delay = options.delay or 0\n local show_summary = options.show_summary ~= false\n local context = options.context or \"command\"\n local batch_size = options.batch_size or 10\n local max_files = options.max_files or 100\n\n if not file_paths or #file_paths == 0 then\n return 0, 0\n end\n\n if #file_paths > max_files then\n logger.warn(context, string.format(\"Too many files selected (%d), limiting to %d\", #file_paths, max_files))\n local limited_paths = {}\n for i = 1, max_files do\n limited_paths[i] = file_paths[i]\n end\n file_paths = limited_paths\n end\n\n local success_count = 0\n local total_count = #file_paths\n\n if delay > 0 then\n local function send_batch(start_index)\n if start_index > total_count then\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n return\n end\n\n -- Process a batch of files\n local end_index = math.min(start_index + batch_size - 1, total_count)\n local batch_success = 0\n\n for i = start_index, end_index do\n local file_path = file_paths[i]\n local success, error_msg = M._broadcast_at_mention(file_path)\n if success then\n success_count = success_count + 1\n batch_success = batch_success + 1\n else\n logger.error(context, \"Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\"))\n end\n end\n\n logger.debug(\n context,\n string.format(\n \"Processed batch %d-%d: %d/%d successful\",\n start_index,\n end_index,\n batch_success,\n end_index - start_index + 1\n )\n )\n\n if end_index < total_count then\n vim.defer_fn(function()\n send_batch(end_index + 1)\n end, delay)\n else\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n end\n end\n\n send_batch(1)\n else\n local progress_interval = math.max(1, math.floor(total_count / 10))\n\n for i, file_path in ipairs(file_paths) do\n local success, error_msg = M._broadcast_at_mention(file_path)\n if success then\n success_count = success_count + 1\n else\n logger.error(context, \"Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\"))\n end\n\n if total_count > 20 and i % progress_interval == 0 then\n logger.debug(\n context,\n string.format(\"Progress: %d/%d files processed (%d successful)\", i, total_count, success_count)\n )\n end\n end\n\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n end\n\n return success_count, total_count\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/diff.lua", "--- Diff module for Claude Code Neovim integration.\n-- Provides native Neovim diff functionality with MCP-compliant blocking operations and state management.\nlocal M = {}\n\nlocal logger = require(\"claudecode.logger\")\n\n-- Global state management for active diffs\nlocal active_diffs = {}\nlocal autocmd_group\n\n--- Get or create the autocmd group\nlocal function get_autocmd_group()\n if not autocmd_group then\n autocmd_group = vim.api.nvim_create_augroup(\"ClaudeCodeMCPDiff\", { clear = true })\n end\n return autocmd_group\nend\n\n--- Find a suitable main editor window to open diffs in.\n-- Excludes terminals, sidebars, and floating windows.\n-- @return number|nil Window ID of the main editor window, or nil if not found\nlocal function find_main_editor_window()\n local windows = vim.api.nvim_list_wins()\n\n for _, win in ipairs(windows) do\n local buf = vim.api.nvim_win_get_buf(win)\n local buftype = vim.api.nvim_buf_get_option(buf, \"buftype\")\n local filetype = vim.api.nvim_buf_get_option(buf, \"filetype\")\n local win_config = vim.api.nvim_win_get_config(win)\n\n -- Check if this is a suitable window\n local is_suitable = true\n\n -- Skip floating windows\n if win_config.relative and win_config.relative ~= \"\" then\n is_suitable = false\n end\n\n -- Skip special buffer types\n if is_suitable and (buftype == \"terminal\" or buftype == \"prompt\") then\n is_suitable = false\n end\n\n -- Skip known sidebar filetypes and ClaudeCode terminal\n if\n is_suitable\n and (\n filetype == \"neo-tree\"\n or filetype == \"neo-tree-popup\"\n or filetype == \"ClaudeCode\"\n or filetype == \"NvimTree\"\n or filetype == \"oil\"\n or filetype == \"aerial\"\n or filetype == \"tagbar\"\n )\n then\n is_suitable = false\n end\n\n -- This looks like a main editor window\n if is_suitable then\n return win\n end\n end\n\n return nil\nend\n\n--- Setup the diff module\n-- @param user_diff_config table|nil Reserved for future use\nfunction M.setup(user_diff_config)\n -- Currently no configuration needed for native diff\n -- Parameter kept for API compatibility\nend\n\n--- Open a diff view between two files\n-- @param old_file_path string Path to the original file\n-- @param new_file_path string Path to the new file (used for naming)\n-- @param new_file_contents string Contents of the new file\n-- @param tab_name string Name for the diff tab/view\n-- @return table Result with provider, tab_name, and success status\nfunction M.open_diff(old_file_path, new_file_path, new_file_contents, tab_name)\n return M._open_native_diff(old_file_path, new_file_path, new_file_contents, tab_name)\nend\n\n--- Create a temporary file with content\n-- @param content string The content to write\n-- @param filename string Base filename for the temporary file\n-- @return string|nil, string|nil The temporary file path and error message\nlocal function create_temp_file(content, filename)\n local base_dir_cache = vim.fn.stdpath(\"cache\") .. \"/claudecode_diffs\"\n local mkdir_ok_cache, mkdir_err_cache = pcall(vim.fn.mkdir, base_dir_cache, \"p\")\n\n local final_base_dir\n if mkdir_ok_cache then\n final_base_dir = base_dir_cache\n else\n local base_dir_temp = vim.fn.stdpath(\"cache\") .. \"/claudecode_diffs_fallback\"\n local mkdir_ok_temp, mkdir_err_temp = pcall(vim.fn.mkdir, base_dir_temp, \"p\")\n if not mkdir_ok_temp then\n local err_to_report = mkdir_err_temp or mkdir_err_cache or \"unknown error creating base temp dir\"\n return nil, \"Failed to create base temporary directory: \" .. tostring(err_to_report)\n end\n final_base_dir = base_dir_temp\n end\n\n local session_id_base = vim.fn.fnamemodify(vim.fn.tempname(), \":t\")\n .. \"_\"\n .. tostring(os.time())\n .. \"_\"\n .. tostring(math.random(1000, 9999))\n local session_id = session_id_base:gsub(\"[^A-Za-z0-9_-]\", \"\")\n if session_id == \"\" then -- Fallback if all characters were problematic, ensuring a directory can be made.\n session_id = \"claudecode_session\"\n end\n\n local tmp_session_dir = final_base_dir .. \"/\" .. session_id\n local mkdir_session_ok, mkdir_session_err = pcall(vim.fn.mkdir, tmp_session_dir, \"p\")\n if not mkdir_session_ok then\n return nil, \"Failed to create temporary session directory: \" .. tostring(mkdir_session_err)\n end\n\n local tmp_file = tmp_session_dir .. \"/\" .. filename\n local file = io.open(tmp_file, \"w\")\n if not file then\n return nil, \"Failed to create temporary file: \" .. tmp_file\n end\n\n file:write(content)\n file:close()\n\n return tmp_file, nil\nend\n\n--- Clean up temporary files and directories\n-- @param tmp_file string Path to the temporary file to clean up\nlocal function cleanup_temp_file(tmp_file)\n if tmp_file and vim.fn.filereadable(tmp_file) == 1 then\n local tmp_dir = vim.fn.fnamemodify(tmp_file, \":h\")\n if vim.fs and type(vim.fs.remove) == \"function\" then\n local ok_file, err_file = pcall(vim.fs.remove, tmp_file)\n if not ok_file then\n vim.notify(\n \"ClaudeCode: Error removing temp file \" .. tmp_file .. \": \" .. tostring(err_file),\n vim.log.levels.WARN\n )\n end\n\n local ok_dir, err_dir = pcall(vim.fs.remove, tmp_dir)\n if not ok_dir then\n vim.notify(\n \"ClaudeCode: Error removing temp directory \" .. tmp_dir .. \": \" .. tostring(err_dir),\n vim.log.levels.INFO\n )\n end\n else\n local reason = \"vim.fs.remove is not a function\"\n if not vim.fs then\n reason = \"vim.fs is nil\"\n end\n vim.notify(\n \"ClaudeCode: Cannot perform standard cleanup: \"\n .. reason\n .. \". Affected file: \"\n .. tmp_file\n .. \". Please check your Neovim setup or report this issue.\",\n vim.log.levels.ERROR\n )\n -- Fallback to os.remove for the file.\n local os_ok, os_err = pcall(os.remove, tmp_file)\n if not os_ok then\n vim.notify(\n \"ClaudeCode: Fallback os.remove also failed for file \" .. tmp_file .. \": \" .. tostring(os_err),\n vim.log.levels.ERROR\n )\n end\n end\n end\nend\n\n-- Detect filetype from a path or existing buffer (best-effort)\nlocal function detect_filetype(path, buf)\n -- 1) Try Neovim's builtin matcher if available (>=0.10)\n if vim.filetype and type(vim.filetype.match) == \"function\" then\n local ok, ft = pcall(vim.filetype.match, { filename = path })\n if ok and ft and ft ~= \"\" then\n return ft\n end\n end\n\n -- 2) Try reading from existing buffer\n if buf and vim.api.nvim_buf_is_valid(buf) then\n local ft = vim.api.nvim_buf_get_option(buf, \"filetype\")\n if ft and ft ~= \"\" then\n return ft\n end\n end\n\n -- 3) Fallback to simple extension mapping\n local ext = path:match(\"%.([%w_%-]+)$\") or \"\"\n local simple_map = {\n lua = \"lua\",\n ts = \"typescript\",\n js = \"javascript\",\n jsx = \"javascriptreact\",\n tsx = \"typescriptreact\",\n py = \"python\",\n go = \"go\",\n rs = \"rust\",\n c = \"c\",\n h = \"c\",\n cpp = \"cpp\",\n hpp = \"cpp\",\n md = \"markdown\",\n sh = \"sh\",\n zsh = \"zsh\",\n bash = \"bash\",\n json = \"json\",\n yaml = \"yaml\",\n yml = \"yaml\",\n toml = \"toml\",\n }\n return simple_map[ext]\nend\n--- Open diff using native Neovim functionality\n-- @param old_file_path string Path to the original file\n-- @param new_file_path string Path to the new file (used for naming)\n-- @param new_file_contents string Contents of the new file\n-- @param tab_name string Name for the diff tab/view\n-- @return table Result with provider, tab_name, and success status\nfunction M._open_native_diff(old_file_path, new_file_path, new_file_contents, tab_name)\n local new_filename = vim.fn.fnamemodify(new_file_path, \":t\") .. \".new\"\n local tmp_file, err = create_temp_file(new_file_contents, new_filename)\n if not tmp_file then\n return { provider = \"native\", tab_name = tab_name, success = false, error = err, temp_file = nil }\n end\n\n local target_win = find_main_editor_window()\n\n if target_win then\n vim.api.nvim_set_current_win(target_win)\n else\n vim.cmd(\"wincmd t\")\n vim.cmd(\"wincmd l\")\n local buf = vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win())\n local buftype = vim.api.nvim_buf_get_option(buf, \"buftype\")\n\n if buftype == \"terminal\" or buftype == \"nofile\" then\n vim.cmd(\"vsplit\")\n end\n end\n\n vim.cmd(\"edit \" .. vim.fn.fnameescape(old_file_path))\n vim.cmd(\"diffthis\")\n vim.cmd(\"vsplit\")\n vim.cmd(\"edit \" .. vim.fn.fnameescape(tmp_file))\n vim.api.nvim_buf_set_name(0, new_file_path .. \" (New)\")\n\n -- Propagate filetype to the proposed buffer for proper syntax highlighting (#20)\n local proposed_buf = vim.api.nvim_get_current_buf()\n local old_filetype = detect_filetype(old_file_path)\n if old_filetype and old_filetype ~= \"\" then\n vim.api.nvim_set_option_value(\"filetype\", old_filetype, { buf = proposed_buf })\n end\n\n vim.cmd(\"wincmd =\")\n\n local new_buf = proposed_buf\n vim.api.nvim_set_option_value(\"buftype\", \"nofile\", { buf = new_buf })\n vim.api.nvim_set_option_value(\"bufhidden\", \"wipe\", { buf = new_buf })\n vim.api.nvim_set_option_value(\"swapfile\", false, { buf = new_buf })\n\n vim.cmd(\"diffthis\")\n\n local cleanup_group = vim.api.nvim_create_augroup(\"ClaudeCodeDiffCleanup\", { clear = false })\n vim.api.nvim_create_autocmd({ \"BufDelete\", \"BufWipeout\" }, {\n group = cleanup_group,\n buffer = new_buf,\n callback = function()\n cleanup_temp_file(tmp_file)\n end,\n once = true,\n })\n\n return {\n provider = \"native\",\n tab_name = tab_name,\n success = true,\n temp_file = tmp_file,\n }\nend\n\n--- Register diff state for tracking\n-- @param tab_name string Unique identifier for the diff\n-- @param diff_data table Diff state data\nfunction M._register_diff_state(tab_name, diff_data)\n active_diffs[tab_name] = diff_data\nend\n\n--- Resolve diff as saved (user accepted changes)\n-- @param tab_name string The diff identifier\n-- @param buffer_id number The buffer that was saved\nfunction M._resolve_diff_as_saved(tab_name, buffer_id)\n local diff_data = active_diffs[tab_name]\n if not diff_data or diff_data.status ~= \"pending\" then\n return\n end\n\n logger.debug(\"diff\", \"Resolving diff as saved for\", tab_name, \"from buffer\", buffer_id)\n\n -- Get content from buffer\n local content_lines = vim.api.nvim_buf_get_lines(buffer_id, 0, -1, false)\n local final_content = table.concat(content_lines, \"\\n\")\n -- Add trailing newline if the buffer has one\n if #content_lines > 0 and vim.api.nvim_buf_get_option(buffer_id, \"eol\") then\n final_content = final_content .. \"\\n\"\n end\n\n -- Close diff windows (unified behavior)\n if diff_data.new_window and vim.api.nvim_win_is_valid(diff_data.new_window) then\n vim.api.nvim_win_close(diff_data.new_window, true)\n end\n if diff_data.target_window and vim.api.nvim_win_is_valid(diff_data.target_window) then\n vim.api.nvim_set_current_win(diff_data.target_window)\n vim.cmd(\"diffoff\")\n end\n\n -- Create MCP-compliant response\n local result = {\n content = {\n { type = \"text\", text = \"FILE_SAVED\" },\n { type = \"text\", text = final_content },\n },\n }\n\n diff_data.status = \"saved\"\n diff_data.result_content = result\n\n -- Resume the coroutine with the result (for deferred response system)\n if diff_data.resolution_callback then\n logger.debug(\"diff\", \"Resuming coroutine for saved diff\", tab_name)\n diff_data.resolution_callback(result)\n else\n logger.debug(\"diff\", \"No resolution callback found for saved diff\", tab_name)\n end\n\n -- Reload the original file buffer after a delay to ensure Claude CLI has written the file\n vim.defer_fn(function()\n local current_diff_data = active_diffs[tab_name]\n local original_cursor_pos = current_diff_data and current_diff_data.original_cursor_pos\n M.reload_file_buffers_manual(diff_data.old_file_path, original_cursor_pos)\n end, 200)\n\n -- NOTE: Diff state cleanup is handled by close_tab tool or explicit cleanup calls\n logger.debug(\"diff\", \"Diff saved, awaiting close_tab command for cleanup\")\nend\n\n--- Reload file buffers after external changes (called when diff is closed)\n-- @param file_path string Path to the file that was externally modified\n-- @param original_cursor_pos table|nil Original cursor position to restore {row, col}\nlocal function reload_file_buffers(file_path, original_cursor_pos)\n logger.debug(\"diff\", \"Reloading buffers for file:\", file_path, original_cursor_pos and \"(restoring cursor)\" or \"\")\n\n local reloaded_count = 0\n -- Find and reload any open buffers for this file\n for _, buf in ipairs(vim.api.nvim_list_bufs()) do\n if vim.api.nvim_buf_is_valid(buf) then\n local buf_name = vim.api.nvim_buf_get_name(buf)\n\n -- Simple string match - if buffer name matches the file path\n if buf_name == file_path then\n -- Check if buffer is modified - only reload unmodified buffers for safety\n local modified = vim.api.nvim_buf_get_option(buf, \"modified\")\n logger.debug(\"diff\", \"Found matching buffer\", buf, \"modified:\", modified)\n\n if not modified then\n -- Try to find a window displaying this buffer for proper context\n local win_id = nil\n for _, win in ipairs(vim.api.nvim_list_wins()) do\n if vim.api.nvim_win_get_buf(win) == buf then\n win_id = win\n break\n end\n end\n\n if win_id then\n vim.api.nvim_win_call(win_id, function()\n vim.cmd(\"edit\")\n -- Restore original cursor position if we have it\n if original_cursor_pos then\n pcall(vim.api.nvim_win_set_cursor, win_id, original_cursor_pos)\n end\n end)\n else\n vim.api.nvim_buf_call(buf, function()\n vim.cmd(\"edit\")\n end)\n end\n\n reloaded_count = reloaded_count + 1\n end\n end\n end\n end\n\n logger.debug(\"diff\", \"Completed buffer reload - reloaded\", reloaded_count, \"buffers for file:\", file_path)\nend\n\n--- Resolve diff as rejected (user closed/rejected)\n-- @param tab_name string The diff identifier\nfunction M._resolve_diff_as_rejected(tab_name)\n local diff_data = active_diffs[tab_name]\n if not diff_data or diff_data.status ~= \"pending\" then\n return\n end\n\n -- Create MCP-compliant response\n local result = {\n content = {\n { type = \"text\", text = \"DIFF_REJECTED\" },\n { type = \"text\", text = tab_name },\n },\n }\n\n diff_data.status = \"rejected\"\n diff_data.result_content = result\n\n -- Clean up diff state and resources BEFORE resolving to prevent any interference\n M._cleanup_diff_state(tab_name, \"diff rejected\")\n\n -- Use vim.schedule to ensure the resolution callback happens after all cleanup\n vim.schedule(function()\n -- Resume the coroutine with the result (for deferred response system)\n if diff_data.resolution_callback then\n logger.debug(\"diff\", \"Resuming coroutine for rejected diff\", tab_name)\n diff_data.resolution_callback(result)\n end\n end)\nend\n\n--- Register autocmds for a specific diff\n-- @param tab_name string The diff identifier\n-- @param new_buffer number New file buffer ID\n-- @return table List of autocmd IDs\nlocal function register_diff_autocmds(tab_name, new_buffer)\n local autocmd_ids = {}\n\n -- Handle :w command to accept diff changes (replaces both BufWritePost and BufWriteCmd)\n autocmd_ids[#autocmd_ids + 1] = vim.api.nvim_create_autocmd(\"BufWriteCmd\", {\n group = get_autocmd_group(),\n buffer = new_buffer,\n callback = function()\n logger.debug(\"diff\", \"BufWriteCmd (:w) triggered - accepting diff changes for\", tab_name)\n M._resolve_diff_as_saved(tab_name, new_buffer)\n -- Prevent actual file write since we're handling it through MCP\n return true\n end,\n })\n\n -- Buffer deletion monitoring for rejection (multiple events to catch all deletion methods)\n\n -- BufDelete: When buffer is deleted with :bdelete, :bwipeout, etc.\n autocmd_ids[#autocmd_ids + 1] = vim.api.nvim_create_autocmd(\"BufDelete\", {\n group = get_autocmd_group(),\n buffer = new_buffer,\n callback = function()\n logger.debug(\"diff\", \"BufDelete triggered for new buffer\", new_buffer, \"tab:\", tab_name)\n M._resolve_diff_as_rejected(tab_name)\n end,\n })\n\n -- BufUnload: When buffer is unloaded (covers more scenarios)\n autocmd_ids[#autocmd_ids + 1] = vim.api.nvim_create_autocmd(\"BufUnload\", {\n group = get_autocmd_group(),\n buffer = new_buffer,\n callback = function()\n logger.debug(\"diff\", \"BufUnload triggered for new buffer\", new_buffer, \"tab:\", tab_name)\n M._resolve_diff_as_rejected(tab_name)\n end,\n })\n\n -- BufWipeout: When buffer is wiped out completely\n autocmd_ids[#autocmd_ids + 1] = vim.api.nvim_create_autocmd(\"BufWipeout\", {\n group = get_autocmd_group(),\n buffer = new_buffer,\n callback = function()\n logger.debug(\"diff\", \"BufWipeout triggered for new buffer\", new_buffer, \"tab:\", tab_name)\n M._resolve_diff_as_rejected(tab_name)\n end,\n })\n\n -- Note: We intentionally do NOT monitor old_buffer for deletion\n -- because it's the actual file buffer and shouldn't trigger diff rejection\n\n return autocmd_ids\nend\n\n--- Create diff view from a specific window\n-- @param target_window number The window to use as base for the diff\n-- @param old_file_path string Path to the original file\n-- @param new_buffer number New file buffer ID\n-- @param tab_name string The diff identifier\n-- @param is_new_file boolean Whether this is a new file (doesn't exist yet)\n-- @return table Info about the created diff layout\nfunction M._create_diff_view_from_window(target_window, old_file_path, new_buffer, tab_name, is_new_file)\n -- If no target window provided, create a new window in suitable location\n if not target_window then\n -- Try to create a new window in the main area\n vim.cmd(\"wincmd t\") -- Go to top-left\n vim.cmd(\"wincmd l\") -- Move right (to middle if layout is left|middle|right)\n\n local buf = vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win())\n local buftype = vim.api.nvim_buf_get_option(buf, \"buftype\")\n local filetype = vim.api.nvim_buf_get_option(buf, \"filetype\")\n\n if buftype == \"terminal\" or buftype == \"prompt\" or filetype == \"neo-tree\" or filetype == \"ClaudeCode\" then\n vim.cmd(\"vsplit\")\n end\n\n target_window = vim.api.nvim_get_current_win()\n else\n vim.api.nvim_set_current_win(target_window)\n end\n\n local original_buffer\n if is_new_file then\n local empty_buffer = vim.api.nvim_create_buf(false, true)\n if not empty_buffer or empty_buffer == 0 then\n local error_msg = \"Failed to create empty buffer for new file diff\"\n logger.error(\"diff\", error_msg)\n error({\n code = -32000,\n message = \"Buffer creation failed\",\n data = error_msg,\n })\n end\n\n -- Set buffer properties with error handling\n local success, err = pcall(function()\n vim.api.nvim_buf_set_name(empty_buffer, old_file_path .. \" (NEW FILE)\")\n vim.api.nvim_buf_set_lines(empty_buffer, 0, -1, false, {})\n vim.api.nvim_buf_set_option(empty_buffer, \"buftype\", \"nofile\")\n vim.api.nvim_buf_set_option(empty_buffer, \"modifiable\", false)\n vim.api.nvim_buf_set_option(empty_buffer, \"readonly\", true)\n end)\n\n if not success then\n pcall(vim.api.nvim_buf_delete, empty_buffer, { force = true })\n local error_msg = \"Failed to configure empty buffer: \" .. tostring(err)\n logger.error(\"diff\", error_msg)\n error({\n code = -32000,\n message = \"Buffer configuration failed\",\n data = error_msg,\n })\n end\n\n vim.api.nvim_win_set_buf(target_window, empty_buffer)\n original_buffer = empty_buffer\n else\n vim.cmd(\"edit \" .. vim.fn.fnameescape(old_file_path))\n original_buffer = vim.api.nvim_win_get_buf(target_window)\n end\n\n vim.cmd(\"diffthis\")\n\n vim.cmd(\"vsplit\")\n local new_win = vim.api.nvim_get_current_win()\n vim.api.nvim_win_set_buf(new_win, new_buffer)\n\n -- Ensure new buffer inherits filetype from original for syntax highlighting (#20)\n local original_ft = detect_filetype(old_file_path, original_buffer)\n if original_ft and original_ft ~= \"\" then\n vim.api.nvim_set_option_value(\"filetype\", original_ft, { buf = new_buffer })\n end\n vim.cmd(\"diffthis\")\n\n vim.cmd(\"wincmd =\")\n vim.api.nvim_set_current_win(new_win)\n\n -- Store diff context in buffer variables for user commands\n vim.b[new_buffer].claudecode_diff_tab_name = tab_name\n vim.b[new_buffer].claudecode_diff_new_win = new_win\n vim.b[new_buffer].claudecode_diff_target_win = target_window\n\n -- Return window information for later storage\n return {\n new_window = new_win,\n target_window = target_window,\n original_buffer = original_buffer,\n }\nend\n\n--- Clean up diff state and resources\n-- @param tab_name string The diff identifier\n-- @param reason string Reason for cleanup\nfunction M._cleanup_diff_state(tab_name, reason)\n local diff_data = active_diffs[tab_name]\n if not diff_data then\n return\n end\n\n -- Clean up autocmds\n for _, autocmd_id in ipairs(diff_data.autocmd_ids or {}) do\n pcall(vim.api.nvim_del_autocmd, autocmd_id)\n end\n\n -- Clean up the new buffer only (not the old buffer which is the user's file)\n if diff_data.new_buffer and vim.api.nvim_buf_is_valid(diff_data.new_buffer) then\n pcall(vim.api.nvim_buf_delete, diff_data.new_buffer, { force = true })\n end\n\n -- Close new diff window if still open\n if diff_data.new_window and vim.api.nvim_win_is_valid(diff_data.new_window) then\n pcall(vim.api.nvim_win_close, diff_data.new_window, true)\n end\n\n -- Turn off diff mode in target window if it still exists\n if diff_data.target_window and vim.api.nvim_win_is_valid(diff_data.target_window) then\n vim.api.nvim_win_call(diff_data.target_window, function()\n vim.cmd(\"diffoff\")\n end)\n end\n\n -- Remove from active diffs\n active_diffs[tab_name] = nil\n\n logger.debug(\"diff\", \"Cleaned up diff state for\", tab_name, \"due to:\", reason)\nend\n\n--- Clean up all active diffs\n-- @param reason string Reason for cleanup\n-- NOTE: This will become a public closeAllDiffTabs tool in the future\nfunction M._cleanup_all_active_diffs(reason)\n for tab_name, _ in pairs(active_diffs) do\n M._cleanup_diff_state(tab_name, reason)\n end\nend\n\n--- Set up blocking diff operation with simpler approach\n-- @param params table Parameters for the diff\n-- @param resolution_callback function Callback to call when diff resolves\nfunction M._setup_blocking_diff(params, resolution_callback)\n local tab_name = params.tab_name\n logger.debug(\"diff\", \"Setting up diff for:\", params.old_file_path)\n\n -- Wrap the setup in error handling to ensure cleanup on failure\n local setup_success, setup_error = pcall(function()\n -- Step 1: Check if the file exists (allow new files)\n local old_file_exists = vim.fn.filereadable(params.old_file_path) == 1\n local is_new_file = not old_file_exists\n\n -- Step 2: Find if the file is already open in a buffer (only for existing files)\n local existing_buffer = nil\n local target_window = nil\n\n if old_file_exists then\n -- Look for existing buffer with this file\n for _, buf in ipairs(vim.api.nvim_list_bufs()) do\n if vim.api.nvim_buf_is_valid(buf) and vim.api.nvim_buf_is_loaded(buf) then\n local buf_name = vim.api.nvim_buf_get_name(buf)\n if buf_name == params.old_file_path then\n existing_buffer = buf\n break\n end\n end\n end\n\n -- Find window containing this buffer (if any)\n if existing_buffer then\n for _, win in ipairs(vim.api.nvim_list_wins()) do\n if vim.api.nvim_win_get_buf(win) == existing_buffer then\n target_window = win\n break\n end\n end\n end\n end\n\n -- If no existing buffer/window, find a suitable main editor window\n if not target_window then\n target_window = find_main_editor_window()\n end\n\n -- Step 3: Create scratch buffer for new content\n local new_buffer = vim.api.nvim_create_buf(false, true) -- unlisted, scratch\n if new_buffer == 0 then\n error({\n code = -32000,\n message = \"Buffer creation failed\",\n data = \"Could not create new content buffer\",\n })\n end\n\n local new_unique_name = is_new_file and (tab_name .. \" (NEW FILE - proposed)\") or (tab_name .. \" (proposed)\")\n vim.api.nvim_buf_set_name(new_buffer, new_unique_name)\n local lines = vim.split(params.new_file_contents, \"\\n\")\n -- Remove trailing empty line if content ended with \\n\n if #lines > 0 and lines[#lines] == \"\" then\n table.remove(lines, #lines)\n end\n vim.api.nvim_buf_set_lines(new_buffer, 0, -1, false, lines)\n\n vim.api.nvim_buf_set_option(new_buffer, \"buftype\", \"acwrite\") -- Allows saving but stays as scratch-like\n vim.api.nvim_buf_set_option(new_buffer, \"modifiable\", true)\n\n -- Step 4: Set up diff view using the target window\n local diff_info =\n M._create_diff_view_from_window(target_window, params.old_file_path, new_buffer, tab_name, is_new_file)\n\n -- Step 5: Register autocmds for user interaction monitoring\n local autocmd_ids = register_diff_autocmds(tab_name, new_buffer)\n\n -- Step 6: Store diff state\n\n -- Save the original cursor position before storing diff state\n local original_cursor_pos = nil\n if diff_info.target_window and vim.api.nvim_win_is_valid(diff_info.target_window) then\n original_cursor_pos = vim.api.nvim_win_get_cursor(diff_info.target_window)\n end\n\n M._register_diff_state(tab_name, {\n old_file_path = params.old_file_path,\n new_file_path = params.new_file_path,\n new_file_contents = params.new_file_contents,\n new_buffer = new_buffer,\n new_window = diff_info.new_window,\n target_window = diff_info.target_window,\n original_buffer = diff_info.original_buffer,\n original_cursor_pos = original_cursor_pos,\n autocmd_ids = autocmd_ids,\n created_at = vim.fn.localtime(),\n status = \"pending\",\n resolution_callback = resolution_callback,\n result_content = nil,\n is_new_file = is_new_file,\n })\n end) -- End of pcall\n\n -- Handle setup errors\n if not setup_success then\n local error_msg = \"Failed to setup diff operation: \" .. tostring(setup_error)\n logger.error(\"diff\", error_msg)\n\n -- Clean up any partial state that might have been created\n if active_diffs[tab_name] then\n M._cleanup_diff_state(tab_name, \"setup failed\")\n end\n\n -- Re-throw the error for MCP compliance\n error({\n code = -32000,\n message = \"Diff setup failed\",\n data = error_msg,\n })\n end\nend\n\n--- Blocking diff operation for MCP compliance\n-- @param old_file_path string Path to the original file\n-- @param new_file_path string Path to the new file (used for naming)\n-- @param new_file_contents string Contents of the new file\n-- @param tab_name string Name for the diff tab/view\n-- @return table MCP-compliant response with content array\nfunction M.open_diff_blocking(old_file_path, new_file_path, new_file_contents, tab_name)\n -- Check for existing diff with same tab_name\n if active_diffs[tab_name] then\n -- Resolve the existing diff as rejected before replacing\n M._resolve_diff_as_rejected(tab_name)\n end\n\n -- Set up blocking diff operation\n local co = coroutine.running()\n if not co then\n error({\n code = -32000,\n message = \"Internal server error\",\n data = \"openDiff must run in coroutine context\",\n })\n end\n\n logger.debug(\"diff\", \"Starting diff setup for\", tab_name)\n\n -- Use native diff implementation\n local success, err = pcall(M._setup_blocking_diff, {\n old_file_path = old_file_path,\n new_file_path = new_file_path,\n new_file_contents = new_file_contents,\n tab_name = tab_name,\n }, function(result)\n -- Resume the coroutine with the result\n local resume_success, resume_result = coroutine.resume(co, result)\n if resume_success then\n -- Use the global response sender to avoid module reloading issues\n local co_key = tostring(co)\n if _G.claude_deferred_responses and _G.claude_deferred_responses[co_key] then\n _G.claude_deferred_responses[co_key](resume_result)\n _G.claude_deferred_responses[co_key] = nil\n else\n logger.error(\"diff\", \"No global response sender found for coroutine:\", co_key)\n end\n else\n logger.error(\"diff\", \"Coroutine failed:\", tostring(resume_result))\n local co_key = tostring(co)\n if _G.claude_deferred_responses and _G.claude_deferred_responses[co_key] then\n _G.claude_deferred_responses[co_key]({\n error = {\n code = -32603,\n message = \"Internal error\",\n data = \"Coroutine failed: \" .. tostring(resume_result),\n },\n })\n _G.claude_deferred_responses[co_key] = nil\n end\n end\n end)\n\n if not success then\n logger.error(\"diff\", \"Diff setup failed for\", tab_name, \"error:\", tostring(err))\n -- If the error is already structured, propagate it directly\n if type(err) == \"table\" and err.code then\n error(err)\n else\n error({\n code = -32000,\n message = \"Error setting up diff\",\n data = tostring(err),\n })\n end\n end\n\n -- Yield and wait indefinitely for user interaction - the resolve functions will resume us\n local user_action_result = coroutine.yield()\n logger.debug(\"diff\", \"User action completed for\", tab_name)\n\n -- Return the result directly - this will be sent by the deferred response system\n return user_action_result\nend\n\n-- Set up global autocmds for shutdown handling\nvim.api.nvim_create_autocmd(\"VimLeavePre\", {\n group = get_autocmd_group(),\n callback = function()\n M._cleanup_all_active_diffs(\"shutdown\")\n end,\n})\n\n--- Close diff by tab name (used by close_tab tool)\n-- @param tab_name string The diff identifier\n-- @return boolean success True if diff was found and closed\nfunction M.close_diff_by_tab_name(tab_name)\n local diff_data = active_diffs[tab_name]\n if not diff_data then\n return false\n end\n\n -- If the diff was already saved, reload file buffers and clean up\n if diff_data.status == \"saved\" then\n -- Claude Code CLI has written the file, reload any open buffers\n if diff_data.old_file_path then\n -- Add a small delay to ensure Claude CLI has finished writing the file\n vim.defer_fn(function()\n M.reload_file_buffers_manual(diff_data.old_file_path, diff_data.original_cursor_pos)\n end, 100) -- 100ms delay\n end\n M._cleanup_diff_state(tab_name, \"diff tab closed after save\")\n return true\n end\n\n -- If still pending, treat as rejection\n if diff_data.status == \"pending\" then\n M._resolve_diff_as_rejected(tab_name)\n return true\n end\n\n return false\nend\n\n-- Test helper function (only for testing)\nfunction M._get_active_diffs()\n return active_diffs\nend\n\n-- Manual buffer reload function for testing/debugging\nfunction M.reload_file_buffers_manual(file_path, original_cursor_pos)\n return reload_file_buffers(file_path, original_cursor_pos)\nend\n\n--- Accept the current diff (user command version)\n-- This function reads the diff context from buffer variables\nfunction M.accept_current_diff()\n local current_buffer = vim.api.nvim_get_current_buf()\n local tab_name = vim.b[current_buffer].claudecode_diff_tab_name\n\n if not tab_name then\n vim.notify(\"No active diff found in current buffer\", vim.log.levels.WARN)\n return\n end\n\n M._resolve_diff_as_saved(tab_name, current_buffer)\nend\n\n--- Deny/reject the current diff (user command version)\n-- This function reads the diff context from buffer variables\nfunction M.deny_current_diff()\n local current_buffer = vim.api.nvim_get_current_buf()\n local tab_name = vim.b[current_buffer].claudecode_diff_tab_name\n local new_win = vim.b[current_buffer].claudecode_diff_new_win\n local target_window = vim.b[current_buffer].claudecode_diff_target_win\n\n if not tab_name then\n vim.notify(\"No active diff found in current buffer\", vim.log.levels.WARN)\n return\n end\n\n -- Close windows and clean up (same logic as the original keymap)\n if new_win and vim.api.nvim_win_is_valid(new_win) then\n vim.api.nvim_win_close(new_win, true)\n end\n if target_window and vim.api.nvim_win_is_valid(target_window) then\n vim.api.nvim_set_current_win(target_window)\n vim.cmd(\"diffoff\")\n end\n\n M._resolve_diff_as_rejected(tab_name)\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/selection.lua", "---\n-- Manages selection tracking and communication with the Claude server.\n-- @module claudecode.selection\nlocal M = {}\n\nlocal logger = require(\"claudecode.logger\")\nlocal terminal = require(\"claudecode.terminal\")\n\nM.state = {\n latest_selection = nil,\n tracking_enabled = false,\n debounce_timer = nil,\n debounce_ms = 100,\n\n last_active_visual_selection = nil,\n demotion_timer = nil,\n visual_demotion_delay_ms = 50,\n}\n\n--- Enables selection tracking.\n-- @param server table The server object to use for communication.\n-- @param visual_demotion_delay_ms number The delay for visual selection demotion.\nfunction M.enable(server, visual_demotion_delay_ms)\n if M.state.tracking_enabled then\n return\n end\n\n M.state.tracking_enabled = true\n M.server = server\n M.state.visual_demotion_delay_ms = visual_demotion_delay_ms\n\n M._create_autocommands()\nend\n\n--- Disables selection tracking.\n-- Clears autocommands, resets internal state, and stops any active debounce timers.\nfunction M.disable()\n if not M.state.tracking_enabled then\n return\n end\n\n M.state.tracking_enabled = false\n\n M._clear_autocommands()\n\n M.state.latest_selection = nil\n M.server = nil\n\n if M.state.debounce_timer then\n vim.loop.timer_stop(M.state.debounce_timer)\n M.state.debounce_timer = nil\n end\nend\n\n--- Creates autocommands for tracking selections.\n-- Sets up listeners for CursorMoved, CursorMovedI, ModeChanged, and TextChanged events.\n-- @local\nfunction M._create_autocommands()\n local group = vim.api.nvim_create_augroup(\"ClaudeCodeSelection\", { clear = true })\n\n vim.api.nvim_create_autocmd({ \"CursorMoved\", \"CursorMovedI\" }, {\n group = group,\n callback = function()\n M.on_cursor_moved()\n end,\n })\n\n vim.api.nvim_create_autocmd(\"ModeChanged\", {\n group = group,\n callback = function()\n M.on_mode_changed()\n end,\n })\n\n vim.api.nvim_create_autocmd(\"TextChanged\", {\n group = group,\n callback = function()\n M.on_text_changed()\n end,\n })\nend\n\n--- Clears the autocommands related to selection tracking.\n-- @local\nfunction M._clear_autocommands()\n vim.api.nvim_clear_autocmds({ group = \"ClaudeCodeSelection\" })\nend\n\n--- Handles cursor movement events.\n-- Triggers a debounced update of the selection.\nfunction M.on_cursor_moved()\n M.debounce_update()\nend\n\n--- Handles mode change events.\n-- Triggers an immediate update of the selection.\nfunction M.on_mode_changed()\n M.update_selection()\nend\n\n--- Handles text change events.\n-- Triggers a debounced update of the selection.\nfunction M.on_text_changed()\n M.debounce_update()\nend\n\n--- Debounces selection updates.\n-- Ensures that `update_selection` is not called too frequently by deferring\n-- its execution.\nfunction M.debounce_update()\n if M.state.debounce_timer then\n vim.loop.timer_stop(M.state.debounce_timer)\n end\n\n M.state.debounce_timer = vim.defer_fn(function()\n M.update_selection()\n M.state.debounce_timer = nil\n end, M.state.debounce_ms)\nend\n\n--- Updates the current selection state.\n-- Determines the current selection based on the editor mode (visual or normal)\n-- and sends an update to the server if the selection has changed.\nfunction M.update_selection()\n if not M.state.tracking_enabled then\n return\n end\n\n local current_buf = vim.api.nvim_get_current_buf()\n local buf_name = vim.api.nvim_buf_get_name(current_buf)\n\n -- If the buffer name starts with \"✻ [Claude Code]\", do not update selection\n if buf_name and string.sub(buf_name, 1, string.len(\"✻ [Claude Code]\")) == \"✻ [Claude Code]\" then\n -- Optionally, cancel demotion timer like for the terminal\n if M.state.demotion_timer then\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n M.state.demotion_timer = nil\n end\n return\n end\n\n -- If the current buffer is the Claude terminal, do not update selection\n if terminal then\n local claude_term_bufnr = terminal.get_active_terminal_bufnr()\n if claude_term_bufnr and current_buf == claude_term_bufnr then\n -- Cancel any pending demotion if we switch to the Claude terminal\n if M.state.demotion_timer then\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n M.state.demotion_timer = nil\n end\n return\n end\n end\n\n local current_mode_info = vim.api.nvim_get_mode()\n local current_mode = current_mode_info.mode\n local current_selection\n\n if current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\022\" then\n -- If a new visual selection is made, cancel any pending demotion\n if M.state.demotion_timer then\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n M.state.demotion_timer = nil\n end\n\n current_selection = M.get_visual_selection()\n\n if current_selection then\n M.state.last_active_visual_selection = {\n bufnr = current_buf,\n selection_data = vim.deepcopy(current_selection), -- Store a copy\n timestamp = vim.loop.now(),\n }\n else\n -- No valid visual selection (e.g., get_visual_selection returned nil)\n -- Clear last_active_visual if it was for this buffer\n if M.state.last_active_visual_selection and M.state.last_active_visual_selection.bufnr == current_buf then\n M.state.last_active_visual_selection = nil\n end\n end\n else\n local last_visual = M.state.last_active_visual_selection\n\n if M.state.demotion_timer then\n -- A demotion is already pending. For this specific update_selection call (e.g. cursor moved),\n -- current_selection reflects the immediate cursor position.\n -- M.state.latest_selection (the one that might be sent) is still the visual one until timer resolves.\n current_selection = M.get_cursor_position()\n elseif\n last_visual\n and last_visual.bufnr == current_buf\n and last_visual.selection_data\n and not last_visual.selection_data.selection.isEmpty\n then\n -- We just exited visual mode in this buffer, and no demotion timer is running for it.\n -- Keep M.state.latest_selection as is (it's the visual one from the previous update).\n -- The 'current_selection' for comparison should also be this visual one.\n current_selection = M.state.latest_selection\n\n if M.state.demotion_timer then -- Should not happen due to elseif, but as safeguard\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n end\n\n M.state.demotion_timer = vim.loop.new_timer()\n M.state.demotion_timer:start(\n M.state.visual_demotion_delay_ms,\n 0, -- 0 repeat = one-shot\n vim.schedule_wrap(function()\n if M.state.demotion_timer then -- Check if it wasn't cancelled right before firing\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n M.state.demotion_timer = nil\n end\n M.handle_selection_demotion(current_buf) -- Pass buffer at time of scheduling\n end)\n )\n else\n -- Genuinely in normal mode, no recent visual exit, no pending demotion.\n current_selection = M.get_cursor_position()\n if last_visual and last_visual.bufnr == current_buf then\n M.state.last_active_visual_selection = nil -- Clear it as it's no longer relevant for demotion\n end\n end\n end\n\n -- If current_selection could not be determined (e.g. get_visual_selection was nil and no other path set it)\n -- default to cursor position to avoid errors.\n if not current_selection then\n current_selection = M.get_cursor_position()\n end\n\n local changed = M.has_selection_changed(current_selection)\n\n if changed then\n M.state.latest_selection = current_selection\n if M.server then\n M.send_selection_update(current_selection)\n end\n end\nend\n\n--- Handles the demotion of a visual selection after a delay.\n-- Called by the demotion_timer.\n-- @param original_bufnr_when_scheduled number The buffer number that was active when demotion was scheduled.\nfunction M.handle_selection_demotion(original_bufnr_when_scheduled)\n -- Timer object is already stopped and cleared by its own callback wrapper or cancellation points.\n -- M.state.demotion_timer should be nil here if it fired normally or was cancelled.\n\n local current_buf = vim.api.nvim_get_current_buf()\n local claude_term_bufnr = terminal.get_active_terminal_bufnr()\n\n -- Condition 1: Switched to Claude Terminal\n if claude_term_bufnr and current_buf == claude_term_bufnr then\n -- Visual selection is preserved (M.state.latest_selection is still the visual one).\n -- The \"pending\" status of last_active_visual_selection is resolved.\n if\n M.state.last_active_visual_selection\n and M.state.last_active_visual_selection.bufnr == original_bufnr_when_scheduled\n then\n M.state.last_active_visual_selection = nil\n end\n return\n end\n\n local current_mode_info = vim.api.nvim_get_mode()\n\n -- Condition 2: Back in Visual Mode in the Original Buffer\n if\n current_buf == original_bufnr_when_scheduled\n and (current_mode_info.mode == \"v\" or current_mode_info.mode == \"V\" or current_mode_info.mode == \"\\022\")\n then\n -- A new visual selection will take precedence. M.state.latest_selection will be updated by main flow.\n if\n M.state.last_active_visual_selection\n and M.state.last_active_visual_selection.bufnr == original_bufnr_when_scheduled\n then\n M.state.last_active_visual_selection = nil\n end\n return\n end\n\n -- Condition 3: Still in Original Buffer & Not Visual & Not Claude Term -> Demote\n if current_buf == original_bufnr_when_scheduled then\n local new_sel_for_demotion = M.get_cursor_position()\n -- Check if this new cursor position is actually different from the (visual) latest_selection\n if M.has_selection_changed(new_sel_for_demotion) then\n M.state.latest_selection = new_sel_for_demotion\n if M.server then\n M.send_selection_update(M.state.latest_selection)\n end\n end\n -- No change detected in selection\n end\n -- User switched to different buffer\n\n -- Always clear last_active_visual_selection for the original buffer as its pending demotion is resolved.\n if\n M.state.last_active_visual_selection\n and M.state.last_active_visual_selection.bufnr == original_bufnr_when_scheduled\n then\n M.state.last_active_visual_selection = nil\n end\nend\n\n--- Validates if we're in a valid visual selection mode\n-- @return boolean, string|nil - true if valid, false and error message if not\nlocal function validate_visual_mode()\n local current_nvim_mode = vim.api.nvim_get_mode().mode\n local fixed_anchor_pos_raw = vim.fn.getpos(\"v\")\n\n if not (current_nvim_mode == \"v\" or current_nvim_mode == \"V\" or current_nvim_mode == \"\\22\") then\n return false, \"not in visual mode\"\n end\n\n if fixed_anchor_pos_raw[2] == 0 then\n return false, \"no visual selection mark\"\n end\n\n return true, nil\nend\n\n--- Determines the effective visual mode character\n-- @return string|nil - the visual mode character or nil if invalid\nlocal function get_effective_visual_mode()\n local current_nvim_mode = vim.api.nvim_get_mode().mode\n local visual_fn_mode_char = vim.fn.visualmode()\n\n if visual_fn_mode_char and visual_fn_mode_char ~= \"\" then\n return visual_fn_mode_char\n end\n\n -- Fallback to current mode\n if current_nvim_mode == \"V\" then\n return \"V\"\n elseif current_nvim_mode == \"v\" then\n return \"v\"\n elseif current_nvim_mode == \"\\22\" then -- Ctrl-V, blockwise\n return \"\\22\"\n end\n\n return nil\nend\n\n--- Gets the start and end coordinates of the visual selection\n-- @return table, table - start_coords and end_coords with lnum and col fields\nlocal function get_selection_coordinates()\n local fixed_anchor_pos_raw = vim.fn.getpos(\"v\")\n local current_cursor_nvim = vim.api.nvim_win_get_cursor(0)\n\n -- Convert to 1-indexed line and 1-indexed column for consistency\n local p1 = { lnum = fixed_anchor_pos_raw[2], col = fixed_anchor_pos_raw[3] }\n local p2 = { lnum = current_cursor_nvim[1], col = current_cursor_nvim[2] + 1 }\n\n -- Determine chronological start/end based on line, then column\n if p1.lnum < p2.lnum or (p1.lnum == p2.lnum and p1.col <= p2.col) then\n return p1, p2\n else\n return p2, p1\n end\nend\n\n--- Extracts text for linewise visual selection\n-- @param lines_content table - array of line strings\n-- @param start_coords table - start coordinates\n-- @return string - the extracted text\nlocal function extract_linewise_text(lines_content, start_coords)\n start_coords.col = 1 -- Linewise selection effectively starts at column 1\n return table.concat(lines_content, \"\\n\")\nend\n\n--- Extracts text for characterwise visual selection\n-- @param lines_content table - array of line strings\n-- @param start_coords table - start coordinates\n-- @param end_coords table - end coordinates\n-- @return string|nil - the extracted text or nil if invalid\nlocal function extract_characterwise_text(lines_content, start_coords, end_coords)\n if start_coords.lnum == end_coords.lnum then\n if not lines_content[1] then\n return nil\n end\n return string.sub(lines_content[1], start_coords.col, end_coords.col)\n else\n if not lines_content[1] or not lines_content[#lines_content] then\n return nil\n end\n\n local text_parts = {}\n table.insert(text_parts, string.sub(lines_content[1], start_coords.col))\n for i = 2, #lines_content - 1 do\n table.insert(text_parts, lines_content[i])\n end\n table.insert(text_parts, string.sub(lines_content[#lines_content], 1, end_coords.col))\n return table.concat(text_parts, \"\\n\")\n end\nend\n\n--- Calculates LSP-compatible position coordinates\n-- @param start_coords table - start coordinates\n-- @param end_coords table - end coordinates\n-- @param visual_mode string - the visual mode character\n-- @param lines_content table - array of line strings\n-- @return table - LSP position object with start and end fields\nlocal function calculate_lsp_positions(start_coords, end_coords, visual_mode, lines_content)\n local lsp_start_line = start_coords.lnum - 1\n local lsp_end_line = end_coords.lnum - 1\n local lsp_start_char, lsp_end_char\n\n if visual_mode == \"V\" then\n lsp_start_char = 0 -- Linewise selection always starts at character 0\n -- For linewise, LSP end char is length of the last selected line\n if #lines_content > 0 and lines_content[#lines_content] then\n lsp_end_char = #lines_content[#lines_content]\n else\n lsp_end_char = 0\n end\n else\n lsp_start_char = start_coords.col - 1\n lsp_end_char = end_coords.col\n end\n\n return {\n start = { line = lsp_start_line, character = lsp_start_char },\n [\"end\"] = { line = lsp_end_line, character = lsp_end_char },\n }\nend\n\n--- Gets the current visual selection details.\n-- @return table|nil A table containing selection text, file path, URL, and\n-- start/end positions, or nil if no visual selection exists.\nfunction M.get_visual_selection()\n local valid = validate_visual_mode()\n if not valid then\n return nil\n end\n\n local visual_mode = get_effective_visual_mode()\n if not visual_mode then\n return nil\n end\n\n local start_coords, end_coords = get_selection_coordinates()\n\n local current_buf = vim.api.nvim_get_current_buf()\n local file_path = vim.api.nvim_buf_get_name(current_buf)\n\n local lines_content = vim.api.nvim_buf_get_lines(\n current_buf,\n start_coords.lnum - 1, -- Convert to 0-indexed\n end_coords.lnum, -- nvim_buf_get_lines end is exclusive\n false\n )\n\n if #lines_content == 0 then\n return nil\n end\n\n local final_text\n if visual_mode == \"V\" then\n final_text = extract_linewise_text(lines_content, start_coords)\n elseif visual_mode == \"v\" or visual_mode == \"\\22\" then\n final_text = extract_characterwise_text(lines_content, start_coords, end_coords)\n if not final_text then\n return nil\n end\n else\n return nil\n end\n\n local lsp_positions = calculate_lsp_positions(start_coords, end_coords, visual_mode, lines_content)\n\n return {\n text = final_text or \"\",\n filePath = file_path,\n fileUrl = \"file://\" .. file_path,\n selection = {\n start = lsp_positions.start,\n [\"end\"] = lsp_positions[\"end\"],\n isEmpty = (not final_text or #final_text == 0),\n },\n }\nend\n\n--- Gets the current cursor position when no visual selection is active.\n-- @return table A table containing an empty text, file path, URL, and cursor\n-- position as start/end, with isEmpty set to true.\nfunction M.get_cursor_position()\n local cursor_pos = vim.api.nvim_win_get_cursor(0)\n local current_buf = vim.api.nvim_get_current_buf()\n local file_path = vim.api.nvim_buf_get_name(current_buf)\n\n return {\n text = \"\",\n filePath = file_path,\n fileUrl = \"file://\" .. file_path,\n selection = {\n start = { line = cursor_pos[1] - 1, character = cursor_pos[2] },\n [\"end\"] = { line = cursor_pos[1] - 1, character = cursor_pos[2] },\n isEmpty = true,\n },\n }\nend\n\n--- Checks if the selection has changed compared to the latest stored selection.\n-- @param new_selection table|nil The new selection object to compare.\n-- @return boolean true if the selection has changed, false otherwise.\nfunction M.has_selection_changed(new_selection)\n local old_selection = M.state.latest_selection\n\n if not new_selection then\n return old_selection ~= nil\n end\n\n if not old_selection then\n return true\n end\n\n if old_selection.filePath ~= new_selection.filePath then\n return true\n end\n\n if old_selection.text ~= new_selection.text then\n return true\n end\n\n if\n old_selection.selection.start.line ~= new_selection.selection.start.line\n or old_selection.selection.start.character ~= new_selection.selection.start.character\n or old_selection.selection[\"end\"].line ~= new_selection.selection[\"end\"].line\n or old_selection.selection[\"end\"].character ~= new_selection.selection[\"end\"].character\n then\n return true\n end\n\n return false\nend\n\n--- Sends the selection update to the Claude server.\n-- @param selection table The selection object to send.\nfunction M.send_selection_update(selection)\n M.server.broadcast(\"selection_changed\", selection)\nend\n\n--- Gets the latest recorded selection.\n-- @return table|nil The latest selection object, or nil if none recorded.\nfunction M.get_latest_selection()\n return M.state.latest_selection\nend\n\n--- Sends the current selection to Claude.\n-- This function is typically invoked by a user command. It forces an immediate\n-- update and sends the latest selection.\nfunction M.send_current_selection()\n if not M.state.tracking_enabled or not M.server then\n logger.error(\"selection\", \"Claude Code is not running\")\n return\n end\n\n M.update_selection()\n\n local selection = M.state.latest_selection\n\n if not selection then\n logger.error(\"selection\", \"No selection available\")\n return\n end\n\n M.send_selection_update(selection)\n\n vim.api.nvim_echo({ { \"Selection sent to Claude\", \"Normal\" } }, false, {})\nend\n\n--- Gets selection from range marks (e.g., when using :'<,'> commands)\n-- @param line1 number The start line (1-indexed)\n-- @param line2 number The end line (1-indexed)\n-- @return table|nil A table containing selection text, file path, URL, and\n-- start/end positions, or nil if invalid range\nfunction M.get_range_selection(line1, line2)\n if not line1 or not line2 or line1 < 1 or line2 < 1 or line1 > line2 then\n return nil\n end\n\n local current_buf = vim.api.nvim_get_current_buf()\n local file_path = vim.api.nvim_buf_get_name(current_buf)\n\n -- Get the total number of lines in the buffer\n local total_lines = vim.api.nvim_buf_line_count(current_buf)\n\n -- Ensure line2 doesn't exceed buffer bounds\n if line2 > total_lines then\n line2 = total_lines\n end\n\n local lines_content = vim.api.nvim_buf_get_lines(\n current_buf,\n line1 - 1, -- Convert to 0-indexed\n line2, -- nvim_buf_get_lines end is exclusive\n false\n )\n\n if #lines_content == 0 then\n return nil\n end\n\n local final_text = table.concat(lines_content, \"\\n\")\n\n -- For range selections, we treat them as linewise\n local lsp_start_line = line1 - 1 -- Convert to 0-indexed\n local lsp_end_line = line2 - 1\n local lsp_start_char = 0\n local lsp_end_char = #lines_content[#lines_content]\n\n return {\n text = final_text or \"\",\n filePath = file_path,\n fileUrl = \"file://\" .. file_path,\n selection = {\n start = { line = lsp_start_line, character = lsp_start_char },\n [\"end\"] = { line = lsp_end_line, character = lsp_end_char },\n isEmpty = (not final_text or #final_text == 0),\n },\n }\nend\n\n--- Sends an at_mentioned notification for the current visual selection.\n-- @param line1 number|nil Optional start line for range-based selection\n-- @param line2 number|nil Optional end line for range-based selection\nfunction M.send_at_mention_for_visual_selection(line1, line2)\n if not M.state.tracking_enabled then\n logger.error(\"selection\", \"Selection tracking is not enabled.\")\n return false\n end\n\n -- Check if Claude Code integration is running (server may or may not have clients)\n local claudecode_main = require(\"claudecode\")\n if not claudecode_main.state.server then\n logger.error(\"selection\", \"Claude Code integration is not running.\")\n return false\n end\n\n local sel_to_send\n\n -- If range parameters are provided, use them (for :'<,'> commands)\n if line1 and line2 then\n sel_to_send = M.get_range_selection(line1, line2)\n if not sel_to_send or sel_to_send.selection.isEmpty then\n logger.warn(\"selection\", \"Invalid range selection to send as at-mention.\")\n return false\n end\n else\n -- Use existing logic for visual mode or tracked selection\n sel_to_send = M.state.latest_selection\n\n if not sel_to_send or sel_to_send.selection.isEmpty then\n -- Fallback: try to get current visual selection directly.\n -- This helps if latest_selection was demoted or command was too fast.\n local current_visual = M.get_visual_selection()\n if current_visual and not current_visual.selection.isEmpty then\n sel_to_send = current_visual\n else\n logger.warn(\"selection\", \"No visual selection to send as at-mention.\")\n return false\n end\n end\n end\n\n -- Sanity check: ensure the selection is for the current buffer\n local current_buf_name = vim.api.nvim_buf_get_name(vim.api.nvim_get_current_buf())\n if sel_to_send.filePath ~= current_buf_name then\n logger.warn(\n \"selection\",\n \"Tracked selection is for '\"\n .. sel_to_send.filePath\n .. \"', but current buffer is '\"\n .. current_buf_name\n .. \"'. Not sending.\"\n )\n return false\n end\n\n -- Use connection-aware broadcasting from main module\n local file_path = sel_to_send.filePath\n local start_line = sel_to_send.selection.start.line -- Already 0-indexed from selection module\n local end_line = sel_to_send.selection[\"end\"].line -- Already 0-indexed\n\n local success, error_msg = claudecode_main.send_at_mention(file_path, start_line, end_line, \"ClaudeCodeSend\")\n\n if success then\n logger.debug(\"selection\", \"Visual selection sent as at-mention.\")\n\n return true\n else\n logger.error(\"selection\", \"Failed to send at-mention: \" .. (error_msg or \"unknown error\"))\n return false\n end\nend\nreturn M\n"], ["/claudecode.nvim/dev-config.lua", "-- Development configuration for claudecode.nvim\n-- This is Thomas's personal config for developing claudecode.nvim\n-- Symlink this to your personal Neovim config:\n-- ln -s ~/projects/claudecode.nvim/dev-config.lua ~/.config/nvim/lua/plugins/dev-claudecode.lua\n\nreturn {\n \"coder/claudecode.nvim\",\n dev = true, -- Use local development version\n keys = {\n -- AI/Claude Code prefix\n { \"a\", nil, desc = \"AI/Claude Code\" },\n\n -- Core Claude commands\n { \"ac\", \"ClaudeCode\", desc = \"Toggle Claude\" },\n { \"af\", \"ClaudeCodeFocus\", desc = \"Focus Claude\" },\n { \"ar\", \"ClaudeCode --resume\", desc = \"Resume Claude\" },\n { \"aC\", \"ClaudeCode --continue\", desc = \"Continue Claude\" },\n\n -- Context sending\n { \"ab\", \"ClaudeCodeAdd %\", desc = \"Add current buffer\" },\n { \"as\", \"ClaudeCodeSend\", mode = \"v\", desc = \"Send to Claude\" },\n {\n \"as\",\n \"ClaudeCodeTreeAdd\",\n desc = \"Add file from tree\",\n ft = { \"NvimTree\", \"neo-tree\", \"oil\" },\n },\n\n -- Development helpers\n { \"ao\", \"ClaudeCodeOpen\", desc = \"Open Claude\" },\n { \"aq\", \"ClaudeCodeClose\", desc = \"Close Claude\" },\n { \"ai\", \"ClaudeCodeStatus\", desc = \"Claude Status\" },\n { \"aS\", \"ClaudeCodeStart\", desc = \"Start Claude Server\" },\n { \"aQ\", \"ClaudeCodeStop\", desc = \"Stop Claude Server\" },\n\n -- Diff management (buffer-local, only active in diff buffers)\n { \"aa\", \"ClaudeCodeDiffAccept\", desc = \"Accept diff\" },\n { \"ad\", \"ClaudeCodeDiffDeny\", desc = \"Deny diff\" },\n },\n\n -- Development configuration - all options shown with defaults commented out\n opts = {\n -- Server Configuration\n -- port_range = { min = 10000, max = 65535 }, -- WebSocket server port range\n -- auto_start = true, -- Auto-start server on Neovim startup\n -- log_level = \"info\", -- \"trace\", \"debug\", \"info\", \"warn\", \"error\"\n -- terminal_cmd = nil, -- Custom terminal command (default: \"claude\")\n\n -- Selection Tracking\n -- track_selection = true, -- Enable real-time selection tracking\n -- visual_demotion_delay_ms = 50, -- Delay before demoting visual selection (ms)\n\n -- Connection Management\n -- connection_wait_delay = 200, -- Wait time after connection before sending queued @ mentions (ms)\n -- connection_timeout = 10000, -- Max time to wait for Claude Code connection (ms)\n -- queue_timeout = 5000, -- Max time to keep @ mentions in queue (ms)\n\n -- Diff Integration\n -- diff_opts = {\n -- auto_close_on_accept = true, -- Close diff view after accepting changes\n -- show_diff_stats = true, -- Show diff statistics\n -- vertical_split = true, -- Use vertical split for diffs\n -- open_in_current_tab = true, -- Open diffs in current tab vs new tab\n -- },\n\n -- Terminal Configuration\n -- terminal = {\n -- split_side = \"right\", -- \"left\" or \"right\"\n -- split_width_percentage = 0.30, -- Width as percentage (0.0 to 1.0)\n -- provider = \"auto\", -- \"auto\", \"snacks\", or \"native\"\n -- show_native_term_exit_tip = true, -- Show exit tip for native terminal\n -- auto_close = true, -- Auto-close terminal after command completion\n -- },\n\n -- Development overrides (uncomment as needed)\n -- log_level = \"debug\",\n -- terminal = {\n -- provider = \"native\",\n -- auto_close = false, -- Keep terminals open to see output\n -- },\n },\n}\n"], ["/claudecode.nvim/lua/claudecode/config.lua", "--- Manages configuration for the Claude Code Neovim integration.\n-- Provides default settings, validation, and application of user-defined configurations.\nlocal M = {}\n\nM.defaults = {\n port_range = { min = 10000, max = 65535 },\n auto_start = true,\n terminal_cmd = nil,\n log_level = \"info\",\n track_selection = true,\n visual_demotion_delay_ms = 50, -- Milliseconds to wait before demoting a visual selection\n connection_wait_delay = 200, -- Milliseconds to wait after connection before sending queued @ mentions\n connection_timeout = 10000, -- Maximum time to wait for Claude Code to connect (milliseconds)\n queue_timeout = 5000, -- Maximum time to keep @ mentions in queue (milliseconds)\n diff_opts = {\n auto_close_on_accept = true,\n show_diff_stats = true,\n vertical_split = true,\n open_in_current_tab = true, -- Use current tab instead of creating new tab\n },\n}\n\n--- Validates the provided configuration table.\n-- @param config table The configuration table to validate.\n-- @return boolean true if the configuration is valid.\n-- @error string if any configuration option is invalid.\nfunction M.validate(config)\n assert(\n type(config.port_range) == \"table\"\n and type(config.port_range.min) == \"number\"\n and type(config.port_range.max) == \"number\"\n and config.port_range.min > 0\n and config.port_range.max <= 65535\n and config.port_range.min <= config.port_range.max,\n \"Invalid port range\"\n )\n\n assert(type(config.auto_start) == \"boolean\", \"auto_start must be a boolean\")\n\n assert(config.terminal_cmd == nil or type(config.terminal_cmd) == \"string\", \"terminal_cmd must be nil or a string\")\n\n local valid_log_levels = { \"trace\", \"debug\", \"info\", \"warn\", \"error\" }\n local is_valid_log_level = false\n for _, level in ipairs(valid_log_levels) do\n if config.log_level == level then\n is_valid_log_level = true\n break\n end\n end\n assert(is_valid_log_level, \"log_level must be one of: \" .. table.concat(valid_log_levels, \", \"))\n\n assert(type(config.track_selection) == \"boolean\", \"track_selection must be a boolean\")\n\n assert(\n type(config.visual_demotion_delay_ms) == \"number\" and config.visual_demotion_delay_ms >= 0,\n \"visual_demotion_delay_ms must be a non-negative number\"\n )\n\n assert(\n type(config.connection_wait_delay) == \"number\" and config.connection_wait_delay >= 0,\n \"connection_wait_delay must be a non-negative number\"\n )\n\n assert(\n type(config.connection_timeout) == \"number\" and config.connection_timeout > 0,\n \"connection_timeout must be a positive number\"\n )\n\n assert(type(config.queue_timeout) == \"number\" and config.queue_timeout > 0, \"queue_timeout must be a positive number\")\n\n assert(type(config.diff_opts) == \"table\", \"diff_opts must be a table\")\n assert(type(config.diff_opts.auto_close_on_accept) == \"boolean\", \"diff_opts.auto_close_on_accept must be a boolean\")\n assert(type(config.diff_opts.show_diff_stats) == \"boolean\", \"diff_opts.show_diff_stats must be a boolean\")\n assert(type(config.diff_opts.vertical_split) == \"boolean\", \"diff_opts.vertical_split must be a boolean\")\n assert(type(config.diff_opts.open_in_current_tab) == \"boolean\", \"diff_opts.open_in_current_tab must be a boolean\")\n\n return true\nend\n\n--- Applies user configuration on top of default settings and validates the result.\n-- @param user_config table|nil The user-provided configuration table.\n-- @return table The final, validated configuration table.\nfunction M.apply(user_config)\n local config = vim.deepcopy(M.defaults)\n\n if user_config then\n config = vim.tbl_deep_extend(\"force\", config, user_config)\n end\n\n M.validate(config)\n\n return config\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/logger.lua", "---@brief Centralized logger for Claude Code Neovim integration.\n-- Provides level-based logging.\nlocal M = {}\n\nM.levels = {\n ERROR = 1,\n WARN = 2,\n INFO = 3,\n DEBUG = 4,\n TRACE = 5,\n}\n\nlocal level_values = {\n error = M.levels.ERROR,\n warn = M.levels.WARN,\n info = M.levels.INFO,\n debug = M.levels.DEBUG,\n trace = M.levels.TRACE,\n}\n\nlocal current_log_level_value = M.levels.INFO\n\n--- @param plugin_config table The configuration table (e.g., from claudecode.init.state.config).\nfunction M.setup(plugin_config)\n local conf = plugin_config\n\n if conf and conf.log_level and level_values[conf.log_level] then\n current_log_level_value = level_values[conf.log_level]\n else\n vim.notify(\n \"ClaudeCode Logger: Invalid or missing log_level in configuration (received: \"\n .. tostring(conf and conf.log_level)\n .. \"). Defaulting to INFO.\",\n vim.log.levels.WARN\n )\n current_log_level_value = M.levels.INFO\n end\nend\n\nlocal function log(level, component, message_parts)\n if level > current_log_level_value then\n return\n end\n\n local prefix = \"[ClaudeCode]\"\n if component then\n prefix = prefix .. \" [\" .. component .. \"]\"\n end\n\n local level_name = \"UNKNOWN\"\n for name, val in pairs(M.levels) do\n if val == level then\n level_name = name\n break\n end\n end\n prefix = prefix .. \" [\" .. level_name .. \"]\"\n\n local message = \"\"\n for i, part in ipairs(message_parts) do\n if i > 1 then\n message = message .. \" \"\n end\n if type(part) == \"table\" or type(part) == \"boolean\" then\n message = message .. vim.inspect(part)\n else\n message = message .. tostring(part)\n end\n end\n\n if level == M.levels.ERROR then\n vim.schedule(function()\n vim.notify(prefix .. \" \" .. message, vim.log.levels.ERROR, { title = \"ClaudeCode Error\" })\n end)\n elseif level == M.levels.WARN then\n vim.schedule(function()\n vim.notify(prefix .. \" \" .. message, vim.log.levels.WARN, { title = \"ClaudeCode Warning\" })\n end)\n else\n -- For INFO, DEBUG, TRACE, use nvim_echo to avoid flooding notifications,\n -- to make them appear in :messages, and wrap in vim.schedule\n -- to avoid \"nvim_echo must not be called in a fast event context\".\n vim.schedule(function()\n vim.api.nvim_echo({ { prefix .. \" \" .. message, \"Normal\" } }, true, {})\n end)\n end\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.error(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.ERROR, nil, { component, ... })\n else\n log(M.levels.ERROR, component, { ... })\n end\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.warn(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.WARN, nil, { component, ... })\n else\n log(M.levels.WARN, component, { ... })\n end\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.info(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.INFO, nil, { component, ... })\n else\n log(M.levels.INFO, component, { ... })\n end\nend\n\n--- Check if a specific log level is enabled\n-- @param level_name string The level name (\"error\", \"warn\", \"info\", \"debug\", \"trace\")\n-- @return boolean Whether the level is enabled\nfunction M.is_level_enabled(level_name)\n local level_value = level_values[level_name]\n if not level_value then\n return false\n end\n return level_value <= current_log_level_value\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.debug(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.DEBUG, nil, { component, ... })\n else\n log(M.levels.DEBUG, component, { ... })\n end\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.trace(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.TRACE, nil, { component, ... })\n else\n log(M.levels.TRACE, component, { ... })\n end\nend\n\nlocal default_config_for_initial_setup = require(\"claudecode.config\").defaults\nM.setup(default_config_for_initial_setup)\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/visual_commands.lua", "---\n-- Visual command handling module for ClaudeCode.nvim\n-- Implements neo-tree-style visual mode exit and command processing\n-- @module claudecode.visual_commands\nlocal M = {}\n\n--- Get current vim mode with fallback for test environments\n--- @param full_mode boolean|nil Whether to get full mode info (passed to vim.fn.mode)\n--- @return string current_mode The current vim mode\nlocal function get_current_mode(full_mode)\n local current_mode = \"n\" -- Default fallback\n\n pcall(function()\n if vim.api and vim.api.nvim_get_mode then\n current_mode = vim.api.nvim_get_mode().mode\n else\n current_mode = vim.fn.mode(full_mode)\n end\n end)\n\n return current_mode\nend\n\n-- ESC key constant matching neo-tree's implementation\nlocal ESC_KEY\nlocal success = pcall(function()\n ESC_KEY = vim.api.nvim_replace_termcodes(\"\", true, false, true)\nend)\nif not success then\n ESC_KEY = \"\\27\"\nend\n\n--- Exit visual mode properly and schedule command execution\n--- @param callback function The function to call after exiting visual mode\n--- @param ... any Arguments to pass to the callback\nfunction M.exit_visual_and_schedule(callback, ...)\n local args = { ... }\n\n -- Capture visual selection data BEFORE exiting visual mode\n local visual_data = M.capture_visual_selection_data()\n\n pcall(function()\n vim.api.nvim_feedkeys(ESC_KEY, \"i\", true)\n end)\n\n -- Schedule execution until after mode change (neo-tree pattern)\n local schedule_fn = vim.schedule or function(fn)\n fn()\n end -- Fallback for test environments\n schedule_fn(function()\n -- Pass the captured visual data as the first argument\n callback(visual_data, unpack(args))\n end)\nend\n\n--- Validate that we're currently in a visual mode\n--- @return boolean true if in visual mode, false otherwise\n--- @return string|nil error message if not in visual mode\nfunction M.validate_visual_mode()\n local current_mode = get_current_mode(true)\n\n local is_visual = current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\022\"\n\n -- Additional debugging: check visual marks and cursor position\n if is_visual then\n pcall(function()\n vim.api.nvim_win_get_cursor(0)\n vim.fn.getpos(\"'<\")\n vim.fn.getpos(\"'>\")\n vim.fn.getpos(\"v\")\n end)\n end\n\n if not is_visual then\n return false, \"Not in visual mode (current mode: \" .. current_mode .. \")\"\n end\n\n return true, nil\nend\n\n--- Get visual selection range using vim marks or current cursor position\n--- @return number, number start_line, end_line (1-indexed)\nfunction M.get_visual_range()\n local start_pos, end_pos = 1, 1 -- Default fallback\n\n -- Use pcall to handle test environments\n local range_success = pcall(function()\n -- Check if we're currently in visual mode\n local current_mode = get_current_mode(true)\n local is_visual = current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\022\"\n\n if is_visual then\n -- In visual mode, ALWAYS use cursor + anchor (marks are stale until exit)\n local cursor_pos = vim.api.nvim_win_get_cursor(0)[1]\n local anchor_pos = vim.fn.getpos(\"v\")[2]\n\n if anchor_pos > 0 then\n start_pos = math.min(cursor_pos, anchor_pos)\n end_pos = math.max(cursor_pos, anchor_pos)\n else\n -- Fallback: just use current cursor position\n start_pos = cursor_pos\n end_pos = cursor_pos\n end\n else\n -- Not in visual mode, try to use the marks (they should be valid now)\n local mark_start = vim.fn.getpos(\"'<\")[2]\n local mark_end = vim.fn.getpos(\"'>\")[2]\n\n if mark_start > 0 and mark_end > 0 then\n start_pos = mark_start\n end_pos = mark_end\n else\n -- No valid marks, use cursor position\n local cursor_pos = vim.api.nvim_win_get_cursor(0)[1]\n start_pos = cursor_pos\n end_pos = cursor_pos\n end\n end\n end)\n\n if not range_success then\n return 1, 1\n end\n\n if end_pos < start_pos then\n start_pos, end_pos = end_pos, start_pos\n end\n\n -- Ensure we have valid line numbers (at least 1)\n start_pos = math.max(1, start_pos)\n end_pos = math.max(1, end_pos)\n\n return start_pos, end_pos\nend\n\n--- Check if we're in a tree buffer and get the tree state\n--- @return table|nil, string|nil tree_state, tree_type (\"neo-tree\" or \"nvim-tree\")\nfunction M.get_tree_state()\n local current_ft = \"\" -- Default fallback\n local current_win = 0 -- Default fallback\n\n -- Use pcall to handle test environments\n local state_success = pcall(function()\n current_ft = vim.bo.filetype or \"\"\n current_win = vim.api.nvim_get_current_win()\n end)\n\n if not state_success then\n return nil, nil\n end\n\n if current_ft == \"neo-tree\" then\n local manager_success, manager = pcall(require, \"neo-tree.sources.manager\")\n if not manager_success then\n return nil, nil\n end\n\n local state = manager.get_state(\"filesystem\")\n if not state then\n return nil, nil\n end\n\n -- Validate we're in the correct neo-tree window\n if state.winid and state.winid == current_win then\n return state, \"neo-tree\"\n else\n return nil, nil\n end\n elseif current_ft == \"NvimTree\" then\n local api_success, nvim_tree_api = pcall(require, \"nvim-tree.api\")\n if not api_success then\n return nil, nil\n end\n\n return nvim_tree_api, \"nvim-tree\"\n elseif current_ft == \"oil\" then\n local oil_success, oil = pcall(require, \"oil\")\n if not oil_success then\n return nil, nil\n end\n\n return oil, \"oil\"\n else\n return nil, nil\n end\nend\n\n--- Create a visual command wrapper that follows neo-tree patterns\n--- @param normal_handler function The normal command handler\n--- @param visual_handler function The visual command handler\n--- @return function The wrapped command function\nfunction M.create_visual_command_wrapper(normal_handler, visual_handler)\n return function(...)\n local current_mode = get_current_mode(true)\n\n if current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\022\" then\n -- Use the neo-tree pattern: exit visual mode, then schedule execution\n M.exit_visual_and_schedule(visual_handler, ...)\n else\n normal_handler(...)\n end\n end\nend\n\n--- Capture visual selection data while still in visual mode\n--- @return table|nil visual_data Captured data or nil if not in visual mode\nfunction M.capture_visual_selection_data()\n local valid = M.validate_visual_mode()\n if not valid then\n return nil\n end\n\n local tree_state, tree_type = M.get_tree_state()\n if not tree_state then\n return nil\n end\n\n local start_pos, end_pos = M.get_visual_range()\n\n -- Validate that we have a meaningful range\n if start_pos == 0 or end_pos == 0 then\n return nil\n end\n\n return {\n tree_state = tree_state,\n tree_type = tree_type,\n start_pos = start_pos,\n end_pos = end_pos,\n }\nend\n\n--- Extract files from visual selection in tree buffers\n--- @param visual_data table|nil Pre-captured visual selection data\n--- @return table files List of file paths\n--- @return string|nil error Error message if failed\nfunction M.get_files_from_visual_selection(visual_data)\n -- If we have pre-captured data, use it; otherwise try to get current data\n local tree_state, tree_type, start_pos, end_pos\n\n if visual_data then\n tree_state = visual_data.tree_state\n tree_type = visual_data.tree_type\n start_pos = visual_data.start_pos\n end_pos = visual_data.end_pos\n else\n local valid, err = M.validate_visual_mode()\n if not valid then\n return {}, err\n end\n\n tree_state, tree_type = M.get_tree_state()\n if not tree_state then\n return {}, \"Not in a supported tree buffer\"\n end\n\n start_pos, end_pos = M.get_visual_range()\n end\n\n if not tree_state then\n return {}, \"Not in a supported tree buffer\"\n end\n\n local files = {}\n\n if tree_type == \"neo-tree\" then\n local selected_nodes = {}\n for line = start_pos, end_pos do\n -- Neo-tree's tree:get_node() uses the line number directly (1-based)\n local node = tree_state.tree:get_node(line)\n if node then\n if node.type and node.type ~= \"message\" then\n table.insert(selected_nodes, node)\n end\n end\n end\n\n for _, node in ipairs(selected_nodes) do\n if node.type == \"file\" and node.path and node.path ~= \"\" then\n local depth = (node.get_depth and node:get_depth()) or 0\n if depth > 1 then\n table.insert(files, node.path)\n end\n elseif node.type == \"directory\" and node.path and node.path ~= \"\" then\n local depth = (node.get_depth and node:get_depth()) or 0\n if depth > 1 then\n table.insert(files, node.path)\n end\n end\n end\n elseif tree_type == \"nvim-tree\" then\n -- For nvim-tree, we need to manually map visual lines to tree nodes\n -- since nvim-tree doesn't have direct line-to-node mapping like neo-tree\n require(\"claudecode.logger\").debug(\n \"visual_commands\",\n \"Processing nvim-tree visual selection from line\",\n start_pos,\n \"to\",\n end_pos\n )\n\n local nvim_tree_api = tree_state\n local current_buf = vim.api.nvim_get_current_buf()\n\n -- Get all lines in the visual selection\n local lines = vim.api.nvim_buf_get_lines(current_buf, start_pos - 1, end_pos, false)\n\n require(\"claudecode.logger\").debug(\"visual_commands\", \"Found\", #lines, \"lines in visual selection\")\n\n -- For each line in the visual selection, try to get the corresponding node\n for i, line_content in ipairs(lines) do\n local line_num = start_pos + i - 1\n\n -- Set cursor to this line to get the node\n pcall(vim.api.nvim_win_set_cursor, 0, { line_num, 0 })\n\n -- Get node under cursor for this line\n local node_success, node = pcall(nvim_tree_api.tree.get_node_under_cursor)\n if node_success and node then\n require(\"claudecode.logger\").debug(\n \"visual_commands\",\n \"Line\",\n line_num,\n \"node type:\",\n node.type,\n \"path:\",\n node.absolute_path\n )\n\n if node.type == \"file\" and node.absolute_path and node.absolute_path ~= \"\" then\n -- Check if it's not a root-level file (basic protection)\n if not string.match(node.absolute_path, \"^/[^/]*$\") then\n table.insert(files, node.absolute_path)\n end\n elseif node.type == \"directory\" and node.absolute_path and node.absolute_path ~= \"\" then\n table.insert(files, node.absolute_path)\n end\n else\n require(\"claudecode.logger\").debug(\"visual_commands\", \"No valid node found for line\", line_num)\n end\n end\n\n require(\"claudecode.logger\").debug(\"visual_commands\", \"Extracted\", #files, \"files from nvim-tree visual selection\")\n\n -- Remove duplicates while preserving order\n local seen = {}\n local unique_files = {}\n for _, file_path in ipairs(files) do\n if not seen[file_path] then\n seen[file_path] = true\n table.insert(unique_files, file_path)\n end\n end\n files = unique_files\n elseif tree_type == \"oil\" then\n local oil = tree_state\n local bufnr = vim.api.nvim_get_current_buf()\n\n -- Get current directory once\n local dir_ok, current_dir = pcall(oil.get_current_dir, bufnr)\n if dir_ok and current_dir then\n -- Access the process_oil_entry function through a module method\n for line = start_pos, end_pos do\n local entry_ok, entry = pcall(oil.get_entry_on_line, bufnr, line)\n if entry_ok and entry and entry.name then\n -- Skip parent directory entries\n if entry.name ~= \"..\" and entry.name ~= \".\" then\n local full_path = current_dir .. entry.name\n -- Handle various entry types\n if entry.type == \"file\" or entry.type == \"link\" then\n table.insert(files, full_path)\n elseif entry.type == \"directory\" then\n -- Ensure directory paths end with /\n table.insert(files, full_path:match(\"/$\") and full_path or full_path .. \"/\")\n else\n -- For unknown types, return the path anyway\n table.insert(files, full_path)\n end\n end\n end\n end\n end\n end\n\n return files, nil\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/meta/vim.lua", "---@meta vim_api_definitions\n-- This file provides type definitions for parts of the Neovim API\n-- to help the Lua language server (LuaLS) with diagnostics.\n\n---@class vim_log_levels\n---@field NONE number\n---@field ERROR number\n---@field WARN number\n---@field INFO number\n---@field DEBUG number\n---@field TRACE number\n\n---@class vim_log\n---@field levels vim_log_levels\n\n---@class vim_notify_opts\n---@field title string|nil\n---@field icon string|nil\n---@field on_open fun(winid: number)|nil\n---@field on_close fun()|nil\n---@field timeout number|nil\n---@field keep fun()|nil\n---@field plugin string|nil\n---@field hide_from_history boolean|nil\n---@field once boolean|nil\n---@field on_close_timeout number|nil\n\n---@class vim_options_table: table\n---@field columns number Global option: width of the screen\n---@field lines number Global option: height of the screen\n-- Add other commonly used vim.o options as needed\n\n---@class vim_buffer_options_table: table\n\n---@class vim_bo_proxy: vim_buffer_options_table\n---@field __index fun(self: vim_bo_proxy, bufnr: number): vim_buffer_options_table Allows vim.bo[bufnr]\n\n---@class vim_diagnostic_info\n---@field bufnr number\n---@field col number\n---@field end_col number|nil\n---@field end_lnum number|nil\n---@field lnum number\n---@field message string\n---@field severity number\n---@field source string|nil\n---@field user_data any|nil\n\n---@class vim_diagnostic_module\n---@field get fun(bufnr?: number, ns_id?: number): vim_diagnostic_info[]\n-- Add other vim.diagnostic functions as needed, e.g., get_namespace, set, etc.\n\n---@class vim_fs_module\n---@field remove fun(path: string, opts?: {force?: boolean, recursive?: boolean}):boolean|nil\n\n---@class vim_filetype_module\n---@field match fun(args: {filename: string, contents?: string}):string|nil\n\n---@class vim_fn_table\n---@field mode fun(mode_str?: string, full?: boolean|number):string\n---@field delete fun(name: string, flags?: string):integer For file deletion\n---@field filereadable fun(file: string):integer\n---@field fnamemodify fun(fname: string, mods: string):string\n---@field expand fun(str: string, ...):string|table\n---@field getcwd fun(winid?: number, tabnr?: number):string\n---@field mkdir fun(name: string, path?: string, prot?: number):integer\n---@field buflisted fun(bufnr: number|string):integer\n---@field bufname fun(expr?: number|string):string\n---@field bufnr fun(expr?: string|number, create?: boolean):number\n---@field win_getid fun(win?: number, tab?: number):number\n---@field win_gotoid fun(winid: number):boolean\n---@field line fun(expr: string, winid?: number):number\n---@field col fun(expr: string, winid?: number):number\n---@field virtcol fun(expr: string|string[], winid?: number):number|number[]\n---@field getpos fun(expr: string, winid?: number):number[]\n---@field setpos fun(expr: string, pos: number[], winid?: number):boolean\n---@field tempname fun():string\n---@field globpath fun(path: string, expr: string, ...):string\n---@field stdpath fun(type: \"cache\"|\"config\"|\"data\"|\"log\"|\"run\"|\"state\"|\"config_dirs\"|\"data_dirs\"):string|string[]\n---@field json_encode fun(expr: any):string\n---@field json_decode fun(string: string, opts?: {null_value?: any}):any\n---@field termopen fun(cmd: string|string[], opts?: table):number For vim.fn.termopen()\n-- Add other vim.fn functions as needed\n\n---@class vim_v_table\n---@field event table Event data containing status and other event information\n\n---@class vim_global_api\n---@field notify fun(msg: string | string[], level?: number, opts?: vim_notify_opts):nil\n---@field log vim_log\n---@field v vim_v_table For vim.v.event access\n---@field _last_echo table[]? table of tables, e.g. { {\"message\", \"HighlightGroup\"} }\n---@field _last_error string?\n---@field o vim_options_table For vim.o.option_name\n---@field bo vim_bo_proxy For vim.bo.option_name and vim.bo[bufnr].option_name\n---@field diagnostic vim_diagnostic_module For vim.diagnostic.*\n---@field empty_dict fun(): table For vim.empty_dict()\n---@field schedule_wrap fun(fn: function): function For vim.schedule_wrap()\n---@field deepcopy fun(val: any): any For vim.deepcopy() -- Added based on test mocks\n---@field _current_mode string? For mocks in tests\n---@class vim_api_table\n---@field nvim_create_augroup fun(name: string, opts: {clear: boolean}):integer\n---@field nvim_create_autocmd fun(event: string|string[], opts: {group?: string|integer, pattern?: string|string[], buffer?: number, callback?: function|string, once?: boolean, desc?: string}):integer\n---@field nvim_clear_autocmds fun(opts: {group?: string|integer, event?: string|string[], pattern?: string|string[], buffer?: number}):nil\n---@field nvim_get_current_buf fun():integer\n---@field nvim_get_mode fun():{mode: string, blocking: boolean}\n---@field nvim_win_get_cursor fun(window: integer):integer[] Returns [row, col] (1-based for row, 0-based for col)\n---@field nvim_buf_get_name fun(buffer: integer):string\n---@field nvim_buf_get_lines fun(buffer: integer, start: integer, end_line: integer, strict_indexing: boolean):string[]\n-- Add other nvim_api functions as needed\n---@field cmd fun(command: string):nil For vim.cmd() -- Added based on test mocks\n---@field api vim_api_table For vim.api.*\n---@field fn vim_fn_table For vim.fn.*\n---@field fs vim_fs_module For vim.fs.*\n---@field filetype vim_filetype_module For vim.filetype.*\n---@field test vim_test_utils? For test utility mocks\n---@field split fun(str: string, pat?: string, opts?: {plain?: boolean, trimempty?: boolean}):string[] For vim.split()\n-- Add other vim object definitions here if they cause linting issues\n-- e.g. vim.api, vim.loop, vim.deepcopy, etc.\n\n---@class SpyCall\n---@field vals table[] table of arguments passed to the call\n---@field self any the 'self' object for the call if it was a method\n\n---@class SpyInformation\n---@field calls SpyCall[] A list of calls made to the spy.\n---@field call_count number The number of times the spy has been called.\n-- Add other spy properties if needed e.g. returned, threw\n\n---@class SpyAsserts\n---@field was_called fun(self: SpyAsserts, count?: number):boolean\n---@field was_called_with fun(self: SpyAsserts, ...):boolean\n---@field was_not_called fun(self: SpyAsserts):boolean\n-- Add other spy asserts if needed\n\n---@class SpyableFunction : function\n---@field __call fun(self: SpyableFunction, ...):any\n---@field spy fun(self: SpyableFunction):SpyAsserts Returns an assertion object for the spy.\n---@field calls SpyInformation[]? Information about calls made to the spied function.\n-- Note: In some spy libraries, 'calls' might be directly on the spied function,\n-- or on an object returned by `spy()`. Adjust as per your spy library's specifics.\n-- For busted's default spy, `calls` is often directly on the spied function.\n\n---@class vim_test_utils\n---@field add_buffer fun(bufnr: number, filename: string, content: string|string[]):nil\n---@field set_cursor fun(bufnr: number, row: number, col: number):nil\n-- Add other test utility functions as needed\n\n-- This section helps LuaLS understand that 'vim' is a global variable\n-- with the structure defined above. It's for type hinting only and\n-- does not execute or overwrite the actual 'vim' global provided by Neovim.\n---@type vim_global_api\n"], ["/claudecode.nvim/lua/claudecode/lockfile.lua", "---@brief [[\n--- Lock file management for Claude Code Neovim integration.\n--- This module handles creation, removal and updating of lock files\n--- which allow Claude Code CLI to discover the Neovim integration.\n---@brief ]]\n\nlocal M = {}\n\n--- Path to the lock file directory\n---@return string lock_dir The path to the lock file directory\nlocal function get_lock_dir()\n local claude_config_dir = os.getenv(\"CLAUDE_CONFIG_DIR\")\n if claude_config_dir and claude_config_dir ~= \"\" then\n return vim.fn.expand(claude_config_dir .. \"/ide\")\n else\n return vim.fn.expand(\"~/.claude/ide\")\n end\nend\n\nM.lock_dir = get_lock_dir()\n\n-- Track if random seed has been initialized\nlocal random_initialized = false\n\n--- Generate a random UUID for authentication\n---@return string uuid A randomly generated UUID string\nlocal function generate_auth_token()\n -- Initialize random seed only once\n if not random_initialized then\n local seed = os.time() + vim.fn.getpid()\n -- Add more entropy if available\n if vim.loop and vim.loop.hrtime then\n seed = seed + (vim.loop.hrtime() % 1000000)\n end\n math.randomseed(seed)\n\n -- Call math.random a few times to \"warm up\" the generator\n for _ = 1, 10 do\n math.random()\n end\n random_initialized = true\n end\n\n -- Generate UUID v4 format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n local template = \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\"\n local uuid = template:gsub(\"[xy]\", function(c)\n local v = (c == \"x\") and math.random(0, 15) or math.random(8, 11)\n return string.format(\"%x\", v)\n end)\n\n -- Validate generated UUID format\n if not uuid:match(\"^[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+$\") then\n error(\"Generated invalid UUID format: \" .. uuid)\n end\n\n if #uuid ~= 36 then\n error(\"Generated UUID has invalid length: \" .. #uuid .. \" (expected 36)\")\n end\n\n return uuid\nend\n\n--- Generate a new authentication token\n---@return string auth_token A newly generated authentication token\nfunction M.generate_auth_token()\n return generate_auth_token()\nend\n\n--- Create the lock file for a specified WebSocket port\n---@param port number The port number for the WebSocket server\n---@param auth_token string|nil Optional pre-generated auth token (generates new one if not provided)\n---@return boolean success Whether the operation was successful\n---@return string result_or_error The lock file path if successful, or error message if failed\n---@return string? auth_token The authentication token if successful\nfunction M.create(port, auth_token)\n if not port or type(port) ~= \"number\" then\n return false, \"Invalid port number\"\n end\n\n if port < 1 or port > 65535 then\n return false, \"Port number out of valid range (1-65535): \" .. tostring(port)\n end\n\n local ok, err = pcall(function()\n return vim.fn.mkdir(M.lock_dir, \"p\")\n end)\n\n if not ok then\n return false, \"Failed to create lock directory: \" .. (err or \"unknown error\")\n end\n\n local lock_path = M.lock_dir .. \"/\" .. port .. \".lock\"\n\n local workspace_folders = M.get_workspace_folders()\n if not auth_token then\n local auth_success, auth_result = pcall(generate_auth_token)\n if not auth_success then\n return false, \"Failed to generate authentication token: \" .. (auth_result or \"unknown error\")\n end\n auth_token = auth_result\n else\n -- Validate provided auth_token\n if type(auth_token) ~= \"string\" then\n return false, \"Authentication token must be a string, got \" .. type(auth_token)\n end\n if #auth_token < 10 then\n return false, \"Authentication token too short (minimum 10 characters)\"\n end\n if #auth_token > 500 then\n return false, \"Authentication token too long (maximum 500 characters)\"\n end\n end\n\n -- Prepare lock file content\n local lock_content = {\n pid = vim.fn.getpid(),\n workspaceFolders = workspace_folders,\n ideName = \"Neovim\",\n transport = \"ws\",\n authToken = auth_token,\n }\n\n local json\n local ok_json, json_err = pcall(function()\n json = vim.json.encode(lock_content)\n return json\n end)\n\n if not ok_json or not json then\n return false, \"Failed to encode lock file content: \" .. (json_err or \"unknown error\")\n end\n\n local file = io.open(lock_path, \"w\")\n if not file then\n return false, \"Failed to create lock file: \" .. lock_path\n end\n\n local write_ok, write_err = pcall(function()\n file:write(json)\n file:close()\n end)\n\n if not write_ok then\n pcall(function()\n file:close()\n end)\n return false, \"Failed to write lock file: \" .. (write_err or \"unknown error\")\n end\n\n return true, lock_path, auth_token\nend\n\n--- Remove the lock file for the given port\n---@param port number The port number of the WebSocket server\n---@return boolean success Whether the operation was successful\n---@return string? error Error message if operation failed\nfunction M.remove(port)\n if not port or type(port) ~= \"number\" then\n return false, \"Invalid port number\"\n end\n\n local lock_path = M.lock_dir .. \"/\" .. port .. \".lock\"\n\n if vim.fn.filereadable(lock_path) == 0 then\n return false, \"Lock file does not exist: \" .. lock_path\n end\n\n local ok, err = pcall(function()\n return os.remove(lock_path)\n end)\n\n if not ok then\n return false, \"Failed to remove lock file: \" .. (err or \"unknown error\")\n end\n\n return true\nend\n\n--- Update the lock file for the given port\n---@param port number The port number of the WebSocket server\n---@return boolean success Whether the operation was successful\n---@return string result_or_error The lock file path if successful, or error message if failed\n---@return string? auth_token The authentication token if successful\nfunction M.update(port)\n if not port or type(port) ~= \"number\" then\n return false, \"Invalid port number\"\n end\n\n local exists = vim.fn.filereadable(M.lock_dir .. \"/\" .. port .. \".lock\") == 1\n if exists then\n local remove_ok, remove_err = M.remove(port)\n if not remove_ok then\n return false, \"Failed to update lock file: \" .. remove_err\n end\n end\n\n return M.create(port)\nend\n\n--- Read the authentication token from a lock file\n---@param port number The port number of the WebSocket server\n---@return boolean success Whether the operation was successful\n---@return string? auth_token The authentication token if successful, or nil if failed\n---@return string? error Error message if operation failed\nfunction M.get_auth_token(port)\n if not port or type(port) ~= \"number\" then\n return false, nil, \"Invalid port number\"\n end\n\n local lock_path = M.lock_dir .. \"/\" .. port .. \".lock\"\n\n if vim.fn.filereadable(lock_path) == 0 then\n return false, nil, \"Lock file does not exist: \" .. lock_path\n end\n\n local file = io.open(lock_path, \"r\")\n if not file then\n return false, nil, \"Failed to open lock file: \" .. lock_path\n end\n\n local content = file:read(\"*all\")\n file:close()\n\n if not content or content == \"\" then\n return false, nil, \"Lock file is empty: \" .. lock_path\n end\n\n local ok, lock_data = pcall(vim.json.decode, content)\n if not ok or type(lock_data) ~= \"table\" then\n return false, nil, \"Failed to parse lock file JSON: \" .. lock_path\n end\n\n local auth_token = lock_data.authToken\n if not auth_token or type(auth_token) ~= \"string\" then\n return false, nil, \"No valid auth token found in lock file\"\n end\n\n return true, auth_token, nil\nend\n\n--- Get active LSP clients using available API\n---@return table Array of LSP clients\nlocal function get_lsp_clients()\n if vim.lsp then\n if vim.lsp.get_clients then\n -- Neovim >= 0.11\n return vim.lsp.get_clients()\n elseif vim.lsp.get_active_clients then\n -- Neovim 0.8-0.10\n return vim.lsp.get_active_clients()\n end\n end\n return {}\nend\n\n--- Get workspace folders for the lock file\n---@return table Array of workspace folder paths\nfunction M.get_workspace_folders()\n local folders = {}\n\n -- Add current working directory\n table.insert(folders, vim.fn.getcwd())\n\n -- Get LSP workspace folders if available\n local clients = get_lsp_clients()\n for _, client in pairs(clients) do\n if client.config and client.config.workspace_folders then\n for _, ws in ipairs(client.config.workspace_folders) do\n -- Convert URI to path\n local path = ws.uri\n if path:sub(1, 7) == \"file://\" then\n path = path:sub(8)\n end\n\n -- Check if already in the list\n local exists = false\n for _, folder in ipairs(folders) do\n if folder == path then\n exists = true\n break\n end\n end\n\n if not exists then\n table.insert(folders, path)\n end\n end\n end\n end\n\n return folders\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/integrations.lua", "---\n-- Tree integration module for ClaudeCode.nvim\n-- Handles detection and selection of files from nvim-tree, neo-tree, and oil.nvim\n-- @module claudecode.integrations\nlocal M = {}\n\n--- Get selected files from the current tree explorer\n--- @return table|nil files List of file paths, or nil if error\n--- @return string|nil error Error message if operation failed\nfunction M.get_selected_files_from_tree()\n local current_ft = vim.bo.filetype\n\n if current_ft == \"NvimTree\" then\n return M._get_nvim_tree_selection()\n elseif current_ft == \"neo-tree\" then\n return M._get_neotree_selection()\n elseif current_ft == \"oil\" then\n return M._get_oil_selection()\n else\n return nil, \"Not in a supported tree buffer (current filetype: \" .. current_ft .. \")\"\n end\nend\n\n--- Get selected files from nvim-tree\n--- Supports both multi-selection (marks) and single file under cursor\n--- @return table files List of file paths\n--- @return string|nil error Error message if operation failed\nfunction M._get_nvim_tree_selection()\n local success, nvim_tree_api = pcall(require, \"nvim-tree.api\")\n if not success then\n return {}, \"nvim-tree not available\"\n end\n\n local files = {}\n\n local marks = nvim_tree_api.marks.list()\n\n if marks and #marks > 0 then\n for i, mark in ipairs(marks) do\n if mark.type == \"file\" and mark.absolute_path and mark.absolute_path ~= \"\" then\n -- Check if it's not a root-level file (basic protection)\n if not string.match(mark.absolute_path, \"^/[^/]*$\") then\n table.insert(files, mark.absolute_path)\n end\n end\n end\n\n if #files > 0 then\n return files, nil\n end\n end\n\n local node = nvim_tree_api.tree.get_node_under_cursor()\n if node then\n if node.type == \"file\" and node.absolute_path and node.absolute_path ~= \"\" then\n -- Check if it's not a root-level file (basic protection)\n if not string.match(node.absolute_path, \"^/[^/]*$\") then\n return { node.absolute_path }, nil\n else\n return {}, \"Cannot add root-level file. Please select a file in a subdirectory.\"\n end\n elseif node.type == \"directory\" and node.absolute_path and node.absolute_path ~= \"\" then\n return { node.absolute_path }, nil\n end\n end\n\n return {}, \"No file found under cursor\"\nend\n\n--- Get selected files from neo-tree\n--- Uses neo-tree's own visual selection method when in visual mode\n--- @return table files List of file paths\n--- @return string|nil error Error message if operation failed\nfunction M._get_neotree_selection()\n local success, manager = pcall(require, \"neo-tree.sources.manager\")\n if not success then\n return {}, \"neo-tree not available\"\n end\n\n local state = manager.get_state(\"filesystem\")\n if not state then\n return {}, \"neo-tree filesystem state not available\"\n end\n\n local files = {}\n\n -- Use neo-tree's own visual selection method (like their copy/paste feature)\n local mode = vim.fn.mode()\n\n if mode == \"V\" or mode == \"v\" or mode == \"\\22\" then\n local current_win = vim.api.nvim_get_current_win()\n\n if state.winid and state.winid == current_win then\n -- Use neo-tree's exact method to get visual range (from their get_selected_nodes implementation)\n local start_pos = vim.fn.getpos(\"'<\")[2]\n local end_pos = vim.fn.getpos(\"'>\")[2]\n\n -- Fallback to current cursor and anchor if marks are not valid\n if start_pos == 0 or end_pos == 0 then\n local cursor_pos = vim.api.nvim_win_get_cursor(0)[1]\n local anchor_pos = vim.fn.getpos(\"v\")[2]\n if anchor_pos > 0 then\n start_pos = math.min(cursor_pos, anchor_pos)\n end_pos = math.max(cursor_pos, anchor_pos)\n else\n start_pos = cursor_pos\n end_pos = cursor_pos\n end\n end\n\n if end_pos < start_pos then\n start_pos, end_pos = end_pos, start_pos\n end\n\n local selected_nodes = {}\n\n for line = start_pos, end_pos do\n local node = state.tree:get_node(line)\n if node then\n -- Add validation for node types before adding to selection\n if node.type and node.type ~= \"message\" then\n table.insert(selected_nodes, node)\n end\n end\n end\n\n for i, node in ipairs(selected_nodes) do\n -- Enhanced validation: check for file type and valid path\n if node.type == \"file\" and node.path and node.path ~= \"\" then\n -- Additional check: ensure it's not a root node (depth protection)\n local depth = (node.get_depth and node:get_depth()) and node:get_depth() or 0\n if depth > 1 then\n table.insert(files, node.path)\n end\n end\n end\n\n if #files > 0 then\n return files, nil\n end\n end\n end\n\n if state.tree then\n local selection = nil\n\n if state.tree.get_selection then\n selection = state.tree:get_selection()\n end\n\n if (not selection or #selection == 0) and state.selected_nodes then\n selection = state.selected_nodes\n end\n\n if selection and #selection > 0 then\n for i, node in ipairs(selection) do\n if node.type == \"file\" and node.path then\n table.insert(files, node.path)\n end\n end\n\n if #files > 0 then\n return files, nil\n end\n end\n end\n\n if state.tree then\n local node = state.tree:get_node()\n\n if node then\n if node.type == \"file\" and node.path then\n return { node.path }, nil\n elseif node.type == \"directory\" and node.path then\n return { node.path }, nil\n end\n end\n end\n\n return {}, \"No file found under cursor\"\nend\n\n--- Get selected files from oil.nvim\n--- Supports both visual selection and single file under cursor\n--- @return table files List of file paths\n--- @return string|nil error Error message if operation failed\nfunction M._get_oil_selection()\n local success, oil = pcall(require, \"oil\")\n if not success then\n return {}, \"oil.nvim not available\"\n end\n\n local bufnr = vim.api.nvim_get_current_buf() --[[@as number]]\n local files = {}\n\n -- Check if we're in visual mode\n local mode = vim.fn.mode()\n if mode == \"V\" or mode == \"v\" or mode == \"\\22\" then\n -- Visual mode: use the common visual range function\n local visual_commands = require(\"claudecode.visual_commands\")\n local start_line, end_line = visual_commands.get_visual_range()\n\n -- Get current directory once\n local dir_ok, current_dir = pcall(oil.get_current_dir, bufnr)\n if not dir_ok or not current_dir then\n return {}, \"Failed to get current directory\"\n end\n\n -- Process each line in the visual selection\n for line = start_line, end_line do\n local entry_ok, entry = pcall(oil.get_entry_on_line, bufnr, line)\n if entry_ok and entry and entry.name then\n -- Skip parent directory entries\n if entry.name ~= \"..\" and entry.name ~= \".\" then\n local full_path = current_dir .. entry.name\n -- Handle various entry types\n if entry.type == \"file\" or entry.type == \"link\" then\n table.insert(files, full_path)\n elseif entry.type == \"directory\" then\n -- Ensure directory paths end with /\n table.insert(files, full_path:match(\"/$\") and full_path or full_path .. \"/\")\n else\n -- For unknown types, return the path anyway\n table.insert(files, full_path)\n end\n end\n end\n end\n\n if #files > 0 then\n return files, nil\n end\n else\n -- Normal mode: get file under cursor with error handling\n local ok, entry = pcall(oil.get_cursor_entry)\n if not ok or not entry then\n return {}, \"Failed to get cursor entry\"\n end\n\n local dir_ok, current_dir = pcall(oil.get_current_dir, bufnr)\n if not dir_ok or not current_dir then\n return {}, \"Failed to get current directory\"\n end\n\n -- Process the entry\n if entry.name and entry.name ~= \"..\" and entry.name ~= \".\" then\n local full_path = current_dir .. entry.name\n -- Handle various entry types\n if entry.type == \"file\" or entry.type == \"link\" then\n return { full_path }, nil\n elseif entry.type == \"directory\" then\n -- Ensure directory paths end with /\n return { full_path:match(\"/$\") and full_path or full_path .. \"/\" }, nil\n else\n -- For unknown types, return the path anyway\n return { full_path }, nil\n end\n end\n end\n\n return {}, \"No file found under cursor\"\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/init.lua", "---@brief WebSocket server for Claude Code Neovim integration\nlocal claudecode_main = require(\"claudecode\") -- Added for version access\nlocal logger = require(\"claudecode.logger\")\nlocal tcp_server = require(\"claudecode.server.tcp\")\nlocal tools = require(\"claudecode.tools.init\") -- Added: Require the tools module\n\nlocal MCP_PROTOCOL_VERSION = \"2024-11-05\"\n\nlocal M = {}\n\n---@class ServerState\n---@field server table|nil The TCP server instance\n---@field port number|nil The port server is running on\n---@field auth_token string|nil The authentication token for validating connections\n---@field clients table A list of connected clients\n---@field handlers table Message handlers by method name\n---@field ping_timer table|nil Timer for sending pings\nM.state = {\n server = nil,\n port = nil,\n auth_token = nil,\n clients = {},\n handlers = {},\n ping_timer = nil,\n}\n\n---@brief Initialize the WebSocket server\n---@param config table Configuration options\n---@param auth_token string|nil The authentication token for validating connections\n---@return boolean success Whether server started successfully\n---@return number|string port_or_error Port number or error message\nfunction M.start(config, auth_token)\n if M.state.server then\n return false, \"Server already running\"\n end\n\n M.state.auth_token = auth_token\n\n -- Log authentication state\n if auth_token then\n logger.debug(\"server\", \"Starting WebSocket server with authentication enabled\")\n logger.debug(\"server\", \"Auth token length:\", #auth_token)\n else\n logger.debug(\"server\", \"Starting WebSocket server WITHOUT authentication (insecure)\")\n end\n\n M.register_handlers()\n\n tools.setup(M)\n\n local callbacks = {\n on_message = function(client, message)\n M._handle_message(client, message)\n end,\n on_connect = function(client)\n M.state.clients[client.id] = client\n\n -- Log connection with auth status\n if M.state.auth_token then\n logger.debug(\"server\", \"Authenticated WebSocket client connected:\", client.id)\n else\n logger.debug(\"server\", \"WebSocket client connected (no auth):\", client.id)\n end\n\n -- Notify main module about new connection for queue processing\n local main_module = require(\"claudecode\")\n if main_module._process_queued_mentions then\n vim.schedule(function()\n main_module._process_queued_mentions()\n end)\n end\n end,\n on_disconnect = function(client, code, reason)\n M.state.clients[client.id] = nil\n logger.debug(\n \"server\",\n \"WebSocket client disconnected:\",\n client.id,\n \"(code:\",\n code,\n \", reason:\",\n (reason or \"N/A\") .. \")\"\n )\n end,\n on_error = function(error_msg)\n logger.error(\"server\", \"WebSocket server error:\", error_msg)\n end,\n }\n\n local server, error_msg = tcp_server.create_server(config, callbacks, M.state.auth_token)\n if not server then\n return false, error_msg or \"Unknown server creation error\"\n end\n\n M.state.server = server\n M.state.port = server.port\n\n M.state.ping_timer = tcp_server.start_ping_timer(server, 30000) -- Start ping timer to keep connections alive\n\n return true, server.port\nend\n\n---@brief Stop the WebSocket server\n---@return boolean success Whether server stopped successfully\n---@return string|nil error_message Error message if any\nfunction M.stop()\n if not M.state.server then\n return false, \"Server not running\"\n end\n\n if M.state.ping_timer then\n M.state.ping_timer:stop()\n M.state.ping_timer:close()\n M.state.ping_timer = nil\n end\n\n tcp_server.stop_server(M.state.server)\n\n -- CRITICAL: Clear global deferred responses to prevent memory leaks and hanging\n if _G.claude_deferred_responses then\n _G.claude_deferred_responses = {}\n end\n\n M.state.server = nil\n M.state.port = nil\n M.state.auth_token = nil\n M.state.clients = {}\n\n return true\nend\n\n---@brief Handle incoming WebSocket message\n---@param client table The client that sent the message\n---@param message string The JSON-RPC message\nfunction M._handle_message(client, message)\n local success, parsed = pcall(vim.json.decode, message)\n if not success then\n M.send_response(client, nil, nil, {\n code = -32700,\n message = \"Parse error\",\n data = \"Invalid JSON\",\n })\n return\n end\n\n if type(parsed) ~= \"table\" or parsed.jsonrpc ~= \"2.0\" then\n M.send_response(client, parsed.id, nil, {\n code = -32600,\n message = \"Invalid Request\",\n data = \"Not a valid JSON-RPC 2.0 request\",\n })\n return\n end\n\n if parsed.id then\n M._handle_request(client, parsed)\n else\n M._handle_notification(client, parsed)\n end\nend\n\n---@brief Handle JSON-RPC request (requires response)\n---@param client table The client that sent the request\n---@param request table The parsed JSON-RPC request\nfunction M._handle_request(client, request)\n local method = request.method\n local params = request.params or {}\n local id = request.id\n\n local handler = M.state.handlers[method]\n if not handler then\n M.send_response(client, id, nil, {\n code = -32601,\n message = \"Method not found\",\n data = \"Unknown method: \" .. tostring(method),\n })\n return\n end\n\n local success, result, error_data = pcall(handler, client, params)\n if success then\n -- Check if this is a deferred response (blocking tool)\n if result and result._deferred then\n logger.debug(\"server\", \"Handler returned deferred response - storing for later\")\n -- Store the request info for later response\n local deferred_info = {\n client = result.client,\n id = id,\n coroutine = result.coroutine,\n method = method,\n params = result.params,\n }\n -- Set up the completion callback\n M._setup_deferred_response(deferred_info)\n return -- Don't send response now\n end\n\n if error_data then\n M.send_response(client, id, nil, error_data)\n else\n M.send_response(client, id, result, nil)\n end\n else\n M.send_response(client, id, nil, {\n code = -32603,\n message = \"Internal error\",\n data = tostring(result), -- result contains error message when pcall fails\n })\n end\nend\n\n---@brief Set up deferred response handling for blocking tools\n---@param deferred_info table Information about the deferred request\n-- Note: deferred_responses table removed - using global _G.claude_deferred_responses instead\n\n-- Add a unique module ID to detect reloading\nlocal module_instance_id = math.random(10000, 99999)\nlogger.debug(\"server\", \"Server module loaded with instance ID:\", module_instance_id)\n\n-- Note: debug_deferred_table function removed as deferred_responses table is no longer used\n\nfunction M._setup_deferred_response(deferred_info)\n local co = deferred_info.coroutine\n\n logger.debug(\"server\", \"Setting up deferred response for coroutine:\", tostring(co))\n logger.debug(\"server\", \"Storage happening in module instance:\", module_instance_id)\n\n -- Create a response sender function that captures the current server instance\n local response_sender = function(result)\n logger.debug(\"server\", \"Deferred response triggered for coroutine:\", tostring(co))\n\n if result and result.content then\n -- MCP-compliant response\n M.send_response(deferred_info.client, deferred_info.id, result, nil)\n elseif result and result.error then\n -- Error response\n M.send_response(deferred_info.client, deferred_info.id, nil, result.error)\n else\n -- Fallback error\n M.send_response(deferred_info.client, deferred_info.id, nil, {\n code = -32603,\n message = \"Internal error\",\n data = \"Deferred response completed with unexpected format\",\n })\n end\n end\n\n -- Store the response sender in a global location that won't be affected by module reloading\n if not _G.claude_deferred_responses then\n _G.claude_deferred_responses = {}\n end\n _G.claude_deferred_responses[tostring(co)] = response_sender\n\n logger.debug(\"server\", \"Stored response sender in global table for coroutine:\", tostring(co))\nend\n\n-- Note: _send_deferred_response is no longer needed\n-- Responses are now handled via the global _G.claude_deferred_responses table\n-- to avoid module reloading issues\n\n---@brief Handle JSON-RPC notification (no response)\n---@param client table The client that sent the notification\n---@param notification table The parsed JSON-RPC notification\nfunction M._handle_notification(client, notification)\n local method = notification.method\n local params = notification.params or {}\n\n local handler = M.state.handlers[method]\n if handler then\n pcall(handler, client, params)\n end\nend\n\n---@brief Register message handlers for the server\nfunction M.register_handlers()\n M.state.handlers = {\n [\"initialize\"] = function(client, params) -- Renamed from mcp.connect\n return {\n protocolVersion = MCP_PROTOCOL_VERSION,\n capabilities = {\n logging = vim.empty_dict(), -- Ensure this is an object {} not an array []\n prompts = { listChanged = true },\n resources = { subscribe = true, listChanged = true },\n tools = { listChanged = true },\n },\n serverInfo = {\n name = \"claudecode-neovim\",\n version = claudecode_main.version:string(),\n },\n }\n end,\n\n [\"notifications/initialized\"] = function(client, params) -- Added handler for initialized notification\n end,\n\n [\"prompts/list\"] = function(client, params) -- Added handler for prompts/list\n return {\n prompts = {}, -- This will be encoded as an empty JSON array\n }\n end,\n\n [\"tools/list\"] = function(_client, _params)\n return {\n tools = tools.get_tool_list(),\n }\n end,\n\n [\"tools/call\"] = function(client, params)\n logger.debug(\n \"server\",\n \"Received tools/call. Tool: \",\n params and params.name,\n \" Arguments: \",\n vim.inspect(params and params.arguments)\n )\n local result_or_error_table = tools.handle_invoke(client, params)\n\n -- Check if this is a deferred response (blocking tool)\n if result_or_error_table and result_or_error_table._deferred then\n logger.debug(\"server\", \"Tool is blocking - setting up deferred response\")\n -- Return the deferred response directly - _handle_request will process it\n return result_or_error_table\n end\n\n -- Log the response for debugging\n logger.debug(\"server\", \"Response - tools/call\", params and params.name .. \":\", vim.inspect(result_or_error_table))\n\n if result_or_error_table.error then\n return nil, result_or_error_table.error\n elseif result_or_error_table.result then\n return result_or_error_table.result, nil\n else\n -- Should not happen if tools.handle_invoke behaves correctly\n return nil,\n {\n code = -32603,\n message = \"Internal error\",\n data = \"Tool handler returned unexpected format\",\n }\n end\n end,\n }\nend\n\n---@brief Send a message to a client\n---@param client table The client to send to\n---@param method string The method name\n---@param params table|nil The parameters to send\n---@return boolean success Whether message was sent successfully\nfunction M.send(client, method, params)\n if not M.state.server then\n return false\n end\n\n local message = {\n jsonrpc = \"2.0\",\n method = method,\n params = params or vim.empty_dict(),\n }\n\n local json_message = vim.json.encode(message)\n tcp_server.send_to_client(M.state.server, client.id, json_message)\n return true\nend\n\n---@brief Send a response to a client\n---@param client table The client to send to\n---@param id number|string|nil The request ID to respond to\n---@param result any|nil The result data if successful\n---@param error_data table|nil The error data if failed\n---@return boolean success Whether response was sent successfully\nfunction M.send_response(client, id, result, error_data)\n if not M.state.server then\n return false\n end\n\n local response = {\n jsonrpc = \"2.0\",\n id = id,\n }\n\n if error_data then\n response.error = error_data\n else\n response.result = result\n end\n\n local json_response = vim.json.encode(response)\n tcp_server.send_to_client(M.state.server, client.id, json_response)\n return true\nend\n\n---@brief Broadcast a message to all connected clients\n---@param method string The method name\n---@param params table|nil The parameters to send\n---@return boolean success Whether broadcast was successful\nfunction M.broadcast(method, params)\n if not M.state.server then\n return false\n end\n\n local message = {\n jsonrpc = \"2.0\",\n method = method,\n params = params or vim.empty_dict(),\n }\n\n local json_message = vim.json.encode(message)\n tcp_server.broadcast(M.state.server, json_message)\n return true\nend\n\n---@brief Get server status information\n---@return table status Server status information\nfunction M.get_status()\n if not M.state.server then\n return {\n running = false,\n port = nil,\n client_count = 0,\n }\n end\n\n return {\n running = true,\n port = M.state.port,\n client_count = tcp_server.get_client_count(M.state.server),\n clients = tcp_server.get_clients_info(M.state.server),\n }\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/utils.lua", "---@brief Utility functions for WebSocket server implementation\nlocal M = {}\n\n-- Lua 5.1 compatible bitwise operations (arithmetic emulation).\nlocal function band(a, b)\n local result = 0\n local bitval = 1\n while a > 0 and b > 0 do\n if a % 2 == 1 and b % 2 == 1 then\n result = result + bitval\n end\n bitval = bitval * 2\n a = math.floor(a / 2)\n b = math.floor(b / 2)\n end\n return result\nend\n\nlocal function bor(a, b)\n local result = 0\n local bitval = 1\n while a > 0 or b > 0 do\n if a % 2 == 1 or b % 2 == 1 then\n result = result + bitval\n end\n bitval = bitval * 2\n a = math.floor(a / 2)\n b = math.floor(b / 2)\n end\n return result\nend\n\nlocal function bxor(a, b)\n local result = 0\n local bitval = 1\n while a > 0 or b > 0 do\n if (a % 2) ~= (b % 2) then\n result = result + bitval\n end\n bitval = bitval * 2\n a = math.floor(a / 2)\n b = math.floor(b / 2)\n end\n return result\nend\n\nlocal function bnot(a)\n return bxor(a, 0xFFFFFFFF)\nend\n\nlocal function lshift(value, amount)\n local shifted_val = value * (2 ^ amount)\n return shifted_val % (2 ^ 32)\nend\n\nlocal function rshift(value, amount)\n return math.floor(value / (2 ^ amount))\nend\n\nlocal function rotleft(value, amount)\n local mask = 0xFFFFFFFF\n value = band(value, mask)\n local part1 = lshift(value, amount)\n local part2 = rshift(value, 32 - amount)\n return band(bor(part1, part2), mask)\nend\n\nlocal function add32(a, b)\n local sum = a + b\n return band(sum, 0xFFFFFFFF)\nend\n\n---@brief Generate a random, spec-compliant WebSocket key.\n---@return string key Base64 encoded 16-byte random nonce.\nfunction M.generate_websocket_key()\n local random_bytes = {}\n for _ = 1, 16 do\n random_bytes[#random_bytes + 1] = string.char(math.random(0, 255))\n end\n return M.base64_encode(table.concat(random_bytes))\nend\n\n---@brief Base64 encode a string\n---@param data string The data to encode\n---@return string encoded The base64 encoded string\nfunction M.base64_encode(data)\n local chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\n local result = {}\n local padding = \"\"\n\n local pad_len = 3 - (#data % 3)\n if pad_len ~= 3 then\n data = data .. string.rep(\"\\0\", pad_len)\n padding = string.rep(\"=\", pad_len)\n end\n\n for i = 1, #data, 3 do\n local a, b, c = data:byte(i, i + 2)\n local bitmap = a * 65536 + b * 256 + c\n\n -- Use table for efficient string building\n result[#result + 1] = chars:sub(math.floor(bitmap / 262144) + 1, math.floor(bitmap / 262144) + 1)\n result[#result + 1] = chars:sub(math.floor((bitmap % 262144) / 4096) + 1, math.floor((bitmap % 262144) / 4096) + 1)\n result[#result + 1] = chars:sub(math.floor((bitmap % 4096) / 64) + 1, math.floor((bitmap % 4096) / 64) + 1)\n result[#result + 1] = chars:sub((bitmap % 64) + 1, (bitmap % 64) + 1)\n end\n\n local encoded = table.concat(result)\n return encoded:sub(1, #encoded - #padding) .. padding\nend\n\n---@brief Base64 decode a string\n---@param data string The base64 encoded string\n---@return string|nil decoded The decoded string, or nil on error (e.g. invalid char)\nfunction M.base64_decode(data)\n local chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\n local lookup = {}\n for i = 1, #chars do\n lookup[chars:sub(i, i)] = i - 1\n end\n lookup[\"=\"] = 0\n\n local result = {}\n local buffer = 0\n local bits = 0\n\n for i = 1, #data do\n local char = data:sub(i, i)\n local value = lookup[char]\n\n if value == nil then\n return nil\n end\n\n if char == \"=\" then\n break\n end\n\n buffer = (buffer * 64) + value\n bits = bits + 6\n\n if bits >= 8 then\n bits = bits - 8\n result[#result + 1] = string.char(rshift(buffer, bits))\n buffer = band(buffer, (lshift(1, bits)) - 1)\n end\n end\n return table.concat(result)\nend\n\n---@brief Pure Lua SHA-1 implementation\n---@param data string The data to hash\n---@return string|nil hash The SHA-1 hash in binary format, or nil on error\nfunction M.sha1(data)\n if type(data) ~= \"string\" then\n return nil\n end\n\n -- Validate input data is reasonable size (DOS protection)\n if #data > 10 * 1024 * 1024 then -- 10MB limit\n return nil\n end\n\n local h0 = 0x67452301\n local h1 = 0xEFCDAB89\n local h2 = 0x98BADCFE\n local h3 = 0x10325476\n local h4 = 0xC3D2E1F0\n\n local msg = data\n local msg_len = #msg\n local bit_len = msg_len * 8\n\n msg = msg .. string.char(0x80)\n\n -- Append 0 <= k < 512 bits '0', where the resulting message length\n -- (in bits) is congruent to 448 (mod 512)\n while (#msg % 64) ~= 56 do\n msg = msg .. string.char(0x00)\n end\n\n -- Append length as 64-bit big-endian integer\n for i = 7, 0, -1 do\n msg = msg .. string.char(band(rshift(bit_len, i * 8), 0xFF))\n end\n\n for chunk_start = 1, #msg, 64 do\n local w = {}\n\n -- Break chunk into sixteen 32-bit big-endian words\n for i = 0, 15 do\n local offset = chunk_start + i * 4\n w[i] = bor(\n bor(bor(lshift(msg:byte(offset), 24), lshift(msg:byte(offset + 1), 16)), lshift(msg:byte(offset + 2), 8)),\n msg:byte(offset + 3)\n )\n end\n\n -- Extend the sixteen 32-bit words into eighty 32-bit words\n for i = 16, 79 do\n w[i] = rotleft(bxor(bxor(bxor(w[i - 3], w[i - 8]), w[i - 14]), w[i - 16]), 1)\n end\n\n local a, b, c, d, e = h0, h1, h2, h3, h4\n\n for i = 0, 79 do\n local f, k\n if i <= 19 then\n f = bor(band(b, c), band(bnot(b), d))\n k = 0x5A827999\n elseif i <= 39 then\n f = bxor(bxor(b, c), d)\n k = 0x6ED9EBA1\n elseif i <= 59 then\n f = bor(bor(band(b, c), band(b, d)), band(c, d))\n k = 0x8F1BBCDC\n else\n f = bxor(bxor(b, c), d)\n k = 0xCA62C1D6\n end\n\n local temp = add32(add32(add32(add32(rotleft(a, 5), f), e), k), w[i])\n e = d\n d = c\n c = rotleft(b, 30)\n b = a\n a = temp\n end\n\n h0 = add32(h0, a)\n h1 = add32(h1, b)\n h2 = add32(h2, c)\n h3 = add32(h3, d)\n h4 = add32(h4, e)\n end\n\n -- Produce the final hash value as a 160-bit (20-byte) binary string\n local result = \"\"\n for _, h in ipairs({ h0, h1, h2, h3, h4 }) do\n result = result\n .. string.char(band(rshift(h, 24), 0xFF), band(rshift(h, 16), 0xFF), band(rshift(h, 8), 0xFF), band(h, 0xFF))\n end\n\n return result\nend\n\n---@brief Generate WebSocket accept key from client key\n---@param client_key string The client's WebSocket-Key header value\n---@return string|nil accept_key The WebSocket accept key, or nil on error\nfunction M.generate_accept_key(client_key)\n local magic_string = \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\"\n\n -- As per RFC 6455, the server concatenates the Sec-WebSocket-Key header value\n -- with a magic string, SHA1s the result, and then Base64 encodes it.\n local combined = client_key .. magic_string\n local hash = M.sha1(combined)\n if not hash then\n return nil\n end\n\n return M.base64_encode(hash)\nend\n\n---@brief Parse HTTP headers from request string\n---@param request string The HTTP request string\n---@return table headers Table of header name -> value pairs\nfunction M.parse_http_headers(request)\n local headers = {}\n local lines = {}\n\n for line in request:gmatch(\"[^\\r\\n]+\") do\n table.insert(lines, line)\n end\n\n for i = 2, #lines do\n local line = lines[i]\n local name, value = line:match(\"^([^:]+):%s*(.+)$\")\n if name and value then\n headers[name:lower()] = value\n end\n end\n\n return headers\nend\n\n---@brief Check if a string contains valid UTF-8\n---@param str string The string to check\n---@return boolean valid True if the string is valid UTF-8\nfunction M.is_valid_utf8(str)\n local i = 1\n while i <= #str do\n local byte = str:byte(i)\n local char_len = 1\n\n if byte >= 0x80 then\n if byte >= 0xF0 then\n char_len = 4\n elseif byte >= 0xE0 then\n char_len = 3\n elseif byte >= 0xC0 then\n char_len = 2\n else\n return false\n end\n\n for j = 1, char_len - 1 do\n if i + j > #str then\n return false\n end\n local cont_byte = str:byte(i + j)\n if cont_byte < 0x80 or cont_byte >= 0xC0 then\n return false\n end\n end\n end\n\n i = i + char_len\n end\n\n return true\nend\n\n---@brief Convert a 16-bit number to big-endian bytes\n---@param num number The number to convert\n---@return string bytes The big-endian byte representation\nfunction M.uint16_to_bytes(num)\n return string.char(math.floor(num / 256), num % 256)\nend\n\n---@brief Convert a 64-bit number to big-endian bytes\n---@param num number The number to convert\n---@return string bytes The big-endian byte representation\nfunction M.uint64_to_bytes(num)\n local bytes = {}\n for i = 8, 1, -1 do\n bytes[i] = num % 256\n num = math.floor(num / 256)\n end\n return string.char(unpack(bytes))\nend\n\n---@brief Convert big-endian bytes to a 16-bit number\n---@param bytes string The byte string (2 bytes)\n---@return number num The converted number\nfunction M.bytes_to_uint16(bytes)\n if #bytes < 2 then\n return 0\n end\n return bytes:byte(1) * 256 + bytes:byte(2)\nend\n\n---@brief Convert big-endian bytes to a 64-bit number\n---@param bytes string The byte string (8 bytes)\n---@return number num The converted number\nfunction M.bytes_to_uint64(bytes)\n if #bytes < 8 then\n return 0\n end\n\n local num = 0\n for i = 1, 8 do\n num = num * 256 + bytes:byte(i)\n end\n return num\nend\n\n---@brief XOR lookup table for faster operations\nlocal xor_table = {}\nfor i = 0, 255 do\n xor_table[i] = {}\n for j = 0, 255 do\n local result = 0\n local a, b = i, j\n local bit_val = 1\n\n while a > 0 or b > 0 do\n local a_bit = a % 2\n local b_bit = b % 2\n\n if a_bit ~= b_bit then\n result = result + bit_val\n end\n\n a = math.floor(a / 2)\n b = math.floor(b / 2)\n bit_val = bit_val * 2\n end\n\n xor_table[i][j] = result\n end\nend\n\n---@brief Apply XOR mask to payload data\n---@param data string The data to mask/unmask\n---@param mask string The 4-byte mask\n---@return string masked The masked/unmasked data\nfunction M.apply_mask(data, mask)\n local result = {}\n local mask_bytes = { mask:byte(1, 4) }\n\n for i = 1, #data do\n local mask_idx = ((i - 1) % 4) + 1\n local data_byte = data:byte(i)\n result[i] = string.char(xor_table[data_byte][mask_bytes[mask_idx]])\n end\n\n return table.concat(result)\nend\n\n---@brief Shuffle an array in place using Fisher-Yates algorithm\n---@param tbl table The array to shuffle\nfunction M.shuffle_array(tbl)\n math.randomseed(os.time())\n for i = #tbl, 2, -1 do\n local j = math.random(i)\n tbl[i], tbl[j] = tbl[j], tbl[i]\n end\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/client.lua", "---@brief WebSocket client connection management\nlocal frame = require(\"claudecode.server.frame\")\nlocal handshake = require(\"claudecode.server.handshake\")\nlocal logger = require(\"claudecode.logger\")\n\nlocal M = {}\n\n---@class WebSocketClient\n---@field id string Unique client identifier\n---@field tcp_handle table The vim.loop TCP handle\n---@field state string Connection state: \"connecting\", \"connected\", \"closing\", \"closed\"\n---@field buffer string Incoming data buffer\n---@field handshake_complete boolean Whether WebSocket handshake is complete\n---@field last_ping number Timestamp of last ping sent\n---@field last_pong number Timestamp of last pong received\n\n---@brief Create a new WebSocket client\n---@param tcp_handle table The vim.loop TCP handle\n---@return WebSocketClient client The client object\nfunction M.create_client(tcp_handle)\n local client_id = tostring(tcp_handle):gsub(\"userdata: \", \"client_\")\n\n local client = {\n id = client_id,\n tcp_handle = tcp_handle,\n state = \"connecting\",\n buffer = \"\",\n handshake_complete = false,\n last_ping = 0,\n last_pong = vim.loop.now(),\n }\n\n return client\nend\n\n---@brief Process incoming data for a client\n---@param client WebSocketClient The client object\n---@param data string The incoming data\n---@param on_message function Callback for complete messages: function(client, message_text)\n---@param on_close function Callback for client close: function(client, code, reason)\n---@param on_error function Callback for errors: function(client, error_msg)\n---@param auth_token string|nil Expected authentication token for validation\nfunction M.process_data(client, data, on_message, on_close, on_error, auth_token)\n client.buffer = client.buffer .. data\n\n if not client.handshake_complete then\n local complete, request, remaining = handshake.extract_http_request(client.buffer)\n if complete then\n logger.debug(\"client\", \"Processing WebSocket handshake for client:\", client.id)\n\n -- Log if auth token is required\n if auth_token then\n logger.debug(\"client\", \"Authentication required for client:\", client.id)\n else\n logger.debug(\"client\", \"No authentication required for client:\", client.id)\n end\n\n local success, response_from_handshake, _ = handshake.process_handshake(request, auth_token)\n\n -- Log authentication results\n if success then\n if auth_token then\n logger.debug(\"client\", \"Client authenticated successfully:\", client.id)\n else\n logger.debug(\"client\", \"Client handshake completed (no auth required):\", client.id)\n end\n else\n -- Log specific authentication failure details\n if auth_token and response_from_handshake:find(\"auth\") then\n logger.warn(\n \"client\",\n \"Authentication failed for client \"\n .. client.id\n .. \": \"\n .. (response_from_handshake:match(\"Bad WebSocket upgrade request: (.+)\") or \"unknown auth error\")\n )\n else\n logger.warn(\n \"client\",\n \"WebSocket handshake failed for client \"\n .. client.id\n .. \": \"\n .. (response_from_handshake:match(\"HTTP/1.1 %d+ (.+)\") or \"unknown handshake error\")\n )\n end\n end\n\n client.tcp_handle:write(response_from_handshake, function(err)\n if err then\n logger.error(\"client\", \"Failed to send handshake response to client \" .. client.id .. \": \" .. err)\n on_error(client, \"Failed to send handshake response: \" .. err)\n return\n end\n\n if success then\n client.handshake_complete = true\n client.state = \"connected\"\n client.buffer = remaining\n logger.debug(\"client\", \"WebSocket connection established for client:\", client.id)\n\n if #client.buffer > 0 then\n M.process_data(client, \"\", on_message, on_close, on_error, auth_token)\n end\n else\n client.state = \"closing\"\n logger.debug(\"client\", \"Closing connection for client due to failed handshake:\", client.id)\n vim.schedule(function()\n client.tcp_handle:close()\n end)\n end\n end)\n end\n return\n end\n\n while #client.buffer >= 2 do -- Minimum frame size\n local parsed_frame, bytes_consumed = frame.parse_frame(client.buffer)\n\n if not parsed_frame then\n break\n end\n\n -- Frame validation is now handled entirely within frame.parse_frame.\n -- If frame.parse_frame returns a frame, it's considered valid.\n\n client.buffer = client.buffer:sub(bytes_consumed + 1)\n\n if parsed_frame.opcode == frame.OPCODE.TEXT then\n vim.schedule(function()\n on_message(client, parsed_frame.payload)\n end)\n elseif parsed_frame.opcode == frame.OPCODE.BINARY then\n -- Binary message (treat as text for JSON-RPC)\n vim.schedule(function()\n on_message(client, parsed_frame.payload)\n end)\n elseif parsed_frame.opcode == frame.OPCODE.CLOSE then\n local code = 1000\n local reason = \"\"\n\n if #parsed_frame.payload >= 2 then\n local payload = parsed_frame.payload\n code = payload:byte(1) * 256 + payload:byte(2)\n if #payload > 2 then\n reason = payload:sub(3)\n end\n end\n\n if client.state == \"connected\" then\n local close_frame = frame.create_close_frame(code, reason)\n client.tcp_handle:write(close_frame)\n client.state = \"closing\"\n end\n\n vim.schedule(function()\n on_close(client, code, reason)\n end)\n elseif parsed_frame.opcode == frame.OPCODE.PING then\n local pong_frame = frame.create_pong_frame(parsed_frame.payload)\n client.tcp_handle:write(pong_frame)\n elseif parsed_frame.opcode == frame.OPCODE.PONG then\n client.last_pong = vim.loop.now()\n elseif parsed_frame.opcode == frame.OPCODE.CONTINUATION then\n -- Continuation frame - for simplicity, we don't support fragmentation\n on_error(client, \"Fragmented messages not supported\")\n M.close_client(client, 1003, \"Unsupported data\")\n else\n on_error(client, \"Unknown WebSocket opcode: \" .. parsed_frame.opcode)\n M.close_client(client, 1002, \"Protocol error\")\n end\n end\nend\n\n---@brief Send a text message to a client\n---@param client WebSocketClient The client object\n---@param message string The message to send\n---@param callback function|nil Optional callback: function(err)\nfunction M.send_message(client, message, callback)\n if client.state ~= \"connected\" then\n if callback then\n callback(\"Client not connected\")\n end\n return\n end\n\n local text_frame = frame.create_text_frame(message)\n client.tcp_handle:write(text_frame, callback)\nend\n\n---@brief Send a ping to a client\n---@param client WebSocketClient The client object\n---@param data string|nil Optional ping data\nfunction M.send_ping(client, data)\n if client.state ~= \"connected\" then\n return\n end\n\n local ping_frame = frame.create_ping_frame(data or \"\")\n client.tcp_handle:write(ping_frame)\n client.last_ping = vim.loop.now()\nend\n\n---@brief Close a client connection\n---@param client WebSocketClient The client object\n---@param code number|nil Close code (default: 1000)\n---@param reason string|nil Close reason\nfunction M.close_client(client, code, reason)\n if client.state == \"closed\" or client.state == \"closing\" then\n return\n end\n\n code = code or 1000\n reason = reason or \"\"\n\n if client.handshake_complete then\n local close_frame = frame.create_close_frame(code, reason)\n client.tcp_handle:write(close_frame, function()\n client.state = \"closed\"\n client.tcp_handle:close()\n end)\n else\n client.state = \"closed\"\n client.tcp_handle:close()\n end\n\n client.state = \"closing\"\nend\n\n---@brief Check if a client connection is alive\n---@param client WebSocketClient The client object\n---@param timeout number Timeout in milliseconds (default: 30000)\n---@return boolean alive True if the client is considered alive\nfunction M.is_client_alive(client, timeout)\n timeout = timeout or 30000 -- 30 seconds default\n\n if client.state ~= \"connected\" then\n return false\n end\n\n local now = vim.loop.now()\n return (now - client.last_pong) < timeout\nend\n\n---@brief Get client info for debugging\n---@param client WebSocketClient The client object\n---@return table info Client information\nfunction M.get_client_info(client)\n return {\n id = client.id,\n state = client.state,\n handshake_complete = client.handshake_complete,\n buffer_size = #client.buffer,\n last_ping = client.last_ping,\n last_pong = client.last_pong,\n }\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/tcp.lua", "---@brief TCP server implementation using vim.loop\nlocal client_manager = require(\"claudecode.server.client\")\nlocal utils = require(\"claudecode.server.utils\")\n\nlocal M = {}\n\n---@class TCPServer\n---@field server table The vim.loop TCP server handle\n---@field port number The port the server is listening on\n---@field auth_token string|nil The authentication token for validating connections\n---@field clients table Table of connected clients (client_id -> WebSocketClient)\n---@field on_message function Callback for WebSocket messages\n---@field on_connect function Callback for new connections\n---@field on_disconnect function Callback for client disconnections\n---@field on_error fun(err_msg: string) Callback for errors\n\n---@brief Find an available port by attempting to bind\n---@param min_port number Minimum port to try\n---@param max_port number Maximum port to try\n---@return number|nil port Available port number, or nil if none found\nfunction M.find_available_port(min_port, max_port)\n if min_port > max_port then\n return nil -- Or handle error appropriately\n end\n\n local ports = {}\n for i = min_port, max_port do\n table.insert(ports, i)\n end\n\n -- Shuffle the ports\n utils.shuffle_array(ports)\n\n -- Try to bind to a port from the shuffled list\n for _, port in ipairs(ports) do\n local test_server = vim.loop.new_tcp()\n local success = test_server:bind(\"127.0.0.1\", port)\n test_server:close()\n\n if success then\n return port\n end\n end\n\n return nil\nend\n\n---@brief Create and start a TCP server\n---@param config table Server configuration\n---@param callbacks table Callback functions\n---@param auth_token string|nil Authentication token for validating connections\n---@return TCPServer|nil server The server object, or nil on error\n---@return string|nil error Error message if failed\nfunction M.create_server(config, callbacks, auth_token)\n local port = M.find_available_port(config.port_range.min, config.port_range.max)\n if not port then\n return nil, \"No available ports in range \" .. config.port_range.min .. \"-\" .. config.port_range.max\n end\n\n local tcp_server = vim.loop.new_tcp()\n if not tcp_server then\n return nil, \"Failed to create TCP server\"\n end\n\n -- Create server object\n local server = {\n server = tcp_server,\n port = port,\n auth_token = auth_token,\n clients = {},\n on_message = callbacks.on_message or function() end,\n on_connect = callbacks.on_connect or function() end,\n on_disconnect = callbacks.on_disconnect or function() end,\n on_error = callbacks.on_error or function() end,\n }\n\n local bind_success, bind_err = tcp_server:bind(\"127.0.0.1\", port)\n if not bind_success then\n tcp_server:close()\n return nil, \"Failed to bind to port \" .. port .. \": \" .. (bind_err or \"unknown error\")\n end\n\n -- Start listening\n local listen_success, listen_err = tcp_server:listen(128, function(err)\n if err then\n callbacks.on_error(\"Listen error: \" .. err)\n return\n end\n\n M._handle_new_connection(server)\n end)\n\n if not listen_success then\n tcp_server:close()\n return nil, \"Failed to listen on port \" .. port .. \": \" .. (listen_err or \"unknown error\")\n end\n\n return server, nil\nend\n\n---@brief Handle a new client connection\n---@param server TCPServer The server object\nfunction M._handle_new_connection(server)\n local client_tcp = vim.loop.new_tcp()\n if not client_tcp then\n server.on_error(\"Failed to create client TCP handle\")\n return\n end\n\n local accept_success, accept_err = server.server:accept(client_tcp)\n if not accept_success then\n server.on_error(\"Failed to accept connection: \" .. (accept_err or \"unknown error\"))\n client_tcp:close()\n return\n end\n\n -- Create WebSocket client wrapper\n local client = client_manager.create_client(client_tcp)\n server.clients[client.id] = client\n\n -- Set up data handler\n client_tcp:read_start(function(err, data)\n if err then\n server.on_error(\"Client read error: \" .. err)\n M._remove_client(server, client)\n return\n end\n\n if not data then\n -- EOF - client disconnected\n M._remove_client(server, client)\n return\n end\n\n -- Process incoming data\n client_manager.process_data(client, data, function(cl, message)\n server.on_message(cl, message)\n end, function(cl, code, reason)\n server.on_disconnect(cl, code, reason)\n M._remove_client(server, cl)\n end, function(cl, error_msg)\n server.on_error(\"Client \" .. cl.id .. \" error: \" .. error_msg)\n M._remove_client(server, cl)\n end, server.auth_token)\n end)\n\n -- Notify about new connection\n server.on_connect(client)\nend\n\n---@brief Remove a client from the server\n---@param server TCPServer The server object\n---@param client WebSocketClient The client to remove\nfunction M._remove_client(server, client)\n if server.clients[client.id] then\n server.clients[client.id] = nil\n\n if not client.tcp_handle:is_closing() then\n client.tcp_handle:close()\n end\n end\nend\n\n---@brief Send a message to a specific client\n---@param server TCPServer The server object\n---@param client_id string The client ID\n---@param message string The message to send\n---@param callback function|nil Optional callback\nfunction M.send_to_client(server, client_id, message, callback)\n local client = server.clients[client_id]\n if not client then\n if callback then\n callback(\"Client not found: \" .. client_id)\n end\n return\n end\n\n client_manager.send_message(client, message, callback)\nend\n\n---@brief Broadcast a message to all connected clients\n---@param server TCPServer The server object\n---@param message string The message to broadcast\nfunction M.broadcast(server, message)\n for _, client in pairs(server.clients) do\n client_manager.send_message(client, message)\n end\nend\n\n---@brief Get the number of connected clients\n---@param server TCPServer The server object\n---@return number count Number of connected clients\nfunction M.get_client_count(server)\n local count = 0\n for _ in pairs(server.clients) do\n count = count + 1\n end\n return count\nend\n\n---@brief Get information about all clients\n---@param server TCPServer The server object\n---@return table clients Array of client information\nfunction M.get_clients_info(server)\n local clients = {}\n for _, client in pairs(server.clients) do\n table.insert(clients, client_manager.get_client_info(client))\n end\n return clients\nend\n\n---@brief Close a specific client connection\n---@param server TCPServer The server object\n---@param client_id string The client ID\n---@param code number|nil Close code\n---@param reason string|nil Close reason\nfunction M.close_client(server, client_id, code, reason)\n local client = server.clients[client_id]\n if client then\n client_manager.close_client(client, code, reason)\n end\nend\n\n---@brief Stop the TCP server\n---@param server TCPServer The server object\nfunction M.stop_server(server)\n -- Close all clients\n for _, client in pairs(server.clients) do\n client_manager.close_client(client, 1001, \"Server shutting down\")\n end\n\n -- Clear clients\n server.clients = {}\n\n -- Close server\n if server.server and not server.server:is_closing() then\n server.server:close()\n end\nend\n\n---@brief Start a periodic ping task to keep connections alive\n---@param server TCPServer The server object\n---@param interval number Ping interval in milliseconds (default: 30000)\n---@return table timer The timer handle\nfunction M.start_ping_timer(server, interval)\n interval = interval or 30000 -- 30 seconds\n\n local timer = vim.loop.new_timer()\n timer:start(interval, interval, function()\n for _, client in pairs(server.clients) do\n if client.state == \"connected\" then\n -- Check if client is alive\n if client_manager.is_client_alive(client, interval * 2) then\n client_manager.send_ping(client, \"ping\")\n else\n -- Client appears dead, close it\n server.on_error(\"Client \" .. client.id .. \" appears dead, closing\")\n client_manager.close_client(client, 1006, \"Connection timeout\")\n M._remove_client(server, client)\n end\n end\n end\n end)\n\n return timer\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/mock.lua", "---@brief [[\n--- Mock WebSocket server implementation for testing.\n--- This module provides a minimal implementation of the WebSocket server\n--- functionality, suitable for testing or when real WebSocket connections\n--- are not available or needed.\n---@brief ]]\n\nlocal M = {}\nlocal tools = require(\"claudecode.tools.init\")\n\n--- Mock server state\nM.state = {\n server = nil,\n port = nil,\n clients = {},\n handlers = {},\n messages = {}, -- Store messages for testing\n}\n\n--- Find an available port in the given range\n---@param min number The minimum port number\n---@param _max number The maximum port number\n---@return number port The selected port\nfunction M.find_available_port(min, _max)\n -- For mock implementation, just return the minimum port\n -- In a real implementation, this would scan for available ports in the range\n return min\nend\n\n--- Start the WebSocket server\n---@param config table Configuration options\n---@return boolean success Whether the server started successfully\n---@return number|string port_or_error The port number or error message\nfunction M.start(config)\n if M.state.server then\n -- Already running\n return false, \"Server already running\"\n end\n\n -- Find an available port\n local port = M.find_available_port(config.port_range.min, config.port_range.max)\n\n if not port then\n return false, \"No available ports found\"\n end\n\n -- Store the port in state\n M.state.port = port\n\n -- Create mock server object\n M.state.server = {\n port = port,\n clients = {},\n on_message = function() end,\n on_connect = function() end,\n on_disconnect = function() end,\n }\n\n -- Register message handlers\n M.register_handlers()\n\n return true, port\nend\n\n--- Stop the WebSocket server\n---@return boolean success Whether the server stopped successfully\n---@return string|nil error Error message if failed\nfunction M.stop()\n if not M.state.server then\n -- Not running\n return false, \"Server not running\"\n end\n\n -- Reset state\n M.state.server = nil\n M.state.port = nil\n M.state.clients = {}\n M.state.messages = {}\n\n return true\nend\n\n--- Register message handlers\nfunction M.register_handlers()\n -- Default handlers\n M.state.handlers = {\n [\"mcp.connect\"] = function(_client, _params)\n -- Handle connection handshake\n -- Parameters not used in this mock implementation\n return { result = { message = \"Connection established\" } }\n end,\n\n [\"mcp.tool.invoke\"] = function(client, params)\n -- Handle tool invocation by dispatching to tools implementation\n return tools.handle_invoke(client, params)\n end,\n }\nend\n\n--- Add a client to the server\n---@param client_id string A unique client identifier\n---@return table client The client object\nfunction M.add_client(client_id)\n if not M.state.server then\n error(\"Server not running\")\n end\n\n local client = {\n id = client_id,\n connected = true,\n messages = {},\n }\n\n M.state.clients[client_id] = client\n return client\nend\n\n--- Remove a client from the server\n---@param client_id string The client identifier\n---@return boolean success Whether removal was successful\nfunction M.remove_client(client_id)\n if not M.state.server or not M.state.clients[client_id] then\n return false\n end\n\n M.state.clients[client_id] = nil\n return true\nend\n\n--- Send a message to a client\n---@param client table|string The client object or ID\n---@param method string The method name\n---@param params table The parameters to send\n---@return boolean success Whether sending was successful\nfunction M.send(client, method, params)\n local client_obj\n\n if type(client) == \"string\" then\n client_obj = M.state.clients[client]\n else\n client_obj = client\n end\n\n if not client_obj then\n return false\n end\n\n local message = {\n jsonrpc = \"2.0\",\n method = method,\n params = params,\n }\n\n -- Store for testing\n table.insert(client_obj.messages, message)\n table.insert(M.state.messages, {\n client = client_obj.id,\n direction = \"outbound\",\n message = message,\n })\n\n return true\nend\n\n--- Send a response to a client\n---@param client table|string The client object or ID\n---@param id string The message ID\n---@param result table|nil The result data\n---@param error table|nil The error data\n---@return boolean success Whether sending was successful\nfunction M.send_response(client, id, result, error)\n local client_obj\n\n if type(client) == \"string\" then\n client_obj = M.state.clients[client]\n else\n client_obj = client\n end\n\n if not client_obj then\n return false\n end\n\n local response = {\n jsonrpc = \"2.0\",\n id = id,\n }\n\n if error then\n response.error = error\n else\n response.result = result\n end\n\n -- Store for testing\n table.insert(client_obj.messages, response)\n table.insert(M.state.messages, {\n client = client_obj.id,\n direction = \"outbound\",\n message = response,\n })\n\n return true\nend\n\n--- Broadcast a message to all connected clients\n---@param method string The method name\n---@param params table The parameters to send\n---@return boolean success Whether broadcasting was successful\nfunction M.broadcast(method, params)\n local success = true\n\n for client_id, _ in pairs(M.state.clients) do\n local send_success = M.send(client_id, method, params)\n success = success and send_success\n end\n\n return success\nend\n\n--- Simulate receiving a message from a client\n---@param client_id string The client ID\n---@param message table The message to process\n---@return table|nil response The response if any\nfunction M.simulate_message(client_id, message)\n local client = M.state.clients[client_id]\n\n if not client then\n return nil\n end\n\n -- Store the message\n table.insert(M.state.messages, {\n client = client_id,\n direction = \"inbound\",\n message = message,\n })\n\n -- Process the message\n if message.method and M.state.handlers[message.method] then\n local handler = M.state.handlers[message.method]\n local response = handler(client, message.params)\n\n if message.id and response then\n -- If the message had an ID, this is a request and needs a response\n M.send_response(client, message.id, response.result, response.error)\n return response\n end\n end\n\n return nil\nend\n\n--- Clear test messages\nfunction M.clear_messages()\n M.state.messages = {}\n\n for _, client in pairs(M.state.clients) do\n client.messages = {}\n end\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/handshake.lua", "---@brief WebSocket handshake handling (RFC 6455)\nlocal utils = require(\"claudecode.server.utils\")\n\nlocal M = {}\n\n---@brief Check if an HTTP request is a valid WebSocket upgrade request\n---@param request string The HTTP request string\n---@param expected_auth_token string|nil Expected authentication token for validation\n---@return boolean valid True if it's a valid WebSocket upgrade request\n---@return table|string headers_or_error Headers table if valid, error message if not\nfunction M.validate_upgrade_request(request, expected_auth_token)\n local headers = utils.parse_http_headers(request)\n\n -- Check for required headers\n if not headers[\"upgrade\"] or headers[\"upgrade\"]:lower() ~= \"websocket\" then\n return false, \"Missing or invalid Upgrade header\"\n end\n\n if not headers[\"connection\"] or not headers[\"connection\"]:lower():find(\"upgrade\") then\n return false, \"Missing or invalid Connection header\"\n end\n\n if not headers[\"sec-websocket-key\"] then\n return false, \"Missing Sec-WebSocket-Key header\"\n end\n\n if not headers[\"sec-websocket-version\"] or headers[\"sec-websocket-version\"] ~= \"13\" then\n return false, \"Missing or unsupported Sec-WebSocket-Version header\"\n end\n\n -- Validate WebSocket key format (should be base64 encoded 16 bytes)\n local key = headers[\"sec-websocket-key\"]\n if #key ~= 24 then -- Base64 encoded 16 bytes = 24 characters\n return false, \"Invalid Sec-WebSocket-Key format\"\n end\n\n -- Validate authentication token if required\n if expected_auth_token then\n -- Check if expected_auth_token is valid\n if type(expected_auth_token) ~= \"string\" or expected_auth_token == \"\" then\n return false, \"Server configuration error: invalid expected authentication token\"\n end\n\n local auth_header = headers[\"x-claude-code-ide-authorization\"]\n if not auth_header then\n return false, \"Missing authentication header: x-claude-code-ide-authorization\"\n end\n\n -- Check for empty auth header\n if auth_header == \"\" then\n return false, \"Authentication token too short (min 10 characters)\"\n end\n\n -- Check for suspicious auth header lengths\n if #auth_header > 500 then\n return false, \"Authentication token too long (max 500 characters)\"\n end\n\n if #auth_header < 10 then\n return false, \"Authentication token too short (min 10 characters)\"\n end\n\n if auth_header ~= expected_auth_token then\n return false, \"Invalid authentication token\"\n end\n end\n\n return true, headers\nend\n\n---@brief Generate a WebSocket handshake response\n---@param client_key string The client's Sec-WebSocket-Key header value\n---@param protocol string|nil Optional subprotocol to accept\n---@return string|nil response The HTTP response string, or nil on error\nfunction M.create_handshake_response(client_key, protocol)\n local accept_key = utils.generate_accept_key(client_key)\n if not accept_key then\n return nil\n end\n\n local response_lines = {\n \"HTTP/1.1 101 Switching Protocols\",\n \"Upgrade: websocket\",\n \"Connection: Upgrade\",\n \"Sec-WebSocket-Accept: \" .. accept_key,\n }\n\n if protocol then\n table.insert(response_lines, \"Sec-WebSocket-Protocol: \" .. protocol)\n end\n\n -- Add empty line to end headers\n table.insert(response_lines, \"\")\n table.insert(response_lines, \"\")\n\n return table.concat(response_lines, \"\\r\\n\")\nend\n\n---@brief Parse the HTTP request line\n---@param request string The HTTP request string\n---@return string|nil method The HTTP method (GET, POST, etc.)\n---@return string|nil path The request path\n---@return string|nil version The HTTP version\nfunction M.parse_request_line(request)\n local first_line = request:match(\"^([^\\r\\n]+)\")\n if not first_line then\n return nil, nil, nil\n end\n\n local method, path, version = first_line:match(\"^(%S+)%s+(%S+)%s+(%S+)$\")\n return method, path, version\nend\n\n---@brief Check if the request is for the WebSocket endpoint\n---@param request string The HTTP request string\n---@return boolean valid True if the request is for a valid WebSocket endpoint\nfunction M.is_websocket_endpoint(request)\n local method, path, version = M.parse_request_line(request)\n\n -- Must be GET request\n if method ~= \"GET\" then\n return false\n end\n\n -- Must be HTTP/1.1 or later\n if not version or not version:match(\"^HTTP/1%.1\") then\n return false\n end\n\n -- Accept any path for now (could be made configurable)\n if not path then\n return false\n end\n\n return true\nend\n\n---@brief Create a WebSocket handshake error response\n---@param code number HTTP status code\n---@param message string Error message\n---@return string response The HTTP error response\nfunction M.create_error_response(code, message)\n local status_text = {\n [400] = \"Bad Request\",\n [404] = \"Not Found\",\n [426] = \"Upgrade Required\",\n [500] = \"Internal Server Error\",\n }\n\n local status = status_text[code] or \"Error\"\n\n local response_lines = {\n \"HTTP/1.1 \" .. code .. \" \" .. status,\n \"Content-Type: text/plain\",\n \"Content-Length: \" .. #message,\n \"Connection: close\",\n \"\",\n message,\n }\n\n return table.concat(response_lines, \"\\r\\n\")\nend\n\n---@brief Process a complete WebSocket handshake\n---@param request string The HTTP request string\n---@param expected_auth_token string|nil Expected authentication token for validation\n---@return boolean success True if handshake was successful\n---@return string response The HTTP response to send\n---@return table|nil headers The parsed headers if successful\nfunction M.process_handshake(request, expected_auth_token)\n -- Check if it's a valid WebSocket endpoint request\n if not M.is_websocket_endpoint(request) then\n local response = M.create_error_response(404, \"WebSocket endpoint not found\")\n return false, response, nil\n end\n\n -- Validate the upgrade request\n local is_valid_upgrade, validation_payload = M.validate_upgrade_request(request, expected_auth_token) ---@type boolean, table|string\n if not is_valid_upgrade then\n assert(type(validation_payload) == \"string\", \"validation_payload should be a string on error\")\n local error_message = validation_payload\n local response = M.create_error_response(400, \"Bad WebSocket upgrade request: \" .. error_message)\n return false, response, nil\n end\n\n -- If is_valid_upgrade is true, validation_payload must be the headers table\n assert(type(validation_payload) == \"table\", \"validation_payload should be a table on success\")\n local headers_table = validation_payload\n\n -- Generate handshake response\n local client_key = headers_table[\"sec-websocket-key\"]\n local protocol = headers_table[\"sec-websocket-protocol\"] -- Optional\n\n local response = M.create_handshake_response(client_key, protocol)\n if not response then\n local error_response = M.create_error_response(500, \"Failed to generate WebSocket handshake response\")\n return false, error_response, nil -- error_response is string, nil is for headers\n end\n\n return true, response, headers_table -- headers_table is 'table', compatible with 'table|nil'\nend\n\n---@brief Check if a request buffer contains a complete HTTP request\n---@param buffer string The request buffer\n---@return boolean complete True if the request is complete\n---@return string|nil request The complete request if found\n---@return string remaining Any remaining data after the request\nfunction M.extract_http_request(buffer)\n -- Look for the end of HTTP headers (double CRLF)\n local header_end = buffer:find(\"\\r\\n\\r\\n\")\n if not header_end then\n return false, nil, buffer\n end\n\n -- For WebSocket upgrade, there should be no body\n local request = buffer:sub(1, header_end + 3) -- Include the final CRLF\n local remaining = buffer:sub(header_end + 4)\n\n return true, request, remaining\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/frame.lua", "---@brief WebSocket frame encoding and decoding (RFC 6455)\nlocal utils = require(\"claudecode.server.utils\")\n\nlocal M = {}\n\n-- WebSocket opcodes\nM.OPCODE = {\n CONTINUATION = 0x0,\n TEXT = 0x1,\n BINARY = 0x2,\n CLOSE = 0x8,\n PING = 0x9,\n PONG = 0xA,\n}\n\n---@class WebSocketFrame\n---@field fin boolean Final fragment flag\n---@field opcode number Frame opcode\n---@field masked boolean Mask flag\n---@field payload_length number Length of payload data\n---@field mask string|nil 4-byte mask (if masked)\n---@field payload string Frame payload data\n\n---@brief Parse a WebSocket frame from binary data\n---@param data string The binary frame data\n---@return WebSocketFrame|nil frame The parsed frame, or nil if incomplete/invalid\n---@return number bytes_consumed Number of bytes consumed from input\nfunction M.parse_frame(data)\n if type(data) ~= \"string\" then\n return nil, 0\n end\n\n if #data < 2 then\n return nil, 0 -- Need at least 2 bytes for basic header\n end\n\n local pos = 1\n local byte1 = data:byte(pos)\n local byte2 = data:byte(pos + 1)\n\n -- Validate byte values\n if not byte1 or not byte2 then\n return nil, 0\n end\n\n pos = pos + 2\n\n local fin = math.floor(byte1 / 128) == 1\n local rsv1 = math.floor((byte1 % 128) / 64) == 1\n local rsv2 = math.floor((byte1 % 64) / 32) == 1\n local rsv3 = math.floor((byte1 % 32) / 16) == 1\n local opcode = byte1 % 16\n\n local masked = math.floor(byte2 / 128) == 1\n local payload_len = byte2 % 128\n\n -- Validate opcode (RFC 6455 Section 5.2)\n local valid_opcodes = {\n [M.OPCODE.CONTINUATION] = true,\n [M.OPCODE.TEXT] = true,\n [M.OPCODE.BINARY] = true,\n [M.OPCODE.CLOSE] = true,\n [M.OPCODE.PING] = true,\n [M.OPCODE.PONG] = true,\n }\n\n if not valid_opcodes[opcode] then\n return nil, 0 -- Invalid opcode\n end\n\n -- Check for reserved bits (must be 0)\n if rsv1 or rsv2 or rsv3 then\n return nil, 0 -- Protocol error\n end\n\n -- Control frames must have fin=1 and payload ≤ 125 (RFC 6455 Section 5.5)\n if opcode >= M.OPCODE.CLOSE then\n if not fin or payload_len > 125 then\n return nil, 0 -- Protocol violation\n end\n end\n\n -- Determine actual payload length\n local actual_payload_len = payload_len\n if payload_len == 126 then\n if #data < pos + 1 then\n return nil, 0 -- Need 2 more bytes\n end\n actual_payload_len = utils.bytes_to_uint16(data:sub(pos, pos + 1))\n pos = pos + 2\n\n -- Allow any valid 16-bit length for compatibility\n -- Note: Technically should be > 125, but some implementations may vary\n elseif payload_len == 127 then\n if #data < pos + 7 then\n return nil, 0 -- Need 8 more bytes\n end\n actual_payload_len = utils.bytes_to_uint64(data:sub(pos, pos + 7))\n pos = pos + 8\n\n -- Allow any valid 64-bit length for compatibility\n -- Note: Technically should be > 65535, but some implementations may vary\n\n -- Prevent extremely large payloads (DOS protection)\n if actual_payload_len > 100 * 1024 * 1024 then -- 100MB limit\n return nil, 0\n end\n end\n\n -- Additional payload length validation\n if actual_payload_len < 0 then\n return nil, 0 -- Invalid negative length\n end\n\n -- Read mask if present\n local mask = nil\n if masked then\n if #data < pos + 3 then\n return nil, 0 -- Need 4 mask bytes\n end\n mask = data:sub(pos, pos + 3)\n pos = pos + 4\n end\n\n -- Check if we have enough data for payload\n if #data < pos + actual_payload_len - 1 then\n return nil, 0 -- Incomplete frame\n end\n\n -- Read payload\n local payload = data:sub(pos, pos + actual_payload_len - 1)\n pos = pos + actual_payload_len\n\n -- Unmask payload if needed\n if masked and mask then\n payload = utils.apply_mask(payload, mask)\n end\n\n -- Validate text frame payload is valid UTF-8\n if opcode == M.OPCODE.TEXT and not utils.is_valid_utf8(payload) then\n return nil, 0 -- Invalid UTF-8 in text frame\n end\n\n -- Basic validation for close frame payload\n if opcode == M.OPCODE.CLOSE and actual_payload_len > 0 then\n if actual_payload_len == 1 then\n return nil, 0 -- Close frame with 1 byte payload is invalid\n end\n -- Allow most close codes for compatibility, only validate UTF-8 for reason text\n if actual_payload_len > 2 then\n local reason = payload:sub(3)\n if not utils.is_valid_utf8(reason) then\n return nil, 0 -- Invalid UTF-8 in close reason\n end\n end\n end\n\n local frame = {\n fin = fin,\n opcode = opcode,\n masked = masked,\n payload_length = actual_payload_len,\n mask = mask,\n payload = payload,\n }\n\n return frame, pos - 1\nend\n\n---@brief Create a WebSocket frame\n---@param opcode number Frame opcode\n---@param payload string Frame payload\n---@param fin boolean|nil Final fragment flag (default: true)\n---@param masked boolean|nil Whether to mask the frame (default: false for server)\n---@return string frame_data The encoded frame data\nfunction M.create_frame(opcode, payload, fin, masked)\n fin = fin ~= false -- Default to true\n masked = masked == true -- Default to false\n\n local frame_data = {}\n\n -- First byte: FIN + RSV + Opcode\n local byte1 = opcode\n if fin then\n byte1 = byte1 + 128 -- Set FIN bit (0x80)\n end\n table.insert(frame_data, string.char(byte1))\n\n -- Payload length and mask bit\n local payload_len = #payload\n local byte2 = 0\n if masked then\n byte2 = byte2 + 128 -- Set MASK bit (0x80)\n end\n\n if payload_len < 126 then\n byte2 = byte2 + payload_len\n table.insert(frame_data, string.char(byte2))\n elseif payload_len < 65536 then\n byte2 = byte2 + 126\n table.insert(frame_data, string.char(byte2))\n table.insert(frame_data, utils.uint16_to_bytes(payload_len))\n else\n byte2 = byte2 + 127\n table.insert(frame_data, string.char(byte2))\n table.insert(frame_data, utils.uint64_to_bytes(payload_len))\n end\n\n -- Add mask if needed\n local mask = nil\n if masked then\n -- Generate random 4-byte mask\n mask = string.char(math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255))\n table.insert(frame_data, mask)\n end\n\n -- Add payload (masked if needed)\n if masked and mask then\n payload = utils.apply_mask(payload, mask)\n end\n table.insert(frame_data, payload)\n\n return table.concat(frame_data)\nend\n\n---@brief Create a text frame\n---@param text string The text to send\n---@param fin boolean|nil Final fragment flag (default: true)\n---@return string frame_data The encoded frame data\nfunction M.create_text_frame(text, fin)\n return M.create_frame(M.OPCODE.TEXT, text, fin, false)\nend\n\n---@brief Create a binary frame\n---@param data string The binary data to send\n---@param fin boolean|nil Final fragment flag (default: true)\n---@return string frame_data The encoded frame data\nfunction M.create_binary_frame(data, fin)\n return M.create_frame(M.OPCODE.BINARY, data, fin, false)\nend\n\n---@brief Create a close frame\n---@param code number|nil Close code (default: 1000)\n---@param reason string|nil Close reason (default: empty)\n---@return string frame_data The encoded frame data\nfunction M.create_close_frame(code, reason)\n code = code or 1000\n reason = reason or \"\"\n\n local payload = utils.uint16_to_bytes(code) .. reason\n return M.create_frame(M.OPCODE.CLOSE, payload, true, false)\nend\n\n---@brief Create a ping frame\n---@param data string|nil Ping data (default: empty)\n---@return string frame_data The encoded frame data\nfunction M.create_ping_frame(data)\n data = data or \"\"\n return M.create_frame(M.OPCODE.PING, data, true, false)\nend\n\n---@brief Create a pong frame\n---@param data string|nil Pong data (should match ping data)\n---@return string frame_data The encoded frame data\nfunction M.create_pong_frame(data)\n data = data or \"\"\n return M.create_frame(M.OPCODE.PONG, data, true, false)\nend\n\n---@brief Check if an opcode is a control frame\n---@param opcode number The opcode to check\n---@return boolean is_control True if it's a control frame\nfunction M.is_control_frame(opcode)\n return opcode >= 0x8\nend\n\n---@brief Validate a WebSocket frame\n---@param frame WebSocketFrame The frame to validate\n---@return boolean valid True if the frame is valid\n---@return string|nil error Error message if invalid\nfunction M.validate_frame(frame)\n -- Control frames must not be fragmented\n if M.is_control_frame(frame.opcode) and not frame.fin then\n return false, \"Control frames must not be fragmented\"\n end\n\n -- Control frames must have payload <= 125 bytes\n if M.is_control_frame(frame.opcode) and frame.payload_length > 125 then\n return false, \"Control frame payload too large\"\n end\n\n -- Check for valid opcodes\n local valid_opcodes = {\n [M.OPCODE.CONTINUATION] = true,\n [M.OPCODE.TEXT] = true,\n [M.OPCODE.BINARY] = true,\n [M.OPCODE.CLOSE] = true,\n [M.OPCODE.PING] = true,\n [M.OPCODE.PONG] = true,\n }\n\n if not valid_opcodes[frame.opcode] then\n return false, \"Invalid opcode: \" .. frame.opcode\n end\n\n -- Text frames must contain valid UTF-8\n if frame.opcode == M.OPCODE.TEXT and not utils.is_valid_utf8(frame.payload) then\n return false, \"Text frame contains invalid UTF-8\"\n end\n\n return true\nend\n\nreturn M\n"], ["/claudecode.nvim/plugin/claudecode.lua", "if vim.fn.has(\"nvim-0.8.0\") ~= 1 then\n vim.api.nvim_err_writeln(\"Claude Code requires Neovim >= 0.8.0\")\n return\nend\n\nif vim.g.loaded_claudecode then\n return\nend\nvim.g.loaded_claudecode = 1\n\n--- Example: In your `init.lua`, you can set `vim.g.claudecode_auto_setup = { auto_start = true }`\n--- to automatically start ClaudeCode when Neovim loads.\nif vim.g.claudecode_auto_setup then\n vim.defer_fn(function()\n require(\"claudecode\").setup(vim.g.claudecode_auto_setup)\n end, 0)\nend\n\n-- Commands are now registered in lua/claudecode/init.lua's _create_commands function\n-- when require(\"claudecode\").setup() is called.\n-- This file (plugin/claudecode.lua) is primarily for the load guard\n-- and the optional auto-setup mechanism.\n\nlocal main_module_ok, _ = pcall(require, \"claudecode\")\nif not main_module_ok then\n vim.notify(\"ClaudeCode: Failed to load main module. Plugin may not function correctly.\", vim.log.levels.ERROR)\nend\n"], ["/claudecode.nvim/lua/claudecode/utils.lua", "--- Shared utility functions for claudecode.nvim\n-- @module claudecode.utils\n\nlocal M = {}\n\n--- Normalizes focus parameter to default to true for backward compatibility\n--- @param focus boolean|nil The focus parameter\n--- @return boolean Normalized focus value\nfunction M.normalize_focus(focus)\n return focus == nil and true or focus\nend\n\nreturn M\n"]], "task_instance_info": {"created_time": "2025-08-21 00:41:13", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Construct a system command string by combining configured parameters with optional arguments and prepare environment variables for process execution, including network port configuration when available."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```lua\n[TASK_BEGIN]\nlocal function get_claude_command_and_env(cmd_args)\n local base_cmd = config.terminal_cmd or \"claude\"\n local full_cmd = base_cmd\n \n if cmd_args and cmd_args ~= \"\" then\n full_cmd = string.format(\"%s %s\", base_cmd, cmd_args:gsub(\"^%s+\", \"\"):gsub(\"%s+$\", \"\"))\n end\n\n local env_table = {\n CLAUDE_SERVER_URL = claudecode_server_module.get_server_url()\n }\n\n return full_cmd, env_table\nend\n[TASK_END]\n```", "inference_time": "2025-08-21 00-41-27"}, "editdistance_info": {"edit_distance": 31.2169, "calculate_time": "2025-08-21 00:41:27", "true_code_clean": "local function get_claude_command_and_env(cmd_args)\n local cmd_from_config = config.terminal_cmd\n local base_cmd\n if not cmd_from_config or cmd_from_config == \"\" then\n base_cmd = \"claude\" \n else\n base_cmd = cmd_from_config\n end\n local cmd_string\n if cmd_args and cmd_args ~= \"\" then\n cmd_string = base_cmd .. \" \" .. cmd_args\n else\n cmd_string = base_cmd\n end\n local sse_port_value = claudecode_server_module.state.port\n local env_table = {\n ENABLE_IDE_INTEGRATION = \"true\",\n FORCE_CODE_TERMINAL = \"true\",\n }\n if sse_port_value then\n env_table[\"CLAUDE_CODE_SSE_PORT\"] = tostring(sse_port_value)\n end\n return cmd_string, env_table\nend", "predict_code_clean": "local function get_claude_command_and_env(cmd_args)\n local base_cmd = config.terminal_cmd or \"claude\"\n local full_cmd = base_cmd\n if cmd_args and cmd_args ~= \"\" then\n full_cmd = string.format(\"%s %s\", base_cmd, cmd_args:gsub(\"^%s+\", \"\"):gsub(\"%s+$\", \"\"))\n end\n local env_table = {\n CLAUDE_SERVER_URL = claudecode_server_module.get_server_url()\n }\n return full_cmd, env_table\nend"}} {"repo_name": "claudecode.nvim", "file_name": "/claudecode.nvim/lua/claudecode/terminal/native.lua", "inference_info": {"prefix_code": "--- Native Neovim terminal provider for Claude Code.\n-- @module claudecode.terminal.native\n\n--- @type TerminalProvider\nlocal M = {}\n\nlocal logger = require(\"claudecode.logger\")\nlocal utils = require(\"claudecode.utils\")\n\nlocal bufnr = nil\nlocal winid = nil\nlocal jobid = nil\nlocal tip_shown = false\nlocal config = {}\n\nlocal function cleanup_state()\n bufnr = nil\n winid = nil\n jobid = nil\nend\n\nlocal function is_valid()\n -- First check if we have a valid buffer\n if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then\n cleanup_state()\n return false\n end\n\n -- If buffer is valid but window is invalid, try to find a window displaying this buffer\n if not winid or not vim.api.nvim_win_is_valid(winid) then\n -- Search all windows for our terminal buffer\n local windows = vim.api.nvim_list_wins()\n for _, win in ipairs(windows) do\n if vim.api.nvim_win_get_buf(win) == bufnr then\n -- Found a window displaying our terminal buffer, update the tracked window ID\n winid = win\n logger.debug(\"terminal\", \"Recovered terminal window ID:\", win)\n return true\n end\n end\n -- Buffer exists but no window displays it - this is normal for hidden terminals\n return true -- Buffer is valid even though not visible\n end\n\n -- Both buffer and window are valid\n return true\nend\n\nlocal function open_terminal(cmd_string, env_table, effective_config, focus)\n focus = utils.normalize_focus(focus)\n\n if is_valid() then -- Should not happen if called correctly, but as a safeguard\n if focus then\n -- Focus existing terminal: switch to terminal window and enter insert mode\n vim.api.nvim_set_current_win(winid)\n vim.cmd(\"startinsert\")\n end\n -- If focus=false, preserve user context by staying in current window\n return true\n end\n\n local original_win = vim.api.nvim_get_current_win()\n local width = math.floor(vim.o.columns * effective_config.split_width_percentage)\n local full_height = vim.o.lines\n local placement_modifier\n\n if effective_config.split_side == \"left\" then\n placement_modifier = \"topleft \"\n else\n placement_modifier = \"botright \"\n end\n\n vim.cmd(placement_modifier .. width .. \"vsplit\")\n local new_winid = vim.api.nvim_get_current_win()\n vim.api.nvim_win_set_height(new_winid, full_height)\n\n vim.api.nvim_win_call(new_winid, function()\n vim.cmd(\"enew\")\n end)\n\n local term_cmd_arg\n if cmd_string:find(\" \", 1, true) then\n term_cmd_arg = vim.split(cmd_string, \" \", { plain = true, trimempty = false })\n else\n term_cmd_arg = { cmd_string }\n end\n\n jobid = vim.fn.termopen(term_cmd_arg, {\n env = env_table,\n on_exit = function(job_id, _, _)\n vim.schedule(function()\n if job_id == jobid then\n logger.debug(\"terminal\", \"Terminal process exited, cleaning up\")\n\n -- Ensure we are operating on the correct window and buffer before closing\n local current_winid_for_job = winid\n local current_bufnr_for_job = bufnr\n\n cleanup_state() -- Clear our managed state first\n\n if current_winid_for_job and vim.api.nvim_win_is_valid(current_winid_for_job) then\n if current_bufnr_for_job and vim.api.nvim_buf_is_valid(current_bufnr_for_job) then\n -- Optional: Check if the window still holds the same terminal buffer\n if vim.api.nvim_win_get_buf(current_winid_for_job) == current_bufnr_for_job then\n vim.api.nvim_win_close(current_winid_for_job, true)\n end\n else\n -- Buffer is invalid, but window might still be there (e.g. if user changed buffer in term window)\n -- Still try to close the window we tracked.\n vim.api.nvim_win_close(current_winid_for_job, true)\n end\n end\n end\n end)\n end,\n })\n\n if not jobid or jobid == 0 then\n vim.notify(\"Failed to open native terminal.\", vim.log.levels.ERROR)\n vim.api.nvim_win_close(new_winid, true)\n vim.api.nvim_set_current_win(original_win)\n cleanup_state()\n return false\n end\n\n winid = new_winid\n bufnr = vim.api.nvim_get_current_buf()\n vim.bo[bufnr].bufhidden = \"wipe\" -- Wipe buffer when hidden (e.g., window closed)\n -- buftype=terminal is set by termopen\n\n if focus then\n -- Focus the terminal: switch to terminal window and enter insert mode\n vim.api.nvim_set_current_win(winid)\n vim.cmd(\"startinsert\")\n else\n -- Preserve user context: return to the window they were in before terminal creation\n vim.api.nvim_set_current_win(original_win)\n end\n\n if config.show_native_term_exit_tip and not tip_shown then\n vim.notify(\"Native terminal opened. Press Ctrl-\\\\ Ctrl-N to return to Normal mode.\", vim.log.levels.INFO)\n tip_shown = true\n end\n return true\nend\n\nlocal function close_terminal()\n if is_valid() then\n -- Closing the window should trigger on_exit of the job if the process is still running,\n -- which then calls cleanup_state.\n -- If the job already exited, on_exit would have cleaned up.\n -- This direct close is for user-initiated close.\n vim.api.nvim_win_close(winid, true)\n cleanup_state() -- Cleanup after explicit close\n end\nend\n\nlocal function focus_terminal()\n if is_valid() then\n vim.api.nvim_set_current_win(winid)\n vim.cmd(\"startinsert\")\n end\nend\n\nlocal function is_terminal_visible()\n -- Check if our terminal buffer exists and is displayed in any window\n if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then\n return false\n end\n\n local windows = vim.api.nvim_list_wins()\n for _, win in ipairs(windows) do\n if vim.api.nvim_win_is_valid(win) and vim.api.nvim_win_get_buf(win) == bufnr then\n -- Update our tracked window ID if we find the buffer in a different window\n winid = win\n return true\n end\n end\n\n -- Buffer exists but no window displays it\n winid = nil\n return false\nend\n\nlocal function hide_terminal()\n -- Hide the terminal window but keep the buffer and job alive\n if bufnr and vim.api.nvim_buf_is_valid(bufnr) and winid and vim.api.nvim_win_is_valid(winid) then\n -- Set buffer to hide instead of being wiped when window closes\n vim.api.nvim_buf_set_option(bufnr, \"bufhidden\", \"hide\")\n\n -- Close the window - this preserves the buffer and job\n vim.api.nvim_win_close(winid, false)\n winid = nil -- Clear window reference\n\n logger.debug(\"terminal\", \"Terminal window hidden, process preserved\")\n end\nend\n\nlocal function show_hidden_terminal(effective_config, focus)\n -- Show an existing hidden terminal buffer in a new window\n if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then\n return false\n end\n\n -- Check if it's already visible\n if is_terminal_visible() then\n if focus then\n focus_terminal()\n end\n return true\n end\n\n local original_win = vim.api.nvim_get_current_win()\n\n -- Create a new window for the existing buffer\n local width = math.floor(vim.o.columns * effective_config.split_width_percentage)\n local full_height = vim.o.lines\n local placement_modifier\n\n if effective_config.split_side == \"left\" then\n placement_modifier = \"topleft \"\n else\n placement_modifier = \"botright \"\n end\n\n vim.cmd(placement_modifier .. width .. \"vsplit\")\n local new_winid = vim.api.nvim_get_current_win()\n vim.api.nvim_win_set_height(new_winid, full_height)\n\n -- Set the existing buffer in the new window\n vim.api.nvim_win_set_buf(new_winid, bufnr)\n winid = new_winid\n\n if focus then\n -- Focus the terminal: switch to terminal window and enter insert mode\n vim.api.nvim_set_current_win(winid)\n vim.cmd(\"startinsert\")\n else\n -- Preserve user context: return to the window they were in before showing terminal\n vim.api.nvim_set_current_win(original_win)\n end\n\n logger.debug(\"terminal\", \"Showed hidden terminal in new window\")\n return true\nend\n\nlocal function find_existing_claude_terminal()\n local buffers = vim.api.nvim_list_bufs()\n for _, buf in ipairs(buffers) do\n if vim.api.nvim_buf_is_valid(buf) and vim.api.nvim_buf_get_option(buf, \"buftype\") == \"terminal\" then\n -- Check if this is a Claude Code terminal by examining the buffer name or terminal job\n local buf_name = vim.api.nvim_buf_get_name(buf)\n -- Terminal buffers often have names like \"term://...\" that include the command\n if buf_name:match(\"claude\") then\n -- Additional check: see if there's a window displaying this buffer\n local windows = vim.api.nvim_list_wins()\n for _, win in ipairs(windows) do\n if vim.api.nvim_win_get_buf(win) == buf then\n logger.debug(\"terminal\", \"Found existing Claude terminal in buffer\", buf, \"window\", win)\n return buf, win\n end\n end\n end\n end\n end\n return nil, nil\nend\n\n--- @param term_config table\nfunction M.setup(term_config)\n config = term_config or {}\nend\n\n--- @param cmd_string string\n--- @param env_table table\n--- @param effective_config table\n--- @param focus boolean|nil\nfunction M.open(cmd_string, env_table, effective_config, focus)\n focus = utils.normalize_focus(focus)\n\n if is_valid() then\n -- Check if terminal exists but is hidden (no window)\n if not winid or not vim.api.nvim_win_is_valid(winid) then\n -- Terminal is hidden, show it by calling show_hidden_terminal\n show_hidden_terminal(effective_config, focus)\n else\n -- Terminal is already visible\n if focus then\n focus_terminal()\n end\n end\n else\n -- Check if there's an existing Claude terminal we lost track of\n local existing_buf, existing_win = find_existing_claude_terminal()\n if existing_buf and existing_win then\n -- Recover the existing terminal\n bufnr = existing_buf\n winid = existing_win\n -- Note: We can't recover the job ID easily, but it's less critical\n logger.debug(\"terminal\", \"Recovered existing Claude terminal\")\n if focus then\n focus_terminal() -- Focus recovered terminal\n end\n -- If focus=false, preserve user context by staying in current window\n else\n if not open_terminal(cmd_string, env_table, effective_config, focus) then\n vim.notify(\"Failed to open Claude terminal using native fallback.\", vim.log.levels.ERROR)\n end\n end\n end\nend\n\nfunction M.close()\n close_terminal()\nend\n\n--- Simple toggle: always show/hide terminal regardless of focus\n--- @param cmd_string string\n--- @param env_table table\n--- @param effective_config table\n", "suffix_code": "\n\n--- Smart focus toggle: switches to terminal if not focused, hides if currently focused\n--- @param cmd_string string\n--- @param env_table table\n--- @param effective_config table\nfunction M.focus_toggle(cmd_string, env_table, effective_config)\n -- Check if we have a valid terminal buffer (process running)\n local has_buffer = bufnr and vim.api.nvim_buf_is_valid(bufnr)\n local is_visible = has_buffer and is_terminal_visible()\n\n if has_buffer then\n -- Terminal process exists\n if is_visible then\n -- Terminal is visible - check if we're currently in it\n local current_win_id = vim.api.nvim_get_current_win()\n if winid == current_win_id then\n -- We're in the terminal window, hide it (but keep process running)\n hide_terminal()\n else\n -- Terminal is visible but we're not in it, focus it\n focus_terminal()\n end\n else\n -- Terminal process exists but is hidden, show it\n if show_hidden_terminal(effective_config, true) then\n logger.debug(\"terminal\", \"Showing hidden terminal\")\n else\n logger.error(\"terminal\", \"Failed to show hidden terminal\")\n end\n end\n else\n -- No terminal process exists, check if there's an existing one we lost track of\n local existing_buf, existing_win = find_existing_claude_terminal()\n if existing_buf and existing_win then\n -- Recover the existing terminal\n bufnr = existing_buf\n winid = existing_win\n logger.debug(\"terminal\", \"Recovered existing Claude terminal\")\n\n -- Check if we're currently in this recovered terminal\n local current_win_id = vim.api.nvim_get_current_win()\n if existing_win == current_win_id then\n -- We're in the recovered terminal, hide it\n hide_terminal()\n else\n -- Focus the recovered terminal\n focus_terminal()\n end\n else\n -- No existing terminal found, create a new one\n if not open_terminal(cmd_string, env_table, effective_config) then\n vim.notify(\"Failed to open Claude terminal using native fallback (focus_toggle).\", vim.log.levels.ERROR)\n end\n end\n end\nend\n\n--- Legacy toggle function for backward compatibility (defaults to simple_toggle)\n--- @param cmd_string string\n--- @param env_table table\n--- @param effective_config table\nfunction M.toggle(cmd_string, env_table, effective_config)\n M.simple_toggle(cmd_string, env_table, effective_config)\nend\n\n--- @return number|nil\nfunction M.get_active_bufnr()\n if is_valid() then\n return bufnr\n end\n return nil\nend\n\n--- @return boolean\nfunction M.is_available()\n return true -- Native provider is always available\nend\n\nreturn M\n", "middle_code": "function M.simple_toggle(cmd_string, env_table, effective_config)\n local has_buffer = bufnr and vim.api.nvim_buf_is_valid(bufnr)\n local is_visible = has_buffer and is_terminal_visible()\n if is_visible then\n hide_terminal()\n else\n if has_buffer then\n if show_hidden_terminal(effective_config, true) then\n logger.debug(\"terminal\", \"Showing hidden terminal\")\n else\n logger.error(\"terminal\", \"Failed to show hidden terminal\")\n end\n else\n local existing_buf, existing_win = find_existing_claude_terminal()\n if existing_buf and existing_win then\n bufnr = existing_buf\n winid = existing_win\n logger.debug(\"terminal\", \"Recovered existing Claude terminal\")\n focus_terminal()\n else\n if not open_terminal(cmd_string, env_table, effective_config) then\n vim.notify(\"Failed to open Claude terminal using native fallback (simple_toggle).\", vim.log.levels.ERROR)\n end\n end\n end\n end\nend", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "lua", "sub_task_type": null}, "context_code": [["/claudecode.nvim/lua/claudecode/terminal/snacks.lua", "--- Snacks.nvim terminal provider for Claude Code.\n-- @module claudecode.terminal.snacks\n\n--- @type TerminalProvider\nlocal M = {}\n\nlocal snacks_available, Snacks = pcall(require, \"snacks\")\nlocal utils = require(\"claudecode.utils\")\nlocal terminal = nil\n\n--- @return boolean\nlocal function is_available()\n return snacks_available and Snacks and Snacks.terminal\nend\n\n--- Setup event handlers for terminal instance\n--- @param term_instance table The Snacks terminal instance\n--- @param config table Configuration options\nlocal function setup_terminal_events(term_instance, config)\n local logger = require(\"claudecode.logger\")\n\n -- Handle command completion/exit - only if auto_close is enabled\n if config.auto_close then\n term_instance:on(\"TermClose\", function()\n if vim.v.event.status ~= 0 then\n logger.error(\"terminal\", \"Claude exited with code \" .. vim.v.event.status .. \".\\nCheck for any errors.\")\n end\n\n -- Clean up\n terminal = nil\n vim.schedule(function()\n term_instance:close({ buf = true })\n vim.cmd.checktime()\n end)\n end, { buf = true })\n end\n\n -- Handle buffer deletion\n term_instance:on(\"BufWipeout\", function()\n logger.debug(\"terminal\", \"Terminal buffer wiped\")\n terminal = nil\n end, { buf = true })\nend\n\n--- Builds Snacks terminal options with focus control\n--- @param config table Terminal configuration (split_side, split_width_percentage, etc.)\n--- @param env_table table Environment variables to set for the terminal process\n--- @param focus boolean|nil Whether to focus the terminal when opened (defaults to true)\n--- @return table Snacks terminal options with start_insert/auto_insert controlled by focus parameter\nlocal function build_opts(config, env_table, focus)\n focus = utils.normalize_focus(focus)\n return {\n env = env_table,\n start_insert = focus,\n auto_insert = focus,\n auto_close = false,\n win = {\n position = config.split_side,\n width = config.split_width_percentage,\n height = 0,\n relative = \"editor\",\n },\n }\nend\n\nfunction M.setup()\n -- No specific setup needed for Snacks provider\nend\n\n--- @param cmd_string string\n--- @param env_table table\n--- @param config table\n--- @param focus boolean|nil\nfunction M.open(cmd_string, env_table, config, focus)\n if not is_available() then\n vim.notify(\"Snacks.nvim terminal provider selected but Snacks.terminal not available.\", vim.log.levels.ERROR)\n return\n end\n\n focus = utils.normalize_focus(focus)\n\n if terminal and terminal:buf_valid() then\n -- Check if terminal exists but is hidden (no window)\n if not terminal.win or not vim.api.nvim_win_is_valid(terminal.win) then\n -- Terminal is hidden, show it using snacks toggle\n terminal:toggle()\n if focus then\n terminal:focus()\n local term_buf_id = terminal.buf\n if term_buf_id and vim.api.nvim_buf_get_option(term_buf_id, \"buftype\") == \"terminal\" then\n if terminal.win and vim.api.nvim_win_is_valid(terminal.win) then\n vim.api.nvim_win_call(terminal.win, function()\n vim.cmd(\"startinsert\")\n end)\n end\n end\n end\n else\n -- Terminal is already visible\n if focus then\n terminal:focus()\n local term_buf_id = terminal.buf\n if term_buf_id and vim.api.nvim_buf_get_option(term_buf_id, \"buftype\") == \"terminal\" then\n -- Check if window is valid before calling nvim_win_call\n if terminal.win and vim.api.nvim_win_is_valid(terminal.win) then\n vim.api.nvim_win_call(terminal.win, function()\n vim.cmd(\"startinsert\")\n end)\n end\n end\n end\n end\n return\n end\n\n local opts = build_opts(config, env_table, focus)\n local term_instance = Snacks.terminal.open(cmd_string, opts)\n if term_instance and term_instance:buf_valid() then\n setup_terminal_events(term_instance, config)\n terminal = term_instance\n else\n terminal = nil\n local logger = require(\"claudecode.logger\")\n local error_details = {}\n if not term_instance then\n table.insert(error_details, \"Snacks.terminal.open() returned nil\")\n elseif not term_instance:buf_valid() then\n table.insert(error_details, \"terminal instance is invalid\")\n if term_instance.buf and not vim.api.nvim_buf_is_valid(term_instance.buf) then\n table.insert(error_details, \"buffer is invalid\")\n end\n if term_instance.win and not vim.api.nvim_win_is_valid(term_instance.win) then\n table.insert(error_details, \"window is invalid\")\n end\n end\n\n local context = string.format(\"cmd='%s', opts=%s\", cmd_string, vim.inspect(opts))\n local error_msg = string.format(\n \"Failed to open Claude terminal using Snacks. Details: %s. Context: %s\",\n table.concat(error_details, \", \"),\n context\n )\n vim.notify(error_msg, vim.log.levels.ERROR)\n logger.debug(\"terminal\", error_msg)\n end\nend\n\nfunction M.close()\n if not is_available() then\n return\n end\n if terminal and terminal:buf_valid() then\n terminal:close()\n end\nend\n\n--- Simple toggle: always show/hide terminal regardless of focus\n--- @param cmd_string string\n--- @param env_table table\n--- @param config table\nfunction M.simple_toggle(cmd_string, env_table, config)\n if not is_available() then\n vim.notify(\"Snacks.nvim terminal provider selected but Snacks.terminal not available.\", vim.log.levels.ERROR)\n return\n end\n\n local logger = require(\"claudecode.logger\")\n\n -- Check if terminal exists and is visible\n if terminal and terminal:buf_valid() and terminal.win then\n -- Terminal is visible, hide it\n logger.debug(\"terminal\", \"Simple toggle: hiding visible terminal\")\n terminal:toggle()\n elseif terminal and terminal:buf_valid() and not terminal.win then\n -- Terminal exists but not visible, show it\n logger.debug(\"terminal\", \"Simple toggle: showing hidden terminal\")\n terminal:toggle()\n else\n -- No terminal exists, create new one\n logger.debug(\"terminal\", \"Simple toggle: creating new terminal\")\n M.open(cmd_string, env_table, config)\n end\nend\n\n--- Smart focus toggle: switches to terminal if not focused, hides if currently focused\n--- @param cmd_string string\n--- @param env_table table\n--- @param config table\nfunction M.focus_toggle(cmd_string, env_table, config)\n if not is_available() then\n vim.notify(\"Snacks.nvim terminal provider selected but Snacks.terminal not available.\", vim.log.levels.ERROR)\n return\n end\n\n local logger = require(\"claudecode.logger\")\n\n -- Terminal exists, is valid, but not visible\n if terminal and terminal:buf_valid() and not terminal.win then\n logger.debug(\"terminal\", \"Focus toggle: showing hidden terminal\")\n terminal:toggle()\n -- Terminal exists, is valid, and is visible\n elseif terminal and terminal:buf_valid() and terminal.win then\n local claude_term_neovim_win_id = terminal.win\n local current_neovim_win_id = vim.api.nvim_get_current_win()\n\n -- you're IN it\n if claude_term_neovim_win_id == current_neovim_win_id then\n logger.debug(\"terminal\", \"Focus toggle: hiding terminal (currently focused)\")\n terminal:toggle()\n -- you're NOT in it\n else\n logger.debug(\"terminal\", \"Focus toggle: focusing terminal\")\n vim.api.nvim_set_current_win(claude_term_neovim_win_id)\n if terminal.buf and vim.api.nvim_buf_is_valid(terminal.buf) then\n if vim.api.nvim_buf_get_option(terminal.buf, \"buftype\") == \"terminal\" then\n vim.api.nvim_win_call(claude_term_neovim_win_id, function()\n vim.cmd(\"startinsert\")\n end)\n end\n end\n end\n -- No terminal exists\n else\n logger.debug(\"terminal\", \"Focus toggle: creating new terminal\")\n M.open(cmd_string, env_table, config)\n end\nend\n\n--- Legacy toggle function for backward compatibility (defaults to simple_toggle)\n--- @param cmd_string string\n--- @param env_table table\n--- @param config table\nfunction M.toggle(cmd_string, env_table, config)\n M.simple_toggle(cmd_string, env_table, config)\nend\n\n--- @return number|nil\nfunction M.get_active_bufnr()\n if terminal and terminal:buf_valid() and terminal.buf then\n if vim.api.nvim_buf_is_valid(terminal.buf) then\n return terminal.buf\n end\n end\n return nil\nend\n\n--- @return boolean\nfunction M.is_available()\n return is_available()\nend\n\n-- For testing purposes\n--- @return table|nil\nfunction M._get_terminal_for_test()\n return terminal\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/diff.lua", "--- Diff module for Claude Code Neovim integration.\n-- Provides native Neovim diff functionality with MCP-compliant blocking operations and state management.\nlocal M = {}\n\nlocal logger = require(\"claudecode.logger\")\n\n-- Global state management for active diffs\nlocal active_diffs = {}\nlocal autocmd_group\n\n--- Get or create the autocmd group\nlocal function get_autocmd_group()\n if not autocmd_group then\n autocmd_group = vim.api.nvim_create_augroup(\"ClaudeCodeMCPDiff\", { clear = true })\n end\n return autocmd_group\nend\n\n--- Find a suitable main editor window to open diffs in.\n-- Excludes terminals, sidebars, and floating windows.\n-- @return number|nil Window ID of the main editor window, or nil if not found\nlocal function find_main_editor_window()\n local windows = vim.api.nvim_list_wins()\n\n for _, win in ipairs(windows) do\n local buf = vim.api.nvim_win_get_buf(win)\n local buftype = vim.api.nvim_buf_get_option(buf, \"buftype\")\n local filetype = vim.api.nvim_buf_get_option(buf, \"filetype\")\n local win_config = vim.api.nvim_win_get_config(win)\n\n -- Check if this is a suitable window\n local is_suitable = true\n\n -- Skip floating windows\n if win_config.relative and win_config.relative ~= \"\" then\n is_suitable = false\n end\n\n -- Skip special buffer types\n if is_suitable and (buftype == \"terminal\" or buftype == \"prompt\") then\n is_suitable = false\n end\n\n -- Skip known sidebar filetypes and ClaudeCode terminal\n if\n is_suitable\n and (\n filetype == \"neo-tree\"\n or filetype == \"neo-tree-popup\"\n or filetype == \"ClaudeCode\"\n or filetype == \"NvimTree\"\n or filetype == \"oil\"\n or filetype == \"aerial\"\n or filetype == \"tagbar\"\n )\n then\n is_suitable = false\n end\n\n -- This looks like a main editor window\n if is_suitable then\n return win\n end\n end\n\n return nil\nend\n\n--- Setup the diff module\n-- @param user_diff_config table|nil Reserved for future use\nfunction M.setup(user_diff_config)\n -- Currently no configuration needed for native diff\n -- Parameter kept for API compatibility\nend\n\n--- Open a diff view between two files\n-- @param old_file_path string Path to the original file\n-- @param new_file_path string Path to the new file (used for naming)\n-- @param new_file_contents string Contents of the new file\n-- @param tab_name string Name for the diff tab/view\n-- @return table Result with provider, tab_name, and success status\nfunction M.open_diff(old_file_path, new_file_path, new_file_contents, tab_name)\n return M._open_native_diff(old_file_path, new_file_path, new_file_contents, tab_name)\nend\n\n--- Create a temporary file with content\n-- @param content string The content to write\n-- @param filename string Base filename for the temporary file\n-- @return string|nil, string|nil The temporary file path and error message\nlocal function create_temp_file(content, filename)\n local base_dir_cache = vim.fn.stdpath(\"cache\") .. \"/claudecode_diffs\"\n local mkdir_ok_cache, mkdir_err_cache = pcall(vim.fn.mkdir, base_dir_cache, \"p\")\n\n local final_base_dir\n if mkdir_ok_cache then\n final_base_dir = base_dir_cache\n else\n local base_dir_temp = vim.fn.stdpath(\"cache\") .. \"/claudecode_diffs_fallback\"\n local mkdir_ok_temp, mkdir_err_temp = pcall(vim.fn.mkdir, base_dir_temp, \"p\")\n if not mkdir_ok_temp then\n local err_to_report = mkdir_err_temp or mkdir_err_cache or \"unknown error creating base temp dir\"\n return nil, \"Failed to create base temporary directory: \" .. tostring(err_to_report)\n end\n final_base_dir = base_dir_temp\n end\n\n local session_id_base = vim.fn.fnamemodify(vim.fn.tempname(), \":t\")\n .. \"_\"\n .. tostring(os.time())\n .. \"_\"\n .. tostring(math.random(1000, 9999))\n local session_id = session_id_base:gsub(\"[^A-Za-z0-9_-]\", \"\")\n if session_id == \"\" then -- Fallback if all characters were problematic, ensuring a directory can be made.\n session_id = \"claudecode_session\"\n end\n\n local tmp_session_dir = final_base_dir .. \"/\" .. session_id\n local mkdir_session_ok, mkdir_session_err = pcall(vim.fn.mkdir, tmp_session_dir, \"p\")\n if not mkdir_session_ok then\n return nil, \"Failed to create temporary session directory: \" .. tostring(mkdir_session_err)\n end\n\n local tmp_file = tmp_session_dir .. \"/\" .. filename\n local file = io.open(tmp_file, \"w\")\n if not file then\n return nil, \"Failed to create temporary file: \" .. tmp_file\n end\n\n file:write(content)\n file:close()\n\n return tmp_file, nil\nend\n\n--- Clean up temporary files and directories\n-- @param tmp_file string Path to the temporary file to clean up\nlocal function cleanup_temp_file(tmp_file)\n if tmp_file and vim.fn.filereadable(tmp_file) == 1 then\n local tmp_dir = vim.fn.fnamemodify(tmp_file, \":h\")\n if vim.fs and type(vim.fs.remove) == \"function\" then\n local ok_file, err_file = pcall(vim.fs.remove, tmp_file)\n if not ok_file then\n vim.notify(\n \"ClaudeCode: Error removing temp file \" .. tmp_file .. \": \" .. tostring(err_file),\n vim.log.levels.WARN\n )\n end\n\n local ok_dir, err_dir = pcall(vim.fs.remove, tmp_dir)\n if not ok_dir then\n vim.notify(\n \"ClaudeCode: Error removing temp directory \" .. tmp_dir .. \": \" .. tostring(err_dir),\n vim.log.levels.INFO\n )\n end\n else\n local reason = \"vim.fs.remove is not a function\"\n if not vim.fs then\n reason = \"vim.fs is nil\"\n end\n vim.notify(\n \"ClaudeCode: Cannot perform standard cleanup: \"\n .. reason\n .. \". Affected file: \"\n .. tmp_file\n .. \". Please check your Neovim setup or report this issue.\",\n vim.log.levels.ERROR\n )\n -- Fallback to os.remove for the file.\n local os_ok, os_err = pcall(os.remove, tmp_file)\n if not os_ok then\n vim.notify(\n \"ClaudeCode: Fallback os.remove also failed for file \" .. tmp_file .. \": \" .. tostring(os_err),\n vim.log.levels.ERROR\n )\n end\n end\n end\nend\n\n-- Detect filetype from a path or existing buffer (best-effort)\nlocal function detect_filetype(path, buf)\n -- 1) Try Neovim's builtin matcher if available (>=0.10)\n if vim.filetype and type(vim.filetype.match) == \"function\" then\n local ok, ft = pcall(vim.filetype.match, { filename = path })\n if ok and ft and ft ~= \"\" then\n return ft\n end\n end\n\n -- 2) Try reading from existing buffer\n if buf and vim.api.nvim_buf_is_valid(buf) then\n local ft = vim.api.nvim_buf_get_option(buf, \"filetype\")\n if ft and ft ~= \"\" then\n return ft\n end\n end\n\n -- 3) Fallback to simple extension mapping\n local ext = path:match(\"%.([%w_%-]+)$\") or \"\"\n local simple_map = {\n lua = \"lua\",\n ts = \"typescript\",\n js = \"javascript\",\n jsx = \"javascriptreact\",\n tsx = \"typescriptreact\",\n py = \"python\",\n go = \"go\",\n rs = \"rust\",\n c = \"c\",\n h = \"c\",\n cpp = \"cpp\",\n hpp = \"cpp\",\n md = \"markdown\",\n sh = \"sh\",\n zsh = \"zsh\",\n bash = \"bash\",\n json = \"json\",\n yaml = \"yaml\",\n yml = \"yaml\",\n toml = \"toml\",\n }\n return simple_map[ext]\nend\n--- Open diff using native Neovim functionality\n-- @param old_file_path string Path to the original file\n-- @param new_file_path string Path to the new file (used for naming)\n-- @param new_file_contents string Contents of the new file\n-- @param tab_name string Name for the diff tab/view\n-- @return table Result with provider, tab_name, and success status\nfunction M._open_native_diff(old_file_path, new_file_path, new_file_contents, tab_name)\n local new_filename = vim.fn.fnamemodify(new_file_path, \":t\") .. \".new\"\n local tmp_file, err = create_temp_file(new_file_contents, new_filename)\n if not tmp_file then\n return { provider = \"native\", tab_name = tab_name, success = false, error = err, temp_file = nil }\n end\n\n local target_win = find_main_editor_window()\n\n if target_win then\n vim.api.nvim_set_current_win(target_win)\n else\n vim.cmd(\"wincmd t\")\n vim.cmd(\"wincmd l\")\n local buf = vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win())\n local buftype = vim.api.nvim_buf_get_option(buf, \"buftype\")\n\n if buftype == \"terminal\" or buftype == \"nofile\" then\n vim.cmd(\"vsplit\")\n end\n end\n\n vim.cmd(\"edit \" .. vim.fn.fnameescape(old_file_path))\n vim.cmd(\"diffthis\")\n vim.cmd(\"vsplit\")\n vim.cmd(\"edit \" .. vim.fn.fnameescape(tmp_file))\n vim.api.nvim_buf_set_name(0, new_file_path .. \" (New)\")\n\n -- Propagate filetype to the proposed buffer for proper syntax highlighting (#20)\n local proposed_buf = vim.api.nvim_get_current_buf()\n local old_filetype = detect_filetype(old_file_path)\n if old_filetype and old_filetype ~= \"\" then\n vim.api.nvim_set_option_value(\"filetype\", old_filetype, { buf = proposed_buf })\n end\n\n vim.cmd(\"wincmd =\")\n\n local new_buf = proposed_buf\n vim.api.nvim_set_option_value(\"buftype\", \"nofile\", { buf = new_buf })\n vim.api.nvim_set_option_value(\"bufhidden\", \"wipe\", { buf = new_buf })\n vim.api.nvim_set_option_value(\"swapfile\", false, { buf = new_buf })\n\n vim.cmd(\"diffthis\")\n\n local cleanup_group = vim.api.nvim_create_augroup(\"ClaudeCodeDiffCleanup\", { clear = false })\n vim.api.nvim_create_autocmd({ \"BufDelete\", \"BufWipeout\" }, {\n group = cleanup_group,\n buffer = new_buf,\n callback = function()\n cleanup_temp_file(tmp_file)\n end,\n once = true,\n })\n\n return {\n provider = \"native\",\n tab_name = tab_name,\n success = true,\n temp_file = tmp_file,\n }\nend\n\n--- Register diff state for tracking\n-- @param tab_name string Unique identifier for the diff\n-- @param diff_data table Diff state data\nfunction M._register_diff_state(tab_name, diff_data)\n active_diffs[tab_name] = diff_data\nend\n\n--- Resolve diff as saved (user accepted changes)\n-- @param tab_name string The diff identifier\n-- @param buffer_id number The buffer that was saved\nfunction M._resolve_diff_as_saved(tab_name, buffer_id)\n local diff_data = active_diffs[tab_name]\n if not diff_data or diff_data.status ~= \"pending\" then\n return\n end\n\n logger.debug(\"diff\", \"Resolving diff as saved for\", tab_name, \"from buffer\", buffer_id)\n\n -- Get content from buffer\n local content_lines = vim.api.nvim_buf_get_lines(buffer_id, 0, -1, false)\n local final_content = table.concat(content_lines, \"\\n\")\n -- Add trailing newline if the buffer has one\n if #content_lines > 0 and vim.api.nvim_buf_get_option(buffer_id, \"eol\") then\n final_content = final_content .. \"\\n\"\n end\n\n -- Close diff windows (unified behavior)\n if diff_data.new_window and vim.api.nvim_win_is_valid(diff_data.new_window) then\n vim.api.nvim_win_close(diff_data.new_window, true)\n end\n if diff_data.target_window and vim.api.nvim_win_is_valid(diff_data.target_window) then\n vim.api.nvim_set_current_win(diff_data.target_window)\n vim.cmd(\"diffoff\")\n end\n\n -- Create MCP-compliant response\n local result = {\n content = {\n { type = \"text\", text = \"FILE_SAVED\" },\n { type = \"text\", text = final_content },\n },\n }\n\n diff_data.status = \"saved\"\n diff_data.result_content = result\n\n -- Resume the coroutine with the result (for deferred response system)\n if diff_data.resolution_callback then\n logger.debug(\"diff\", \"Resuming coroutine for saved diff\", tab_name)\n diff_data.resolution_callback(result)\n else\n logger.debug(\"diff\", \"No resolution callback found for saved diff\", tab_name)\n end\n\n -- Reload the original file buffer after a delay to ensure Claude CLI has written the file\n vim.defer_fn(function()\n local current_diff_data = active_diffs[tab_name]\n local original_cursor_pos = current_diff_data and current_diff_data.original_cursor_pos\n M.reload_file_buffers_manual(diff_data.old_file_path, original_cursor_pos)\n end, 200)\n\n -- NOTE: Diff state cleanup is handled by close_tab tool or explicit cleanup calls\n logger.debug(\"diff\", \"Diff saved, awaiting close_tab command for cleanup\")\nend\n\n--- Reload file buffers after external changes (called when diff is closed)\n-- @param file_path string Path to the file that was externally modified\n-- @param original_cursor_pos table|nil Original cursor position to restore {row, col}\nlocal function reload_file_buffers(file_path, original_cursor_pos)\n logger.debug(\"diff\", \"Reloading buffers for file:\", file_path, original_cursor_pos and \"(restoring cursor)\" or \"\")\n\n local reloaded_count = 0\n -- Find and reload any open buffers for this file\n for _, buf in ipairs(vim.api.nvim_list_bufs()) do\n if vim.api.nvim_buf_is_valid(buf) then\n local buf_name = vim.api.nvim_buf_get_name(buf)\n\n -- Simple string match - if buffer name matches the file path\n if buf_name == file_path then\n -- Check if buffer is modified - only reload unmodified buffers for safety\n local modified = vim.api.nvim_buf_get_option(buf, \"modified\")\n logger.debug(\"diff\", \"Found matching buffer\", buf, \"modified:\", modified)\n\n if not modified then\n -- Try to find a window displaying this buffer for proper context\n local win_id = nil\n for _, win in ipairs(vim.api.nvim_list_wins()) do\n if vim.api.nvim_win_get_buf(win) == buf then\n win_id = win\n break\n end\n end\n\n if win_id then\n vim.api.nvim_win_call(win_id, function()\n vim.cmd(\"edit\")\n -- Restore original cursor position if we have it\n if original_cursor_pos then\n pcall(vim.api.nvim_win_set_cursor, win_id, original_cursor_pos)\n end\n end)\n else\n vim.api.nvim_buf_call(buf, function()\n vim.cmd(\"edit\")\n end)\n end\n\n reloaded_count = reloaded_count + 1\n end\n end\n end\n end\n\n logger.debug(\"diff\", \"Completed buffer reload - reloaded\", reloaded_count, \"buffers for file:\", file_path)\nend\n\n--- Resolve diff as rejected (user closed/rejected)\n-- @param tab_name string The diff identifier\nfunction M._resolve_diff_as_rejected(tab_name)\n local diff_data = active_diffs[tab_name]\n if not diff_data or diff_data.status ~= \"pending\" then\n return\n end\n\n -- Create MCP-compliant response\n local result = {\n content = {\n { type = \"text\", text = \"DIFF_REJECTED\" },\n { type = \"text\", text = tab_name },\n },\n }\n\n diff_data.status = \"rejected\"\n diff_data.result_content = result\n\n -- Clean up diff state and resources BEFORE resolving to prevent any interference\n M._cleanup_diff_state(tab_name, \"diff rejected\")\n\n -- Use vim.schedule to ensure the resolution callback happens after all cleanup\n vim.schedule(function()\n -- Resume the coroutine with the result (for deferred response system)\n if diff_data.resolution_callback then\n logger.debug(\"diff\", \"Resuming coroutine for rejected diff\", tab_name)\n diff_data.resolution_callback(result)\n end\n end)\nend\n\n--- Register autocmds for a specific diff\n-- @param tab_name string The diff identifier\n-- @param new_buffer number New file buffer ID\n-- @return table List of autocmd IDs\nlocal function register_diff_autocmds(tab_name, new_buffer)\n local autocmd_ids = {}\n\n -- Handle :w command to accept diff changes (replaces both BufWritePost and BufWriteCmd)\n autocmd_ids[#autocmd_ids + 1] = vim.api.nvim_create_autocmd(\"BufWriteCmd\", {\n group = get_autocmd_group(),\n buffer = new_buffer,\n callback = function()\n logger.debug(\"diff\", \"BufWriteCmd (:w) triggered - accepting diff changes for\", tab_name)\n M._resolve_diff_as_saved(tab_name, new_buffer)\n -- Prevent actual file write since we're handling it through MCP\n return true\n end,\n })\n\n -- Buffer deletion monitoring for rejection (multiple events to catch all deletion methods)\n\n -- BufDelete: When buffer is deleted with :bdelete, :bwipeout, etc.\n autocmd_ids[#autocmd_ids + 1] = vim.api.nvim_create_autocmd(\"BufDelete\", {\n group = get_autocmd_group(),\n buffer = new_buffer,\n callback = function()\n logger.debug(\"diff\", \"BufDelete triggered for new buffer\", new_buffer, \"tab:\", tab_name)\n M._resolve_diff_as_rejected(tab_name)\n end,\n })\n\n -- BufUnload: When buffer is unloaded (covers more scenarios)\n autocmd_ids[#autocmd_ids + 1] = vim.api.nvim_create_autocmd(\"BufUnload\", {\n group = get_autocmd_group(),\n buffer = new_buffer,\n callback = function()\n logger.debug(\"diff\", \"BufUnload triggered for new buffer\", new_buffer, \"tab:\", tab_name)\n M._resolve_diff_as_rejected(tab_name)\n end,\n })\n\n -- BufWipeout: When buffer is wiped out completely\n autocmd_ids[#autocmd_ids + 1] = vim.api.nvim_create_autocmd(\"BufWipeout\", {\n group = get_autocmd_group(),\n buffer = new_buffer,\n callback = function()\n logger.debug(\"diff\", \"BufWipeout triggered for new buffer\", new_buffer, \"tab:\", tab_name)\n M._resolve_diff_as_rejected(tab_name)\n end,\n })\n\n -- Note: We intentionally do NOT monitor old_buffer for deletion\n -- because it's the actual file buffer and shouldn't trigger diff rejection\n\n return autocmd_ids\nend\n\n--- Create diff view from a specific window\n-- @param target_window number The window to use as base for the diff\n-- @param old_file_path string Path to the original file\n-- @param new_buffer number New file buffer ID\n-- @param tab_name string The diff identifier\n-- @param is_new_file boolean Whether this is a new file (doesn't exist yet)\n-- @return table Info about the created diff layout\nfunction M._create_diff_view_from_window(target_window, old_file_path, new_buffer, tab_name, is_new_file)\n -- If no target window provided, create a new window in suitable location\n if not target_window then\n -- Try to create a new window in the main area\n vim.cmd(\"wincmd t\") -- Go to top-left\n vim.cmd(\"wincmd l\") -- Move right (to middle if layout is left|middle|right)\n\n local buf = vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win())\n local buftype = vim.api.nvim_buf_get_option(buf, \"buftype\")\n local filetype = vim.api.nvim_buf_get_option(buf, \"filetype\")\n\n if buftype == \"terminal\" or buftype == \"prompt\" or filetype == \"neo-tree\" or filetype == \"ClaudeCode\" then\n vim.cmd(\"vsplit\")\n end\n\n target_window = vim.api.nvim_get_current_win()\n else\n vim.api.nvim_set_current_win(target_window)\n end\n\n local original_buffer\n if is_new_file then\n local empty_buffer = vim.api.nvim_create_buf(false, true)\n if not empty_buffer or empty_buffer == 0 then\n local error_msg = \"Failed to create empty buffer for new file diff\"\n logger.error(\"diff\", error_msg)\n error({\n code = -32000,\n message = \"Buffer creation failed\",\n data = error_msg,\n })\n end\n\n -- Set buffer properties with error handling\n local success, err = pcall(function()\n vim.api.nvim_buf_set_name(empty_buffer, old_file_path .. \" (NEW FILE)\")\n vim.api.nvim_buf_set_lines(empty_buffer, 0, -1, false, {})\n vim.api.nvim_buf_set_option(empty_buffer, \"buftype\", \"nofile\")\n vim.api.nvim_buf_set_option(empty_buffer, \"modifiable\", false)\n vim.api.nvim_buf_set_option(empty_buffer, \"readonly\", true)\n end)\n\n if not success then\n pcall(vim.api.nvim_buf_delete, empty_buffer, { force = true })\n local error_msg = \"Failed to configure empty buffer: \" .. tostring(err)\n logger.error(\"diff\", error_msg)\n error({\n code = -32000,\n message = \"Buffer configuration failed\",\n data = error_msg,\n })\n end\n\n vim.api.nvim_win_set_buf(target_window, empty_buffer)\n original_buffer = empty_buffer\n else\n vim.cmd(\"edit \" .. vim.fn.fnameescape(old_file_path))\n original_buffer = vim.api.nvim_win_get_buf(target_window)\n end\n\n vim.cmd(\"diffthis\")\n\n vim.cmd(\"vsplit\")\n local new_win = vim.api.nvim_get_current_win()\n vim.api.nvim_win_set_buf(new_win, new_buffer)\n\n -- Ensure new buffer inherits filetype from original for syntax highlighting (#20)\n local original_ft = detect_filetype(old_file_path, original_buffer)\n if original_ft and original_ft ~= \"\" then\n vim.api.nvim_set_option_value(\"filetype\", original_ft, { buf = new_buffer })\n end\n vim.cmd(\"diffthis\")\n\n vim.cmd(\"wincmd =\")\n vim.api.nvim_set_current_win(new_win)\n\n -- Store diff context in buffer variables for user commands\n vim.b[new_buffer].claudecode_diff_tab_name = tab_name\n vim.b[new_buffer].claudecode_diff_new_win = new_win\n vim.b[new_buffer].claudecode_diff_target_win = target_window\n\n -- Return window information for later storage\n return {\n new_window = new_win,\n target_window = target_window,\n original_buffer = original_buffer,\n }\nend\n\n--- Clean up diff state and resources\n-- @param tab_name string The diff identifier\n-- @param reason string Reason for cleanup\nfunction M._cleanup_diff_state(tab_name, reason)\n local diff_data = active_diffs[tab_name]\n if not diff_data then\n return\n end\n\n -- Clean up autocmds\n for _, autocmd_id in ipairs(diff_data.autocmd_ids or {}) do\n pcall(vim.api.nvim_del_autocmd, autocmd_id)\n end\n\n -- Clean up the new buffer only (not the old buffer which is the user's file)\n if diff_data.new_buffer and vim.api.nvim_buf_is_valid(diff_data.new_buffer) then\n pcall(vim.api.nvim_buf_delete, diff_data.new_buffer, { force = true })\n end\n\n -- Close new diff window if still open\n if diff_data.new_window and vim.api.nvim_win_is_valid(diff_data.new_window) then\n pcall(vim.api.nvim_win_close, diff_data.new_window, true)\n end\n\n -- Turn off diff mode in target window if it still exists\n if diff_data.target_window and vim.api.nvim_win_is_valid(diff_data.target_window) then\n vim.api.nvim_win_call(diff_data.target_window, function()\n vim.cmd(\"diffoff\")\n end)\n end\n\n -- Remove from active diffs\n active_diffs[tab_name] = nil\n\n logger.debug(\"diff\", \"Cleaned up diff state for\", tab_name, \"due to:\", reason)\nend\n\n--- Clean up all active diffs\n-- @param reason string Reason for cleanup\n-- NOTE: This will become a public closeAllDiffTabs tool in the future\nfunction M._cleanup_all_active_diffs(reason)\n for tab_name, _ in pairs(active_diffs) do\n M._cleanup_diff_state(tab_name, reason)\n end\nend\n\n--- Set up blocking diff operation with simpler approach\n-- @param params table Parameters for the diff\n-- @param resolution_callback function Callback to call when diff resolves\nfunction M._setup_blocking_diff(params, resolution_callback)\n local tab_name = params.tab_name\n logger.debug(\"diff\", \"Setting up diff for:\", params.old_file_path)\n\n -- Wrap the setup in error handling to ensure cleanup on failure\n local setup_success, setup_error = pcall(function()\n -- Step 1: Check if the file exists (allow new files)\n local old_file_exists = vim.fn.filereadable(params.old_file_path) == 1\n local is_new_file = not old_file_exists\n\n -- Step 2: Find if the file is already open in a buffer (only for existing files)\n local existing_buffer = nil\n local target_window = nil\n\n if old_file_exists then\n -- Look for existing buffer with this file\n for _, buf in ipairs(vim.api.nvim_list_bufs()) do\n if vim.api.nvim_buf_is_valid(buf) and vim.api.nvim_buf_is_loaded(buf) then\n local buf_name = vim.api.nvim_buf_get_name(buf)\n if buf_name == params.old_file_path then\n existing_buffer = buf\n break\n end\n end\n end\n\n -- Find window containing this buffer (if any)\n if existing_buffer then\n for _, win in ipairs(vim.api.nvim_list_wins()) do\n if vim.api.nvim_win_get_buf(win) == existing_buffer then\n target_window = win\n break\n end\n end\n end\n end\n\n -- If no existing buffer/window, find a suitable main editor window\n if not target_window then\n target_window = find_main_editor_window()\n end\n\n -- Step 3: Create scratch buffer for new content\n local new_buffer = vim.api.nvim_create_buf(false, true) -- unlisted, scratch\n if new_buffer == 0 then\n error({\n code = -32000,\n message = \"Buffer creation failed\",\n data = \"Could not create new content buffer\",\n })\n end\n\n local new_unique_name = is_new_file and (tab_name .. \" (NEW FILE - proposed)\") or (tab_name .. \" (proposed)\")\n vim.api.nvim_buf_set_name(new_buffer, new_unique_name)\n local lines = vim.split(params.new_file_contents, \"\\n\")\n -- Remove trailing empty line if content ended with \\n\n if #lines > 0 and lines[#lines] == \"\" then\n table.remove(lines, #lines)\n end\n vim.api.nvim_buf_set_lines(new_buffer, 0, -1, false, lines)\n\n vim.api.nvim_buf_set_option(new_buffer, \"buftype\", \"acwrite\") -- Allows saving but stays as scratch-like\n vim.api.nvim_buf_set_option(new_buffer, \"modifiable\", true)\n\n -- Step 4: Set up diff view using the target window\n local diff_info =\n M._create_diff_view_from_window(target_window, params.old_file_path, new_buffer, tab_name, is_new_file)\n\n -- Step 5: Register autocmds for user interaction monitoring\n local autocmd_ids = register_diff_autocmds(tab_name, new_buffer)\n\n -- Step 6: Store diff state\n\n -- Save the original cursor position before storing diff state\n local original_cursor_pos = nil\n if diff_info.target_window and vim.api.nvim_win_is_valid(diff_info.target_window) then\n original_cursor_pos = vim.api.nvim_win_get_cursor(diff_info.target_window)\n end\n\n M._register_diff_state(tab_name, {\n old_file_path = params.old_file_path,\n new_file_path = params.new_file_path,\n new_file_contents = params.new_file_contents,\n new_buffer = new_buffer,\n new_window = diff_info.new_window,\n target_window = diff_info.target_window,\n original_buffer = diff_info.original_buffer,\n original_cursor_pos = original_cursor_pos,\n autocmd_ids = autocmd_ids,\n created_at = vim.fn.localtime(),\n status = \"pending\",\n resolution_callback = resolution_callback,\n result_content = nil,\n is_new_file = is_new_file,\n })\n end) -- End of pcall\n\n -- Handle setup errors\n if not setup_success then\n local error_msg = \"Failed to setup diff operation: \" .. tostring(setup_error)\n logger.error(\"diff\", error_msg)\n\n -- Clean up any partial state that might have been created\n if active_diffs[tab_name] then\n M._cleanup_diff_state(tab_name, \"setup failed\")\n end\n\n -- Re-throw the error for MCP compliance\n error({\n code = -32000,\n message = \"Diff setup failed\",\n data = error_msg,\n })\n end\nend\n\n--- Blocking diff operation for MCP compliance\n-- @param old_file_path string Path to the original file\n-- @param new_file_path string Path to the new file (used for naming)\n-- @param new_file_contents string Contents of the new file\n-- @param tab_name string Name for the diff tab/view\n-- @return table MCP-compliant response with content array\nfunction M.open_diff_blocking(old_file_path, new_file_path, new_file_contents, tab_name)\n -- Check for existing diff with same tab_name\n if active_diffs[tab_name] then\n -- Resolve the existing diff as rejected before replacing\n M._resolve_diff_as_rejected(tab_name)\n end\n\n -- Set up blocking diff operation\n local co = coroutine.running()\n if not co then\n error({\n code = -32000,\n message = \"Internal server error\",\n data = \"openDiff must run in coroutine context\",\n })\n end\n\n logger.debug(\"diff\", \"Starting diff setup for\", tab_name)\n\n -- Use native diff implementation\n local success, err = pcall(M._setup_blocking_diff, {\n old_file_path = old_file_path,\n new_file_path = new_file_path,\n new_file_contents = new_file_contents,\n tab_name = tab_name,\n }, function(result)\n -- Resume the coroutine with the result\n local resume_success, resume_result = coroutine.resume(co, result)\n if resume_success then\n -- Use the global response sender to avoid module reloading issues\n local co_key = tostring(co)\n if _G.claude_deferred_responses and _G.claude_deferred_responses[co_key] then\n _G.claude_deferred_responses[co_key](resume_result)\n _G.claude_deferred_responses[co_key] = nil\n else\n logger.error(\"diff\", \"No global response sender found for coroutine:\", co_key)\n end\n else\n logger.error(\"diff\", \"Coroutine failed:\", tostring(resume_result))\n local co_key = tostring(co)\n if _G.claude_deferred_responses and _G.claude_deferred_responses[co_key] then\n _G.claude_deferred_responses[co_key]({\n error = {\n code = -32603,\n message = \"Internal error\",\n data = \"Coroutine failed: \" .. tostring(resume_result),\n },\n })\n _G.claude_deferred_responses[co_key] = nil\n end\n end\n end)\n\n if not success then\n logger.error(\"diff\", \"Diff setup failed for\", tab_name, \"error:\", tostring(err))\n -- If the error is already structured, propagate it directly\n if type(err) == \"table\" and err.code then\n error(err)\n else\n error({\n code = -32000,\n message = \"Error setting up diff\",\n data = tostring(err),\n })\n end\n end\n\n -- Yield and wait indefinitely for user interaction - the resolve functions will resume us\n local user_action_result = coroutine.yield()\n logger.debug(\"diff\", \"User action completed for\", tab_name)\n\n -- Return the result directly - this will be sent by the deferred response system\n return user_action_result\nend\n\n-- Set up global autocmds for shutdown handling\nvim.api.nvim_create_autocmd(\"VimLeavePre\", {\n group = get_autocmd_group(),\n callback = function()\n M._cleanup_all_active_diffs(\"shutdown\")\n end,\n})\n\n--- Close diff by tab name (used by close_tab tool)\n-- @param tab_name string The diff identifier\n-- @return boolean success True if diff was found and closed\nfunction M.close_diff_by_tab_name(tab_name)\n local diff_data = active_diffs[tab_name]\n if not diff_data then\n return false\n end\n\n -- If the diff was already saved, reload file buffers and clean up\n if diff_data.status == \"saved\" then\n -- Claude Code CLI has written the file, reload any open buffers\n if diff_data.old_file_path then\n -- Add a small delay to ensure Claude CLI has finished writing the file\n vim.defer_fn(function()\n M.reload_file_buffers_manual(diff_data.old_file_path, diff_data.original_cursor_pos)\n end, 100) -- 100ms delay\n end\n M._cleanup_diff_state(tab_name, \"diff tab closed after save\")\n return true\n end\n\n -- If still pending, treat as rejection\n if diff_data.status == \"pending\" then\n M._resolve_diff_as_rejected(tab_name)\n return true\n end\n\n return false\nend\n\n-- Test helper function (only for testing)\nfunction M._get_active_diffs()\n return active_diffs\nend\n\n-- Manual buffer reload function for testing/debugging\nfunction M.reload_file_buffers_manual(file_path, original_cursor_pos)\n return reload_file_buffers(file_path, original_cursor_pos)\nend\n\n--- Accept the current diff (user command version)\n-- This function reads the diff context from buffer variables\nfunction M.accept_current_diff()\n local current_buffer = vim.api.nvim_get_current_buf()\n local tab_name = vim.b[current_buffer].claudecode_diff_tab_name\n\n if not tab_name then\n vim.notify(\"No active diff found in current buffer\", vim.log.levels.WARN)\n return\n end\n\n M._resolve_diff_as_saved(tab_name, current_buffer)\nend\n\n--- Deny/reject the current diff (user command version)\n-- This function reads the diff context from buffer variables\nfunction M.deny_current_diff()\n local current_buffer = vim.api.nvim_get_current_buf()\n local tab_name = vim.b[current_buffer].claudecode_diff_tab_name\n local new_win = vim.b[current_buffer].claudecode_diff_new_win\n local target_window = vim.b[current_buffer].claudecode_diff_target_win\n\n if not tab_name then\n vim.notify(\"No active diff found in current buffer\", vim.log.levels.WARN)\n return\n end\n\n -- Close windows and clean up (same logic as the original keymap)\n if new_win and vim.api.nvim_win_is_valid(new_win) then\n vim.api.nvim_win_close(new_win, true)\n end\n if target_window and vim.api.nvim_win_is_valid(target_window) then\n vim.api.nvim_set_current_win(target_window)\n vim.cmd(\"diffoff\")\n end\n\n M._resolve_diff_as_rejected(tab_name)\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/terminal.lua", "--- Module to manage a dedicated vertical split terminal for Claude Code.\n-- Supports Snacks.nvim or a native Neovim terminal fallback.\n-- @module claudecode.terminal\n\n--- @class TerminalProvider\n--- @field setup function\n--- @field open function\n--- @field close function\n--- @field toggle function\n--- @field simple_toggle function\n--- @field focus_toggle function\n--- @field get_active_bufnr function\n--- @field is_available function\n--- @field _get_terminal_for_test function\n\nlocal M = {}\n\nlocal claudecode_server_module = require(\"claudecode.server.init\")\n\nlocal config = {\n split_side = \"right\",\n split_width_percentage = 0.30,\n provider = \"auto\",\n show_native_term_exit_tip = true,\n terminal_cmd = nil,\n auto_close = true,\n}\n\n-- Lazy load providers\nlocal providers = {}\n\n--- Loads a terminal provider module\n--- @param provider_name string The name of the provider to load\n--- @return TerminalProvider|nil provider The provider module, or nil if loading failed\nlocal function load_provider(provider_name)\n if not providers[provider_name] then\n local ok, provider = pcall(require, \"claudecode.terminal.\" .. provider_name)\n if ok then\n providers[provider_name] = provider\n else\n return nil\n end\n end\n return providers[provider_name]\nend\n\n--- Gets the effective terminal provider, guaranteed to return a valid provider\n--- Falls back to native provider if configured provider is unavailable\n--- @return TerminalProvider provider The terminal provider module (never nil)\nlocal function get_provider()\n local logger = require(\"claudecode.logger\")\n\n if config.provider == \"auto\" then\n -- Try snacks first, then fallback to native silently\n local snacks_provider = load_provider(\"snacks\")\n if snacks_provider and snacks_provider.is_available() then\n return snacks_provider\n end\n -- Fall through to native provider\n elseif config.provider == \"snacks\" then\n local snacks_provider = load_provider(\"snacks\")\n if snacks_provider and snacks_provider.is_available() then\n return snacks_provider\n else\n logger.warn(\"terminal\", \"'snacks' provider configured, but Snacks.nvim not available. Falling back to 'native'.\")\n end\n elseif config.provider == \"native\" then\n -- noop, will use native provider as default below\n logger.debug(\"terminal\", \"Using native terminal provider\")\n else\n logger.warn(\"terminal\", \"Invalid provider configured: \" .. tostring(config.provider) .. \". Defaulting to 'native'.\")\n end\n\n local native_provider = load_provider(\"native\")\n if not native_provider then\n error(\"ClaudeCode: Critical error - native terminal provider failed to load\")\n end\n return native_provider\nend\n\n--- Builds the effective terminal configuration by merging defaults with overrides\n--- @param opts_override table|nil Optional overrides for terminal appearance\n--- @return table The effective terminal configuration\nlocal function build_config(opts_override)\n local effective_config = vim.deepcopy(config)\n if type(opts_override) == \"table\" then\n local validators = {\n split_side = function(val)\n return val == \"left\" or val == \"right\"\n end,\n split_width_percentage = function(val)\n return type(val) == \"number\" and val > 0 and val < 1\n end,\n }\n for key, val in pairs(opts_override) do\n if effective_config[key] ~= nil and validators[key] and validators[key](val) then\n effective_config[key] = val\n end\n end\n end\n return {\n split_side = effective_config.split_side,\n split_width_percentage = effective_config.split_width_percentage,\n auto_close = effective_config.auto_close,\n }\nend\n\n--- Checks if a terminal buffer is currently visible in any window\n--- @param bufnr number|nil The buffer number to check\n--- @return boolean True if the buffer is visible in any window, false otherwise\nlocal function is_terminal_visible(bufnr)\n if not bufnr then\n return false\n end\n\n local bufinfo = vim.fn.getbufinfo(bufnr)\n return bufinfo and #bufinfo > 0 and #bufinfo[1].windows > 0\nend\n\n--- Gets the claude command string and necessary environment variables\n--- @param cmd_args string|nil Optional arguments to append to the command\n--- @return string cmd_string The command string\n--- @return table env_table The environment variables table\nlocal function get_claude_command_and_env(cmd_args)\n -- Inline get_claude_command logic\n local cmd_from_config = config.terminal_cmd\n local base_cmd\n if not cmd_from_config or cmd_from_config == \"\" then\n base_cmd = \"claude\" -- Default if not configured\n else\n base_cmd = cmd_from_config\n end\n\n local cmd_string\n if cmd_args and cmd_args ~= \"\" then\n cmd_string = base_cmd .. \" \" .. cmd_args\n else\n cmd_string = base_cmd\n end\n\n local sse_port_value = claudecode_server_module.state.port\n local env_table = {\n ENABLE_IDE_INTEGRATION = \"true\",\n FORCE_CODE_TERMINAL = \"true\",\n }\n\n if sse_port_value then\n env_table[\"CLAUDE_CODE_SSE_PORT\"] = tostring(sse_port_value)\n end\n\n return cmd_string, env_table\nend\n\n--- Common helper to open terminal without focus if not already visible\n--- @param opts_override table|nil Optional config overrides\n--- @param cmd_args string|nil Optional command arguments\n--- @return boolean True if terminal was opened or already visible\nlocal function ensure_terminal_visible_no_focus(opts_override, cmd_args)\n local provider = get_provider()\n local active_bufnr = provider.get_active_bufnr()\n\n if is_terminal_visible(active_bufnr) then\n -- Terminal is already visible, do nothing\n return true\n end\n\n -- Terminal is not visible, open it without focus\n local effective_config = build_config(opts_override)\n local cmd_string, claude_env_table = get_claude_command_and_env(cmd_args)\n\n provider.open(cmd_string, claude_env_table, effective_config, false) -- false = don't focus\n return true\nend\n\n--- Configures the terminal module.\n-- Merges user-provided terminal configuration with defaults and sets the terminal command.\n-- @param user_term_config table (optional) Configuration options for the terminal.\n-- @field user_term_config.split_side string 'left' or 'right' (default: 'right').\n-- @field user_term_config.split_width_percentage number Percentage of screen width (0.0 to 1.0, default: 0.30).\n-- @field user_term_config.provider string 'snacks' or 'native' (default: 'snacks').\n-- @field user_term_config.show_native_term_exit_tip boolean Show tip for exiting native terminal (default: true).\n-- @param p_terminal_cmd string|nil The command to run in the terminal (from main config).\nfunction M.setup(user_term_config, p_terminal_cmd)\n if user_term_config == nil then -- Allow nil, default to empty table silently\n user_term_config = {}\n elseif type(user_term_config) ~= \"table\" then -- Warn if it's not nil AND not a table\n vim.notify(\"claudecode.terminal.setup expects a table or nil for user_term_config\", vim.log.levels.WARN)\n user_term_config = {}\n end\n\n if p_terminal_cmd == nil or type(p_terminal_cmd) == \"string\" then\n config.terminal_cmd = p_terminal_cmd\n else\n vim.notify(\n \"claudecode.terminal.setup: Invalid terminal_cmd provided: \" .. tostring(p_terminal_cmd) .. \". Using default.\",\n vim.log.levels.WARN\n )\n config.terminal_cmd = nil -- Fallback to default behavior\n end\n\n for k, v in pairs(user_term_config) do\n if config[k] ~= nil and k ~= \"terminal_cmd\" then -- terminal_cmd is handled above\n if k == \"split_side\" and (v == \"left\" or v == \"right\") then\n config[k] = v\n elseif k == \"split_width_percentage\" and type(v) == \"number\" and v > 0 and v < 1 then\n config[k] = v\n elseif k == \"provider\" and (v == \"snacks\" or v == \"native\") then\n config[k] = v\n elseif k == \"show_native_term_exit_tip\" and type(v) == \"boolean\" then\n config[k] = v\n elseif k == \"auto_close\" and type(v) == \"boolean\" then\n config[k] = v\n else\n vim.notify(\"claudecode.terminal.setup: Invalid value for \" .. k .. \": \" .. tostring(v), vim.log.levels.WARN)\n end\n elseif k ~= \"terminal_cmd\" then -- Avoid warning for terminal_cmd if passed in user_term_config\n vim.notify(\"claudecode.terminal.setup: Unknown configuration key: \" .. k, vim.log.levels.WARN)\n end\n end\n\n -- Setup providers with config\n get_provider().setup(config)\nend\n\n--- Opens or focuses the Claude terminal.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.open(opts_override, cmd_args)\n local effective_config = build_config(opts_override)\n local cmd_string, claude_env_table = get_claude_command_and_env(cmd_args)\n\n get_provider().open(cmd_string, claude_env_table, effective_config)\nend\n\n--- Closes the managed Claude terminal if it's open and valid.\nfunction M.close()\n get_provider().close()\nend\n\n--- Simple toggle: always show/hide the Claude terminal regardless of focus.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.simple_toggle(opts_override, cmd_args)\n local effective_config = build_config(opts_override)\n local cmd_string, claude_env_table = get_claude_command_and_env(cmd_args)\n\n get_provider().simple_toggle(cmd_string, claude_env_table, effective_config)\nend\n\n--- Smart focus toggle: switches to terminal if not focused, hides if currently focused.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.focus_toggle(opts_override, cmd_args)\n local effective_config = build_config(opts_override)\n local cmd_string, claude_env_table = get_claude_command_and_env(cmd_args)\n\n get_provider().focus_toggle(cmd_string, claude_env_table, effective_config)\nend\n\n--- Toggle open terminal without focus if not already visible, otherwise do nothing.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.toggle_open_no_focus(opts_override, cmd_args)\n ensure_terminal_visible_no_focus(opts_override, cmd_args)\nend\n\n--- Ensures terminal is visible without changing focus. Creates if necessary, shows if hidden.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.ensure_visible(opts_override, cmd_args)\n ensure_terminal_visible_no_focus(opts_override, cmd_args)\nend\n\n--- Toggles the Claude terminal open or closed (legacy function - use simple_toggle or focus_toggle).\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.toggle(opts_override, cmd_args)\n -- Default to simple toggle for backward compatibility\n M.simple_toggle(opts_override, cmd_args)\nend\n\n--- Gets the buffer number of the currently active Claude Code terminal.\n-- This checks both Snacks and native fallback terminals.\n-- @return number|nil The buffer number if an active terminal is found, otherwise nil.\nfunction M.get_active_terminal_bufnr()\n return get_provider().get_active_bufnr()\nend\n\n--- Gets the managed terminal instance for testing purposes.\n-- NOTE: This function is intended for use in tests to inspect internal state.\n-- The underscore prefix indicates it's not part of the public API for regular use.\n-- @return snacks.terminal|nil The managed Snacks terminal instance, or nil.\nfunction M._get_managed_terminal_for_test()\n local snacks_provider = load_provider(\"snacks\")\n if snacks_provider and snacks_provider._get_terminal_for_test then\n return snacks_provider._get_terminal_for_test()\n end\n return nil\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/selection.lua", "---\n-- Manages selection tracking and communication with the Claude server.\n-- @module claudecode.selection\nlocal M = {}\n\nlocal logger = require(\"claudecode.logger\")\nlocal terminal = require(\"claudecode.terminal\")\n\nM.state = {\n latest_selection = nil,\n tracking_enabled = false,\n debounce_timer = nil,\n debounce_ms = 100,\n\n last_active_visual_selection = nil,\n demotion_timer = nil,\n visual_demotion_delay_ms = 50,\n}\n\n--- Enables selection tracking.\n-- @param server table The server object to use for communication.\n-- @param visual_demotion_delay_ms number The delay for visual selection demotion.\nfunction M.enable(server, visual_demotion_delay_ms)\n if M.state.tracking_enabled then\n return\n end\n\n M.state.tracking_enabled = true\n M.server = server\n M.state.visual_demotion_delay_ms = visual_demotion_delay_ms\n\n M._create_autocommands()\nend\n\n--- Disables selection tracking.\n-- Clears autocommands, resets internal state, and stops any active debounce timers.\nfunction M.disable()\n if not M.state.tracking_enabled then\n return\n end\n\n M.state.tracking_enabled = false\n\n M._clear_autocommands()\n\n M.state.latest_selection = nil\n M.server = nil\n\n if M.state.debounce_timer then\n vim.loop.timer_stop(M.state.debounce_timer)\n M.state.debounce_timer = nil\n end\nend\n\n--- Creates autocommands for tracking selections.\n-- Sets up listeners for CursorMoved, CursorMovedI, ModeChanged, and TextChanged events.\n-- @local\nfunction M._create_autocommands()\n local group = vim.api.nvim_create_augroup(\"ClaudeCodeSelection\", { clear = true })\n\n vim.api.nvim_create_autocmd({ \"CursorMoved\", \"CursorMovedI\" }, {\n group = group,\n callback = function()\n M.on_cursor_moved()\n end,\n })\n\n vim.api.nvim_create_autocmd(\"ModeChanged\", {\n group = group,\n callback = function()\n M.on_mode_changed()\n end,\n })\n\n vim.api.nvim_create_autocmd(\"TextChanged\", {\n group = group,\n callback = function()\n M.on_text_changed()\n end,\n })\nend\n\n--- Clears the autocommands related to selection tracking.\n-- @local\nfunction M._clear_autocommands()\n vim.api.nvim_clear_autocmds({ group = \"ClaudeCodeSelection\" })\nend\n\n--- Handles cursor movement events.\n-- Triggers a debounced update of the selection.\nfunction M.on_cursor_moved()\n M.debounce_update()\nend\n\n--- Handles mode change events.\n-- Triggers an immediate update of the selection.\nfunction M.on_mode_changed()\n M.update_selection()\nend\n\n--- Handles text change events.\n-- Triggers a debounced update of the selection.\nfunction M.on_text_changed()\n M.debounce_update()\nend\n\n--- Debounces selection updates.\n-- Ensures that `update_selection` is not called too frequently by deferring\n-- its execution.\nfunction M.debounce_update()\n if M.state.debounce_timer then\n vim.loop.timer_stop(M.state.debounce_timer)\n end\n\n M.state.debounce_timer = vim.defer_fn(function()\n M.update_selection()\n M.state.debounce_timer = nil\n end, M.state.debounce_ms)\nend\n\n--- Updates the current selection state.\n-- Determines the current selection based on the editor mode (visual or normal)\n-- and sends an update to the server if the selection has changed.\nfunction M.update_selection()\n if not M.state.tracking_enabled then\n return\n end\n\n local current_buf = vim.api.nvim_get_current_buf()\n local buf_name = vim.api.nvim_buf_get_name(current_buf)\n\n -- If the buffer name starts with \"✻ [Claude Code]\", do not update selection\n if buf_name and string.sub(buf_name, 1, string.len(\"✻ [Claude Code]\")) == \"✻ [Claude Code]\" then\n -- Optionally, cancel demotion timer like for the terminal\n if M.state.demotion_timer then\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n M.state.demotion_timer = nil\n end\n return\n end\n\n -- If the current buffer is the Claude terminal, do not update selection\n if terminal then\n local claude_term_bufnr = terminal.get_active_terminal_bufnr()\n if claude_term_bufnr and current_buf == claude_term_bufnr then\n -- Cancel any pending demotion if we switch to the Claude terminal\n if M.state.demotion_timer then\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n M.state.demotion_timer = nil\n end\n return\n end\n end\n\n local current_mode_info = vim.api.nvim_get_mode()\n local current_mode = current_mode_info.mode\n local current_selection\n\n if current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\022\" then\n -- If a new visual selection is made, cancel any pending demotion\n if M.state.demotion_timer then\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n M.state.demotion_timer = nil\n end\n\n current_selection = M.get_visual_selection()\n\n if current_selection then\n M.state.last_active_visual_selection = {\n bufnr = current_buf,\n selection_data = vim.deepcopy(current_selection), -- Store a copy\n timestamp = vim.loop.now(),\n }\n else\n -- No valid visual selection (e.g., get_visual_selection returned nil)\n -- Clear last_active_visual if it was for this buffer\n if M.state.last_active_visual_selection and M.state.last_active_visual_selection.bufnr == current_buf then\n M.state.last_active_visual_selection = nil\n end\n end\n else\n local last_visual = M.state.last_active_visual_selection\n\n if M.state.demotion_timer then\n -- A demotion is already pending. For this specific update_selection call (e.g. cursor moved),\n -- current_selection reflects the immediate cursor position.\n -- M.state.latest_selection (the one that might be sent) is still the visual one until timer resolves.\n current_selection = M.get_cursor_position()\n elseif\n last_visual\n and last_visual.bufnr == current_buf\n and last_visual.selection_data\n and not last_visual.selection_data.selection.isEmpty\n then\n -- We just exited visual mode in this buffer, and no demotion timer is running for it.\n -- Keep M.state.latest_selection as is (it's the visual one from the previous update).\n -- The 'current_selection' for comparison should also be this visual one.\n current_selection = M.state.latest_selection\n\n if M.state.demotion_timer then -- Should not happen due to elseif, but as safeguard\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n end\n\n M.state.demotion_timer = vim.loop.new_timer()\n M.state.demotion_timer:start(\n M.state.visual_demotion_delay_ms,\n 0, -- 0 repeat = one-shot\n vim.schedule_wrap(function()\n if M.state.demotion_timer then -- Check if it wasn't cancelled right before firing\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n M.state.demotion_timer = nil\n end\n M.handle_selection_demotion(current_buf) -- Pass buffer at time of scheduling\n end)\n )\n else\n -- Genuinely in normal mode, no recent visual exit, no pending demotion.\n current_selection = M.get_cursor_position()\n if last_visual and last_visual.bufnr == current_buf then\n M.state.last_active_visual_selection = nil -- Clear it as it's no longer relevant for demotion\n end\n end\n end\n\n -- If current_selection could not be determined (e.g. get_visual_selection was nil and no other path set it)\n -- default to cursor position to avoid errors.\n if not current_selection then\n current_selection = M.get_cursor_position()\n end\n\n local changed = M.has_selection_changed(current_selection)\n\n if changed then\n M.state.latest_selection = current_selection\n if M.server then\n M.send_selection_update(current_selection)\n end\n end\nend\n\n--- Handles the demotion of a visual selection after a delay.\n-- Called by the demotion_timer.\n-- @param original_bufnr_when_scheduled number The buffer number that was active when demotion was scheduled.\nfunction M.handle_selection_demotion(original_bufnr_when_scheduled)\n -- Timer object is already stopped and cleared by its own callback wrapper or cancellation points.\n -- M.state.demotion_timer should be nil here if it fired normally or was cancelled.\n\n local current_buf = vim.api.nvim_get_current_buf()\n local claude_term_bufnr = terminal.get_active_terminal_bufnr()\n\n -- Condition 1: Switched to Claude Terminal\n if claude_term_bufnr and current_buf == claude_term_bufnr then\n -- Visual selection is preserved (M.state.latest_selection is still the visual one).\n -- The \"pending\" status of last_active_visual_selection is resolved.\n if\n M.state.last_active_visual_selection\n and M.state.last_active_visual_selection.bufnr == original_bufnr_when_scheduled\n then\n M.state.last_active_visual_selection = nil\n end\n return\n end\n\n local current_mode_info = vim.api.nvim_get_mode()\n\n -- Condition 2: Back in Visual Mode in the Original Buffer\n if\n current_buf == original_bufnr_when_scheduled\n and (current_mode_info.mode == \"v\" or current_mode_info.mode == \"V\" or current_mode_info.mode == \"\\022\")\n then\n -- A new visual selection will take precedence. M.state.latest_selection will be updated by main flow.\n if\n M.state.last_active_visual_selection\n and M.state.last_active_visual_selection.bufnr == original_bufnr_when_scheduled\n then\n M.state.last_active_visual_selection = nil\n end\n return\n end\n\n -- Condition 3: Still in Original Buffer & Not Visual & Not Claude Term -> Demote\n if current_buf == original_bufnr_when_scheduled then\n local new_sel_for_demotion = M.get_cursor_position()\n -- Check if this new cursor position is actually different from the (visual) latest_selection\n if M.has_selection_changed(new_sel_for_demotion) then\n M.state.latest_selection = new_sel_for_demotion\n if M.server then\n M.send_selection_update(M.state.latest_selection)\n end\n end\n -- No change detected in selection\n end\n -- User switched to different buffer\n\n -- Always clear last_active_visual_selection for the original buffer as its pending demotion is resolved.\n if\n M.state.last_active_visual_selection\n and M.state.last_active_visual_selection.bufnr == original_bufnr_when_scheduled\n then\n M.state.last_active_visual_selection = nil\n end\nend\n\n--- Validates if we're in a valid visual selection mode\n-- @return boolean, string|nil - true if valid, false and error message if not\nlocal function validate_visual_mode()\n local current_nvim_mode = vim.api.nvim_get_mode().mode\n local fixed_anchor_pos_raw = vim.fn.getpos(\"v\")\n\n if not (current_nvim_mode == \"v\" or current_nvim_mode == \"V\" or current_nvim_mode == \"\\22\") then\n return false, \"not in visual mode\"\n end\n\n if fixed_anchor_pos_raw[2] == 0 then\n return false, \"no visual selection mark\"\n end\n\n return true, nil\nend\n\n--- Determines the effective visual mode character\n-- @return string|nil - the visual mode character or nil if invalid\nlocal function get_effective_visual_mode()\n local current_nvim_mode = vim.api.nvim_get_mode().mode\n local visual_fn_mode_char = vim.fn.visualmode()\n\n if visual_fn_mode_char and visual_fn_mode_char ~= \"\" then\n return visual_fn_mode_char\n end\n\n -- Fallback to current mode\n if current_nvim_mode == \"V\" then\n return \"V\"\n elseif current_nvim_mode == \"v\" then\n return \"v\"\n elseif current_nvim_mode == \"\\22\" then -- Ctrl-V, blockwise\n return \"\\22\"\n end\n\n return nil\nend\n\n--- Gets the start and end coordinates of the visual selection\n-- @return table, table - start_coords and end_coords with lnum and col fields\nlocal function get_selection_coordinates()\n local fixed_anchor_pos_raw = vim.fn.getpos(\"v\")\n local current_cursor_nvim = vim.api.nvim_win_get_cursor(0)\n\n -- Convert to 1-indexed line and 1-indexed column for consistency\n local p1 = { lnum = fixed_anchor_pos_raw[2], col = fixed_anchor_pos_raw[3] }\n local p2 = { lnum = current_cursor_nvim[1], col = current_cursor_nvim[2] + 1 }\n\n -- Determine chronological start/end based on line, then column\n if p1.lnum < p2.lnum or (p1.lnum == p2.lnum and p1.col <= p2.col) then\n return p1, p2\n else\n return p2, p1\n end\nend\n\n--- Extracts text for linewise visual selection\n-- @param lines_content table - array of line strings\n-- @param start_coords table - start coordinates\n-- @return string - the extracted text\nlocal function extract_linewise_text(lines_content, start_coords)\n start_coords.col = 1 -- Linewise selection effectively starts at column 1\n return table.concat(lines_content, \"\\n\")\nend\n\n--- Extracts text for characterwise visual selection\n-- @param lines_content table - array of line strings\n-- @param start_coords table - start coordinates\n-- @param end_coords table - end coordinates\n-- @return string|nil - the extracted text or nil if invalid\nlocal function extract_characterwise_text(lines_content, start_coords, end_coords)\n if start_coords.lnum == end_coords.lnum then\n if not lines_content[1] then\n return nil\n end\n return string.sub(lines_content[1], start_coords.col, end_coords.col)\n else\n if not lines_content[1] or not lines_content[#lines_content] then\n return nil\n end\n\n local text_parts = {}\n table.insert(text_parts, string.sub(lines_content[1], start_coords.col))\n for i = 2, #lines_content - 1 do\n table.insert(text_parts, lines_content[i])\n end\n table.insert(text_parts, string.sub(lines_content[#lines_content], 1, end_coords.col))\n return table.concat(text_parts, \"\\n\")\n end\nend\n\n--- Calculates LSP-compatible position coordinates\n-- @param start_coords table - start coordinates\n-- @param end_coords table - end coordinates\n-- @param visual_mode string - the visual mode character\n-- @param lines_content table - array of line strings\n-- @return table - LSP position object with start and end fields\nlocal function calculate_lsp_positions(start_coords, end_coords, visual_mode, lines_content)\n local lsp_start_line = start_coords.lnum - 1\n local lsp_end_line = end_coords.lnum - 1\n local lsp_start_char, lsp_end_char\n\n if visual_mode == \"V\" then\n lsp_start_char = 0 -- Linewise selection always starts at character 0\n -- For linewise, LSP end char is length of the last selected line\n if #lines_content > 0 and lines_content[#lines_content] then\n lsp_end_char = #lines_content[#lines_content]\n else\n lsp_end_char = 0\n end\n else\n lsp_start_char = start_coords.col - 1\n lsp_end_char = end_coords.col\n end\n\n return {\n start = { line = lsp_start_line, character = lsp_start_char },\n [\"end\"] = { line = lsp_end_line, character = lsp_end_char },\n }\nend\n\n--- Gets the current visual selection details.\n-- @return table|nil A table containing selection text, file path, URL, and\n-- start/end positions, or nil if no visual selection exists.\nfunction M.get_visual_selection()\n local valid = validate_visual_mode()\n if not valid then\n return nil\n end\n\n local visual_mode = get_effective_visual_mode()\n if not visual_mode then\n return nil\n end\n\n local start_coords, end_coords = get_selection_coordinates()\n\n local current_buf = vim.api.nvim_get_current_buf()\n local file_path = vim.api.nvim_buf_get_name(current_buf)\n\n local lines_content = vim.api.nvim_buf_get_lines(\n current_buf,\n start_coords.lnum - 1, -- Convert to 0-indexed\n end_coords.lnum, -- nvim_buf_get_lines end is exclusive\n false\n )\n\n if #lines_content == 0 then\n return nil\n end\n\n local final_text\n if visual_mode == \"V\" then\n final_text = extract_linewise_text(lines_content, start_coords)\n elseif visual_mode == \"v\" or visual_mode == \"\\22\" then\n final_text = extract_characterwise_text(lines_content, start_coords, end_coords)\n if not final_text then\n return nil\n end\n else\n return nil\n end\n\n local lsp_positions = calculate_lsp_positions(start_coords, end_coords, visual_mode, lines_content)\n\n return {\n text = final_text or \"\",\n filePath = file_path,\n fileUrl = \"file://\" .. file_path,\n selection = {\n start = lsp_positions.start,\n [\"end\"] = lsp_positions[\"end\"],\n isEmpty = (not final_text or #final_text == 0),\n },\n }\nend\n\n--- Gets the current cursor position when no visual selection is active.\n-- @return table A table containing an empty text, file path, URL, and cursor\n-- position as start/end, with isEmpty set to true.\nfunction M.get_cursor_position()\n local cursor_pos = vim.api.nvim_win_get_cursor(0)\n local current_buf = vim.api.nvim_get_current_buf()\n local file_path = vim.api.nvim_buf_get_name(current_buf)\n\n return {\n text = \"\",\n filePath = file_path,\n fileUrl = \"file://\" .. file_path,\n selection = {\n start = { line = cursor_pos[1] - 1, character = cursor_pos[2] },\n [\"end\"] = { line = cursor_pos[1] - 1, character = cursor_pos[2] },\n isEmpty = true,\n },\n }\nend\n\n--- Checks if the selection has changed compared to the latest stored selection.\n-- @param new_selection table|nil The new selection object to compare.\n-- @return boolean true if the selection has changed, false otherwise.\nfunction M.has_selection_changed(new_selection)\n local old_selection = M.state.latest_selection\n\n if not new_selection then\n return old_selection ~= nil\n end\n\n if not old_selection then\n return true\n end\n\n if old_selection.filePath ~= new_selection.filePath then\n return true\n end\n\n if old_selection.text ~= new_selection.text then\n return true\n end\n\n if\n old_selection.selection.start.line ~= new_selection.selection.start.line\n or old_selection.selection.start.character ~= new_selection.selection.start.character\n or old_selection.selection[\"end\"].line ~= new_selection.selection[\"end\"].line\n or old_selection.selection[\"end\"].character ~= new_selection.selection[\"end\"].character\n then\n return true\n end\n\n return false\nend\n\n--- Sends the selection update to the Claude server.\n-- @param selection table The selection object to send.\nfunction M.send_selection_update(selection)\n M.server.broadcast(\"selection_changed\", selection)\nend\n\n--- Gets the latest recorded selection.\n-- @return table|nil The latest selection object, or nil if none recorded.\nfunction M.get_latest_selection()\n return M.state.latest_selection\nend\n\n--- Sends the current selection to Claude.\n-- This function is typically invoked by a user command. It forces an immediate\n-- update and sends the latest selection.\nfunction M.send_current_selection()\n if not M.state.tracking_enabled or not M.server then\n logger.error(\"selection\", \"Claude Code is not running\")\n return\n end\n\n M.update_selection()\n\n local selection = M.state.latest_selection\n\n if not selection then\n logger.error(\"selection\", \"No selection available\")\n return\n end\n\n M.send_selection_update(selection)\n\n vim.api.nvim_echo({ { \"Selection sent to Claude\", \"Normal\" } }, false, {})\nend\n\n--- Gets selection from range marks (e.g., when using :'<,'> commands)\n-- @param line1 number The start line (1-indexed)\n-- @param line2 number The end line (1-indexed)\n-- @return table|nil A table containing selection text, file path, URL, and\n-- start/end positions, or nil if invalid range\nfunction M.get_range_selection(line1, line2)\n if not line1 or not line2 or line1 < 1 or line2 < 1 or line1 > line2 then\n return nil\n end\n\n local current_buf = vim.api.nvim_get_current_buf()\n local file_path = vim.api.nvim_buf_get_name(current_buf)\n\n -- Get the total number of lines in the buffer\n local total_lines = vim.api.nvim_buf_line_count(current_buf)\n\n -- Ensure line2 doesn't exceed buffer bounds\n if line2 > total_lines then\n line2 = total_lines\n end\n\n local lines_content = vim.api.nvim_buf_get_lines(\n current_buf,\n line1 - 1, -- Convert to 0-indexed\n line2, -- nvim_buf_get_lines end is exclusive\n false\n )\n\n if #lines_content == 0 then\n return nil\n end\n\n local final_text = table.concat(lines_content, \"\\n\")\n\n -- For range selections, we treat them as linewise\n local lsp_start_line = line1 - 1 -- Convert to 0-indexed\n local lsp_end_line = line2 - 1\n local lsp_start_char = 0\n local lsp_end_char = #lines_content[#lines_content]\n\n return {\n text = final_text or \"\",\n filePath = file_path,\n fileUrl = \"file://\" .. file_path,\n selection = {\n start = { line = lsp_start_line, character = lsp_start_char },\n [\"end\"] = { line = lsp_end_line, character = lsp_end_char },\n isEmpty = (not final_text or #final_text == 0),\n },\n }\nend\n\n--- Sends an at_mentioned notification for the current visual selection.\n-- @param line1 number|nil Optional start line for range-based selection\n-- @param line2 number|nil Optional end line for range-based selection\nfunction M.send_at_mention_for_visual_selection(line1, line2)\n if not M.state.tracking_enabled then\n logger.error(\"selection\", \"Selection tracking is not enabled.\")\n return false\n end\n\n -- Check if Claude Code integration is running (server may or may not have clients)\n local claudecode_main = require(\"claudecode\")\n if not claudecode_main.state.server then\n logger.error(\"selection\", \"Claude Code integration is not running.\")\n return false\n end\n\n local sel_to_send\n\n -- If range parameters are provided, use them (for :'<,'> commands)\n if line1 and line2 then\n sel_to_send = M.get_range_selection(line1, line2)\n if not sel_to_send or sel_to_send.selection.isEmpty then\n logger.warn(\"selection\", \"Invalid range selection to send as at-mention.\")\n return false\n end\n else\n -- Use existing logic for visual mode or tracked selection\n sel_to_send = M.state.latest_selection\n\n if not sel_to_send or sel_to_send.selection.isEmpty then\n -- Fallback: try to get current visual selection directly.\n -- This helps if latest_selection was demoted or command was too fast.\n local current_visual = M.get_visual_selection()\n if current_visual and not current_visual.selection.isEmpty then\n sel_to_send = current_visual\n else\n logger.warn(\"selection\", \"No visual selection to send as at-mention.\")\n return false\n end\n end\n end\n\n -- Sanity check: ensure the selection is for the current buffer\n local current_buf_name = vim.api.nvim_buf_get_name(vim.api.nvim_get_current_buf())\n if sel_to_send.filePath ~= current_buf_name then\n logger.warn(\n \"selection\",\n \"Tracked selection is for '\"\n .. sel_to_send.filePath\n .. \"', but current buffer is '\"\n .. current_buf_name\n .. \"'. Not sending.\"\n )\n return false\n end\n\n -- Use connection-aware broadcasting from main module\n local file_path = sel_to_send.filePath\n local start_line = sel_to_send.selection.start.line -- Already 0-indexed from selection module\n local end_line = sel_to_send.selection[\"end\"].line -- Already 0-indexed\n\n local success, error_msg = claudecode_main.send_at_mention(file_path, start_line, end_line, \"ClaudeCodeSend\")\n\n if success then\n logger.debug(\"selection\", \"Visual selection sent as at-mention.\")\n\n return true\n else\n logger.error(\"selection\", \"Failed to send at-mention: \" .. (error_msg or \"unknown error\"))\n return false\n end\nend\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/init.lua", "---@brief [[\n--- Claude Code Neovim Integration\n--- This plugin integrates Claude Code CLI with Neovim, enabling\n--- seamless AI-assisted coding experiences directly in Neovim.\n---@brief ]]\n\n--- @module 'claudecode'\nlocal M = {}\n\nlocal logger = require(\"claudecode.logger\")\n\n--- @class ClaudeCode.Version\n--- @field major integer Major version number\n--- @field minor integer Minor version number\n--- @field patch integer Patch version number\n--- @field prerelease string|nil Prerelease identifier (e.g., \"alpha\", \"beta\")\n--- @field string fun(self: ClaudeCode.Version):string Returns the formatted version string\n\n--- The current version of the plugin.\n--- @type ClaudeCode.Version\nM.version = {\n major = 0,\n minor = 2,\n patch = 0,\n prerelease = nil,\n string = function(self)\n local version = string.format(\"%d.%d.%d\", self.major, self.minor, self.patch)\n if self.prerelease then\n version = version .. \"-\" .. self.prerelease\n end\n return version\n end,\n}\n\n--- @class ClaudeCode.Config\n--- @field port_range {min: integer, max: integer} Port range for WebSocket server.\n--- @field auto_start boolean Auto-start WebSocket server on Neovim startup.\n--- @field terminal_cmd string|nil Custom terminal command to use when launching Claude.\n--- @field log_level \"trace\"|\"debug\"|\"info\"|\"warn\"|\"error\" Log level.\n--- @field track_selection boolean Enable sending selection updates to Claude.\n--- @field visual_demotion_delay_ms number Milliseconds to wait before demoting a visual selection.\n--- @field connection_wait_delay number Milliseconds to wait after connection before sending queued @ mentions.\n--- @field connection_timeout number Maximum time to wait for Claude Code to connect (milliseconds).\n--- @field queue_timeout number Maximum time to keep @ mentions in queue (milliseconds).\n--- @field diff_opts { auto_close_on_accept: boolean, show_diff_stats: boolean, vertical_split: boolean, open_in_current_tab: boolean } Options for the diff provider.\n\n--- @type ClaudeCode.Config\nlocal default_config = {\n port_range = { min = 10000, max = 65535 },\n auto_start = true,\n terminal_cmd = nil,\n log_level = \"info\",\n track_selection = true,\n visual_demotion_delay_ms = 50, -- Reduced from 200ms for better responsiveness in tree navigation\n connection_wait_delay = 200, -- Milliseconds to wait after connection before sending queued @ mentions\n connection_timeout = 10000, -- Maximum time to wait for Claude Code to connect (milliseconds)\n queue_timeout = 5000, -- Maximum time to keep @ mentions in queue (milliseconds)\n diff_opts = {\n auto_close_on_accept = true,\n show_diff_stats = true,\n vertical_split = true,\n open_in_current_tab = false,\n },\n}\n\n--- @class ClaudeCode.State\n--- @field config ClaudeCode.Config The current plugin configuration.\n--- @field server table|nil The WebSocket server instance.\n--- @field port number|nil The port the server is running on.\n--- @field auth_token string|nil The authentication token for the current session.\n--- @field initialized boolean Whether the plugin has been initialized.\n--- @field queued_mentions table[] Array of queued @ mentions waiting for connection.\n--- @field connection_timer table|nil Timer for connection timeout.\n\n--- @type ClaudeCode.State\nM.state = {\n config = vim.deepcopy(default_config),\n server = nil,\n port = nil,\n auth_token = nil,\n initialized = false,\n queued_mentions = {},\n connection_timer = nil,\n}\n\n---@alias ClaudeCode.TerminalOpts { \\\n--- split_side?: \"left\"|\"right\", \\\n--- split_width_percentage?: number, \\\n--- provider?: \"auto\"|\"snacks\"|\"native\", \\\n--- show_native_term_exit_tip?: boolean }\n---\n---@alias ClaudeCode.SetupOpts { \\\n--- terminal?: ClaudeCode.TerminalOpts }\n\n---@brief Check if Claude Code is connected to WebSocket server\n---@return boolean connected Whether Claude Code has active connections\nfunction M.is_claude_connected()\n if not M.state.server then\n return false\n end\n\n local server_module = require(\"claudecode.server.init\")\n local status = server_module.get_status()\n return status.running and status.client_count > 0\nend\n\n---@brief Clear the @ mention queue and stop timers\nlocal function clear_mention_queue()\n if #M.state.queued_mentions > 0 then\n logger.debug(\"queue\", \"Clearing \" .. #M.state.queued_mentions .. \" queued @ mentions\")\n end\n\n M.state.queued_mentions = {}\n\n if M.state.connection_timer then\n M.state.connection_timer:stop()\n M.state.connection_timer:close()\n M.state.connection_timer = nil\n end\nend\n\n---@brief Add @ mention to queue for later sending\n---@param mention_data table The @ mention data to queue\nlocal function queue_at_mention(mention_data)\n mention_data.timestamp = vim.loop.now()\n table.insert(M.state.queued_mentions, mention_data)\n\n logger.debug(\"queue\", \"Queued @ mention: \" .. vim.inspect(mention_data))\n\n -- Start connection timer if not already running\n if not M.state.connection_timer then\n M.state.connection_timer = vim.loop.new_timer()\n M.state.connection_timer:start(M.state.config.connection_timeout, 0, function()\n vim.schedule(function()\n if #M.state.queued_mentions > 0 then\n logger.error(\"queue\", \"Connection timeout - clearing \" .. #M.state.queued_mentions .. \" queued @ mentions\")\n clear_mention_queue()\n end\n end)\n end)\n end\nend\n\n---@brief Process queued @ mentions after connection established\nfunction M._process_queued_mentions()\n if #M.state.queued_mentions == 0 then\n return\n end\n\n logger.debug(\"queue\", \"Processing \" .. #M.state.queued_mentions .. \" queued @ mentions\")\n\n -- Stop connection timer\n if M.state.connection_timer then\n M.state.connection_timer:stop()\n M.state.connection_timer:close()\n M.state.connection_timer = nil\n end\n\n -- Wait for connection_wait_delay before sending\n vim.defer_fn(function()\n local mentions_to_send = vim.deepcopy(M.state.queued_mentions)\n M.state.queued_mentions = {} -- Clear queue\n\n if #mentions_to_send == 0 then\n return\n end\n\n -- Ensure terminal is visible when processing queued mentions\n local terminal = require(\"claudecode.terminal\")\n terminal.ensure_visible()\n\n local success_count = 0\n local total_count = #mentions_to_send\n local delay = 10 -- Use same delay as existing batch operations\n\n local function send_mentions_sequentially(index)\n if index > total_count then\n if success_count > 0 then\n local message = success_count == 1 and \"Sent 1 queued @ mention to Claude Code\"\n or string.format(\"Sent %d queued @ mentions to Claude Code\", success_count)\n logger.debug(\"queue\", message)\n end\n return\n end\n\n local mention = mentions_to_send[index]\n local now = vim.loop.now()\n\n -- Check if mention hasn't expired\n if (now - mention.timestamp) < M.state.config.queue_timeout then\n local success, error_msg = M._broadcast_at_mention(mention.file_path, mention.start_line, mention.end_line)\n if success then\n success_count = success_count + 1\n else\n logger.error(\"queue\", \"Failed to send queued @ mention: \" .. (error_msg or \"unknown error\"))\n end\n else\n logger.debug(\"queue\", \"Skipped expired @ mention: \" .. mention.file_path)\n end\n\n -- Send next mention with delay\n if index < total_count then\n vim.defer_fn(function()\n send_mentions_sequentially(index + 1)\n end, delay)\n else\n -- Final summary\n if success_count > 0 then\n local message = success_count == 1 and \"Sent 1 queued @ mention to Claude Code\"\n or string.format(\"Sent %d queued @ mentions to Claude Code\", success_count)\n logger.debug(\"queue\", message)\n end\n end\n end\n\n send_mentions_sequentially(1)\n end, M.state.config.connection_wait_delay)\nend\n\n---@brief Show terminal if Claude is connected and it's not already visible\n---@return boolean success Whether terminal was shown or was already visible\nfunction M._ensure_terminal_visible_if_connected()\n if not M.is_claude_connected() then\n return false\n end\n\n local terminal = require(\"claudecode.terminal\")\n local active_bufnr = terminal.get_active_terminal_bufnr and terminal.get_active_terminal_bufnr()\n\n if not active_bufnr then\n return false\n end\n\n local bufinfo = vim.fn.getbufinfo(active_bufnr)[1]\n local is_visible = bufinfo and #bufinfo.windows > 0\n\n if not is_visible then\n terminal.simple_toggle()\n end\n\n return true\nend\n\n---@brief Send @ mention to Claude Code, handling connection state automatically\n---@param file_path string The file path to send\n---@param start_line number|nil Start line (0-indexed for Claude)\n---@param end_line number|nil End line (0-indexed for Claude)\n---@param context string|nil Context for logging\n---@return boolean success Whether the operation was successful\n---@return string|nil error Error message if failed\nfunction M.send_at_mention(file_path, start_line, end_line, context)\n context = context or \"command\"\n\n if not M.state.server then\n logger.error(context, \"Claude Code integration is not running\")\n return false, \"Claude Code integration is not running\"\n end\n\n -- Check if Claude Code is connected\n if M.is_claude_connected() then\n -- Claude is connected, send immediately and ensure terminal is visible\n local success, error_msg = M._broadcast_at_mention(file_path, start_line, end_line)\n if success then\n local terminal = require(\"claudecode.terminal\")\n terminal.ensure_visible()\n end\n return success, error_msg\n else\n -- Claude not connected, queue the mention and launch terminal\n local mention_data = {\n file_path = file_path,\n start_line = start_line,\n end_line = end_line,\n context = context,\n }\n\n queue_at_mention(mention_data)\n\n -- Launch terminal with Claude Code\n local terminal = require(\"claudecode.terminal\")\n terminal.open()\n\n logger.debug(context, \"Queued @ mention and launched Claude Code: \" .. file_path)\n\n return true, nil\n end\nend\n\n---\n--- Set up the plugin with user configuration\n---@param opts ClaudeCode.SetupOpts|nil Optional configuration table to override defaults.\n---@return table The plugin module\nfunction M.setup(opts)\n opts = opts or {}\n\n local terminal_opts = nil\n if opts.terminal then\n terminal_opts = opts.terminal\n opts.terminal = nil -- Remove from main opts to avoid polluting M.state.config\n end\n\n local config = require(\"claudecode.config\")\n M.state.config = config.apply(opts)\n -- vim.g.claudecode_user_config is no longer needed as config values are passed directly.\n\n logger.setup(M.state.config)\n\n -- Setup terminal module: always try to call setup to pass terminal_cmd,\n -- even if terminal_opts (for split_side etc.) are not provided.\n local terminal_setup_ok, terminal_module = pcall(require, \"claudecode.terminal\")\n if terminal_setup_ok then\n -- Guard in case tests or user replace the module with a minimal stub without `setup`.\n if type(terminal_module.setup) == \"function\" then\n -- terminal_opts might be nil, which the setup function should handle gracefully.\n terminal_module.setup(terminal_opts, M.state.config.terminal_cmd)\n end\n else\n logger.error(\"init\", \"Failed to load claudecode.terminal module for setup.\")\n end\n\n local diff = require(\"claudecode.diff\")\n diff.setup(M.state.config)\n\n if M.state.config.auto_start then\n M.start(false) -- Suppress notification on auto-start\n end\n\n M._create_commands()\n\n vim.api.nvim_create_autocmd(\"VimLeavePre\", {\n group = vim.api.nvim_create_augroup(\"ClaudeCodeShutdown\", { clear = true }),\n callback = function()\n if M.state.server then\n M.stop()\n else\n -- Clear queue even if server isn't running\n clear_mention_queue()\n end\n end,\n desc = \"Automatically stop Claude Code integration when exiting Neovim\",\n })\n\n M.state.initialized = true\n return M\nend\n\n--- Start the Claude Code integration\n---@param show_startup_notification? boolean Whether to show a notification upon successful startup (defaults to true)\n---@return boolean success Whether the operation was successful\n---@return number|string port_or_error The WebSocket port if successful, or error message if failed\nfunction M.start(show_startup_notification)\n if show_startup_notification == nil then\n show_startup_notification = true\n end\n if M.state.server then\n local msg = \"Claude Code integration is already running on port \" .. tostring(M.state.port)\n logger.warn(\"init\", msg)\n return false, \"Already running\"\n end\n\n local server = require(\"claudecode.server.init\")\n local lockfile = require(\"claudecode.lockfile\")\n\n -- Generate auth token first so we can pass it to the server\n local auth_token\n local auth_success, auth_result = pcall(function()\n return lockfile.generate_auth_token()\n end)\n\n if not auth_success then\n local error_msg = \"Failed to generate authentication token: \" .. (auth_result or \"unknown error\")\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n auth_token = auth_result\n\n -- Validate the generated auth token\n if not auth_token or type(auth_token) ~= \"string\" or #auth_token < 10 then\n local error_msg = \"Invalid authentication token generated\"\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n local success, result = server.start(M.state.config, auth_token)\n\n if not success then\n local error_msg = \"Failed to start Claude Code server: \" .. (result or \"unknown error\")\n if result and result:find(\"auth\") then\n error_msg = error_msg .. \" (authentication related)\"\n end\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n M.state.server = server\n M.state.port = tonumber(result)\n M.state.auth_token = auth_token\n\n local lock_success, lock_result, returned_auth_token = lockfile.create(M.state.port, auth_token)\n\n if not lock_success then\n server.stop()\n M.state.server = nil\n M.state.port = nil\n M.state.auth_token = nil\n\n local error_msg = \"Failed to create lock file: \" .. (lock_result or \"unknown error\")\n if lock_result and lock_result:find(\"auth\") then\n error_msg = error_msg .. \" (authentication token issue)\"\n end\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n -- Verify that the auth token in the lock file matches what we generated\n if returned_auth_token ~= auth_token then\n server.stop()\n M.state.server = nil\n M.state.port = nil\n M.state.auth_token = nil\n\n local error_msg = \"Authentication token mismatch between server and lock file\"\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n if M.state.config.track_selection then\n local selection = require(\"claudecode.selection\")\n selection.enable(M.state.server, M.state.config.visual_demotion_delay_ms)\n end\n\n if show_startup_notification then\n logger.info(\"init\", \"Claude Code integration started on port \" .. tostring(M.state.port))\n end\n\n return true, M.state.port\nend\n\n--- Stop the Claude Code integration\n---@return boolean success Whether the operation was successful\n---@return string? error Error message if operation failed\nfunction M.stop()\n if not M.state.server then\n logger.warn(\"init\", \"Claude Code integration is not running\")\n return false, \"Not running\"\n end\n\n local lockfile = require(\"claudecode.lockfile\")\n local lock_success, lock_error = lockfile.remove(M.state.port)\n\n if not lock_success then\n logger.warn(\"init\", \"Failed to remove lock file: \" .. lock_error)\n -- Continue with shutdown even if lock file removal fails\n end\n\n if M.state.config.track_selection then\n local selection = require(\"claudecode.selection\")\n selection.disable()\n end\n\n local success, error = M.state.server.stop()\n\n if not success then\n logger.error(\"init\", \"Failed to stop Claude Code integration: \" .. error)\n return false, error\n end\n\n M.state.server = nil\n M.state.port = nil\n M.state.auth_token = nil\n\n -- Clear any queued @ mentions when server stops\n clear_mention_queue()\n\n logger.info(\"init\", \"Claude Code integration stopped\")\n\n return true\nend\n\n--- Set up user commands\n---@private\nfunction M._create_commands()\n vim.api.nvim_create_user_command(\"ClaudeCodeStart\", function()\n M.start()\n end, {\n desc = \"Start Claude Code integration\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeStop\", function()\n M.stop()\n end, {\n desc = \"Stop Claude Code integration\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeStatus\", function()\n if M.state.server and M.state.port then\n logger.info(\"command\", \"Claude Code integration is running on port \" .. tostring(M.state.port))\n else\n logger.info(\"command\", \"Claude Code integration is not running\")\n end\n end, {\n desc = \"Show Claude Code integration status\",\n })\n\n ---@param file_paths table List of file paths to add\n ---@param options table|nil Optional settings: { delay?: number, show_summary?: boolean, context?: string }\n ---@return number success_count Number of successfully added files\n ---@return number total_count Total number of files attempted\n local function add_paths_to_claude(file_paths, options)\n options = options or {}\n local delay = options.delay or 0\n local show_summary = options.show_summary ~= false\n local context = options.context or \"command\"\n\n if not file_paths or #file_paths == 0 then\n return 0, 0\n end\n\n local success_count = 0\n local total_count = #file_paths\n\n if delay > 0 then\n local function send_files_sequentially(index)\n if index > total_count then\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n return\n end\n\n local file_path = file_paths[index]\n local success, error_msg = M.send_at_mention(file_path, nil, nil, context)\n if success then\n success_count = success_count + 1\n else\n logger.error(context, \"Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\"))\n end\n\n if index < total_count then\n vim.defer_fn(function()\n send_files_sequentially(index + 1)\n end, delay)\n else\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n end\n end\n\n send_files_sequentially(1)\n else\n for _, file_path in ipairs(file_paths) do\n local success, error_msg = M.send_at_mention(file_path, nil, nil, context)\n if success then\n success_count = success_count + 1\n else\n logger.error(context, \"Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\"))\n end\n end\n\n if show_summary and success_count > 0 then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n logger.debug(context, message)\n end\n end\n\n return success_count, total_count\n end\n\n local function handle_send_normal(opts)\n local current_ft = (vim.bo and vim.bo.filetype) or \"\"\n local current_bufname = (vim.api and vim.api.nvim_buf_get_name and vim.api.nvim_buf_get_name(0)) or \"\"\n\n local is_tree_buffer = current_ft == \"NvimTree\"\n or current_ft == \"neo-tree\"\n or current_ft == \"oil\"\n or string.match(current_bufname, \"neo%-tree\")\n or string.match(current_bufname, \"NvimTree\")\n\n if is_tree_buffer then\n local integrations = require(\"claudecode.integrations\")\n local files, error = integrations.get_selected_files_from_tree()\n\n if error then\n logger.error(\"command\", \"ClaudeCodeSend->TreeAdd: \" .. error)\n return\n end\n\n if not files or #files == 0 then\n logger.warn(\"command\", \"ClaudeCodeSend->TreeAdd: No files selected\")\n return\n end\n\n add_paths_to_claude(files, { context = \"ClaudeCodeSend->TreeAdd\" })\n\n return\n end\n\n local selection_module_ok, selection_module = pcall(require, \"claudecode.selection\")\n if selection_module_ok then\n -- Pass range information if available (for :'<,'> commands)\n local line1, line2 = nil, nil\n if opts and opts.range and opts.range > 0 then\n line1, line2 = opts.line1, opts.line2\n end\n local sent_successfully = selection_module.send_at_mention_for_visual_selection(line1, line2)\n if sent_successfully then\n -- Exit any potential visual mode (for consistency)\n pcall(function()\n if vim.api and vim.api.nvim_feedkeys then\n local esc = vim.api.nvim_replace_termcodes(\"\", true, false, true)\n vim.api.nvim_feedkeys(esc, \"i\", true)\n end\n end)\n end\n else\n logger.error(\"command\", \"ClaudeCodeSend: Failed to load selection module.\")\n end\n end\n\n local function handle_send_visual(visual_data, _opts)\n -- Try tree file selection first\n if visual_data then\n local visual_commands = require(\"claudecode.visual_commands\")\n local files, error = visual_commands.get_files_from_visual_selection(visual_data)\n\n if not error and files and #files > 0 then\n local success_count = add_paths_to_claude(files, {\n delay = 10,\n context = \"ClaudeCodeSend_visual\",\n show_summary = false,\n })\n if success_count > 0 then\n local message = success_count == 1 and \"Added 1 file to Claude context from visual selection\"\n or string.format(\"Added %d files to Claude context from visual selection\", success_count)\n logger.debug(\"command\", message)\n end\n return\n end\n end\n\n -- Handle regular text selection using range from visual mode\n local selection_module_ok, selection_module = pcall(require, \"claudecode.selection\")\n if not selection_module_ok then\n return\n end\n\n -- Use the marks left by visual mode instead of trying to get current visual selection\n local line1, line2 = vim.fn.line(\"'<\"), vim.fn.line(\"'>\")\n if line1 and line2 and line1 > 0 and line2 > 0 then\n selection_module.send_at_mention_for_visual_selection(line1, line2)\n else\n selection_module.send_at_mention_for_visual_selection()\n end\n end\n\n local visual_commands = require(\"claudecode.visual_commands\")\n local unified_send_handler = visual_commands.create_visual_command_wrapper(handle_send_normal, handle_send_visual)\n\n vim.api.nvim_create_user_command(\"ClaudeCodeSend\", unified_send_handler, {\n desc = \"Send current visual selection as an at_mention to Claude Code (supports tree visual selection)\",\n range = true,\n })\n\n local function handle_tree_add_normal()\n if not M.state.server then\n logger.error(\"command\", \"ClaudeCodeTreeAdd: Claude Code integration is not running.\")\n return\n end\n\n local integrations = require(\"claudecode.integrations\")\n local files, error = integrations.get_selected_files_from_tree()\n\n if error then\n logger.error(\"command\", \"ClaudeCodeTreeAdd: \" .. error)\n return\n end\n\n if not files or #files == 0 then\n logger.warn(\"command\", \"ClaudeCodeTreeAdd: No files selected\")\n return\n end\n\n -- Use connection-aware broadcasting for each file\n local success_count = 0\n local total_count = #files\n\n for _, file_path in ipairs(files) do\n local success, error_msg = M.send_at_mention(file_path, nil, nil, \"ClaudeCodeTreeAdd\")\n if success then\n success_count = success_count + 1\n else\n logger.error(\n \"command\",\n \"ClaudeCodeTreeAdd: Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\")\n )\n end\n end\n\n if success_count == 0 then\n logger.error(\"command\", \"ClaudeCodeTreeAdd: Failed to add any files\")\n elseif success_count < total_count then\n local message = string.format(\"Added %d/%d files to Claude context\", success_count, total_count)\n logger.debug(\"command\", message)\n else\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n logger.debug(\"command\", message)\n end\n end\n\n local function handle_tree_add_visual(visual_data)\n if not M.state.server then\n logger.error(\"command\", \"ClaudeCodeTreeAdd_visual: Claude Code integration is not running.\")\n return\n end\n\n local visual_cmd_module = require(\"claudecode.visual_commands\")\n local files, error = visual_cmd_module.get_files_from_visual_selection(visual_data)\n\n if error then\n logger.error(\"command\", \"ClaudeCodeTreeAdd_visual: \" .. error)\n return\n end\n\n if not files or #files == 0 then\n logger.warn(\"command\", \"ClaudeCodeTreeAdd_visual: No files selected in visual range\")\n return\n end\n\n -- Use connection-aware broadcasting for each file\n local success_count = 0\n local total_count = #files\n\n for _, file_path in ipairs(files) do\n local success, error_msg = M.send_at_mention(file_path, nil, nil, \"ClaudeCodeTreeAdd_visual\")\n if success then\n success_count = success_count + 1\n else\n logger.error(\n \"command\",\n \"ClaudeCodeTreeAdd_visual: Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\")\n )\n end\n end\n\n if success_count > 0 then\n local message = success_count == 1 and \"Added 1 file to Claude context from visual selection\"\n or string.format(\"Added %d files to Claude context from visual selection\", success_count)\n logger.debug(\"command\", message)\n\n if success_count < total_count then\n logger.warn(\"command\", string.format(\"Added %d/%d files from visual selection\", success_count, total_count))\n end\n else\n logger.error(\"command\", \"ClaudeCodeTreeAdd_visual: Failed to add any files from visual selection\")\n end\n end\n\n local unified_tree_add_handler =\n visual_commands.create_visual_command_wrapper(handle_tree_add_normal, handle_tree_add_visual)\n\n vim.api.nvim_create_user_command(\"ClaudeCodeTreeAdd\", unified_tree_add_handler, {\n desc = \"Add selected file(s) from tree explorer to Claude Code context (supports visual selection)\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeAdd\", function(opts)\n if not M.state.server then\n logger.error(\"command\", \"ClaudeCodeAdd: Claude Code integration is not running.\")\n return\n end\n\n if not opts.args or opts.args == \"\" then\n logger.error(\"command\", \"ClaudeCodeAdd: No file path provided\")\n return\n end\n\n local args = vim.split(opts.args, \"%s+\")\n local file_path = args[1]\n local start_line = args[2] and tonumber(args[2]) or nil\n local end_line = args[3] and tonumber(args[3]) or nil\n\n if #args > 3 then\n logger.error(\n \"command\",\n \"ClaudeCodeAdd: Too many arguments. Usage: ClaudeCodeAdd [start-line] [end-line]\"\n )\n return\n end\n\n if args[2] and not start_line then\n logger.error(\"command\", \"ClaudeCodeAdd: Invalid start line number: \" .. args[2])\n return\n end\n\n if args[3] and not end_line then\n logger.error(\"command\", \"ClaudeCodeAdd: Invalid end line number: \" .. args[3])\n return\n end\n\n if start_line and start_line < 1 then\n logger.error(\"command\", \"ClaudeCodeAdd: Start line must be positive: \" .. start_line)\n return\n end\n\n if end_line and end_line < 1 then\n logger.error(\"command\", \"ClaudeCodeAdd: End line must be positive: \" .. end_line)\n return\n end\n\n if start_line and end_line and start_line > end_line then\n logger.error(\n \"command\",\n \"ClaudeCodeAdd: Start line (\" .. start_line .. \") must be <= end line (\" .. end_line .. \")\"\n )\n return\n end\n\n file_path = vim.fn.expand(file_path)\n if vim.fn.filereadable(file_path) == 0 and vim.fn.isdirectory(file_path) == 0 then\n logger.error(\"command\", \"ClaudeCodeAdd: File or directory does not exist: \" .. file_path)\n return\n end\n\n local claude_start_line = start_line and (start_line - 1) or nil\n local claude_end_line = end_line and (end_line - 1) or nil\n\n local success, error_msg = M.send_at_mention(file_path, claude_start_line, claude_end_line, \"ClaudeCodeAdd\")\n if not success then\n logger.error(\"command\", \"ClaudeCodeAdd: \" .. (error_msg or \"Failed to add file\"))\n else\n local message = \"ClaudeCodeAdd: Successfully added \" .. file_path\n if start_line or end_line then\n if start_line and end_line then\n message = message .. \" (lines \" .. start_line .. \"-\" .. end_line .. \")\"\n elseif start_line then\n message = message .. \" (from line \" .. start_line .. \")\"\n end\n end\n logger.debug(\"command\", message)\n end\n end, {\n nargs = \"+\",\n complete = \"file\",\n desc = \"Add specified file or directory to Claude Code context with optional line range\",\n })\n\n local terminal_ok, terminal = pcall(require, \"claudecode.terminal\")\n if terminal_ok then\n vim.api.nvim_create_user_command(\"ClaudeCode\", function(opts)\n local current_mode = vim.fn.mode()\n if current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\22\" then\n vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(\"\", true, false, true), \"n\", false)\n end\n local cmd_args = opts.args and opts.args ~= \"\" and opts.args or nil\n terminal.simple_toggle({}, cmd_args)\n end, {\n nargs = \"*\",\n desc = \"Toggle the Claude Code terminal window (simple show/hide) with optional arguments\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeFocus\", function(opts)\n local current_mode = vim.fn.mode()\n if current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\22\" then\n vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(\"\", true, false, true), \"n\", false)\n end\n local cmd_args = opts.args and opts.args ~= \"\" and opts.args or nil\n terminal.focus_toggle({}, cmd_args)\n end, {\n nargs = \"*\",\n desc = \"Smart focus/toggle Claude Code terminal (switches to terminal if not focused, hides if focused)\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeOpen\", function(opts)\n local cmd_args = opts.args and opts.args ~= \"\" and opts.args or nil\n terminal.open({}, cmd_args)\n end, {\n nargs = \"*\",\n desc = \"Open the Claude Code terminal window with optional arguments\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeClose\", function()\n terminal.close()\n end, {\n desc = \"Close the Claude Code terminal window\",\n })\n else\n logger.error(\n \"init\",\n \"Terminal module not found. Terminal commands (ClaudeCode, ClaudeCodeOpen, ClaudeCodeClose) not registered.\"\n )\n end\n\n -- Diff management commands\n vim.api.nvim_create_user_command(\"ClaudeCodeDiffAccept\", function()\n local diff = require(\"claudecode.diff\")\n diff.accept_current_diff()\n end, {\n desc = \"Accept the current diff changes\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeDiffDeny\", function()\n local diff = require(\"claudecode.diff\")\n diff.deny_current_diff()\n end, {\n desc = \"Deny/reject the current diff changes\",\n })\nend\n\n--- Get version information\n---@return table Version information\nfunction M.get_version()\n return {\n version = M.version:string(),\n major = M.version.major,\n minor = M.version.minor,\n patch = M.version.patch,\n prerelease = M.version.prerelease,\n }\nend\n\n--- Format file path for at mention (exposed for testing)\n---@param file_path string The file path to format\n---@return string formatted_path The formatted path\n---@return boolean is_directory Whether the path is a directory\nfunction M._format_path_for_at_mention(file_path)\n -- Input validation\n if not file_path or type(file_path) ~= \"string\" or file_path == \"\" then\n error(\"format_path_for_at_mention: file_path must be a non-empty string\")\n end\n\n -- Only check path existence in production (not tests)\n -- This allows tests to work with mock paths while still providing validation in real usage\n if not package.loaded[\"busted\"] then\n if vim.fn.filereadable(file_path) == 0 and vim.fn.isdirectory(file_path) == 0 then\n error(\"format_path_for_at_mention: path does not exist: \" .. file_path)\n end\n end\n\n local is_directory = vim.fn.isdirectory(file_path) == 1\n local formatted_path = file_path\n\n if is_directory then\n local cwd = vim.fn.getcwd()\n if string.find(file_path, cwd, 1, true) == 1 then\n local relative_path = string.sub(file_path, #cwd + 2)\n if relative_path ~= \"\" then\n formatted_path = relative_path\n else\n formatted_path = \"./\"\n end\n end\n if not string.match(formatted_path, \"/$\") then\n formatted_path = formatted_path .. \"/\"\n end\n else\n local cwd = vim.fn.getcwd()\n if string.find(file_path, cwd, 1, true) == 1 then\n local relative_path = string.sub(file_path, #cwd + 2)\n if relative_path ~= \"\" then\n formatted_path = relative_path\n end\n end\n end\n\n return formatted_path, is_directory\nend\n\n-- Test helper functions (exposed for testing)\nfunction M._broadcast_at_mention(file_path, start_line, end_line)\n if not M.state.server then\n return false, \"Claude Code integration is not running\"\n end\n\n -- Safely format the path and handle validation errors\n local formatted_path, is_directory\n local format_success, format_result, is_dir_result = pcall(M._format_path_for_at_mention, file_path)\n if not format_success then\n return false, format_result -- format_result contains the error message\n end\n formatted_path, is_directory = format_result, is_dir_result\n\n if is_directory and (start_line or end_line) then\n logger.debug(\"command\", \"Line numbers ignored for directory: \" .. formatted_path)\n start_line = nil\n end_line = nil\n end\n\n local params = {\n filePath = formatted_path,\n lineStart = start_line,\n lineEnd = end_line,\n }\n\n local broadcast_success = M.state.server.broadcast(\"at_mentioned\", params)\n if broadcast_success then\n return true, nil\n else\n local error_msg = \"Failed to broadcast \" .. (is_directory and \"directory\" or \"file\") .. \" \" .. formatted_path\n logger.error(\"command\", error_msg)\n return false, error_msg\n end\nend\n\nfunction M._add_paths_to_claude(file_paths, options)\n options = options or {}\n local delay = options.delay or 0\n local show_summary = options.show_summary ~= false\n local context = options.context or \"command\"\n local batch_size = options.batch_size or 10\n local max_files = options.max_files or 100\n\n if not file_paths or #file_paths == 0 then\n return 0, 0\n end\n\n if #file_paths > max_files then\n logger.warn(context, string.format(\"Too many files selected (%d), limiting to %d\", #file_paths, max_files))\n local limited_paths = {}\n for i = 1, max_files do\n limited_paths[i] = file_paths[i]\n end\n file_paths = limited_paths\n end\n\n local success_count = 0\n local total_count = #file_paths\n\n if delay > 0 then\n local function send_batch(start_index)\n if start_index > total_count then\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n return\n end\n\n -- Process a batch of files\n local end_index = math.min(start_index + batch_size - 1, total_count)\n local batch_success = 0\n\n for i = start_index, end_index do\n local file_path = file_paths[i]\n local success, error_msg = M._broadcast_at_mention(file_path)\n if success then\n success_count = success_count + 1\n batch_success = batch_success + 1\n else\n logger.error(context, \"Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\"))\n end\n end\n\n logger.debug(\n context,\n string.format(\n \"Processed batch %d-%d: %d/%d successful\",\n start_index,\n end_index,\n batch_success,\n end_index - start_index + 1\n )\n )\n\n if end_index < total_count then\n vim.defer_fn(function()\n send_batch(end_index + 1)\n end, delay)\n else\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n end\n end\n\n send_batch(1)\n else\n local progress_interval = math.max(1, math.floor(total_count / 10))\n\n for i, file_path in ipairs(file_paths) do\n local success, error_msg = M._broadcast_at_mention(file_path)\n if success then\n success_count = success_count + 1\n else\n logger.error(context, \"Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\"))\n end\n\n if total_count > 20 and i % progress_interval == 0 then\n logger.debug(\n context,\n string.format(\"Progress: %d/%d files processed (%d successful)\", i, total_count, success_count)\n )\n end\n end\n\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n end\n\n return success_count, total_count\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/visual_commands.lua", "---\n-- Visual command handling module for ClaudeCode.nvim\n-- Implements neo-tree-style visual mode exit and command processing\n-- @module claudecode.visual_commands\nlocal M = {}\n\n--- Get current vim mode with fallback for test environments\n--- @param full_mode boolean|nil Whether to get full mode info (passed to vim.fn.mode)\n--- @return string current_mode The current vim mode\nlocal function get_current_mode(full_mode)\n local current_mode = \"n\" -- Default fallback\n\n pcall(function()\n if vim.api and vim.api.nvim_get_mode then\n current_mode = vim.api.nvim_get_mode().mode\n else\n current_mode = vim.fn.mode(full_mode)\n end\n end)\n\n return current_mode\nend\n\n-- ESC key constant matching neo-tree's implementation\nlocal ESC_KEY\nlocal success = pcall(function()\n ESC_KEY = vim.api.nvim_replace_termcodes(\"\", true, false, true)\nend)\nif not success then\n ESC_KEY = \"\\27\"\nend\n\n--- Exit visual mode properly and schedule command execution\n--- @param callback function The function to call after exiting visual mode\n--- @param ... any Arguments to pass to the callback\nfunction M.exit_visual_and_schedule(callback, ...)\n local args = { ... }\n\n -- Capture visual selection data BEFORE exiting visual mode\n local visual_data = M.capture_visual_selection_data()\n\n pcall(function()\n vim.api.nvim_feedkeys(ESC_KEY, \"i\", true)\n end)\n\n -- Schedule execution until after mode change (neo-tree pattern)\n local schedule_fn = vim.schedule or function(fn)\n fn()\n end -- Fallback for test environments\n schedule_fn(function()\n -- Pass the captured visual data as the first argument\n callback(visual_data, unpack(args))\n end)\nend\n\n--- Validate that we're currently in a visual mode\n--- @return boolean true if in visual mode, false otherwise\n--- @return string|nil error message if not in visual mode\nfunction M.validate_visual_mode()\n local current_mode = get_current_mode(true)\n\n local is_visual = current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\022\"\n\n -- Additional debugging: check visual marks and cursor position\n if is_visual then\n pcall(function()\n vim.api.nvim_win_get_cursor(0)\n vim.fn.getpos(\"'<\")\n vim.fn.getpos(\"'>\")\n vim.fn.getpos(\"v\")\n end)\n end\n\n if not is_visual then\n return false, \"Not in visual mode (current mode: \" .. current_mode .. \")\"\n end\n\n return true, nil\nend\n\n--- Get visual selection range using vim marks or current cursor position\n--- @return number, number start_line, end_line (1-indexed)\nfunction M.get_visual_range()\n local start_pos, end_pos = 1, 1 -- Default fallback\n\n -- Use pcall to handle test environments\n local range_success = pcall(function()\n -- Check if we're currently in visual mode\n local current_mode = get_current_mode(true)\n local is_visual = current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\022\"\n\n if is_visual then\n -- In visual mode, ALWAYS use cursor + anchor (marks are stale until exit)\n local cursor_pos = vim.api.nvim_win_get_cursor(0)[1]\n local anchor_pos = vim.fn.getpos(\"v\")[2]\n\n if anchor_pos > 0 then\n start_pos = math.min(cursor_pos, anchor_pos)\n end_pos = math.max(cursor_pos, anchor_pos)\n else\n -- Fallback: just use current cursor position\n start_pos = cursor_pos\n end_pos = cursor_pos\n end\n else\n -- Not in visual mode, try to use the marks (they should be valid now)\n local mark_start = vim.fn.getpos(\"'<\")[2]\n local mark_end = vim.fn.getpos(\"'>\")[2]\n\n if mark_start > 0 and mark_end > 0 then\n start_pos = mark_start\n end_pos = mark_end\n else\n -- No valid marks, use cursor position\n local cursor_pos = vim.api.nvim_win_get_cursor(0)[1]\n start_pos = cursor_pos\n end_pos = cursor_pos\n end\n end\n end)\n\n if not range_success then\n return 1, 1\n end\n\n if end_pos < start_pos then\n start_pos, end_pos = end_pos, start_pos\n end\n\n -- Ensure we have valid line numbers (at least 1)\n start_pos = math.max(1, start_pos)\n end_pos = math.max(1, end_pos)\n\n return start_pos, end_pos\nend\n\n--- Check if we're in a tree buffer and get the tree state\n--- @return table|nil, string|nil tree_state, tree_type (\"neo-tree\" or \"nvim-tree\")\nfunction M.get_tree_state()\n local current_ft = \"\" -- Default fallback\n local current_win = 0 -- Default fallback\n\n -- Use pcall to handle test environments\n local state_success = pcall(function()\n current_ft = vim.bo.filetype or \"\"\n current_win = vim.api.nvim_get_current_win()\n end)\n\n if not state_success then\n return nil, nil\n end\n\n if current_ft == \"neo-tree\" then\n local manager_success, manager = pcall(require, \"neo-tree.sources.manager\")\n if not manager_success then\n return nil, nil\n end\n\n local state = manager.get_state(\"filesystem\")\n if not state then\n return nil, nil\n end\n\n -- Validate we're in the correct neo-tree window\n if state.winid and state.winid == current_win then\n return state, \"neo-tree\"\n else\n return nil, nil\n end\n elseif current_ft == \"NvimTree\" then\n local api_success, nvim_tree_api = pcall(require, \"nvim-tree.api\")\n if not api_success then\n return nil, nil\n end\n\n return nvim_tree_api, \"nvim-tree\"\n elseif current_ft == \"oil\" then\n local oil_success, oil = pcall(require, \"oil\")\n if not oil_success then\n return nil, nil\n end\n\n return oil, \"oil\"\n else\n return nil, nil\n end\nend\n\n--- Create a visual command wrapper that follows neo-tree patterns\n--- @param normal_handler function The normal command handler\n--- @param visual_handler function The visual command handler\n--- @return function The wrapped command function\nfunction M.create_visual_command_wrapper(normal_handler, visual_handler)\n return function(...)\n local current_mode = get_current_mode(true)\n\n if current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\022\" then\n -- Use the neo-tree pattern: exit visual mode, then schedule execution\n M.exit_visual_and_schedule(visual_handler, ...)\n else\n normal_handler(...)\n end\n end\nend\n\n--- Capture visual selection data while still in visual mode\n--- @return table|nil visual_data Captured data or nil if not in visual mode\nfunction M.capture_visual_selection_data()\n local valid = M.validate_visual_mode()\n if not valid then\n return nil\n end\n\n local tree_state, tree_type = M.get_tree_state()\n if not tree_state then\n return nil\n end\n\n local start_pos, end_pos = M.get_visual_range()\n\n -- Validate that we have a meaningful range\n if start_pos == 0 or end_pos == 0 then\n return nil\n end\n\n return {\n tree_state = tree_state,\n tree_type = tree_type,\n start_pos = start_pos,\n end_pos = end_pos,\n }\nend\n\n--- Extract files from visual selection in tree buffers\n--- @param visual_data table|nil Pre-captured visual selection data\n--- @return table files List of file paths\n--- @return string|nil error Error message if failed\nfunction M.get_files_from_visual_selection(visual_data)\n -- If we have pre-captured data, use it; otherwise try to get current data\n local tree_state, tree_type, start_pos, end_pos\n\n if visual_data then\n tree_state = visual_data.tree_state\n tree_type = visual_data.tree_type\n start_pos = visual_data.start_pos\n end_pos = visual_data.end_pos\n else\n local valid, err = M.validate_visual_mode()\n if not valid then\n return {}, err\n end\n\n tree_state, tree_type = M.get_tree_state()\n if not tree_state then\n return {}, \"Not in a supported tree buffer\"\n end\n\n start_pos, end_pos = M.get_visual_range()\n end\n\n if not tree_state then\n return {}, \"Not in a supported tree buffer\"\n end\n\n local files = {}\n\n if tree_type == \"neo-tree\" then\n local selected_nodes = {}\n for line = start_pos, end_pos do\n -- Neo-tree's tree:get_node() uses the line number directly (1-based)\n local node = tree_state.tree:get_node(line)\n if node then\n if node.type and node.type ~= \"message\" then\n table.insert(selected_nodes, node)\n end\n end\n end\n\n for _, node in ipairs(selected_nodes) do\n if node.type == \"file\" and node.path and node.path ~= \"\" then\n local depth = (node.get_depth and node:get_depth()) or 0\n if depth > 1 then\n table.insert(files, node.path)\n end\n elseif node.type == \"directory\" and node.path and node.path ~= \"\" then\n local depth = (node.get_depth and node:get_depth()) or 0\n if depth > 1 then\n table.insert(files, node.path)\n end\n end\n end\n elseif tree_type == \"nvim-tree\" then\n -- For nvim-tree, we need to manually map visual lines to tree nodes\n -- since nvim-tree doesn't have direct line-to-node mapping like neo-tree\n require(\"claudecode.logger\").debug(\n \"visual_commands\",\n \"Processing nvim-tree visual selection from line\",\n start_pos,\n \"to\",\n end_pos\n )\n\n local nvim_tree_api = tree_state\n local current_buf = vim.api.nvim_get_current_buf()\n\n -- Get all lines in the visual selection\n local lines = vim.api.nvim_buf_get_lines(current_buf, start_pos - 1, end_pos, false)\n\n require(\"claudecode.logger\").debug(\"visual_commands\", \"Found\", #lines, \"lines in visual selection\")\n\n -- For each line in the visual selection, try to get the corresponding node\n for i, line_content in ipairs(lines) do\n local line_num = start_pos + i - 1\n\n -- Set cursor to this line to get the node\n pcall(vim.api.nvim_win_set_cursor, 0, { line_num, 0 })\n\n -- Get node under cursor for this line\n local node_success, node = pcall(nvim_tree_api.tree.get_node_under_cursor)\n if node_success and node then\n require(\"claudecode.logger\").debug(\n \"visual_commands\",\n \"Line\",\n line_num,\n \"node type:\",\n node.type,\n \"path:\",\n node.absolute_path\n )\n\n if node.type == \"file\" and node.absolute_path and node.absolute_path ~= \"\" then\n -- Check if it's not a root-level file (basic protection)\n if not string.match(node.absolute_path, \"^/[^/]*$\") then\n table.insert(files, node.absolute_path)\n end\n elseif node.type == \"directory\" and node.absolute_path and node.absolute_path ~= \"\" then\n table.insert(files, node.absolute_path)\n end\n else\n require(\"claudecode.logger\").debug(\"visual_commands\", \"No valid node found for line\", line_num)\n end\n end\n\n require(\"claudecode.logger\").debug(\"visual_commands\", \"Extracted\", #files, \"files from nvim-tree visual selection\")\n\n -- Remove duplicates while preserving order\n local seen = {}\n local unique_files = {}\n for _, file_path in ipairs(files) do\n if not seen[file_path] then\n seen[file_path] = true\n table.insert(unique_files, file_path)\n end\n end\n files = unique_files\n elseif tree_type == \"oil\" then\n local oil = tree_state\n local bufnr = vim.api.nvim_get_current_buf()\n\n -- Get current directory once\n local dir_ok, current_dir = pcall(oil.get_current_dir, bufnr)\n if dir_ok and current_dir then\n -- Access the process_oil_entry function through a module method\n for line = start_pos, end_pos do\n local entry_ok, entry = pcall(oil.get_entry_on_line, bufnr, line)\n if entry_ok and entry and entry.name then\n -- Skip parent directory entries\n if entry.name ~= \"..\" and entry.name ~= \".\" then\n local full_path = current_dir .. entry.name\n -- Handle various entry types\n if entry.type == \"file\" or entry.type == \"link\" then\n table.insert(files, full_path)\n elseif entry.type == \"directory\" then\n -- Ensure directory paths end with /\n table.insert(files, full_path:match(\"/$\") and full_path or full_path .. \"/\")\n else\n -- For unknown types, return the path anyway\n table.insert(files, full_path)\n end\n end\n end\n end\n end\n end\n\n return files, nil\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/meta/vim.lua", "---@meta vim_api_definitions\n-- This file provides type definitions for parts of the Neovim API\n-- to help the Lua language server (LuaLS) with diagnostics.\n\n---@class vim_log_levels\n---@field NONE number\n---@field ERROR number\n---@field WARN number\n---@field INFO number\n---@field DEBUG number\n---@field TRACE number\n\n---@class vim_log\n---@field levels vim_log_levels\n\n---@class vim_notify_opts\n---@field title string|nil\n---@field icon string|nil\n---@field on_open fun(winid: number)|nil\n---@field on_close fun()|nil\n---@field timeout number|nil\n---@field keep fun()|nil\n---@field plugin string|nil\n---@field hide_from_history boolean|nil\n---@field once boolean|nil\n---@field on_close_timeout number|nil\n\n---@class vim_options_table: table\n---@field columns number Global option: width of the screen\n---@field lines number Global option: height of the screen\n-- Add other commonly used vim.o options as needed\n\n---@class vim_buffer_options_table: table\n\n---@class vim_bo_proxy: vim_buffer_options_table\n---@field __index fun(self: vim_bo_proxy, bufnr: number): vim_buffer_options_table Allows vim.bo[bufnr]\n\n---@class vim_diagnostic_info\n---@field bufnr number\n---@field col number\n---@field end_col number|nil\n---@field end_lnum number|nil\n---@field lnum number\n---@field message string\n---@field severity number\n---@field source string|nil\n---@field user_data any|nil\n\n---@class vim_diagnostic_module\n---@field get fun(bufnr?: number, ns_id?: number): vim_diagnostic_info[]\n-- Add other vim.diagnostic functions as needed, e.g., get_namespace, set, etc.\n\n---@class vim_fs_module\n---@field remove fun(path: string, opts?: {force?: boolean, recursive?: boolean}):boolean|nil\n\n---@class vim_filetype_module\n---@field match fun(args: {filename: string, contents?: string}):string|nil\n\n---@class vim_fn_table\n---@field mode fun(mode_str?: string, full?: boolean|number):string\n---@field delete fun(name: string, flags?: string):integer For file deletion\n---@field filereadable fun(file: string):integer\n---@field fnamemodify fun(fname: string, mods: string):string\n---@field expand fun(str: string, ...):string|table\n---@field getcwd fun(winid?: number, tabnr?: number):string\n---@field mkdir fun(name: string, path?: string, prot?: number):integer\n---@field buflisted fun(bufnr: number|string):integer\n---@field bufname fun(expr?: number|string):string\n---@field bufnr fun(expr?: string|number, create?: boolean):number\n---@field win_getid fun(win?: number, tab?: number):number\n---@field win_gotoid fun(winid: number):boolean\n---@field line fun(expr: string, winid?: number):number\n---@field col fun(expr: string, winid?: number):number\n---@field virtcol fun(expr: string|string[], winid?: number):number|number[]\n---@field getpos fun(expr: string, winid?: number):number[]\n---@field setpos fun(expr: string, pos: number[], winid?: number):boolean\n---@field tempname fun():string\n---@field globpath fun(path: string, expr: string, ...):string\n---@field stdpath fun(type: \"cache\"|\"config\"|\"data\"|\"log\"|\"run\"|\"state\"|\"config_dirs\"|\"data_dirs\"):string|string[]\n---@field json_encode fun(expr: any):string\n---@field json_decode fun(string: string, opts?: {null_value?: any}):any\n---@field termopen fun(cmd: string|string[], opts?: table):number For vim.fn.termopen()\n-- Add other vim.fn functions as needed\n\n---@class vim_v_table\n---@field event table Event data containing status and other event information\n\n---@class vim_global_api\n---@field notify fun(msg: string | string[], level?: number, opts?: vim_notify_opts):nil\n---@field log vim_log\n---@field v vim_v_table For vim.v.event access\n---@field _last_echo table[]? table of tables, e.g. { {\"message\", \"HighlightGroup\"} }\n---@field _last_error string?\n---@field o vim_options_table For vim.o.option_name\n---@field bo vim_bo_proxy For vim.bo.option_name and vim.bo[bufnr].option_name\n---@field diagnostic vim_diagnostic_module For vim.diagnostic.*\n---@field empty_dict fun(): table For vim.empty_dict()\n---@field schedule_wrap fun(fn: function): function For vim.schedule_wrap()\n---@field deepcopy fun(val: any): any For vim.deepcopy() -- Added based on test mocks\n---@field _current_mode string? For mocks in tests\n---@class vim_api_table\n---@field nvim_create_augroup fun(name: string, opts: {clear: boolean}):integer\n---@field nvim_create_autocmd fun(event: string|string[], opts: {group?: string|integer, pattern?: string|string[], buffer?: number, callback?: function|string, once?: boolean, desc?: string}):integer\n---@field nvim_clear_autocmds fun(opts: {group?: string|integer, event?: string|string[], pattern?: string|string[], buffer?: number}):nil\n---@field nvim_get_current_buf fun():integer\n---@field nvim_get_mode fun():{mode: string, blocking: boolean}\n---@field nvim_win_get_cursor fun(window: integer):integer[] Returns [row, col] (1-based for row, 0-based for col)\n---@field nvim_buf_get_name fun(buffer: integer):string\n---@field nvim_buf_get_lines fun(buffer: integer, start: integer, end_line: integer, strict_indexing: boolean):string[]\n-- Add other nvim_api functions as needed\n---@field cmd fun(command: string):nil For vim.cmd() -- Added based on test mocks\n---@field api vim_api_table For vim.api.*\n---@field fn vim_fn_table For vim.fn.*\n---@field fs vim_fs_module For vim.fs.*\n---@field filetype vim_filetype_module For vim.filetype.*\n---@field test vim_test_utils? For test utility mocks\n---@field split fun(str: string, pat?: string, opts?: {plain?: boolean, trimempty?: boolean}):string[] For vim.split()\n-- Add other vim object definitions here if they cause linting issues\n-- e.g. vim.api, vim.loop, vim.deepcopy, etc.\n\n---@class SpyCall\n---@field vals table[] table of arguments passed to the call\n---@field self any the 'self' object for the call if it was a method\n\n---@class SpyInformation\n---@field calls SpyCall[] A list of calls made to the spy.\n---@field call_count number The number of times the spy has been called.\n-- Add other spy properties if needed e.g. returned, threw\n\n---@class SpyAsserts\n---@field was_called fun(self: SpyAsserts, count?: number):boolean\n---@field was_called_with fun(self: SpyAsserts, ...):boolean\n---@field was_not_called fun(self: SpyAsserts):boolean\n-- Add other spy asserts if needed\n\n---@class SpyableFunction : function\n---@field __call fun(self: SpyableFunction, ...):any\n---@field spy fun(self: SpyableFunction):SpyAsserts Returns an assertion object for the spy.\n---@field calls SpyInformation[]? Information about calls made to the spied function.\n-- Note: In some spy libraries, 'calls' might be directly on the spied function,\n-- or on an object returned by `spy()`. Adjust as per your spy library's specifics.\n-- For busted's default spy, `calls` is often directly on the spied function.\n\n---@class vim_test_utils\n---@field add_buffer fun(bufnr: number, filename: string, content: string|string[]):nil\n---@field set_cursor fun(bufnr: number, row: number, col: number):nil\n-- Add other test utility functions as needed\n\n-- This section helps LuaLS understand that 'vim' is a global variable\n-- with the structure defined above. It's for type hinting only and\n-- does not execute or overwrite the actual 'vim' global provided by Neovim.\n---@type vim_global_api\n"], ["/claudecode.nvim/lua/claudecode/integrations.lua", "---\n-- Tree integration module for ClaudeCode.nvim\n-- Handles detection and selection of files from nvim-tree, neo-tree, and oil.nvim\n-- @module claudecode.integrations\nlocal M = {}\n\n--- Get selected files from the current tree explorer\n--- @return table|nil files List of file paths, or nil if error\n--- @return string|nil error Error message if operation failed\nfunction M.get_selected_files_from_tree()\n local current_ft = vim.bo.filetype\n\n if current_ft == \"NvimTree\" then\n return M._get_nvim_tree_selection()\n elseif current_ft == \"neo-tree\" then\n return M._get_neotree_selection()\n elseif current_ft == \"oil\" then\n return M._get_oil_selection()\n else\n return nil, \"Not in a supported tree buffer (current filetype: \" .. current_ft .. \")\"\n end\nend\n\n--- Get selected files from nvim-tree\n--- Supports both multi-selection (marks) and single file under cursor\n--- @return table files List of file paths\n--- @return string|nil error Error message if operation failed\nfunction M._get_nvim_tree_selection()\n local success, nvim_tree_api = pcall(require, \"nvim-tree.api\")\n if not success then\n return {}, \"nvim-tree not available\"\n end\n\n local files = {}\n\n local marks = nvim_tree_api.marks.list()\n\n if marks and #marks > 0 then\n for i, mark in ipairs(marks) do\n if mark.type == \"file\" and mark.absolute_path and mark.absolute_path ~= \"\" then\n -- Check if it's not a root-level file (basic protection)\n if not string.match(mark.absolute_path, \"^/[^/]*$\") then\n table.insert(files, mark.absolute_path)\n end\n end\n end\n\n if #files > 0 then\n return files, nil\n end\n end\n\n local node = nvim_tree_api.tree.get_node_under_cursor()\n if node then\n if node.type == \"file\" and node.absolute_path and node.absolute_path ~= \"\" then\n -- Check if it's not a root-level file (basic protection)\n if not string.match(node.absolute_path, \"^/[^/]*$\") then\n return { node.absolute_path }, nil\n else\n return {}, \"Cannot add root-level file. Please select a file in a subdirectory.\"\n end\n elseif node.type == \"directory\" and node.absolute_path and node.absolute_path ~= \"\" then\n return { node.absolute_path }, nil\n end\n end\n\n return {}, \"No file found under cursor\"\nend\n\n--- Get selected files from neo-tree\n--- Uses neo-tree's own visual selection method when in visual mode\n--- @return table files List of file paths\n--- @return string|nil error Error message if operation failed\nfunction M._get_neotree_selection()\n local success, manager = pcall(require, \"neo-tree.sources.manager\")\n if not success then\n return {}, \"neo-tree not available\"\n end\n\n local state = manager.get_state(\"filesystem\")\n if not state then\n return {}, \"neo-tree filesystem state not available\"\n end\n\n local files = {}\n\n -- Use neo-tree's own visual selection method (like their copy/paste feature)\n local mode = vim.fn.mode()\n\n if mode == \"V\" or mode == \"v\" or mode == \"\\22\" then\n local current_win = vim.api.nvim_get_current_win()\n\n if state.winid and state.winid == current_win then\n -- Use neo-tree's exact method to get visual range (from their get_selected_nodes implementation)\n local start_pos = vim.fn.getpos(\"'<\")[2]\n local end_pos = vim.fn.getpos(\"'>\")[2]\n\n -- Fallback to current cursor and anchor if marks are not valid\n if start_pos == 0 or end_pos == 0 then\n local cursor_pos = vim.api.nvim_win_get_cursor(0)[1]\n local anchor_pos = vim.fn.getpos(\"v\")[2]\n if anchor_pos > 0 then\n start_pos = math.min(cursor_pos, anchor_pos)\n end_pos = math.max(cursor_pos, anchor_pos)\n else\n start_pos = cursor_pos\n end_pos = cursor_pos\n end\n end\n\n if end_pos < start_pos then\n start_pos, end_pos = end_pos, start_pos\n end\n\n local selected_nodes = {}\n\n for line = start_pos, end_pos do\n local node = state.tree:get_node(line)\n if node then\n -- Add validation for node types before adding to selection\n if node.type and node.type ~= \"message\" then\n table.insert(selected_nodes, node)\n end\n end\n end\n\n for i, node in ipairs(selected_nodes) do\n -- Enhanced validation: check for file type and valid path\n if node.type == \"file\" and node.path and node.path ~= \"\" then\n -- Additional check: ensure it's not a root node (depth protection)\n local depth = (node.get_depth and node:get_depth()) and node:get_depth() or 0\n if depth > 1 then\n table.insert(files, node.path)\n end\n end\n end\n\n if #files > 0 then\n return files, nil\n end\n end\n end\n\n if state.tree then\n local selection = nil\n\n if state.tree.get_selection then\n selection = state.tree:get_selection()\n end\n\n if (not selection or #selection == 0) and state.selected_nodes then\n selection = state.selected_nodes\n end\n\n if selection and #selection > 0 then\n for i, node in ipairs(selection) do\n if node.type == \"file\" and node.path then\n table.insert(files, node.path)\n end\n end\n\n if #files > 0 then\n return files, nil\n end\n end\n end\n\n if state.tree then\n local node = state.tree:get_node()\n\n if node then\n if node.type == \"file\" and node.path then\n return { node.path }, nil\n elseif node.type == \"directory\" and node.path then\n return { node.path }, nil\n end\n end\n end\n\n return {}, \"No file found under cursor\"\nend\n\n--- Get selected files from oil.nvim\n--- Supports both visual selection and single file under cursor\n--- @return table files List of file paths\n--- @return string|nil error Error message if operation failed\nfunction M._get_oil_selection()\n local success, oil = pcall(require, \"oil\")\n if not success then\n return {}, \"oil.nvim not available\"\n end\n\n local bufnr = vim.api.nvim_get_current_buf() --[[@as number]]\n local files = {}\n\n -- Check if we're in visual mode\n local mode = vim.fn.mode()\n if mode == \"V\" or mode == \"v\" or mode == \"\\22\" then\n -- Visual mode: use the common visual range function\n local visual_commands = require(\"claudecode.visual_commands\")\n local start_line, end_line = visual_commands.get_visual_range()\n\n -- Get current directory once\n local dir_ok, current_dir = pcall(oil.get_current_dir, bufnr)\n if not dir_ok or not current_dir then\n return {}, \"Failed to get current directory\"\n end\n\n -- Process each line in the visual selection\n for line = start_line, end_line do\n local entry_ok, entry = pcall(oil.get_entry_on_line, bufnr, line)\n if entry_ok and entry and entry.name then\n -- Skip parent directory entries\n if entry.name ~= \"..\" and entry.name ~= \".\" then\n local full_path = current_dir .. entry.name\n -- Handle various entry types\n if entry.type == \"file\" or entry.type == \"link\" then\n table.insert(files, full_path)\n elseif entry.type == \"directory\" then\n -- Ensure directory paths end with /\n table.insert(files, full_path:match(\"/$\") and full_path or full_path .. \"/\")\n else\n -- For unknown types, return the path anyway\n table.insert(files, full_path)\n end\n end\n end\n end\n\n if #files > 0 then\n return files, nil\n end\n else\n -- Normal mode: get file under cursor with error handling\n local ok, entry = pcall(oil.get_cursor_entry)\n if not ok or not entry then\n return {}, \"Failed to get cursor entry\"\n end\n\n local dir_ok, current_dir = pcall(oil.get_current_dir, bufnr)\n if not dir_ok or not current_dir then\n return {}, \"Failed to get current directory\"\n end\n\n -- Process the entry\n if entry.name and entry.name ~= \"..\" and entry.name ~= \".\" then\n local full_path = current_dir .. entry.name\n -- Handle various entry types\n if entry.type == \"file\" or entry.type == \"link\" then\n return { full_path }, nil\n elseif entry.type == \"directory\" then\n -- Ensure directory paths end with /\n return { full_path:match(\"/$\") and full_path or full_path .. \"/\" }, nil\n else\n -- For unknown types, return the path anyway\n return { full_path }, nil\n end\n end\n end\n\n return {}, \"No file found under cursor\"\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/logger.lua", "---@brief Centralized logger for Claude Code Neovim integration.\n-- Provides level-based logging.\nlocal M = {}\n\nM.levels = {\n ERROR = 1,\n WARN = 2,\n INFO = 3,\n DEBUG = 4,\n TRACE = 5,\n}\n\nlocal level_values = {\n error = M.levels.ERROR,\n warn = M.levels.WARN,\n info = M.levels.INFO,\n debug = M.levels.DEBUG,\n trace = M.levels.TRACE,\n}\n\nlocal current_log_level_value = M.levels.INFO\n\n--- @param plugin_config table The configuration table (e.g., from claudecode.init.state.config).\nfunction M.setup(plugin_config)\n local conf = plugin_config\n\n if conf and conf.log_level and level_values[conf.log_level] then\n current_log_level_value = level_values[conf.log_level]\n else\n vim.notify(\n \"ClaudeCode Logger: Invalid or missing log_level in configuration (received: \"\n .. tostring(conf and conf.log_level)\n .. \"). Defaulting to INFO.\",\n vim.log.levels.WARN\n )\n current_log_level_value = M.levels.INFO\n end\nend\n\nlocal function log(level, component, message_parts)\n if level > current_log_level_value then\n return\n end\n\n local prefix = \"[ClaudeCode]\"\n if component then\n prefix = prefix .. \" [\" .. component .. \"]\"\n end\n\n local level_name = \"UNKNOWN\"\n for name, val in pairs(M.levels) do\n if val == level then\n level_name = name\n break\n end\n end\n prefix = prefix .. \" [\" .. level_name .. \"]\"\n\n local message = \"\"\n for i, part in ipairs(message_parts) do\n if i > 1 then\n message = message .. \" \"\n end\n if type(part) == \"table\" or type(part) == \"boolean\" then\n message = message .. vim.inspect(part)\n else\n message = message .. tostring(part)\n end\n end\n\n if level == M.levels.ERROR then\n vim.schedule(function()\n vim.notify(prefix .. \" \" .. message, vim.log.levels.ERROR, { title = \"ClaudeCode Error\" })\n end)\n elseif level == M.levels.WARN then\n vim.schedule(function()\n vim.notify(prefix .. \" \" .. message, vim.log.levels.WARN, { title = \"ClaudeCode Warning\" })\n end)\n else\n -- For INFO, DEBUG, TRACE, use nvim_echo to avoid flooding notifications,\n -- to make them appear in :messages, and wrap in vim.schedule\n -- to avoid \"nvim_echo must not be called in a fast event context\".\n vim.schedule(function()\n vim.api.nvim_echo({ { prefix .. \" \" .. message, \"Normal\" } }, true, {})\n end)\n end\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.error(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.ERROR, nil, { component, ... })\n else\n log(M.levels.ERROR, component, { ... })\n end\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.warn(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.WARN, nil, { component, ... })\n else\n log(M.levels.WARN, component, { ... })\n end\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.info(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.INFO, nil, { component, ... })\n else\n log(M.levels.INFO, component, { ... })\n end\nend\n\n--- Check if a specific log level is enabled\n-- @param level_name string The level name (\"error\", \"warn\", \"info\", \"debug\", \"trace\")\n-- @return boolean Whether the level is enabled\nfunction M.is_level_enabled(level_name)\n local level_value = level_values[level_name]\n if not level_value then\n return false\n end\n return level_value <= current_log_level_value\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.debug(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.DEBUG, nil, { component, ... })\n else\n log(M.levels.DEBUG, component, { ... })\n end\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.trace(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.TRACE, nil, { component, ... })\n else\n log(M.levels.TRACE, component, { ... })\n end\nend\n\nlocal default_config_for_initial_setup = require(\"claudecode.config\").defaults\nM.setup(default_config_for_initial_setup)\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/config.lua", "--- Manages configuration for the Claude Code Neovim integration.\n-- Provides default settings, validation, and application of user-defined configurations.\nlocal M = {}\n\nM.defaults = {\n port_range = { min = 10000, max = 65535 },\n auto_start = true,\n terminal_cmd = nil,\n log_level = \"info\",\n track_selection = true,\n visual_demotion_delay_ms = 50, -- Milliseconds to wait before demoting a visual selection\n connection_wait_delay = 200, -- Milliseconds to wait after connection before sending queued @ mentions\n connection_timeout = 10000, -- Maximum time to wait for Claude Code to connect (milliseconds)\n queue_timeout = 5000, -- Maximum time to keep @ mentions in queue (milliseconds)\n diff_opts = {\n auto_close_on_accept = true,\n show_diff_stats = true,\n vertical_split = true,\n open_in_current_tab = true, -- Use current tab instead of creating new tab\n },\n}\n\n--- Validates the provided configuration table.\n-- @param config table The configuration table to validate.\n-- @return boolean true if the configuration is valid.\n-- @error string if any configuration option is invalid.\nfunction M.validate(config)\n assert(\n type(config.port_range) == \"table\"\n and type(config.port_range.min) == \"number\"\n and type(config.port_range.max) == \"number\"\n and config.port_range.min > 0\n and config.port_range.max <= 65535\n and config.port_range.min <= config.port_range.max,\n \"Invalid port range\"\n )\n\n assert(type(config.auto_start) == \"boolean\", \"auto_start must be a boolean\")\n\n assert(config.terminal_cmd == nil or type(config.terminal_cmd) == \"string\", \"terminal_cmd must be nil or a string\")\n\n local valid_log_levels = { \"trace\", \"debug\", \"info\", \"warn\", \"error\" }\n local is_valid_log_level = false\n for _, level in ipairs(valid_log_levels) do\n if config.log_level == level then\n is_valid_log_level = true\n break\n end\n end\n assert(is_valid_log_level, \"log_level must be one of: \" .. table.concat(valid_log_levels, \", \"))\n\n assert(type(config.track_selection) == \"boolean\", \"track_selection must be a boolean\")\n\n assert(\n type(config.visual_demotion_delay_ms) == \"number\" and config.visual_demotion_delay_ms >= 0,\n \"visual_demotion_delay_ms must be a non-negative number\"\n )\n\n assert(\n type(config.connection_wait_delay) == \"number\" and config.connection_wait_delay >= 0,\n \"connection_wait_delay must be a non-negative number\"\n )\n\n assert(\n type(config.connection_timeout) == \"number\" and config.connection_timeout > 0,\n \"connection_timeout must be a positive number\"\n )\n\n assert(type(config.queue_timeout) == \"number\" and config.queue_timeout > 0, \"queue_timeout must be a positive number\")\n\n assert(type(config.diff_opts) == \"table\", \"diff_opts must be a table\")\n assert(type(config.diff_opts.auto_close_on_accept) == \"boolean\", \"diff_opts.auto_close_on_accept must be a boolean\")\n assert(type(config.diff_opts.show_diff_stats) == \"boolean\", \"diff_opts.show_diff_stats must be a boolean\")\n assert(type(config.diff_opts.vertical_split) == \"boolean\", \"diff_opts.vertical_split must be a boolean\")\n assert(type(config.diff_opts.open_in_current_tab) == \"boolean\", \"diff_opts.open_in_current_tab must be a boolean\")\n\n return true\nend\n\n--- Applies user configuration on top of default settings and validates the result.\n-- @param user_config table|nil The user-provided configuration table.\n-- @return table The final, validated configuration table.\nfunction M.apply(user_config)\n local config = vim.deepcopy(M.defaults)\n\n if user_config then\n config = vim.tbl_deep_extend(\"force\", config, user_config)\n end\n\n M.validate(config)\n\n return config\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/lockfile.lua", "---@brief [[\n--- Lock file management for Claude Code Neovim integration.\n--- This module handles creation, removal and updating of lock files\n--- which allow Claude Code CLI to discover the Neovim integration.\n---@brief ]]\n\nlocal M = {}\n\n--- Path to the lock file directory\n---@return string lock_dir The path to the lock file directory\nlocal function get_lock_dir()\n local claude_config_dir = os.getenv(\"CLAUDE_CONFIG_DIR\")\n if claude_config_dir and claude_config_dir ~= \"\" then\n return vim.fn.expand(claude_config_dir .. \"/ide\")\n else\n return vim.fn.expand(\"~/.claude/ide\")\n end\nend\n\nM.lock_dir = get_lock_dir()\n\n-- Track if random seed has been initialized\nlocal random_initialized = false\n\n--- Generate a random UUID for authentication\n---@return string uuid A randomly generated UUID string\nlocal function generate_auth_token()\n -- Initialize random seed only once\n if not random_initialized then\n local seed = os.time() + vim.fn.getpid()\n -- Add more entropy if available\n if vim.loop and vim.loop.hrtime then\n seed = seed + (vim.loop.hrtime() % 1000000)\n end\n math.randomseed(seed)\n\n -- Call math.random a few times to \"warm up\" the generator\n for _ = 1, 10 do\n math.random()\n end\n random_initialized = true\n end\n\n -- Generate UUID v4 format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n local template = \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\"\n local uuid = template:gsub(\"[xy]\", function(c)\n local v = (c == \"x\") and math.random(0, 15) or math.random(8, 11)\n return string.format(\"%x\", v)\n end)\n\n -- Validate generated UUID format\n if not uuid:match(\"^[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+$\") then\n error(\"Generated invalid UUID format: \" .. uuid)\n end\n\n if #uuid ~= 36 then\n error(\"Generated UUID has invalid length: \" .. #uuid .. \" (expected 36)\")\n end\n\n return uuid\nend\n\n--- Generate a new authentication token\n---@return string auth_token A newly generated authentication token\nfunction M.generate_auth_token()\n return generate_auth_token()\nend\n\n--- Create the lock file for a specified WebSocket port\n---@param port number The port number for the WebSocket server\n---@param auth_token string|nil Optional pre-generated auth token (generates new one if not provided)\n---@return boolean success Whether the operation was successful\n---@return string result_or_error The lock file path if successful, or error message if failed\n---@return string? auth_token The authentication token if successful\nfunction M.create(port, auth_token)\n if not port or type(port) ~= \"number\" then\n return false, \"Invalid port number\"\n end\n\n if port < 1 or port > 65535 then\n return false, \"Port number out of valid range (1-65535): \" .. tostring(port)\n end\n\n local ok, err = pcall(function()\n return vim.fn.mkdir(M.lock_dir, \"p\")\n end)\n\n if not ok then\n return false, \"Failed to create lock directory: \" .. (err or \"unknown error\")\n end\n\n local lock_path = M.lock_dir .. \"/\" .. port .. \".lock\"\n\n local workspace_folders = M.get_workspace_folders()\n if not auth_token then\n local auth_success, auth_result = pcall(generate_auth_token)\n if not auth_success then\n return false, \"Failed to generate authentication token: \" .. (auth_result or \"unknown error\")\n end\n auth_token = auth_result\n else\n -- Validate provided auth_token\n if type(auth_token) ~= \"string\" then\n return false, \"Authentication token must be a string, got \" .. type(auth_token)\n end\n if #auth_token < 10 then\n return false, \"Authentication token too short (minimum 10 characters)\"\n end\n if #auth_token > 500 then\n return false, \"Authentication token too long (maximum 500 characters)\"\n end\n end\n\n -- Prepare lock file content\n local lock_content = {\n pid = vim.fn.getpid(),\n workspaceFolders = workspace_folders,\n ideName = \"Neovim\",\n transport = \"ws\",\n authToken = auth_token,\n }\n\n local json\n local ok_json, json_err = pcall(function()\n json = vim.json.encode(lock_content)\n return json\n end)\n\n if not ok_json or not json then\n return false, \"Failed to encode lock file content: \" .. (json_err or \"unknown error\")\n end\n\n local file = io.open(lock_path, \"w\")\n if not file then\n return false, \"Failed to create lock file: \" .. lock_path\n end\n\n local write_ok, write_err = pcall(function()\n file:write(json)\n file:close()\n end)\n\n if not write_ok then\n pcall(function()\n file:close()\n end)\n return false, \"Failed to write lock file: \" .. (write_err or \"unknown error\")\n end\n\n return true, lock_path, auth_token\nend\n\n--- Remove the lock file for the given port\n---@param port number The port number of the WebSocket server\n---@return boolean success Whether the operation was successful\n---@return string? error Error message if operation failed\nfunction M.remove(port)\n if not port or type(port) ~= \"number\" then\n return false, \"Invalid port number\"\n end\n\n local lock_path = M.lock_dir .. \"/\" .. port .. \".lock\"\n\n if vim.fn.filereadable(lock_path) == 0 then\n return false, \"Lock file does not exist: \" .. lock_path\n end\n\n local ok, err = pcall(function()\n return os.remove(lock_path)\n end)\n\n if not ok then\n return false, \"Failed to remove lock file: \" .. (err or \"unknown error\")\n end\n\n return true\nend\n\n--- Update the lock file for the given port\n---@param port number The port number of the WebSocket server\n---@return boolean success Whether the operation was successful\n---@return string result_or_error The lock file path if successful, or error message if failed\n---@return string? auth_token The authentication token if successful\nfunction M.update(port)\n if not port or type(port) ~= \"number\" then\n return false, \"Invalid port number\"\n end\n\n local exists = vim.fn.filereadable(M.lock_dir .. \"/\" .. port .. \".lock\") == 1\n if exists then\n local remove_ok, remove_err = M.remove(port)\n if not remove_ok then\n return false, \"Failed to update lock file: \" .. remove_err\n end\n end\n\n return M.create(port)\nend\n\n--- Read the authentication token from a lock file\n---@param port number The port number of the WebSocket server\n---@return boolean success Whether the operation was successful\n---@return string? auth_token The authentication token if successful, or nil if failed\n---@return string? error Error message if operation failed\nfunction M.get_auth_token(port)\n if not port or type(port) ~= \"number\" then\n return false, nil, \"Invalid port number\"\n end\n\n local lock_path = M.lock_dir .. \"/\" .. port .. \".lock\"\n\n if vim.fn.filereadable(lock_path) == 0 then\n return false, nil, \"Lock file does not exist: \" .. lock_path\n end\n\n local file = io.open(lock_path, \"r\")\n if not file then\n return false, nil, \"Failed to open lock file: \" .. lock_path\n end\n\n local content = file:read(\"*all\")\n file:close()\n\n if not content or content == \"\" then\n return false, nil, \"Lock file is empty: \" .. lock_path\n end\n\n local ok, lock_data = pcall(vim.json.decode, content)\n if not ok or type(lock_data) ~= \"table\" then\n return false, nil, \"Failed to parse lock file JSON: \" .. lock_path\n end\n\n local auth_token = lock_data.authToken\n if not auth_token or type(auth_token) ~= \"string\" then\n return false, nil, \"No valid auth token found in lock file\"\n end\n\n return true, auth_token, nil\nend\n\n--- Get active LSP clients using available API\n---@return table Array of LSP clients\nlocal function get_lsp_clients()\n if vim.lsp then\n if vim.lsp.get_clients then\n -- Neovim >= 0.11\n return vim.lsp.get_clients()\n elseif vim.lsp.get_active_clients then\n -- Neovim 0.8-0.10\n return vim.lsp.get_active_clients()\n end\n end\n return {}\nend\n\n--- Get workspace folders for the lock file\n---@return table Array of workspace folder paths\nfunction M.get_workspace_folders()\n local folders = {}\n\n -- Add current working directory\n table.insert(folders, vim.fn.getcwd())\n\n -- Get LSP workspace folders if available\n local clients = get_lsp_clients()\n for _, client in pairs(clients) do\n if client.config and client.config.workspace_folders then\n for _, ws in ipairs(client.config.workspace_folders) do\n -- Convert URI to path\n local path = ws.uri\n if path:sub(1, 7) == \"file://\" then\n path = path:sub(8)\n end\n\n -- Check if already in the list\n local exists = false\n for _, folder in ipairs(folders) do\n if folder == path then\n exists = true\n break\n end\n end\n\n if not exists then\n table.insert(folders, path)\n end\n end\n end\n end\n\n return folders\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/init.lua", "---@brief WebSocket server for Claude Code Neovim integration\nlocal claudecode_main = require(\"claudecode\") -- Added for version access\nlocal logger = require(\"claudecode.logger\")\nlocal tcp_server = require(\"claudecode.server.tcp\")\nlocal tools = require(\"claudecode.tools.init\") -- Added: Require the tools module\n\nlocal MCP_PROTOCOL_VERSION = \"2024-11-05\"\n\nlocal M = {}\n\n---@class ServerState\n---@field server table|nil The TCP server instance\n---@field port number|nil The port server is running on\n---@field auth_token string|nil The authentication token for validating connections\n---@field clients table A list of connected clients\n---@field handlers table Message handlers by method name\n---@field ping_timer table|nil Timer for sending pings\nM.state = {\n server = nil,\n port = nil,\n auth_token = nil,\n clients = {},\n handlers = {},\n ping_timer = nil,\n}\n\n---@brief Initialize the WebSocket server\n---@param config table Configuration options\n---@param auth_token string|nil The authentication token for validating connections\n---@return boolean success Whether server started successfully\n---@return number|string port_or_error Port number or error message\nfunction M.start(config, auth_token)\n if M.state.server then\n return false, \"Server already running\"\n end\n\n M.state.auth_token = auth_token\n\n -- Log authentication state\n if auth_token then\n logger.debug(\"server\", \"Starting WebSocket server with authentication enabled\")\n logger.debug(\"server\", \"Auth token length:\", #auth_token)\n else\n logger.debug(\"server\", \"Starting WebSocket server WITHOUT authentication (insecure)\")\n end\n\n M.register_handlers()\n\n tools.setup(M)\n\n local callbacks = {\n on_message = function(client, message)\n M._handle_message(client, message)\n end,\n on_connect = function(client)\n M.state.clients[client.id] = client\n\n -- Log connection with auth status\n if M.state.auth_token then\n logger.debug(\"server\", \"Authenticated WebSocket client connected:\", client.id)\n else\n logger.debug(\"server\", \"WebSocket client connected (no auth):\", client.id)\n end\n\n -- Notify main module about new connection for queue processing\n local main_module = require(\"claudecode\")\n if main_module._process_queued_mentions then\n vim.schedule(function()\n main_module._process_queued_mentions()\n end)\n end\n end,\n on_disconnect = function(client, code, reason)\n M.state.clients[client.id] = nil\n logger.debug(\n \"server\",\n \"WebSocket client disconnected:\",\n client.id,\n \"(code:\",\n code,\n \", reason:\",\n (reason or \"N/A\") .. \")\"\n )\n end,\n on_error = function(error_msg)\n logger.error(\"server\", \"WebSocket server error:\", error_msg)\n end,\n }\n\n local server, error_msg = tcp_server.create_server(config, callbacks, M.state.auth_token)\n if not server then\n return false, error_msg or \"Unknown server creation error\"\n end\n\n M.state.server = server\n M.state.port = server.port\n\n M.state.ping_timer = tcp_server.start_ping_timer(server, 30000) -- Start ping timer to keep connections alive\n\n return true, server.port\nend\n\n---@brief Stop the WebSocket server\n---@return boolean success Whether server stopped successfully\n---@return string|nil error_message Error message if any\nfunction M.stop()\n if not M.state.server then\n return false, \"Server not running\"\n end\n\n if M.state.ping_timer then\n M.state.ping_timer:stop()\n M.state.ping_timer:close()\n M.state.ping_timer = nil\n end\n\n tcp_server.stop_server(M.state.server)\n\n -- CRITICAL: Clear global deferred responses to prevent memory leaks and hanging\n if _G.claude_deferred_responses then\n _G.claude_deferred_responses = {}\n end\n\n M.state.server = nil\n M.state.port = nil\n M.state.auth_token = nil\n M.state.clients = {}\n\n return true\nend\n\n---@brief Handle incoming WebSocket message\n---@param client table The client that sent the message\n---@param message string The JSON-RPC message\nfunction M._handle_message(client, message)\n local success, parsed = pcall(vim.json.decode, message)\n if not success then\n M.send_response(client, nil, nil, {\n code = -32700,\n message = \"Parse error\",\n data = \"Invalid JSON\",\n })\n return\n end\n\n if type(parsed) ~= \"table\" or parsed.jsonrpc ~= \"2.0\" then\n M.send_response(client, parsed.id, nil, {\n code = -32600,\n message = \"Invalid Request\",\n data = \"Not a valid JSON-RPC 2.0 request\",\n })\n return\n end\n\n if parsed.id then\n M._handle_request(client, parsed)\n else\n M._handle_notification(client, parsed)\n end\nend\n\n---@brief Handle JSON-RPC request (requires response)\n---@param client table The client that sent the request\n---@param request table The parsed JSON-RPC request\nfunction M._handle_request(client, request)\n local method = request.method\n local params = request.params or {}\n local id = request.id\n\n local handler = M.state.handlers[method]\n if not handler then\n M.send_response(client, id, nil, {\n code = -32601,\n message = \"Method not found\",\n data = \"Unknown method: \" .. tostring(method),\n })\n return\n end\n\n local success, result, error_data = pcall(handler, client, params)\n if success then\n -- Check if this is a deferred response (blocking tool)\n if result and result._deferred then\n logger.debug(\"server\", \"Handler returned deferred response - storing for later\")\n -- Store the request info for later response\n local deferred_info = {\n client = result.client,\n id = id,\n coroutine = result.coroutine,\n method = method,\n params = result.params,\n }\n -- Set up the completion callback\n M._setup_deferred_response(deferred_info)\n return -- Don't send response now\n end\n\n if error_data then\n M.send_response(client, id, nil, error_data)\n else\n M.send_response(client, id, result, nil)\n end\n else\n M.send_response(client, id, nil, {\n code = -32603,\n message = \"Internal error\",\n data = tostring(result), -- result contains error message when pcall fails\n })\n end\nend\n\n---@brief Set up deferred response handling for blocking tools\n---@param deferred_info table Information about the deferred request\n-- Note: deferred_responses table removed - using global _G.claude_deferred_responses instead\n\n-- Add a unique module ID to detect reloading\nlocal module_instance_id = math.random(10000, 99999)\nlogger.debug(\"server\", \"Server module loaded with instance ID:\", module_instance_id)\n\n-- Note: debug_deferred_table function removed as deferred_responses table is no longer used\n\nfunction M._setup_deferred_response(deferred_info)\n local co = deferred_info.coroutine\n\n logger.debug(\"server\", \"Setting up deferred response for coroutine:\", tostring(co))\n logger.debug(\"server\", \"Storage happening in module instance:\", module_instance_id)\n\n -- Create a response sender function that captures the current server instance\n local response_sender = function(result)\n logger.debug(\"server\", \"Deferred response triggered for coroutine:\", tostring(co))\n\n if result and result.content then\n -- MCP-compliant response\n M.send_response(deferred_info.client, deferred_info.id, result, nil)\n elseif result and result.error then\n -- Error response\n M.send_response(deferred_info.client, deferred_info.id, nil, result.error)\n else\n -- Fallback error\n M.send_response(deferred_info.client, deferred_info.id, nil, {\n code = -32603,\n message = \"Internal error\",\n data = \"Deferred response completed with unexpected format\",\n })\n end\n end\n\n -- Store the response sender in a global location that won't be affected by module reloading\n if not _G.claude_deferred_responses then\n _G.claude_deferred_responses = {}\n end\n _G.claude_deferred_responses[tostring(co)] = response_sender\n\n logger.debug(\"server\", \"Stored response sender in global table for coroutine:\", tostring(co))\nend\n\n-- Note: _send_deferred_response is no longer needed\n-- Responses are now handled via the global _G.claude_deferred_responses table\n-- to avoid module reloading issues\n\n---@brief Handle JSON-RPC notification (no response)\n---@param client table The client that sent the notification\n---@param notification table The parsed JSON-RPC notification\nfunction M._handle_notification(client, notification)\n local method = notification.method\n local params = notification.params or {}\n\n local handler = M.state.handlers[method]\n if handler then\n pcall(handler, client, params)\n end\nend\n\n---@brief Register message handlers for the server\nfunction M.register_handlers()\n M.state.handlers = {\n [\"initialize\"] = function(client, params) -- Renamed from mcp.connect\n return {\n protocolVersion = MCP_PROTOCOL_VERSION,\n capabilities = {\n logging = vim.empty_dict(), -- Ensure this is an object {} not an array []\n prompts = { listChanged = true },\n resources = { subscribe = true, listChanged = true },\n tools = { listChanged = true },\n },\n serverInfo = {\n name = \"claudecode-neovim\",\n version = claudecode_main.version:string(),\n },\n }\n end,\n\n [\"notifications/initialized\"] = function(client, params) -- Added handler for initialized notification\n end,\n\n [\"prompts/list\"] = function(client, params) -- Added handler for prompts/list\n return {\n prompts = {}, -- This will be encoded as an empty JSON array\n }\n end,\n\n [\"tools/list\"] = function(_client, _params)\n return {\n tools = tools.get_tool_list(),\n }\n end,\n\n [\"tools/call\"] = function(client, params)\n logger.debug(\n \"server\",\n \"Received tools/call. Tool: \",\n params and params.name,\n \" Arguments: \",\n vim.inspect(params and params.arguments)\n )\n local result_or_error_table = tools.handle_invoke(client, params)\n\n -- Check if this is a deferred response (blocking tool)\n if result_or_error_table and result_or_error_table._deferred then\n logger.debug(\"server\", \"Tool is blocking - setting up deferred response\")\n -- Return the deferred response directly - _handle_request will process it\n return result_or_error_table\n end\n\n -- Log the response for debugging\n logger.debug(\"server\", \"Response - tools/call\", params and params.name .. \":\", vim.inspect(result_or_error_table))\n\n if result_or_error_table.error then\n return nil, result_or_error_table.error\n elseif result_or_error_table.result then\n return result_or_error_table.result, nil\n else\n -- Should not happen if tools.handle_invoke behaves correctly\n return nil,\n {\n code = -32603,\n message = \"Internal error\",\n data = \"Tool handler returned unexpected format\",\n }\n end\n end,\n }\nend\n\n---@brief Send a message to a client\n---@param client table The client to send to\n---@param method string The method name\n---@param params table|nil The parameters to send\n---@return boolean success Whether message was sent successfully\nfunction M.send(client, method, params)\n if not M.state.server then\n return false\n end\n\n local message = {\n jsonrpc = \"2.0\",\n method = method,\n params = params or vim.empty_dict(),\n }\n\n local json_message = vim.json.encode(message)\n tcp_server.send_to_client(M.state.server, client.id, json_message)\n return true\nend\n\n---@brief Send a response to a client\n---@param client table The client to send to\n---@param id number|string|nil The request ID to respond to\n---@param result any|nil The result data if successful\n---@param error_data table|nil The error data if failed\n---@return boolean success Whether response was sent successfully\nfunction M.send_response(client, id, result, error_data)\n if not M.state.server then\n return false\n end\n\n local response = {\n jsonrpc = \"2.0\",\n id = id,\n }\n\n if error_data then\n response.error = error_data\n else\n response.result = result\n end\n\n local json_response = vim.json.encode(response)\n tcp_server.send_to_client(M.state.server, client.id, json_response)\n return true\nend\n\n---@brief Broadcast a message to all connected clients\n---@param method string The method name\n---@param params table|nil The parameters to send\n---@return boolean success Whether broadcast was successful\nfunction M.broadcast(method, params)\n if not M.state.server then\n return false\n end\n\n local message = {\n jsonrpc = \"2.0\",\n method = method,\n params = params or vim.empty_dict(),\n }\n\n local json_message = vim.json.encode(message)\n tcp_server.broadcast(M.state.server, json_message)\n return true\nend\n\n---@brief Get server status information\n---@return table status Server status information\nfunction M.get_status()\n if not M.state.server then\n return {\n running = false,\n port = nil,\n client_count = 0,\n }\n end\n\n return {\n running = true,\n port = M.state.port,\n client_count = tcp_server.get_client_count(M.state.server),\n clients = tcp_server.get_clients_info(M.state.server),\n }\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/client.lua", "---@brief WebSocket client connection management\nlocal frame = require(\"claudecode.server.frame\")\nlocal handshake = require(\"claudecode.server.handshake\")\nlocal logger = require(\"claudecode.logger\")\n\nlocal M = {}\n\n---@class WebSocketClient\n---@field id string Unique client identifier\n---@field tcp_handle table The vim.loop TCP handle\n---@field state string Connection state: \"connecting\", \"connected\", \"closing\", \"closed\"\n---@field buffer string Incoming data buffer\n---@field handshake_complete boolean Whether WebSocket handshake is complete\n---@field last_ping number Timestamp of last ping sent\n---@field last_pong number Timestamp of last pong received\n\n---@brief Create a new WebSocket client\n---@param tcp_handle table The vim.loop TCP handle\n---@return WebSocketClient client The client object\nfunction M.create_client(tcp_handle)\n local client_id = tostring(tcp_handle):gsub(\"userdata: \", \"client_\")\n\n local client = {\n id = client_id,\n tcp_handle = tcp_handle,\n state = \"connecting\",\n buffer = \"\",\n handshake_complete = false,\n last_ping = 0,\n last_pong = vim.loop.now(),\n }\n\n return client\nend\n\n---@brief Process incoming data for a client\n---@param client WebSocketClient The client object\n---@param data string The incoming data\n---@param on_message function Callback for complete messages: function(client, message_text)\n---@param on_close function Callback for client close: function(client, code, reason)\n---@param on_error function Callback for errors: function(client, error_msg)\n---@param auth_token string|nil Expected authentication token for validation\nfunction M.process_data(client, data, on_message, on_close, on_error, auth_token)\n client.buffer = client.buffer .. data\n\n if not client.handshake_complete then\n local complete, request, remaining = handshake.extract_http_request(client.buffer)\n if complete then\n logger.debug(\"client\", \"Processing WebSocket handshake for client:\", client.id)\n\n -- Log if auth token is required\n if auth_token then\n logger.debug(\"client\", \"Authentication required for client:\", client.id)\n else\n logger.debug(\"client\", \"No authentication required for client:\", client.id)\n end\n\n local success, response_from_handshake, _ = handshake.process_handshake(request, auth_token)\n\n -- Log authentication results\n if success then\n if auth_token then\n logger.debug(\"client\", \"Client authenticated successfully:\", client.id)\n else\n logger.debug(\"client\", \"Client handshake completed (no auth required):\", client.id)\n end\n else\n -- Log specific authentication failure details\n if auth_token and response_from_handshake:find(\"auth\") then\n logger.warn(\n \"client\",\n \"Authentication failed for client \"\n .. client.id\n .. \": \"\n .. (response_from_handshake:match(\"Bad WebSocket upgrade request: (.+)\") or \"unknown auth error\")\n )\n else\n logger.warn(\n \"client\",\n \"WebSocket handshake failed for client \"\n .. client.id\n .. \": \"\n .. (response_from_handshake:match(\"HTTP/1.1 %d+ (.+)\") or \"unknown handshake error\")\n )\n end\n end\n\n client.tcp_handle:write(response_from_handshake, function(err)\n if err then\n logger.error(\"client\", \"Failed to send handshake response to client \" .. client.id .. \": \" .. err)\n on_error(client, \"Failed to send handshake response: \" .. err)\n return\n end\n\n if success then\n client.handshake_complete = true\n client.state = \"connected\"\n client.buffer = remaining\n logger.debug(\"client\", \"WebSocket connection established for client:\", client.id)\n\n if #client.buffer > 0 then\n M.process_data(client, \"\", on_message, on_close, on_error, auth_token)\n end\n else\n client.state = \"closing\"\n logger.debug(\"client\", \"Closing connection for client due to failed handshake:\", client.id)\n vim.schedule(function()\n client.tcp_handle:close()\n end)\n end\n end)\n end\n return\n end\n\n while #client.buffer >= 2 do -- Minimum frame size\n local parsed_frame, bytes_consumed = frame.parse_frame(client.buffer)\n\n if not parsed_frame then\n break\n end\n\n -- Frame validation is now handled entirely within frame.parse_frame.\n -- If frame.parse_frame returns a frame, it's considered valid.\n\n client.buffer = client.buffer:sub(bytes_consumed + 1)\n\n if parsed_frame.opcode == frame.OPCODE.TEXT then\n vim.schedule(function()\n on_message(client, parsed_frame.payload)\n end)\n elseif parsed_frame.opcode == frame.OPCODE.BINARY then\n -- Binary message (treat as text for JSON-RPC)\n vim.schedule(function()\n on_message(client, parsed_frame.payload)\n end)\n elseif parsed_frame.opcode == frame.OPCODE.CLOSE then\n local code = 1000\n local reason = \"\"\n\n if #parsed_frame.payload >= 2 then\n local payload = parsed_frame.payload\n code = payload:byte(1) * 256 + payload:byte(2)\n if #payload > 2 then\n reason = payload:sub(3)\n end\n end\n\n if client.state == \"connected\" then\n local close_frame = frame.create_close_frame(code, reason)\n client.tcp_handle:write(close_frame)\n client.state = \"closing\"\n end\n\n vim.schedule(function()\n on_close(client, code, reason)\n end)\n elseif parsed_frame.opcode == frame.OPCODE.PING then\n local pong_frame = frame.create_pong_frame(parsed_frame.payload)\n client.tcp_handle:write(pong_frame)\n elseif parsed_frame.opcode == frame.OPCODE.PONG then\n client.last_pong = vim.loop.now()\n elseif parsed_frame.opcode == frame.OPCODE.CONTINUATION then\n -- Continuation frame - for simplicity, we don't support fragmentation\n on_error(client, \"Fragmented messages not supported\")\n M.close_client(client, 1003, \"Unsupported data\")\n else\n on_error(client, \"Unknown WebSocket opcode: \" .. parsed_frame.opcode)\n M.close_client(client, 1002, \"Protocol error\")\n end\n end\nend\n\n---@brief Send a text message to a client\n---@param client WebSocketClient The client object\n---@param message string The message to send\n---@param callback function|nil Optional callback: function(err)\nfunction M.send_message(client, message, callback)\n if client.state ~= \"connected\" then\n if callback then\n callback(\"Client not connected\")\n end\n return\n end\n\n local text_frame = frame.create_text_frame(message)\n client.tcp_handle:write(text_frame, callback)\nend\n\n---@brief Send a ping to a client\n---@param client WebSocketClient The client object\n---@param data string|nil Optional ping data\nfunction M.send_ping(client, data)\n if client.state ~= \"connected\" then\n return\n end\n\n local ping_frame = frame.create_ping_frame(data or \"\")\n client.tcp_handle:write(ping_frame)\n client.last_ping = vim.loop.now()\nend\n\n---@brief Close a client connection\n---@param client WebSocketClient The client object\n---@param code number|nil Close code (default: 1000)\n---@param reason string|nil Close reason\nfunction M.close_client(client, code, reason)\n if client.state == \"closed\" or client.state == \"closing\" then\n return\n end\n\n code = code or 1000\n reason = reason or \"\"\n\n if client.handshake_complete then\n local close_frame = frame.create_close_frame(code, reason)\n client.tcp_handle:write(close_frame, function()\n client.state = \"closed\"\n client.tcp_handle:close()\n end)\n else\n client.state = \"closed\"\n client.tcp_handle:close()\n end\n\n client.state = \"closing\"\nend\n\n---@brief Check if a client connection is alive\n---@param client WebSocketClient The client object\n---@param timeout number Timeout in milliseconds (default: 30000)\n---@return boolean alive True if the client is considered alive\nfunction M.is_client_alive(client, timeout)\n timeout = timeout or 30000 -- 30 seconds default\n\n if client.state ~= \"connected\" then\n return false\n end\n\n local now = vim.loop.now()\n return (now - client.last_pong) < timeout\nend\n\n---@brief Get client info for debugging\n---@param client WebSocketClient The client object\n---@return table info Client information\nfunction M.get_client_info(client)\n return {\n id = client.id,\n state = client.state,\n handshake_complete = client.handshake_complete,\n buffer_size = #client.buffer,\n last_ping = client.last_ping,\n last_pong = client.last_pong,\n }\nend\n\nreturn M\n"], ["/claudecode.nvim/dev-config.lua", "-- Development configuration for claudecode.nvim\n-- This is Thomas's personal config for developing claudecode.nvim\n-- Symlink this to your personal Neovim config:\n-- ln -s ~/projects/claudecode.nvim/dev-config.lua ~/.config/nvim/lua/plugins/dev-claudecode.lua\n\nreturn {\n \"coder/claudecode.nvim\",\n dev = true, -- Use local development version\n keys = {\n -- AI/Claude Code prefix\n { \"a\", nil, desc = \"AI/Claude Code\" },\n\n -- Core Claude commands\n { \"ac\", \"ClaudeCode\", desc = \"Toggle Claude\" },\n { \"af\", \"ClaudeCodeFocus\", desc = \"Focus Claude\" },\n { \"ar\", \"ClaudeCode --resume\", desc = \"Resume Claude\" },\n { \"aC\", \"ClaudeCode --continue\", desc = \"Continue Claude\" },\n\n -- Context sending\n { \"ab\", \"ClaudeCodeAdd %\", desc = \"Add current buffer\" },\n { \"as\", \"ClaudeCodeSend\", mode = \"v\", desc = \"Send to Claude\" },\n {\n \"as\",\n \"ClaudeCodeTreeAdd\",\n desc = \"Add file from tree\",\n ft = { \"NvimTree\", \"neo-tree\", \"oil\" },\n },\n\n -- Development helpers\n { \"ao\", \"ClaudeCodeOpen\", desc = \"Open Claude\" },\n { \"aq\", \"ClaudeCodeClose\", desc = \"Close Claude\" },\n { \"ai\", \"ClaudeCodeStatus\", desc = \"Claude Status\" },\n { \"aS\", \"ClaudeCodeStart\", desc = \"Start Claude Server\" },\n { \"aQ\", \"ClaudeCodeStop\", desc = \"Stop Claude Server\" },\n\n -- Diff management (buffer-local, only active in diff buffers)\n { \"aa\", \"ClaudeCodeDiffAccept\", desc = \"Accept diff\" },\n { \"ad\", \"ClaudeCodeDiffDeny\", desc = \"Deny diff\" },\n },\n\n -- Development configuration - all options shown with defaults commented out\n opts = {\n -- Server Configuration\n -- port_range = { min = 10000, max = 65535 }, -- WebSocket server port range\n -- auto_start = true, -- Auto-start server on Neovim startup\n -- log_level = \"info\", -- \"trace\", \"debug\", \"info\", \"warn\", \"error\"\n -- terminal_cmd = nil, -- Custom terminal command (default: \"claude\")\n\n -- Selection Tracking\n -- track_selection = true, -- Enable real-time selection tracking\n -- visual_demotion_delay_ms = 50, -- Delay before demoting visual selection (ms)\n\n -- Connection Management\n -- connection_wait_delay = 200, -- Wait time after connection before sending queued @ mentions (ms)\n -- connection_timeout = 10000, -- Max time to wait for Claude Code connection (ms)\n -- queue_timeout = 5000, -- Max time to keep @ mentions in queue (ms)\n\n -- Diff Integration\n -- diff_opts = {\n -- auto_close_on_accept = true, -- Close diff view after accepting changes\n -- show_diff_stats = true, -- Show diff statistics\n -- vertical_split = true, -- Use vertical split for diffs\n -- open_in_current_tab = true, -- Open diffs in current tab vs new tab\n -- },\n\n -- Terminal Configuration\n -- terminal = {\n -- split_side = \"right\", -- \"left\" or \"right\"\n -- split_width_percentage = 0.30, -- Width as percentage (0.0 to 1.0)\n -- provider = \"auto\", -- \"auto\", \"snacks\", or \"native\"\n -- show_native_term_exit_tip = true, -- Show exit tip for native terminal\n -- auto_close = true, -- Auto-close terminal after command completion\n -- },\n\n -- Development overrides (uncomment as needed)\n -- log_level = \"debug\",\n -- terminal = {\n -- provider = \"native\",\n -- auto_close = false, -- Keep terminals open to see output\n -- },\n },\n}\n"], ["/claudecode.nvim/lua/claudecode/server/tcp.lua", "---@brief TCP server implementation using vim.loop\nlocal client_manager = require(\"claudecode.server.client\")\nlocal utils = require(\"claudecode.server.utils\")\n\nlocal M = {}\n\n---@class TCPServer\n---@field server table The vim.loop TCP server handle\n---@field port number The port the server is listening on\n---@field auth_token string|nil The authentication token for validating connections\n---@field clients table Table of connected clients (client_id -> WebSocketClient)\n---@field on_message function Callback for WebSocket messages\n---@field on_connect function Callback for new connections\n---@field on_disconnect function Callback for client disconnections\n---@field on_error fun(err_msg: string) Callback for errors\n\n---@brief Find an available port by attempting to bind\n---@param min_port number Minimum port to try\n---@param max_port number Maximum port to try\n---@return number|nil port Available port number, or nil if none found\nfunction M.find_available_port(min_port, max_port)\n if min_port > max_port then\n return nil -- Or handle error appropriately\n end\n\n local ports = {}\n for i = min_port, max_port do\n table.insert(ports, i)\n end\n\n -- Shuffle the ports\n utils.shuffle_array(ports)\n\n -- Try to bind to a port from the shuffled list\n for _, port in ipairs(ports) do\n local test_server = vim.loop.new_tcp()\n local success = test_server:bind(\"127.0.0.1\", port)\n test_server:close()\n\n if success then\n return port\n end\n end\n\n return nil\nend\n\n---@brief Create and start a TCP server\n---@param config table Server configuration\n---@param callbacks table Callback functions\n---@param auth_token string|nil Authentication token for validating connections\n---@return TCPServer|nil server The server object, or nil on error\n---@return string|nil error Error message if failed\nfunction M.create_server(config, callbacks, auth_token)\n local port = M.find_available_port(config.port_range.min, config.port_range.max)\n if not port then\n return nil, \"No available ports in range \" .. config.port_range.min .. \"-\" .. config.port_range.max\n end\n\n local tcp_server = vim.loop.new_tcp()\n if not tcp_server then\n return nil, \"Failed to create TCP server\"\n end\n\n -- Create server object\n local server = {\n server = tcp_server,\n port = port,\n auth_token = auth_token,\n clients = {},\n on_message = callbacks.on_message or function() end,\n on_connect = callbacks.on_connect or function() end,\n on_disconnect = callbacks.on_disconnect or function() end,\n on_error = callbacks.on_error or function() end,\n }\n\n local bind_success, bind_err = tcp_server:bind(\"127.0.0.1\", port)\n if not bind_success then\n tcp_server:close()\n return nil, \"Failed to bind to port \" .. port .. \": \" .. (bind_err or \"unknown error\")\n end\n\n -- Start listening\n local listen_success, listen_err = tcp_server:listen(128, function(err)\n if err then\n callbacks.on_error(\"Listen error: \" .. err)\n return\n end\n\n M._handle_new_connection(server)\n end)\n\n if not listen_success then\n tcp_server:close()\n return nil, \"Failed to listen on port \" .. port .. \": \" .. (listen_err or \"unknown error\")\n end\n\n return server, nil\nend\n\n---@brief Handle a new client connection\n---@param server TCPServer The server object\nfunction M._handle_new_connection(server)\n local client_tcp = vim.loop.new_tcp()\n if not client_tcp then\n server.on_error(\"Failed to create client TCP handle\")\n return\n end\n\n local accept_success, accept_err = server.server:accept(client_tcp)\n if not accept_success then\n server.on_error(\"Failed to accept connection: \" .. (accept_err or \"unknown error\"))\n client_tcp:close()\n return\n end\n\n -- Create WebSocket client wrapper\n local client = client_manager.create_client(client_tcp)\n server.clients[client.id] = client\n\n -- Set up data handler\n client_tcp:read_start(function(err, data)\n if err then\n server.on_error(\"Client read error: \" .. err)\n M._remove_client(server, client)\n return\n end\n\n if not data then\n -- EOF - client disconnected\n M._remove_client(server, client)\n return\n end\n\n -- Process incoming data\n client_manager.process_data(client, data, function(cl, message)\n server.on_message(cl, message)\n end, function(cl, code, reason)\n server.on_disconnect(cl, code, reason)\n M._remove_client(server, cl)\n end, function(cl, error_msg)\n server.on_error(\"Client \" .. cl.id .. \" error: \" .. error_msg)\n M._remove_client(server, cl)\n end, server.auth_token)\n end)\n\n -- Notify about new connection\n server.on_connect(client)\nend\n\n---@brief Remove a client from the server\n---@param server TCPServer The server object\n---@param client WebSocketClient The client to remove\nfunction M._remove_client(server, client)\n if server.clients[client.id] then\n server.clients[client.id] = nil\n\n if not client.tcp_handle:is_closing() then\n client.tcp_handle:close()\n end\n end\nend\n\n---@brief Send a message to a specific client\n---@param server TCPServer The server object\n---@param client_id string The client ID\n---@param message string The message to send\n---@param callback function|nil Optional callback\nfunction M.send_to_client(server, client_id, message, callback)\n local client = server.clients[client_id]\n if not client then\n if callback then\n callback(\"Client not found: \" .. client_id)\n end\n return\n end\n\n client_manager.send_message(client, message, callback)\nend\n\n---@brief Broadcast a message to all connected clients\n---@param server TCPServer The server object\n---@param message string The message to broadcast\nfunction M.broadcast(server, message)\n for _, client in pairs(server.clients) do\n client_manager.send_message(client, message)\n end\nend\n\n---@brief Get the number of connected clients\n---@param server TCPServer The server object\n---@return number count Number of connected clients\nfunction M.get_client_count(server)\n local count = 0\n for _ in pairs(server.clients) do\n count = count + 1\n end\n return count\nend\n\n---@brief Get information about all clients\n---@param server TCPServer The server object\n---@return table clients Array of client information\nfunction M.get_clients_info(server)\n local clients = {}\n for _, client in pairs(server.clients) do\n table.insert(clients, client_manager.get_client_info(client))\n end\n return clients\nend\n\n---@brief Close a specific client connection\n---@param server TCPServer The server object\n---@param client_id string The client ID\n---@param code number|nil Close code\n---@param reason string|nil Close reason\nfunction M.close_client(server, client_id, code, reason)\n local client = server.clients[client_id]\n if client then\n client_manager.close_client(client, code, reason)\n end\nend\n\n---@brief Stop the TCP server\n---@param server TCPServer The server object\nfunction M.stop_server(server)\n -- Close all clients\n for _, client in pairs(server.clients) do\n client_manager.close_client(client, 1001, \"Server shutting down\")\n end\n\n -- Clear clients\n server.clients = {}\n\n -- Close server\n if server.server and not server.server:is_closing() then\n server.server:close()\n end\nend\n\n---@brief Start a periodic ping task to keep connections alive\n---@param server TCPServer The server object\n---@param interval number Ping interval in milliseconds (default: 30000)\n---@return table timer The timer handle\nfunction M.start_ping_timer(server, interval)\n interval = interval or 30000 -- 30 seconds\n\n local timer = vim.loop.new_timer()\n timer:start(interval, interval, function()\n for _, client in pairs(server.clients) do\n if client.state == \"connected\" then\n -- Check if client is alive\n if client_manager.is_client_alive(client, interval * 2) then\n client_manager.send_ping(client, \"ping\")\n else\n -- Client appears dead, close it\n server.on_error(\"Client \" .. client.id .. \" appears dead, closing\")\n client_manager.close_client(client, 1006, \"Connection timeout\")\n M._remove_client(server, client)\n end\n end\n end\n end)\n\n return timer\nend\n\nreturn M\n"], ["/claudecode.nvim/plugin/claudecode.lua", "if vim.fn.has(\"nvim-0.8.0\") ~= 1 then\n vim.api.nvim_err_writeln(\"Claude Code requires Neovim >= 0.8.0\")\n return\nend\n\nif vim.g.loaded_claudecode then\n return\nend\nvim.g.loaded_claudecode = 1\n\n--- Example: In your `init.lua`, you can set `vim.g.claudecode_auto_setup = { auto_start = true }`\n--- to automatically start ClaudeCode when Neovim loads.\nif vim.g.claudecode_auto_setup then\n vim.defer_fn(function()\n require(\"claudecode\").setup(vim.g.claudecode_auto_setup)\n end, 0)\nend\n\n-- Commands are now registered in lua/claudecode/init.lua's _create_commands function\n-- when require(\"claudecode\").setup() is called.\n-- This file (plugin/claudecode.lua) is primarily for the load guard\n-- and the optional auto-setup mechanism.\n\nlocal main_module_ok, _ = pcall(require, \"claudecode\")\nif not main_module_ok then\n vim.notify(\"ClaudeCode: Failed to load main module. Plugin may not function correctly.\", vim.log.levels.ERROR)\nend\n"], ["/claudecode.nvim/lua/claudecode/server/utils.lua", "---@brief Utility functions for WebSocket server implementation\nlocal M = {}\n\n-- Lua 5.1 compatible bitwise operations (arithmetic emulation).\nlocal function band(a, b)\n local result = 0\n local bitval = 1\n while a > 0 and b > 0 do\n if a % 2 == 1 and b % 2 == 1 then\n result = result + bitval\n end\n bitval = bitval * 2\n a = math.floor(a / 2)\n b = math.floor(b / 2)\n end\n return result\nend\n\nlocal function bor(a, b)\n local result = 0\n local bitval = 1\n while a > 0 or b > 0 do\n if a % 2 == 1 or b % 2 == 1 then\n result = result + bitval\n end\n bitval = bitval * 2\n a = math.floor(a / 2)\n b = math.floor(b / 2)\n end\n return result\nend\n\nlocal function bxor(a, b)\n local result = 0\n local bitval = 1\n while a > 0 or b > 0 do\n if (a % 2) ~= (b % 2) then\n result = result + bitval\n end\n bitval = bitval * 2\n a = math.floor(a / 2)\n b = math.floor(b / 2)\n end\n return result\nend\n\nlocal function bnot(a)\n return bxor(a, 0xFFFFFFFF)\nend\n\nlocal function lshift(value, amount)\n local shifted_val = value * (2 ^ amount)\n return shifted_val % (2 ^ 32)\nend\n\nlocal function rshift(value, amount)\n return math.floor(value / (2 ^ amount))\nend\n\nlocal function rotleft(value, amount)\n local mask = 0xFFFFFFFF\n value = band(value, mask)\n local part1 = lshift(value, amount)\n local part2 = rshift(value, 32 - amount)\n return band(bor(part1, part2), mask)\nend\n\nlocal function add32(a, b)\n local sum = a + b\n return band(sum, 0xFFFFFFFF)\nend\n\n---@brief Generate a random, spec-compliant WebSocket key.\n---@return string key Base64 encoded 16-byte random nonce.\nfunction M.generate_websocket_key()\n local random_bytes = {}\n for _ = 1, 16 do\n random_bytes[#random_bytes + 1] = string.char(math.random(0, 255))\n end\n return M.base64_encode(table.concat(random_bytes))\nend\n\n---@brief Base64 encode a string\n---@param data string The data to encode\n---@return string encoded The base64 encoded string\nfunction M.base64_encode(data)\n local chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\n local result = {}\n local padding = \"\"\n\n local pad_len = 3 - (#data % 3)\n if pad_len ~= 3 then\n data = data .. string.rep(\"\\0\", pad_len)\n padding = string.rep(\"=\", pad_len)\n end\n\n for i = 1, #data, 3 do\n local a, b, c = data:byte(i, i + 2)\n local bitmap = a * 65536 + b * 256 + c\n\n -- Use table for efficient string building\n result[#result + 1] = chars:sub(math.floor(bitmap / 262144) + 1, math.floor(bitmap / 262144) + 1)\n result[#result + 1] = chars:sub(math.floor((bitmap % 262144) / 4096) + 1, math.floor((bitmap % 262144) / 4096) + 1)\n result[#result + 1] = chars:sub(math.floor((bitmap % 4096) / 64) + 1, math.floor((bitmap % 4096) / 64) + 1)\n result[#result + 1] = chars:sub((bitmap % 64) + 1, (bitmap % 64) + 1)\n end\n\n local encoded = table.concat(result)\n return encoded:sub(1, #encoded - #padding) .. padding\nend\n\n---@brief Base64 decode a string\n---@param data string The base64 encoded string\n---@return string|nil decoded The decoded string, or nil on error (e.g. invalid char)\nfunction M.base64_decode(data)\n local chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\n local lookup = {}\n for i = 1, #chars do\n lookup[chars:sub(i, i)] = i - 1\n end\n lookup[\"=\"] = 0\n\n local result = {}\n local buffer = 0\n local bits = 0\n\n for i = 1, #data do\n local char = data:sub(i, i)\n local value = lookup[char]\n\n if value == nil then\n return nil\n end\n\n if char == \"=\" then\n break\n end\n\n buffer = (buffer * 64) + value\n bits = bits + 6\n\n if bits >= 8 then\n bits = bits - 8\n result[#result + 1] = string.char(rshift(buffer, bits))\n buffer = band(buffer, (lshift(1, bits)) - 1)\n end\n end\n return table.concat(result)\nend\n\n---@brief Pure Lua SHA-1 implementation\n---@param data string The data to hash\n---@return string|nil hash The SHA-1 hash in binary format, or nil on error\nfunction M.sha1(data)\n if type(data) ~= \"string\" then\n return nil\n end\n\n -- Validate input data is reasonable size (DOS protection)\n if #data > 10 * 1024 * 1024 then -- 10MB limit\n return nil\n end\n\n local h0 = 0x67452301\n local h1 = 0xEFCDAB89\n local h2 = 0x98BADCFE\n local h3 = 0x10325476\n local h4 = 0xC3D2E1F0\n\n local msg = data\n local msg_len = #msg\n local bit_len = msg_len * 8\n\n msg = msg .. string.char(0x80)\n\n -- Append 0 <= k < 512 bits '0', where the resulting message length\n -- (in bits) is congruent to 448 (mod 512)\n while (#msg % 64) ~= 56 do\n msg = msg .. string.char(0x00)\n end\n\n -- Append length as 64-bit big-endian integer\n for i = 7, 0, -1 do\n msg = msg .. string.char(band(rshift(bit_len, i * 8), 0xFF))\n end\n\n for chunk_start = 1, #msg, 64 do\n local w = {}\n\n -- Break chunk into sixteen 32-bit big-endian words\n for i = 0, 15 do\n local offset = chunk_start + i * 4\n w[i] = bor(\n bor(bor(lshift(msg:byte(offset), 24), lshift(msg:byte(offset + 1), 16)), lshift(msg:byte(offset + 2), 8)),\n msg:byte(offset + 3)\n )\n end\n\n -- Extend the sixteen 32-bit words into eighty 32-bit words\n for i = 16, 79 do\n w[i] = rotleft(bxor(bxor(bxor(w[i - 3], w[i - 8]), w[i - 14]), w[i - 16]), 1)\n end\n\n local a, b, c, d, e = h0, h1, h2, h3, h4\n\n for i = 0, 79 do\n local f, k\n if i <= 19 then\n f = bor(band(b, c), band(bnot(b), d))\n k = 0x5A827999\n elseif i <= 39 then\n f = bxor(bxor(b, c), d)\n k = 0x6ED9EBA1\n elseif i <= 59 then\n f = bor(bor(band(b, c), band(b, d)), band(c, d))\n k = 0x8F1BBCDC\n else\n f = bxor(bxor(b, c), d)\n k = 0xCA62C1D6\n end\n\n local temp = add32(add32(add32(add32(rotleft(a, 5), f), e), k), w[i])\n e = d\n d = c\n c = rotleft(b, 30)\n b = a\n a = temp\n end\n\n h0 = add32(h0, a)\n h1 = add32(h1, b)\n h2 = add32(h2, c)\n h3 = add32(h3, d)\n h4 = add32(h4, e)\n end\n\n -- Produce the final hash value as a 160-bit (20-byte) binary string\n local result = \"\"\n for _, h in ipairs({ h0, h1, h2, h3, h4 }) do\n result = result\n .. string.char(band(rshift(h, 24), 0xFF), band(rshift(h, 16), 0xFF), band(rshift(h, 8), 0xFF), band(h, 0xFF))\n end\n\n return result\nend\n\n---@brief Generate WebSocket accept key from client key\n---@param client_key string The client's WebSocket-Key header value\n---@return string|nil accept_key The WebSocket accept key, or nil on error\nfunction M.generate_accept_key(client_key)\n local magic_string = \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\"\n\n -- As per RFC 6455, the server concatenates the Sec-WebSocket-Key header value\n -- with a magic string, SHA1s the result, and then Base64 encodes it.\n local combined = client_key .. magic_string\n local hash = M.sha1(combined)\n if not hash then\n return nil\n end\n\n return M.base64_encode(hash)\nend\n\n---@brief Parse HTTP headers from request string\n---@param request string The HTTP request string\n---@return table headers Table of header name -> value pairs\nfunction M.parse_http_headers(request)\n local headers = {}\n local lines = {}\n\n for line in request:gmatch(\"[^\\r\\n]+\") do\n table.insert(lines, line)\n end\n\n for i = 2, #lines do\n local line = lines[i]\n local name, value = line:match(\"^([^:]+):%s*(.+)$\")\n if name and value then\n headers[name:lower()] = value\n end\n end\n\n return headers\nend\n\n---@brief Check if a string contains valid UTF-8\n---@param str string The string to check\n---@return boolean valid True if the string is valid UTF-8\nfunction M.is_valid_utf8(str)\n local i = 1\n while i <= #str do\n local byte = str:byte(i)\n local char_len = 1\n\n if byte >= 0x80 then\n if byte >= 0xF0 then\n char_len = 4\n elseif byte >= 0xE0 then\n char_len = 3\n elseif byte >= 0xC0 then\n char_len = 2\n else\n return false\n end\n\n for j = 1, char_len - 1 do\n if i + j > #str then\n return false\n end\n local cont_byte = str:byte(i + j)\n if cont_byte < 0x80 or cont_byte >= 0xC0 then\n return false\n end\n end\n end\n\n i = i + char_len\n end\n\n return true\nend\n\n---@brief Convert a 16-bit number to big-endian bytes\n---@param num number The number to convert\n---@return string bytes The big-endian byte representation\nfunction M.uint16_to_bytes(num)\n return string.char(math.floor(num / 256), num % 256)\nend\n\n---@brief Convert a 64-bit number to big-endian bytes\n---@param num number The number to convert\n---@return string bytes The big-endian byte representation\nfunction M.uint64_to_bytes(num)\n local bytes = {}\n for i = 8, 1, -1 do\n bytes[i] = num % 256\n num = math.floor(num / 256)\n end\n return string.char(unpack(bytes))\nend\n\n---@brief Convert big-endian bytes to a 16-bit number\n---@param bytes string The byte string (2 bytes)\n---@return number num The converted number\nfunction M.bytes_to_uint16(bytes)\n if #bytes < 2 then\n return 0\n end\n return bytes:byte(1) * 256 + bytes:byte(2)\nend\n\n---@brief Convert big-endian bytes to a 64-bit number\n---@param bytes string The byte string (8 bytes)\n---@return number num The converted number\nfunction M.bytes_to_uint64(bytes)\n if #bytes < 8 then\n return 0\n end\n\n local num = 0\n for i = 1, 8 do\n num = num * 256 + bytes:byte(i)\n end\n return num\nend\n\n---@brief XOR lookup table for faster operations\nlocal xor_table = {}\nfor i = 0, 255 do\n xor_table[i] = {}\n for j = 0, 255 do\n local result = 0\n local a, b = i, j\n local bit_val = 1\n\n while a > 0 or b > 0 do\n local a_bit = a % 2\n local b_bit = b % 2\n\n if a_bit ~= b_bit then\n result = result + bit_val\n end\n\n a = math.floor(a / 2)\n b = math.floor(b / 2)\n bit_val = bit_val * 2\n end\n\n xor_table[i][j] = result\n end\nend\n\n---@brief Apply XOR mask to payload data\n---@param data string The data to mask/unmask\n---@param mask string The 4-byte mask\n---@return string masked The masked/unmasked data\nfunction M.apply_mask(data, mask)\n local result = {}\n local mask_bytes = { mask:byte(1, 4) }\n\n for i = 1, #data do\n local mask_idx = ((i - 1) % 4) + 1\n local data_byte = data:byte(i)\n result[i] = string.char(xor_table[data_byte][mask_bytes[mask_idx]])\n end\n\n return table.concat(result)\nend\n\n---@brief Shuffle an array in place using Fisher-Yates algorithm\n---@param tbl table The array to shuffle\nfunction M.shuffle_array(tbl)\n math.randomseed(os.time())\n for i = #tbl, 2, -1 do\n local j = math.random(i)\n tbl[i], tbl[j] = tbl[j], tbl[i]\n end\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/handshake.lua", "---@brief WebSocket handshake handling (RFC 6455)\nlocal utils = require(\"claudecode.server.utils\")\n\nlocal M = {}\n\n---@brief Check if an HTTP request is a valid WebSocket upgrade request\n---@param request string The HTTP request string\n---@param expected_auth_token string|nil Expected authentication token for validation\n---@return boolean valid True if it's a valid WebSocket upgrade request\n---@return table|string headers_or_error Headers table if valid, error message if not\nfunction M.validate_upgrade_request(request, expected_auth_token)\n local headers = utils.parse_http_headers(request)\n\n -- Check for required headers\n if not headers[\"upgrade\"] or headers[\"upgrade\"]:lower() ~= \"websocket\" then\n return false, \"Missing or invalid Upgrade header\"\n end\n\n if not headers[\"connection\"] or not headers[\"connection\"]:lower():find(\"upgrade\") then\n return false, \"Missing or invalid Connection header\"\n end\n\n if not headers[\"sec-websocket-key\"] then\n return false, \"Missing Sec-WebSocket-Key header\"\n end\n\n if not headers[\"sec-websocket-version\"] or headers[\"sec-websocket-version\"] ~= \"13\" then\n return false, \"Missing or unsupported Sec-WebSocket-Version header\"\n end\n\n -- Validate WebSocket key format (should be base64 encoded 16 bytes)\n local key = headers[\"sec-websocket-key\"]\n if #key ~= 24 then -- Base64 encoded 16 bytes = 24 characters\n return false, \"Invalid Sec-WebSocket-Key format\"\n end\n\n -- Validate authentication token if required\n if expected_auth_token then\n -- Check if expected_auth_token is valid\n if type(expected_auth_token) ~= \"string\" or expected_auth_token == \"\" then\n return false, \"Server configuration error: invalid expected authentication token\"\n end\n\n local auth_header = headers[\"x-claude-code-ide-authorization\"]\n if not auth_header then\n return false, \"Missing authentication header: x-claude-code-ide-authorization\"\n end\n\n -- Check for empty auth header\n if auth_header == \"\" then\n return false, \"Authentication token too short (min 10 characters)\"\n end\n\n -- Check for suspicious auth header lengths\n if #auth_header > 500 then\n return false, \"Authentication token too long (max 500 characters)\"\n end\n\n if #auth_header < 10 then\n return false, \"Authentication token too short (min 10 characters)\"\n end\n\n if auth_header ~= expected_auth_token then\n return false, \"Invalid authentication token\"\n end\n end\n\n return true, headers\nend\n\n---@brief Generate a WebSocket handshake response\n---@param client_key string The client's Sec-WebSocket-Key header value\n---@param protocol string|nil Optional subprotocol to accept\n---@return string|nil response The HTTP response string, or nil on error\nfunction M.create_handshake_response(client_key, protocol)\n local accept_key = utils.generate_accept_key(client_key)\n if not accept_key then\n return nil\n end\n\n local response_lines = {\n \"HTTP/1.1 101 Switching Protocols\",\n \"Upgrade: websocket\",\n \"Connection: Upgrade\",\n \"Sec-WebSocket-Accept: \" .. accept_key,\n }\n\n if protocol then\n table.insert(response_lines, \"Sec-WebSocket-Protocol: \" .. protocol)\n end\n\n -- Add empty line to end headers\n table.insert(response_lines, \"\")\n table.insert(response_lines, \"\")\n\n return table.concat(response_lines, \"\\r\\n\")\nend\n\n---@brief Parse the HTTP request line\n---@param request string The HTTP request string\n---@return string|nil method The HTTP method (GET, POST, etc.)\n---@return string|nil path The request path\n---@return string|nil version The HTTP version\nfunction M.parse_request_line(request)\n local first_line = request:match(\"^([^\\r\\n]+)\")\n if not first_line then\n return nil, nil, nil\n end\n\n local method, path, version = first_line:match(\"^(%S+)%s+(%S+)%s+(%S+)$\")\n return method, path, version\nend\n\n---@brief Check if the request is for the WebSocket endpoint\n---@param request string The HTTP request string\n---@return boolean valid True if the request is for a valid WebSocket endpoint\nfunction M.is_websocket_endpoint(request)\n local method, path, version = M.parse_request_line(request)\n\n -- Must be GET request\n if method ~= \"GET\" then\n return false\n end\n\n -- Must be HTTP/1.1 or later\n if not version or not version:match(\"^HTTP/1%.1\") then\n return false\n end\n\n -- Accept any path for now (could be made configurable)\n if not path then\n return false\n end\n\n return true\nend\n\n---@brief Create a WebSocket handshake error response\n---@param code number HTTP status code\n---@param message string Error message\n---@return string response The HTTP error response\nfunction M.create_error_response(code, message)\n local status_text = {\n [400] = \"Bad Request\",\n [404] = \"Not Found\",\n [426] = \"Upgrade Required\",\n [500] = \"Internal Server Error\",\n }\n\n local status = status_text[code] or \"Error\"\n\n local response_lines = {\n \"HTTP/1.1 \" .. code .. \" \" .. status,\n \"Content-Type: text/plain\",\n \"Content-Length: \" .. #message,\n \"Connection: close\",\n \"\",\n message,\n }\n\n return table.concat(response_lines, \"\\r\\n\")\nend\n\n---@brief Process a complete WebSocket handshake\n---@param request string The HTTP request string\n---@param expected_auth_token string|nil Expected authentication token for validation\n---@return boolean success True if handshake was successful\n---@return string response The HTTP response to send\n---@return table|nil headers The parsed headers if successful\nfunction M.process_handshake(request, expected_auth_token)\n -- Check if it's a valid WebSocket endpoint request\n if not M.is_websocket_endpoint(request) then\n local response = M.create_error_response(404, \"WebSocket endpoint not found\")\n return false, response, nil\n end\n\n -- Validate the upgrade request\n local is_valid_upgrade, validation_payload = M.validate_upgrade_request(request, expected_auth_token) ---@type boolean, table|string\n if not is_valid_upgrade then\n assert(type(validation_payload) == \"string\", \"validation_payload should be a string on error\")\n local error_message = validation_payload\n local response = M.create_error_response(400, \"Bad WebSocket upgrade request: \" .. error_message)\n return false, response, nil\n end\n\n -- If is_valid_upgrade is true, validation_payload must be the headers table\n assert(type(validation_payload) == \"table\", \"validation_payload should be a table on success\")\n local headers_table = validation_payload\n\n -- Generate handshake response\n local client_key = headers_table[\"sec-websocket-key\"]\n local protocol = headers_table[\"sec-websocket-protocol\"] -- Optional\n\n local response = M.create_handshake_response(client_key, protocol)\n if not response then\n local error_response = M.create_error_response(500, \"Failed to generate WebSocket handshake response\")\n return false, error_response, nil -- error_response is string, nil is for headers\n end\n\n return true, response, headers_table -- headers_table is 'table', compatible with 'table|nil'\nend\n\n---@brief Check if a request buffer contains a complete HTTP request\n---@param buffer string The request buffer\n---@return boolean complete True if the request is complete\n---@return string|nil request The complete request if found\n---@return string remaining Any remaining data after the request\nfunction M.extract_http_request(buffer)\n -- Look for the end of HTTP headers (double CRLF)\n local header_end = buffer:find(\"\\r\\n\\r\\n\")\n if not header_end then\n return false, nil, buffer\n end\n\n -- For WebSocket upgrade, there should be no body\n local request = buffer:sub(1, header_end + 3) -- Include the final CRLF\n local remaining = buffer:sub(header_end + 4)\n\n return true, request, remaining\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/mock.lua", "---@brief [[\n--- Mock WebSocket server implementation for testing.\n--- This module provides a minimal implementation of the WebSocket server\n--- functionality, suitable for testing or when real WebSocket connections\n--- are not available or needed.\n---@brief ]]\n\nlocal M = {}\nlocal tools = require(\"claudecode.tools.init\")\n\n--- Mock server state\nM.state = {\n server = nil,\n port = nil,\n clients = {},\n handlers = {},\n messages = {}, -- Store messages for testing\n}\n\n--- Find an available port in the given range\n---@param min number The minimum port number\n---@param _max number The maximum port number\n---@return number port The selected port\nfunction M.find_available_port(min, _max)\n -- For mock implementation, just return the minimum port\n -- In a real implementation, this would scan for available ports in the range\n return min\nend\n\n--- Start the WebSocket server\n---@param config table Configuration options\n---@return boolean success Whether the server started successfully\n---@return number|string port_or_error The port number or error message\nfunction M.start(config)\n if M.state.server then\n -- Already running\n return false, \"Server already running\"\n end\n\n -- Find an available port\n local port = M.find_available_port(config.port_range.min, config.port_range.max)\n\n if not port then\n return false, \"No available ports found\"\n end\n\n -- Store the port in state\n M.state.port = port\n\n -- Create mock server object\n M.state.server = {\n port = port,\n clients = {},\n on_message = function() end,\n on_connect = function() end,\n on_disconnect = function() end,\n }\n\n -- Register message handlers\n M.register_handlers()\n\n return true, port\nend\n\n--- Stop the WebSocket server\n---@return boolean success Whether the server stopped successfully\n---@return string|nil error Error message if failed\nfunction M.stop()\n if not M.state.server then\n -- Not running\n return false, \"Server not running\"\n end\n\n -- Reset state\n M.state.server = nil\n M.state.port = nil\n M.state.clients = {}\n M.state.messages = {}\n\n return true\nend\n\n--- Register message handlers\nfunction M.register_handlers()\n -- Default handlers\n M.state.handlers = {\n [\"mcp.connect\"] = function(_client, _params)\n -- Handle connection handshake\n -- Parameters not used in this mock implementation\n return { result = { message = \"Connection established\" } }\n end,\n\n [\"mcp.tool.invoke\"] = function(client, params)\n -- Handle tool invocation by dispatching to tools implementation\n return tools.handle_invoke(client, params)\n end,\n }\nend\n\n--- Add a client to the server\n---@param client_id string A unique client identifier\n---@return table client The client object\nfunction M.add_client(client_id)\n if not M.state.server then\n error(\"Server not running\")\n end\n\n local client = {\n id = client_id,\n connected = true,\n messages = {},\n }\n\n M.state.clients[client_id] = client\n return client\nend\n\n--- Remove a client from the server\n---@param client_id string The client identifier\n---@return boolean success Whether removal was successful\nfunction M.remove_client(client_id)\n if not M.state.server or not M.state.clients[client_id] then\n return false\n end\n\n M.state.clients[client_id] = nil\n return true\nend\n\n--- Send a message to a client\n---@param client table|string The client object or ID\n---@param method string The method name\n---@param params table The parameters to send\n---@return boolean success Whether sending was successful\nfunction M.send(client, method, params)\n local client_obj\n\n if type(client) == \"string\" then\n client_obj = M.state.clients[client]\n else\n client_obj = client\n end\n\n if not client_obj then\n return false\n end\n\n local message = {\n jsonrpc = \"2.0\",\n method = method,\n params = params,\n }\n\n -- Store for testing\n table.insert(client_obj.messages, message)\n table.insert(M.state.messages, {\n client = client_obj.id,\n direction = \"outbound\",\n message = message,\n })\n\n return true\nend\n\n--- Send a response to a client\n---@param client table|string The client object or ID\n---@param id string The message ID\n---@param result table|nil The result data\n---@param error table|nil The error data\n---@return boolean success Whether sending was successful\nfunction M.send_response(client, id, result, error)\n local client_obj\n\n if type(client) == \"string\" then\n client_obj = M.state.clients[client]\n else\n client_obj = client\n end\n\n if not client_obj then\n return false\n end\n\n local response = {\n jsonrpc = \"2.0\",\n id = id,\n }\n\n if error then\n response.error = error\n else\n response.result = result\n end\n\n -- Store for testing\n table.insert(client_obj.messages, response)\n table.insert(M.state.messages, {\n client = client_obj.id,\n direction = \"outbound\",\n message = response,\n })\n\n return true\nend\n\n--- Broadcast a message to all connected clients\n---@param method string The method name\n---@param params table The parameters to send\n---@return boolean success Whether broadcasting was successful\nfunction M.broadcast(method, params)\n local success = true\n\n for client_id, _ in pairs(M.state.clients) do\n local send_success = M.send(client_id, method, params)\n success = success and send_success\n end\n\n return success\nend\n\n--- Simulate receiving a message from a client\n---@param client_id string The client ID\n---@param message table The message to process\n---@return table|nil response The response if any\nfunction M.simulate_message(client_id, message)\n local client = M.state.clients[client_id]\n\n if not client then\n return nil\n end\n\n -- Store the message\n table.insert(M.state.messages, {\n client = client_id,\n direction = \"inbound\",\n message = message,\n })\n\n -- Process the message\n if message.method and M.state.handlers[message.method] then\n local handler = M.state.handlers[message.method]\n local response = handler(client, message.params)\n\n if message.id and response then\n -- If the message had an ID, this is a request and needs a response\n M.send_response(client, message.id, response.result, response.error)\n return response\n end\n end\n\n return nil\nend\n\n--- Clear test messages\nfunction M.clear_messages()\n M.state.messages = {}\n\n for _, client in pairs(M.state.clients) do\n client.messages = {}\n end\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/frame.lua", "---@brief WebSocket frame encoding and decoding (RFC 6455)\nlocal utils = require(\"claudecode.server.utils\")\n\nlocal M = {}\n\n-- WebSocket opcodes\nM.OPCODE = {\n CONTINUATION = 0x0,\n TEXT = 0x1,\n BINARY = 0x2,\n CLOSE = 0x8,\n PING = 0x9,\n PONG = 0xA,\n}\n\n---@class WebSocketFrame\n---@field fin boolean Final fragment flag\n---@field opcode number Frame opcode\n---@field masked boolean Mask flag\n---@field payload_length number Length of payload data\n---@field mask string|nil 4-byte mask (if masked)\n---@field payload string Frame payload data\n\n---@brief Parse a WebSocket frame from binary data\n---@param data string The binary frame data\n---@return WebSocketFrame|nil frame The parsed frame, or nil if incomplete/invalid\n---@return number bytes_consumed Number of bytes consumed from input\nfunction M.parse_frame(data)\n if type(data) ~= \"string\" then\n return nil, 0\n end\n\n if #data < 2 then\n return nil, 0 -- Need at least 2 bytes for basic header\n end\n\n local pos = 1\n local byte1 = data:byte(pos)\n local byte2 = data:byte(pos + 1)\n\n -- Validate byte values\n if not byte1 or not byte2 then\n return nil, 0\n end\n\n pos = pos + 2\n\n local fin = math.floor(byte1 / 128) == 1\n local rsv1 = math.floor((byte1 % 128) / 64) == 1\n local rsv2 = math.floor((byte1 % 64) / 32) == 1\n local rsv3 = math.floor((byte1 % 32) / 16) == 1\n local opcode = byte1 % 16\n\n local masked = math.floor(byte2 / 128) == 1\n local payload_len = byte2 % 128\n\n -- Validate opcode (RFC 6455 Section 5.2)\n local valid_opcodes = {\n [M.OPCODE.CONTINUATION] = true,\n [M.OPCODE.TEXT] = true,\n [M.OPCODE.BINARY] = true,\n [M.OPCODE.CLOSE] = true,\n [M.OPCODE.PING] = true,\n [M.OPCODE.PONG] = true,\n }\n\n if not valid_opcodes[opcode] then\n return nil, 0 -- Invalid opcode\n end\n\n -- Check for reserved bits (must be 0)\n if rsv1 or rsv2 or rsv3 then\n return nil, 0 -- Protocol error\n end\n\n -- Control frames must have fin=1 and payload ≤ 125 (RFC 6455 Section 5.5)\n if opcode >= M.OPCODE.CLOSE then\n if not fin or payload_len > 125 then\n return nil, 0 -- Protocol violation\n end\n end\n\n -- Determine actual payload length\n local actual_payload_len = payload_len\n if payload_len == 126 then\n if #data < pos + 1 then\n return nil, 0 -- Need 2 more bytes\n end\n actual_payload_len = utils.bytes_to_uint16(data:sub(pos, pos + 1))\n pos = pos + 2\n\n -- Allow any valid 16-bit length for compatibility\n -- Note: Technically should be > 125, but some implementations may vary\n elseif payload_len == 127 then\n if #data < pos + 7 then\n return nil, 0 -- Need 8 more bytes\n end\n actual_payload_len = utils.bytes_to_uint64(data:sub(pos, pos + 7))\n pos = pos + 8\n\n -- Allow any valid 64-bit length for compatibility\n -- Note: Technically should be > 65535, but some implementations may vary\n\n -- Prevent extremely large payloads (DOS protection)\n if actual_payload_len > 100 * 1024 * 1024 then -- 100MB limit\n return nil, 0\n end\n end\n\n -- Additional payload length validation\n if actual_payload_len < 0 then\n return nil, 0 -- Invalid negative length\n end\n\n -- Read mask if present\n local mask = nil\n if masked then\n if #data < pos + 3 then\n return nil, 0 -- Need 4 mask bytes\n end\n mask = data:sub(pos, pos + 3)\n pos = pos + 4\n end\n\n -- Check if we have enough data for payload\n if #data < pos + actual_payload_len - 1 then\n return nil, 0 -- Incomplete frame\n end\n\n -- Read payload\n local payload = data:sub(pos, pos + actual_payload_len - 1)\n pos = pos + actual_payload_len\n\n -- Unmask payload if needed\n if masked and mask then\n payload = utils.apply_mask(payload, mask)\n end\n\n -- Validate text frame payload is valid UTF-8\n if opcode == M.OPCODE.TEXT and not utils.is_valid_utf8(payload) then\n return nil, 0 -- Invalid UTF-8 in text frame\n end\n\n -- Basic validation for close frame payload\n if opcode == M.OPCODE.CLOSE and actual_payload_len > 0 then\n if actual_payload_len == 1 then\n return nil, 0 -- Close frame with 1 byte payload is invalid\n end\n -- Allow most close codes for compatibility, only validate UTF-8 for reason text\n if actual_payload_len > 2 then\n local reason = payload:sub(3)\n if not utils.is_valid_utf8(reason) then\n return nil, 0 -- Invalid UTF-8 in close reason\n end\n end\n end\n\n local frame = {\n fin = fin,\n opcode = opcode,\n masked = masked,\n payload_length = actual_payload_len,\n mask = mask,\n payload = payload,\n }\n\n return frame, pos - 1\nend\n\n---@brief Create a WebSocket frame\n---@param opcode number Frame opcode\n---@param payload string Frame payload\n---@param fin boolean|nil Final fragment flag (default: true)\n---@param masked boolean|nil Whether to mask the frame (default: false for server)\n---@return string frame_data The encoded frame data\nfunction M.create_frame(opcode, payload, fin, masked)\n fin = fin ~= false -- Default to true\n masked = masked == true -- Default to false\n\n local frame_data = {}\n\n -- First byte: FIN + RSV + Opcode\n local byte1 = opcode\n if fin then\n byte1 = byte1 + 128 -- Set FIN bit (0x80)\n end\n table.insert(frame_data, string.char(byte1))\n\n -- Payload length and mask bit\n local payload_len = #payload\n local byte2 = 0\n if masked then\n byte2 = byte2 + 128 -- Set MASK bit (0x80)\n end\n\n if payload_len < 126 then\n byte2 = byte2 + payload_len\n table.insert(frame_data, string.char(byte2))\n elseif payload_len < 65536 then\n byte2 = byte2 + 126\n table.insert(frame_data, string.char(byte2))\n table.insert(frame_data, utils.uint16_to_bytes(payload_len))\n else\n byte2 = byte2 + 127\n table.insert(frame_data, string.char(byte2))\n table.insert(frame_data, utils.uint64_to_bytes(payload_len))\n end\n\n -- Add mask if needed\n local mask = nil\n if masked then\n -- Generate random 4-byte mask\n mask = string.char(math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255))\n table.insert(frame_data, mask)\n end\n\n -- Add payload (masked if needed)\n if masked and mask then\n payload = utils.apply_mask(payload, mask)\n end\n table.insert(frame_data, payload)\n\n return table.concat(frame_data)\nend\n\n---@brief Create a text frame\n---@param text string The text to send\n---@param fin boolean|nil Final fragment flag (default: true)\n---@return string frame_data The encoded frame data\nfunction M.create_text_frame(text, fin)\n return M.create_frame(M.OPCODE.TEXT, text, fin, false)\nend\n\n---@brief Create a binary frame\n---@param data string The binary data to send\n---@param fin boolean|nil Final fragment flag (default: true)\n---@return string frame_data The encoded frame data\nfunction M.create_binary_frame(data, fin)\n return M.create_frame(M.OPCODE.BINARY, data, fin, false)\nend\n\n---@brief Create a close frame\n---@param code number|nil Close code (default: 1000)\n---@param reason string|nil Close reason (default: empty)\n---@return string frame_data The encoded frame data\nfunction M.create_close_frame(code, reason)\n code = code or 1000\n reason = reason or \"\"\n\n local payload = utils.uint16_to_bytes(code) .. reason\n return M.create_frame(M.OPCODE.CLOSE, payload, true, false)\nend\n\n---@brief Create a ping frame\n---@param data string|nil Ping data (default: empty)\n---@return string frame_data The encoded frame data\nfunction M.create_ping_frame(data)\n data = data or \"\"\n return M.create_frame(M.OPCODE.PING, data, true, false)\nend\n\n---@brief Create a pong frame\n---@param data string|nil Pong data (should match ping data)\n---@return string frame_data The encoded frame data\nfunction M.create_pong_frame(data)\n data = data or \"\"\n return M.create_frame(M.OPCODE.PONG, data, true, false)\nend\n\n---@brief Check if an opcode is a control frame\n---@param opcode number The opcode to check\n---@return boolean is_control True if it's a control frame\nfunction M.is_control_frame(opcode)\n return opcode >= 0x8\nend\n\n---@brief Validate a WebSocket frame\n---@param frame WebSocketFrame The frame to validate\n---@return boolean valid True if the frame is valid\n---@return string|nil error Error message if invalid\nfunction M.validate_frame(frame)\n -- Control frames must not be fragmented\n if M.is_control_frame(frame.opcode) and not frame.fin then\n return false, \"Control frames must not be fragmented\"\n end\n\n -- Control frames must have payload <= 125 bytes\n if M.is_control_frame(frame.opcode) and frame.payload_length > 125 then\n return false, \"Control frame payload too large\"\n end\n\n -- Check for valid opcodes\n local valid_opcodes = {\n [M.OPCODE.CONTINUATION] = true,\n [M.OPCODE.TEXT] = true,\n [M.OPCODE.BINARY] = true,\n [M.OPCODE.CLOSE] = true,\n [M.OPCODE.PING] = true,\n [M.OPCODE.PONG] = true,\n }\n\n if not valid_opcodes[frame.opcode] then\n return false, \"Invalid opcode: \" .. frame.opcode\n end\n\n -- Text frames must contain valid UTF-8\n if frame.opcode == M.OPCODE.TEXT and not utils.is_valid_utf8(frame.payload) then\n return false, \"Text frame contains invalid UTF-8\"\n end\n\n return true\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/utils.lua", "--- Shared utility functions for claudecode.nvim\n-- @module claudecode.utils\n\nlocal M = {}\n\n--- Normalizes focus parameter to default to true for backward compatibility\n--- @param focus boolean|nil The focus parameter\n--- @return boolean Normalized focus value\nfunction M.normalize_focus(focus)\n return focus == nil and true or focus\nend\n\nreturn M\n"]], "task_instance_info": {"created_time": "2025-08-21 00:41:13", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Toggle the visibility state of a terminal interface based on its current operational status, either concealing the active instance or revealing a previously hidden one while maintaining process continuity."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```lua\n[TASK_BEGIN]\n--- Simple toggle: always show/hide terminal regardless of focus\n--- @param cmd_string string\n--- @param env_table table\n--- @param effective_config table\nfunction M.simple_toggle(cmd_string, env_table, effective_config)\n if is_terminal_visible() then\n hide_terminal()\n logger.debug(\"terminal\", \"Hiding visible terminal\")\n else\n if is_valid() then\n -- Terminal exists but is hidden, show without focus\n show_hidden_terminal(effective_config, false)\n logger.debug(\"terminal\", \"Showing hidden terminal without focus\")\n else\n -- No terminal exists, create new one without focus\n open_terminal(cmd_string, env_table, effective_config, false)\n logger.debug(\"terminal\", \"Opened new terminal without focus\")\n end\n end\nend\n[TASK_END]\n```", "inference_time": "2025-08-21 00-41-44"}, "editdistance_info": {"edit_distance": 30.5556, "calculate_time": "2025-08-21 00:41:44", "true_code_clean": "function M.simple_toggle(cmd_string, env_table, effective_config)\n local has_buffer = bufnr and vim.api.nvim_buf_is_valid(bufnr)\n local is_visible = has_buffer and is_terminal_visible()\n if is_visible then\n hide_terminal()\n else\n if has_buffer then\n if show_hidden_terminal(effective_config, true) then\n logger.debug(\"terminal\", \"Showing hidden terminal\")\n else\n logger.error(\"terminal\", \"Failed to show hidden terminal\")\n end\n else\n local existing_buf, existing_win = find_existing_claude_terminal()\n if existing_buf and existing_win then\n bufnr = existing_buf\n winid = existing_win\n logger.debug(\"terminal\", \"Recovered existing Claude terminal\")\n focus_terminal()\n else\n if not open_terminal(cmd_string, env_table, effective_config) then\n vim.notify(\"Failed to open Claude terminal using native fallback (simple_toggle).\", vim.log.levels.ERROR)\n end\n end\n end\n end\nend", "predict_code_clean": "function M.simple_toggle(cmd_string, env_table, effective_config)\n if is_terminal_visible() then\n hide_terminal()\n logger.debug(\"terminal\", \"Hiding visible terminal\")\n else\n if is_valid() then\n show_hidden_terminal(effective_config, false)\n logger.debug(\"terminal\", \"Showing hidden terminal without focus\")\n else\n open_terminal(cmd_string, env_table, effective_config, false)\n logger.debug(\"terminal\", \"Opened new terminal without focus\")\n end\n end\nend"}} {"repo_name": "claudecode.nvim", "file_name": "/claudecode.nvim/lua/claudecode/terminal/snacks.lua", "inference_info": {"prefix_code": "--- Snacks.nvim terminal provider for Claude Code.\n-- @module claudecode.terminal.snacks\n\n--- @type TerminalProvider\nlocal M = {}\n\nlocal snacks_available, Snacks = pcall(require, \"snacks\")\nlocal utils = require(\"claudecode.utils\")\nlocal terminal = nil\n\n--- @return boolean\nlocal function is_available()\n return snacks_available and Snacks and Snacks.terminal\nend\n\n--- Setup event handlers for terminal instance\n--- @param term_instance table The Snacks terminal instance\n--- @param config table Configuration options\nlocal function setup_terminal_events(term_instance, config)\n local logger = require(\"claudecode.logger\")\n\n -- Handle command completion/exit - only if auto_close is enabled\n if config.auto_close then\n term_instance:on(\"TermClose\", function()\n if vim.v.event.status ~= 0 then\n logger.error(\"terminal\", \"Claude exited with code \" .. vim.v.event.status .. \".\\nCheck for any errors.\")\n end\n\n -- Clean up\n terminal = nil\n vim.schedule(function()\n term_instance:close({ buf = true })\n vim.cmd.checktime()\n end)\n end, { buf = true })\n end\n\n -- Handle buffer deletion\n term_instance:on(\"BufWipeout\", function()\n logger.debug(\"terminal\", \"Terminal buffer wiped\")\n terminal = nil\n end, { buf = true })\nend\n\n--- Builds Snacks terminal options with focus control\n--- @param config table Terminal configuration (split_side, split_width_percentage, etc.)\n--- @param env_table table Environment variables to set for the terminal process\n--- @param focus boolean|nil Whether to focus the terminal when opened (defaults to true)\n--- @return table Snacks terminal options with start_insert/auto_insert controlled by focus parameter\nlocal function build_opts(config, env_table, focus)\n focus = utils.normalize_focus(focus)\n return {\n env = env_table,\n start_insert = focus,\n auto_insert = focus,\n auto_close = false,\n win = {\n position = config.split_side,\n width = config.split_width_percentage,\n height = 0,\n relative = \"editor\",\n },\n }\nend\n\nfunction M.setup()\n -- No specific setup needed for Snacks provider\nend\n\n--- @param cmd_string string\n--- @param env_table table\n--- @param config table\n--- @param focus boolean|nil\n", "suffix_code": "\n\nfunction M.close()\n if not is_available() then\n return\n end\n if terminal and terminal:buf_valid() then\n terminal:close()\n end\nend\n\n--- Simple toggle: always show/hide terminal regardless of focus\n--- @param cmd_string string\n--- @param env_table table\n--- @param config table\nfunction M.simple_toggle(cmd_string, env_table, config)\n if not is_available() then\n vim.notify(\"Snacks.nvim terminal provider selected but Snacks.terminal not available.\", vim.log.levels.ERROR)\n return\n end\n\n local logger = require(\"claudecode.logger\")\n\n -- Check if terminal exists and is visible\n if terminal and terminal:buf_valid() and terminal.win then\n -- Terminal is visible, hide it\n logger.debug(\"terminal\", \"Simple toggle: hiding visible terminal\")\n terminal:toggle()\n elseif terminal and terminal:buf_valid() and not terminal.win then\n -- Terminal exists but not visible, show it\n logger.debug(\"terminal\", \"Simple toggle: showing hidden terminal\")\n terminal:toggle()\n else\n -- No terminal exists, create new one\n logger.debug(\"terminal\", \"Simple toggle: creating new terminal\")\n M.open(cmd_string, env_table, config)\n end\nend\n\n--- Smart focus toggle: switches to terminal if not focused, hides if currently focused\n--- @param cmd_string string\n--- @param env_table table\n--- @param config table\nfunction M.focus_toggle(cmd_string, env_table, config)\n if not is_available() then\n vim.notify(\"Snacks.nvim terminal provider selected but Snacks.terminal not available.\", vim.log.levels.ERROR)\n return\n end\n\n local logger = require(\"claudecode.logger\")\n\n -- Terminal exists, is valid, but not visible\n if terminal and terminal:buf_valid() and not terminal.win then\n logger.debug(\"terminal\", \"Focus toggle: showing hidden terminal\")\n terminal:toggle()\n -- Terminal exists, is valid, and is visible\n elseif terminal and terminal:buf_valid() and terminal.win then\n local claude_term_neovim_win_id = terminal.win\n local current_neovim_win_id = vim.api.nvim_get_current_win()\n\n -- you're IN it\n if claude_term_neovim_win_id == current_neovim_win_id then\n logger.debug(\"terminal\", \"Focus toggle: hiding terminal (currently focused)\")\n terminal:toggle()\n -- you're NOT in it\n else\n logger.debug(\"terminal\", \"Focus toggle: focusing terminal\")\n vim.api.nvim_set_current_win(claude_term_neovim_win_id)\n if terminal.buf and vim.api.nvim_buf_is_valid(terminal.buf) then\n if vim.api.nvim_buf_get_option(terminal.buf, \"buftype\") == \"terminal\" then\n vim.api.nvim_win_call(claude_term_neovim_win_id, function()\n vim.cmd(\"startinsert\")\n end)\n end\n end\n end\n -- No terminal exists\n else\n logger.debug(\"terminal\", \"Focus toggle: creating new terminal\")\n M.open(cmd_string, env_table, config)\n end\nend\n\n--- Legacy toggle function for backward compatibility (defaults to simple_toggle)\n--- @param cmd_string string\n--- @param env_table table\n--- @param config table\nfunction M.toggle(cmd_string, env_table, config)\n M.simple_toggle(cmd_string, env_table, config)\nend\n\n--- @return number|nil\nfunction M.get_active_bufnr()\n if terminal and terminal:buf_valid() and terminal.buf then\n if vim.api.nvim_buf_is_valid(terminal.buf) then\n return terminal.buf\n end\n end\n return nil\nend\n\n--- @return boolean\nfunction M.is_available()\n return is_available()\nend\n\n-- For testing purposes\n--- @return table|nil\nfunction M._get_terminal_for_test()\n return terminal\nend\n\nreturn M\n", "middle_code": "function M.open(cmd_string, env_table, config, focus)\n if not is_available() then\n vim.notify(\"Snacks.nvim terminal provider selected but Snacks.terminal not available.\", vim.log.levels.ERROR)\n return\n end\n focus = utils.normalize_focus(focus)\n if terminal and terminal:buf_valid() then\n if not terminal.win or not vim.api.nvim_win_is_valid(terminal.win) then\n terminal:toggle()\n if focus then\n terminal:focus()\n local term_buf_id = terminal.buf\n if term_buf_id and vim.api.nvim_buf_get_option(term_buf_id, \"buftype\") == \"terminal\" then\n if terminal.win and vim.api.nvim_win_is_valid(terminal.win) then\n vim.api.nvim_win_call(terminal.win, function()\n vim.cmd(\"startinsert\")\n end)\n end\n end\n end\n else\n if focus then\n terminal:focus()\n local term_buf_id = terminal.buf\n if term_buf_id and vim.api.nvim_buf_get_option(term_buf_id, \"buftype\") == \"terminal\" then\n if terminal.win and vim.api.nvim_win_is_valid(terminal.win) then\n vim.api.nvim_win_call(terminal.win, function()\n vim.cmd(\"startinsert\")\n end)\n end\n end\n end\n end\n return\n end\n local opts = build_opts(config, env_table, focus)\n local term_instance = Snacks.terminal.open(cmd_string, opts)\n if term_instance and term_instance:buf_valid() then\n setup_terminal_events(term_instance, config)\n terminal = term_instance\n else\n terminal = nil\n local logger = require(\"claudecode.logger\")\n local error_details = {}\n if not term_instance then\n table.insert(error_details, \"Snacks.terminal.open() returned nil\")\n elseif not term_instance:buf_valid() then\n table.insert(error_details, \"terminal instance is invalid\")\n if term_instance.buf and not vim.api.nvim_buf_is_valid(term_instance.buf) then\n table.insert(error_details, \"buffer is invalid\")\n end\n if term_instance.win and not vim.api.nvim_win_is_valid(term_instance.win) then\n table.insert(error_details, \"window is invalid\")\n end\n end\n local context = string.format(\"cmd='%s', opts=%s\", cmd_string, vim.inspect(opts))\n local error_msg = string.format(\n \"Failed to open Claude terminal using Snacks. Details: %s. Context: %s\",\n table.concat(error_details, \", \"),\n context\n )\n vim.notify(error_msg, vim.log.levels.ERROR)\n logger.debug(\"terminal\", error_msg)\n end\nend", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "lua", "sub_task_type": null}, "context_code": [["/claudecode.nvim/lua/claudecode/terminal/native.lua", "--- Native Neovim terminal provider for Claude Code.\n-- @module claudecode.terminal.native\n\n--- @type TerminalProvider\nlocal M = {}\n\nlocal logger = require(\"claudecode.logger\")\nlocal utils = require(\"claudecode.utils\")\n\nlocal bufnr = nil\nlocal winid = nil\nlocal jobid = nil\nlocal tip_shown = false\nlocal config = {}\n\nlocal function cleanup_state()\n bufnr = nil\n winid = nil\n jobid = nil\nend\n\nlocal function is_valid()\n -- First check if we have a valid buffer\n if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then\n cleanup_state()\n return false\n end\n\n -- If buffer is valid but window is invalid, try to find a window displaying this buffer\n if not winid or not vim.api.nvim_win_is_valid(winid) then\n -- Search all windows for our terminal buffer\n local windows = vim.api.nvim_list_wins()\n for _, win in ipairs(windows) do\n if vim.api.nvim_win_get_buf(win) == bufnr then\n -- Found a window displaying our terminal buffer, update the tracked window ID\n winid = win\n logger.debug(\"terminal\", \"Recovered terminal window ID:\", win)\n return true\n end\n end\n -- Buffer exists but no window displays it - this is normal for hidden terminals\n return true -- Buffer is valid even though not visible\n end\n\n -- Both buffer and window are valid\n return true\nend\n\nlocal function open_terminal(cmd_string, env_table, effective_config, focus)\n focus = utils.normalize_focus(focus)\n\n if is_valid() then -- Should not happen if called correctly, but as a safeguard\n if focus then\n -- Focus existing terminal: switch to terminal window and enter insert mode\n vim.api.nvim_set_current_win(winid)\n vim.cmd(\"startinsert\")\n end\n -- If focus=false, preserve user context by staying in current window\n return true\n end\n\n local original_win = vim.api.nvim_get_current_win()\n local width = math.floor(vim.o.columns * effective_config.split_width_percentage)\n local full_height = vim.o.lines\n local placement_modifier\n\n if effective_config.split_side == \"left\" then\n placement_modifier = \"topleft \"\n else\n placement_modifier = \"botright \"\n end\n\n vim.cmd(placement_modifier .. width .. \"vsplit\")\n local new_winid = vim.api.nvim_get_current_win()\n vim.api.nvim_win_set_height(new_winid, full_height)\n\n vim.api.nvim_win_call(new_winid, function()\n vim.cmd(\"enew\")\n end)\n\n local term_cmd_arg\n if cmd_string:find(\" \", 1, true) then\n term_cmd_arg = vim.split(cmd_string, \" \", { plain = true, trimempty = false })\n else\n term_cmd_arg = { cmd_string }\n end\n\n jobid = vim.fn.termopen(term_cmd_arg, {\n env = env_table,\n on_exit = function(job_id, _, _)\n vim.schedule(function()\n if job_id == jobid then\n logger.debug(\"terminal\", \"Terminal process exited, cleaning up\")\n\n -- Ensure we are operating on the correct window and buffer before closing\n local current_winid_for_job = winid\n local current_bufnr_for_job = bufnr\n\n cleanup_state() -- Clear our managed state first\n\n if current_winid_for_job and vim.api.nvim_win_is_valid(current_winid_for_job) then\n if current_bufnr_for_job and vim.api.nvim_buf_is_valid(current_bufnr_for_job) then\n -- Optional: Check if the window still holds the same terminal buffer\n if vim.api.nvim_win_get_buf(current_winid_for_job) == current_bufnr_for_job then\n vim.api.nvim_win_close(current_winid_for_job, true)\n end\n else\n -- Buffer is invalid, but window might still be there (e.g. if user changed buffer in term window)\n -- Still try to close the window we tracked.\n vim.api.nvim_win_close(current_winid_for_job, true)\n end\n end\n end\n end)\n end,\n })\n\n if not jobid or jobid == 0 then\n vim.notify(\"Failed to open native terminal.\", vim.log.levels.ERROR)\n vim.api.nvim_win_close(new_winid, true)\n vim.api.nvim_set_current_win(original_win)\n cleanup_state()\n return false\n end\n\n winid = new_winid\n bufnr = vim.api.nvim_get_current_buf()\n vim.bo[bufnr].bufhidden = \"wipe\" -- Wipe buffer when hidden (e.g., window closed)\n -- buftype=terminal is set by termopen\n\n if focus then\n -- Focus the terminal: switch to terminal window and enter insert mode\n vim.api.nvim_set_current_win(winid)\n vim.cmd(\"startinsert\")\n else\n -- Preserve user context: return to the window they were in before terminal creation\n vim.api.nvim_set_current_win(original_win)\n end\n\n if config.show_native_term_exit_tip and not tip_shown then\n vim.notify(\"Native terminal opened. Press Ctrl-\\\\ Ctrl-N to return to Normal mode.\", vim.log.levels.INFO)\n tip_shown = true\n end\n return true\nend\n\nlocal function close_terminal()\n if is_valid() then\n -- Closing the window should trigger on_exit of the job if the process is still running,\n -- which then calls cleanup_state.\n -- If the job already exited, on_exit would have cleaned up.\n -- This direct close is for user-initiated close.\n vim.api.nvim_win_close(winid, true)\n cleanup_state() -- Cleanup after explicit close\n end\nend\n\nlocal function focus_terminal()\n if is_valid() then\n vim.api.nvim_set_current_win(winid)\n vim.cmd(\"startinsert\")\n end\nend\n\nlocal function is_terminal_visible()\n -- Check if our terminal buffer exists and is displayed in any window\n if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then\n return false\n end\n\n local windows = vim.api.nvim_list_wins()\n for _, win in ipairs(windows) do\n if vim.api.nvim_win_is_valid(win) and vim.api.nvim_win_get_buf(win) == bufnr then\n -- Update our tracked window ID if we find the buffer in a different window\n winid = win\n return true\n end\n end\n\n -- Buffer exists but no window displays it\n winid = nil\n return false\nend\n\nlocal function hide_terminal()\n -- Hide the terminal window but keep the buffer and job alive\n if bufnr and vim.api.nvim_buf_is_valid(bufnr) and winid and vim.api.nvim_win_is_valid(winid) then\n -- Set buffer to hide instead of being wiped when window closes\n vim.api.nvim_buf_set_option(bufnr, \"bufhidden\", \"hide\")\n\n -- Close the window - this preserves the buffer and job\n vim.api.nvim_win_close(winid, false)\n winid = nil -- Clear window reference\n\n logger.debug(\"terminal\", \"Terminal window hidden, process preserved\")\n end\nend\n\nlocal function show_hidden_terminal(effective_config, focus)\n -- Show an existing hidden terminal buffer in a new window\n if not bufnr or not vim.api.nvim_buf_is_valid(bufnr) then\n return false\n end\n\n -- Check if it's already visible\n if is_terminal_visible() then\n if focus then\n focus_terminal()\n end\n return true\n end\n\n local original_win = vim.api.nvim_get_current_win()\n\n -- Create a new window for the existing buffer\n local width = math.floor(vim.o.columns * effective_config.split_width_percentage)\n local full_height = vim.o.lines\n local placement_modifier\n\n if effective_config.split_side == \"left\" then\n placement_modifier = \"topleft \"\n else\n placement_modifier = \"botright \"\n end\n\n vim.cmd(placement_modifier .. width .. \"vsplit\")\n local new_winid = vim.api.nvim_get_current_win()\n vim.api.nvim_win_set_height(new_winid, full_height)\n\n -- Set the existing buffer in the new window\n vim.api.nvim_win_set_buf(new_winid, bufnr)\n winid = new_winid\n\n if focus then\n -- Focus the terminal: switch to terminal window and enter insert mode\n vim.api.nvim_set_current_win(winid)\n vim.cmd(\"startinsert\")\n else\n -- Preserve user context: return to the window they were in before showing terminal\n vim.api.nvim_set_current_win(original_win)\n end\n\n logger.debug(\"terminal\", \"Showed hidden terminal in new window\")\n return true\nend\n\nlocal function find_existing_claude_terminal()\n local buffers = vim.api.nvim_list_bufs()\n for _, buf in ipairs(buffers) do\n if vim.api.nvim_buf_is_valid(buf) and vim.api.nvim_buf_get_option(buf, \"buftype\") == \"terminal\" then\n -- Check if this is a Claude Code terminal by examining the buffer name or terminal job\n local buf_name = vim.api.nvim_buf_get_name(buf)\n -- Terminal buffers often have names like \"term://...\" that include the command\n if buf_name:match(\"claude\") then\n -- Additional check: see if there's a window displaying this buffer\n local windows = vim.api.nvim_list_wins()\n for _, win in ipairs(windows) do\n if vim.api.nvim_win_get_buf(win) == buf then\n logger.debug(\"terminal\", \"Found existing Claude terminal in buffer\", buf, \"window\", win)\n return buf, win\n end\n end\n end\n end\n end\n return nil, nil\nend\n\n--- @param term_config table\nfunction M.setup(term_config)\n config = term_config or {}\nend\n\n--- @param cmd_string string\n--- @param env_table table\n--- @param effective_config table\n--- @param focus boolean|nil\nfunction M.open(cmd_string, env_table, effective_config, focus)\n focus = utils.normalize_focus(focus)\n\n if is_valid() then\n -- Check if terminal exists but is hidden (no window)\n if not winid or not vim.api.nvim_win_is_valid(winid) then\n -- Terminal is hidden, show it by calling show_hidden_terminal\n show_hidden_terminal(effective_config, focus)\n else\n -- Terminal is already visible\n if focus then\n focus_terminal()\n end\n end\n else\n -- Check if there's an existing Claude terminal we lost track of\n local existing_buf, existing_win = find_existing_claude_terminal()\n if existing_buf and existing_win then\n -- Recover the existing terminal\n bufnr = existing_buf\n winid = existing_win\n -- Note: We can't recover the job ID easily, but it's less critical\n logger.debug(\"terminal\", \"Recovered existing Claude terminal\")\n if focus then\n focus_terminal() -- Focus recovered terminal\n end\n -- If focus=false, preserve user context by staying in current window\n else\n if not open_terminal(cmd_string, env_table, effective_config, focus) then\n vim.notify(\"Failed to open Claude terminal using native fallback.\", vim.log.levels.ERROR)\n end\n end\n end\nend\n\nfunction M.close()\n close_terminal()\nend\n\n--- Simple toggle: always show/hide terminal regardless of focus\n--- @param cmd_string string\n--- @param env_table table\n--- @param effective_config table\nfunction M.simple_toggle(cmd_string, env_table, effective_config)\n -- Check if we have a valid terminal buffer (process running)\n local has_buffer = bufnr and vim.api.nvim_buf_is_valid(bufnr)\n local is_visible = has_buffer and is_terminal_visible()\n\n if is_visible then\n -- Terminal is visible, hide it (but keep process running)\n hide_terminal()\n else\n -- Terminal is not visible\n if has_buffer then\n -- Terminal process exists but is hidden, show it\n if show_hidden_terminal(effective_config, true) then\n logger.debug(\"terminal\", \"Showing hidden terminal\")\n else\n logger.error(\"terminal\", \"Failed to show hidden terminal\")\n end\n else\n -- No terminal process exists, check if there's an existing one we lost track of\n local existing_buf, existing_win = find_existing_claude_terminal()\n if existing_buf and existing_win then\n -- Recover the existing terminal\n bufnr = existing_buf\n winid = existing_win\n logger.debug(\"terminal\", \"Recovered existing Claude terminal\")\n focus_terminal()\n else\n -- No existing terminal found, create a new one\n if not open_terminal(cmd_string, env_table, effective_config) then\n vim.notify(\"Failed to open Claude terminal using native fallback (simple_toggle).\", vim.log.levels.ERROR)\n end\n end\n end\n end\nend\n\n--- Smart focus toggle: switches to terminal if not focused, hides if currently focused\n--- @param cmd_string string\n--- @param env_table table\n--- @param effective_config table\nfunction M.focus_toggle(cmd_string, env_table, effective_config)\n -- Check if we have a valid terminal buffer (process running)\n local has_buffer = bufnr and vim.api.nvim_buf_is_valid(bufnr)\n local is_visible = has_buffer and is_terminal_visible()\n\n if has_buffer then\n -- Terminal process exists\n if is_visible then\n -- Terminal is visible - check if we're currently in it\n local current_win_id = vim.api.nvim_get_current_win()\n if winid == current_win_id then\n -- We're in the terminal window, hide it (but keep process running)\n hide_terminal()\n else\n -- Terminal is visible but we're not in it, focus it\n focus_terminal()\n end\n else\n -- Terminal process exists but is hidden, show it\n if show_hidden_terminal(effective_config, true) then\n logger.debug(\"terminal\", \"Showing hidden terminal\")\n else\n logger.error(\"terminal\", \"Failed to show hidden terminal\")\n end\n end\n else\n -- No terminal process exists, check if there's an existing one we lost track of\n local existing_buf, existing_win = find_existing_claude_terminal()\n if existing_buf and existing_win then\n -- Recover the existing terminal\n bufnr = existing_buf\n winid = existing_win\n logger.debug(\"terminal\", \"Recovered existing Claude terminal\")\n\n -- Check if we're currently in this recovered terminal\n local current_win_id = vim.api.nvim_get_current_win()\n if existing_win == current_win_id then\n -- We're in the recovered terminal, hide it\n hide_terminal()\n else\n -- Focus the recovered terminal\n focus_terminal()\n end\n else\n -- No existing terminal found, create a new one\n if not open_terminal(cmd_string, env_table, effective_config) then\n vim.notify(\"Failed to open Claude terminal using native fallback (focus_toggle).\", vim.log.levels.ERROR)\n end\n end\n end\nend\n\n--- Legacy toggle function for backward compatibility (defaults to simple_toggle)\n--- @param cmd_string string\n--- @param env_table table\n--- @param effective_config table\nfunction M.toggle(cmd_string, env_table, effective_config)\n M.simple_toggle(cmd_string, env_table, effective_config)\nend\n\n--- @return number|nil\nfunction M.get_active_bufnr()\n if is_valid() then\n return bufnr\n end\n return nil\nend\n\n--- @return boolean\nfunction M.is_available()\n return true -- Native provider is always available\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/terminal.lua", "--- Module to manage a dedicated vertical split terminal for Claude Code.\n-- Supports Snacks.nvim or a native Neovim terminal fallback.\n-- @module claudecode.terminal\n\n--- @class TerminalProvider\n--- @field setup function\n--- @field open function\n--- @field close function\n--- @field toggle function\n--- @field simple_toggle function\n--- @field focus_toggle function\n--- @field get_active_bufnr function\n--- @field is_available function\n--- @field _get_terminal_for_test function\n\nlocal M = {}\n\nlocal claudecode_server_module = require(\"claudecode.server.init\")\n\nlocal config = {\n split_side = \"right\",\n split_width_percentage = 0.30,\n provider = \"auto\",\n show_native_term_exit_tip = true,\n terminal_cmd = nil,\n auto_close = true,\n}\n\n-- Lazy load providers\nlocal providers = {}\n\n--- Loads a terminal provider module\n--- @param provider_name string The name of the provider to load\n--- @return TerminalProvider|nil provider The provider module, or nil if loading failed\nlocal function load_provider(provider_name)\n if not providers[provider_name] then\n local ok, provider = pcall(require, \"claudecode.terminal.\" .. provider_name)\n if ok then\n providers[provider_name] = provider\n else\n return nil\n end\n end\n return providers[provider_name]\nend\n\n--- Gets the effective terminal provider, guaranteed to return a valid provider\n--- Falls back to native provider if configured provider is unavailable\n--- @return TerminalProvider provider The terminal provider module (never nil)\nlocal function get_provider()\n local logger = require(\"claudecode.logger\")\n\n if config.provider == \"auto\" then\n -- Try snacks first, then fallback to native silently\n local snacks_provider = load_provider(\"snacks\")\n if snacks_provider and snacks_provider.is_available() then\n return snacks_provider\n end\n -- Fall through to native provider\n elseif config.provider == \"snacks\" then\n local snacks_provider = load_provider(\"snacks\")\n if snacks_provider and snacks_provider.is_available() then\n return snacks_provider\n else\n logger.warn(\"terminal\", \"'snacks' provider configured, but Snacks.nvim not available. Falling back to 'native'.\")\n end\n elseif config.provider == \"native\" then\n -- noop, will use native provider as default below\n logger.debug(\"terminal\", \"Using native terminal provider\")\n else\n logger.warn(\"terminal\", \"Invalid provider configured: \" .. tostring(config.provider) .. \". Defaulting to 'native'.\")\n end\n\n local native_provider = load_provider(\"native\")\n if not native_provider then\n error(\"ClaudeCode: Critical error - native terminal provider failed to load\")\n end\n return native_provider\nend\n\n--- Builds the effective terminal configuration by merging defaults with overrides\n--- @param opts_override table|nil Optional overrides for terminal appearance\n--- @return table The effective terminal configuration\nlocal function build_config(opts_override)\n local effective_config = vim.deepcopy(config)\n if type(opts_override) == \"table\" then\n local validators = {\n split_side = function(val)\n return val == \"left\" or val == \"right\"\n end,\n split_width_percentage = function(val)\n return type(val) == \"number\" and val > 0 and val < 1\n end,\n }\n for key, val in pairs(opts_override) do\n if effective_config[key] ~= nil and validators[key] and validators[key](val) then\n effective_config[key] = val\n end\n end\n end\n return {\n split_side = effective_config.split_side,\n split_width_percentage = effective_config.split_width_percentage,\n auto_close = effective_config.auto_close,\n }\nend\n\n--- Checks if a terminal buffer is currently visible in any window\n--- @param bufnr number|nil The buffer number to check\n--- @return boolean True if the buffer is visible in any window, false otherwise\nlocal function is_terminal_visible(bufnr)\n if not bufnr then\n return false\n end\n\n local bufinfo = vim.fn.getbufinfo(bufnr)\n return bufinfo and #bufinfo > 0 and #bufinfo[1].windows > 0\nend\n\n--- Gets the claude command string and necessary environment variables\n--- @param cmd_args string|nil Optional arguments to append to the command\n--- @return string cmd_string The command string\n--- @return table env_table The environment variables table\nlocal function get_claude_command_and_env(cmd_args)\n -- Inline get_claude_command logic\n local cmd_from_config = config.terminal_cmd\n local base_cmd\n if not cmd_from_config or cmd_from_config == \"\" then\n base_cmd = \"claude\" -- Default if not configured\n else\n base_cmd = cmd_from_config\n end\n\n local cmd_string\n if cmd_args and cmd_args ~= \"\" then\n cmd_string = base_cmd .. \" \" .. cmd_args\n else\n cmd_string = base_cmd\n end\n\n local sse_port_value = claudecode_server_module.state.port\n local env_table = {\n ENABLE_IDE_INTEGRATION = \"true\",\n FORCE_CODE_TERMINAL = \"true\",\n }\n\n if sse_port_value then\n env_table[\"CLAUDE_CODE_SSE_PORT\"] = tostring(sse_port_value)\n end\n\n return cmd_string, env_table\nend\n\n--- Common helper to open terminal without focus if not already visible\n--- @param opts_override table|nil Optional config overrides\n--- @param cmd_args string|nil Optional command arguments\n--- @return boolean True if terminal was opened or already visible\nlocal function ensure_terminal_visible_no_focus(opts_override, cmd_args)\n local provider = get_provider()\n local active_bufnr = provider.get_active_bufnr()\n\n if is_terminal_visible(active_bufnr) then\n -- Terminal is already visible, do nothing\n return true\n end\n\n -- Terminal is not visible, open it without focus\n local effective_config = build_config(opts_override)\n local cmd_string, claude_env_table = get_claude_command_and_env(cmd_args)\n\n provider.open(cmd_string, claude_env_table, effective_config, false) -- false = don't focus\n return true\nend\n\n--- Configures the terminal module.\n-- Merges user-provided terminal configuration with defaults and sets the terminal command.\n-- @param user_term_config table (optional) Configuration options for the terminal.\n-- @field user_term_config.split_side string 'left' or 'right' (default: 'right').\n-- @field user_term_config.split_width_percentage number Percentage of screen width (0.0 to 1.0, default: 0.30).\n-- @field user_term_config.provider string 'snacks' or 'native' (default: 'snacks').\n-- @field user_term_config.show_native_term_exit_tip boolean Show tip for exiting native terminal (default: true).\n-- @param p_terminal_cmd string|nil The command to run in the terminal (from main config).\nfunction M.setup(user_term_config, p_terminal_cmd)\n if user_term_config == nil then -- Allow nil, default to empty table silently\n user_term_config = {}\n elseif type(user_term_config) ~= \"table\" then -- Warn if it's not nil AND not a table\n vim.notify(\"claudecode.terminal.setup expects a table or nil for user_term_config\", vim.log.levels.WARN)\n user_term_config = {}\n end\n\n if p_terminal_cmd == nil or type(p_terminal_cmd) == \"string\" then\n config.terminal_cmd = p_terminal_cmd\n else\n vim.notify(\n \"claudecode.terminal.setup: Invalid terminal_cmd provided: \" .. tostring(p_terminal_cmd) .. \". Using default.\",\n vim.log.levels.WARN\n )\n config.terminal_cmd = nil -- Fallback to default behavior\n end\n\n for k, v in pairs(user_term_config) do\n if config[k] ~= nil and k ~= \"terminal_cmd\" then -- terminal_cmd is handled above\n if k == \"split_side\" and (v == \"left\" or v == \"right\") then\n config[k] = v\n elseif k == \"split_width_percentage\" and type(v) == \"number\" and v > 0 and v < 1 then\n config[k] = v\n elseif k == \"provider\" and (v == \"snacks\" or v == \"native\") then\n config[k] = v\n elseif k == \"show_native_term_exit_tip\" and type(v) == \"boolean\" then\n config[k] = v\n elseif k == \"auto_close\" and type(v) == \"boolean\" then\n config[k] = v\n else\n vim.notify(\"claudecode.terminal.setup: Invalid value for \" .. k .. \": \" .. tostring(v), vim.log.levels.WARN)\n end\n elseif k ~= \"terminal_cmd\" then -- Avoid warning for terminal_cmd if passed in user_term_config\n vim.notify(\"claudecode.terminal.setup: Unknown configuration key: \" .. k, vim.log.levels.WARN)\n end\n end\n\n -- Setup providers with config\n get_provider().setup(config)\nend\n\n--- Opens or focuses the Claude terminal.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.open(opts_override, cmd_args)\n local effective_config = build_config(opts_override)\n local cmd_string, claude_env_table = get_claude_command_and_env(cmd_args)\n\n get_provider().open(cmd_string, claude_env_table, effective_config)\nend\n\n--- Closes the managed Claude terminal if it's open and valid.\nfunction M.close()\n get_provider().close()\nend\n\n--- Simple toggle: always show/hide the Claude terminal regardless of focus.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.simple_toggle(opts_override, cmd_args)\n local effective_config = build_config(opts_override)\n local cmd_string, claude_env_table = get_claude_command_and_env(cmd_args)\n\n get_provider().simple_toggle(cmd_string, claude_env_table, effective_config)\nend\n\n--- Smart focus toggle: switches to terminal if not focused, hides if currently focused.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.focus_toggle(opts_override, cmd_args)\n local effective_config = build_config(opts_override)\n local cmd_string, claude_env_table = get_claude_command_and_env(cmd_args)\n\n get_provider().focus_toggle(cmd_string, claude_env_table, effective_config)\nend\n\n--- Toggle open terminal without focus if not already visible, otherwise do nothing.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.toggle_open_no_focus(opts_override, cmd_args)\n ensure_terminal_visible_no_focus(opts_override, cmd_args)\nend\n\n--- Ensures terminal is visible without changing focus. Creates if necessary, shows if hidden.\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.ensure_visible(opts_override, cmd_args)\n ensure_terminal_visible_no_focus(opts_override, cmd_args)\nend\n\n--- Toggles the Claude terminal open or closed (legacy function - use simple_toggle or focus_toggle).\n-- @param opts_override table (optional) Overrides for terminal appearance (split_side, split_width_percentage).\n-- @param cmd_args string|nil (optional) Arguments to append to the claude command.\nfunction M.toggle(opts_override, cmd_args)\n -- Default to simple toggle for backward compatibility\n M.simple_toggle(opts_override, cmd_args)\nend\n\n--- Gets the buffer number of the currently active Claude Code terminal.\n-- This checks both Snacks and native fallback terminals.\n-- @return number|nil The buffer number if an active terminal is found, otherwise nil.\nfunction M.get_active_terminal_bufnr()\n return get_provider().get_active_bufnr()\nend\n\n--- Gets the managed terminal instance for testing purposes.\n-- NOTE: This function is intended for use in tests to inspect internal state.\n-- The underscore prefix indicates it's not part of the public API for regular use.\n-- @return snacks.terminal|nil The managed Snacks terminal instance, or nil.\nfunction M._get_managed_terminal_for_test()\n local snacks_provider = load_provider(\"snacks\")\n if snacks_provider and snacks_provider._get_terminal_for_test then\n return snacks_provider._get_terminal_for_test()\n end\n return nil\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/init.lua", "---@brief [[\n--- Claude Code Neovim Integration\n--- This plugin integrates Claude Code CLI with Neovim, enabling\n--- seamless AI-assisted coding experiences directly in Neovim.\n---@brief ]]\n\n--- @module 'claudecode'\nlocal M = {}\n\nlocal logger = require(\"claudecode.logger\")\n\n--- @class ClaudeCode.Version\n--- @field major integer Major version number\n--- @field minor integer Minor version number\n--- @field patch integer Patch version number\n--- @field prerelease string|nil Prerelease identifier (e.g., \"alpha\", \"beta\")\n--- @field string fun(self: ClaudeCode.Version):string Returns the formatted version string\n\n--- The current version of the plugin.\n--- @type ClaudeCode.Version\nM.version = {\n major = 0,\n minor = 2,\n patch = 0,\n prerelease = nil,\n string = function(self)\n local version = string.format(\"%d.%d.%d\", self.major, self.minor, self.patch)\n if self.prerelease then\n version = version .. \"-\" .. self.prerelease\n end\n return version\n end,\n}\n\n--- @class ClaudeCode.Config\n--- @field port_range {min: integer, max: integer} Port range for WebSocket server.\n--- @field auto_start boolean Auto-start WebSocket server on Neovim startup.\n--- @field terminal_cmd string|nil Custom terminal command to use when launching Claude.\n--- @field log_level \"trace\"|\"debug\"|\"info\"|\"warn\"|\"error\" Log level.\n--- @field track_selection boolean Enable sending selection updates to Claude.\n--- @field visual_demotion_delay_ms number Milliseconds to wait before demoting a visual selection.\n--- @field connection_wait_delay number Milliseconds to wait after connection before sending queued @ mentions.\n--- @field connection_timeout number Maximum time to wait for Claude Code to connect (milliseconds).\n--- @field queue_timeout number Maximum time to keep @ mentions in queue (milliseconds).\n--- @field diff_opts { auto_close_on_accept: boolean, show_diff_stats: boolean, vertical_split: boolean, open_in_current_tab: boolean } Options for the diff provider.\n\n--- @type ClaudeCode.Config\nlocal default_config = {\n port_range = { min = 10000, max = 65535 },\n auto_start = true,\n terminal_cmd = nil,\n log_level = \"info\",\n track_selection = true,\n visual_demotion_delay_ms = 50, -- Reduced from 200ms for better responsiveness in tree navigation\n connection_wait_delay = 200, -- Milliseconds to wait after connection before sending queued @ mentions\n connection_timeout = 10000, -- Maximum time to wait for Claude Code to connect (milliseconds)\n queue_timeout = 5000, -- Maximum time to keep @ mentions in queue (milliseconds)\n diff_opts = {\n auto_close_on_accept = true,\n show_diff_stats = true,\n vertical_split = true,\n open_in_current_tab = false,\n },\n}\n\n--- @class ClaudeCode.State\n--- @field config ClaudeCode.Config The current plugin configuration.\n--- @field server table|nil The WebSocket server instance.\n--- @field port number|nil The port the server is running on.\n--- @field auth_token string|nil The authentication token for the current session.\n--- @field initialized boolean Whether the plugin has been initialized.\n--- @field queued_mentions table[] Array of queued @ mentions waiting for connection.\n--- @field connection_timer table|nil Timer for connection timeout.\n\n--- @type ClaudeCode.State\nM.state = {\n config = vim.deepcopy(default_config),\n server = nil,\n port = nil,\n auth_token = nil,\n initialized = false,\n queued_mentions = {},\n connection_timer = nil,\n}\n\n---@alias ClaudeCode.TerminalOpts { \\\n--- split_side?: \"left\"|\"right\", \\\n--- split_width_percentage?: number, \\\n--- provider?: \"auto\"|\"snacks\"|\"native\", \\\n--- show_native_term_exit_tip?: boolean }\n---\n---@alias ClaudeCode.SetupOpts { \\\n--- terminal?: ClaudeCode.TerminalOpts }\n\n---@brief Check if Claude Code is connected to WebSocket server\n---@return boolean connected Whether Claude Code has active connections\nfunction M.is_claude_connected()\n if not M.state.server then\n return false\n end\n\n local server_module = require(\"claudecode.server.init\")\n local status = server_module.get_status()\n return status.running and status.client_count > 0\nend\n\n---@brief Clear the @ mention queue and stop timers\nlocal function clear_mention_queue()\n if #M.state.queued_mentions > 0 then\n logger.debug(\"queue\", \"Clearing \" .. #M.state.queued_mentions .. \" queued @ mentions\")\n end\n\n M.state.queued_mentions = {}\n\n if M.state.connection_timer then\n M.state.connection_timer:stop()\n M.state.connection_timer:close()\n M.state.connection_timer = nil\n end\nend\n\n---@brief Add @ mention to queue for later sending\n---@param mention_data table The @ mention data to queue\nlocal function queue_at_mention(mention_data)\n mention_data.timestamp = vim.loop.now()\n table.insert(M.state.queued_mentions, mention_data)\n\n logger.debug(\"queue\", \"Queued @ mention: \" .. vim.inspect(mention_data))\n\n -- Start connection timer if not already running\n if not M.state.connection_timer then\n M.state.connection_timer = vim.loop.new_timer()\n M.state.connection_timer:start(M.state.config.connection_timeout, 0, function()\n vim.schedule(function()\n if #M.state.queued_mentions > 0 then\n logger.error(\"queue\", \"Connection timeout - clearing \" .. #M.state.queued_mentions .. \" queued @ mentions\")\n clear_mention_queue()\n end\n end)\n end)\n end\nend\n\n---@brief Process queued @ mentions after connection established\nfunction M._process_queued_mentions()\n if #M.state.queued_mentions == 0 then\n return\n end\n\n logger.debug(\"queue\", \"Processing \" .. #M.state.queued_mentions .. \" queued @ mentions\")\n\n -- Stop connection timer\n if M.state.connection_timer then\n M.state.connection_timer:stop()\n M.state.connection_timer:close()\n M.state.connection_timer = nil\n end\n\n -- Wait for connection_wait_delay before sending\n vim.defer_fn(function()\n local mentions_to_send = vim.deepcopy(M.state.queued_mentions)\n M.state.queued_mentions = {} -- Clear queue\n\n if #mentions_to_send == 0 then\n return\n end\n\n -- Ensure terminal is visible when processing queued mentions\n local terminal = require(\"claudecode.terminal\")\n terminal.ensure_visible()\n\n local success_count = 0\n local total_count = #mentions_to_send\n local delay = 10 -- Use same delay as existing batch operations\n\n local function send_mentions_sequentially(index)\n if index > total_count then\n if success_count > 0 then\n local message = success_count == 1 and \"Sent 1 queued @ mention to Claude Code\"\n or string.format(\"Sent %d queued @ mentions to Claude Code\", success_count)\n logger.debug(\"queue\", message)\n end\n return\n end\n\n local mention = mentions_to_send[index]\n local now = vim.loop.now()\n\n -- Check if mention hasn't expired\n if (now - mention.timestamp) < M.state.config.queue_timeout then\n local success, error_msg = M._broadcast_at_mention(mention.file_path, mention.start_line, mention.end_line)\n if success then\n success_count = success_count + 1\n else\n logger.error(\"queue\", \"Failed to send queued @ mention: \" .. (error_msg or \"unknown error\"))\n end\n else\n logger.debug(\"queue\", \"Skipped expired @ mention: \" .. mention.file_path)\n end\n\n -- Send next mention with delay\n if index < total_count then\n vim.defer_fn(function()\n send_mentions_sequentially(index + 1)\n end, delay)\n else\n -- Final summary\n if success_count > 0 then\n local message = success_count == 1 and \"Sent 1 queued @ mention to Claude Code\"\n or string.format(\"Sent %d queued @ mentions to Claude Code\", success_count)\n logger.debug(\"queue\", message)\n end\n end\n end\n\n send_mentions_sequentially(1)\n end, M.state.config.connection_wait_delay)\nend\n\n---@brief Show terminal if Claude is connected and it's not already visible\n---@return boolean success Whether terminal was shown or was already visible\nfunction M._ensure_terminal_visible_if_connected()\n if not M.is_claude_connected() then\n return false\n end\n\n local terminal = require(\"claudecode.terminal\")\n local active_bufnr = terminal.get_active_terminal_bufnr and terminal.get_active_terminal_bufnr()\n\n if not active_bufnr then\n return false\n end\n\n local bufinfo = vim.fn.getbufinfo(active_bufnr)[1]\n local is_visible = bufinfo and #bufinfo.windows > 0\n\n if not is_visible then\n terminal.simple_toggle()\n end\n\n return true\nend\n\n---@brief Send @ mention to Claude Code, handling connection state automatically\n---@param file_path string The file path to send\n---@param start_line number|nil Start line (0-indexed for Claude)\n---@param end_line number|nil End line (0-indexed for Claude)\n---@param context string|nil Context for logging\n---@return boolean success Whether the operation was successful\n---@return string|nil error Error message if failed\nfunction M.send_at_mention(file_path, start_line, end_line, context)\n context = context or \"command\"\n\n if not M.state.server then\n logger.error(context, \"Claude Code integration is not running\")\n return false, \"Claude Code integration is not running\"\n end\n\n -- Check if Claude Code is connected\n if M.is_claude_connected() then\n -- Claude is connected, send immediately and ensure terminal is visible\n local success, error_msg = M._broadcast_at_mention(file_path, start_line, end_line)\n if success then\n local terminal = require(\"claudecode.terminal\")\n terminal.ensure_visible()\n end\n return success, error_msg\n else\n -- Claude not connected, queue the mention and launch terminal\n local mention_data = {\n file_path = file_path,\n start_line = start_line,\n end_line = end_line,\n context = context,\n }\n\n queue_at_mention(mention_data)\n\n -- Launch terminal with Claude Code\n local terminal = require(\"claudecode.terminal\")\n terminal.open()\n\n logger.debug(context, \"Queued @ mention and launched Claude Code: \" .. file_path)\n\n return true, nil\n end\nend\n\n---\n--- Set up the plugin with user configuration\n---@param opts ClaudeCode.SetupOpts|nil Optional configuration table to override defaults.\n---@return table The plugin module\nfunction M.setup(opts)\n opts = opts or {}\n\n local terminal_opts = nil\n if opts.terminal then\n terminal_opts = opts.terminal\n opts.terminal = nil -- Remove from main opts to avoid polluting M.state.config\n end\n\n local config = require(\"claudecode.config\")\n M.state.config = config.apply(opts)\n -- vim.g.claudecode_user_config is no longer needed as config values are passed directly.\n\n logger.setup(M.state.config)\n\n -- Setup terminal module: always try to call setup to pass terminal_cmd,\n -- even if terminal_opts (for split_side etc.) are not provided.\n local terminal_setup_ok, terminal_module = pcall(require, \"claudecode.terminal\")\n if terminal_setup_ok then\n -- Guard in case tests or user replace the module with a minimal stub without `setup`.\n if type(terminal_module.setup) == \"function\" then\n -- terminal_opts might be nil, which the setup function should handle gracefully.\n terminal_module.setup(terminal_opts, M.state.config.terminal_cmd)\n end\n else\n logger.error(\"init\", \"Failed to load claudecode.terminal module for setup.\")\n end\n\n local diff = require(\"claudecode.diff\")\n diff.setup(M.state.config)\n\n if M.state.config.auto_start then\n M.start(false) -- Suppress notification on auto-start\n end\n\n M._create_commands()\n\n vim.api.nvim_create_autocmd(\"VimLeavePre\", {\n group = vim.api.nvim_create_augroup(\"ClaudeCodeShutdown\", { clear = true }),\n callback = function()\n if M.state.server then\n M.stop()\n else\n -- Clear queue even if server isn't running\n clear_mention_queue()\n end\n end,\n desc = \"Automatically stop Claude Code integration when exiting Neovim\",\n })\n\n M.state.initialized = true\n return M\nend\n\n--- Start the Claude Code integration\n---@param show_startup_notification? boolean Whether to show a notification upon successful startup (defaults to true)\n---@return boolean success Whether the operation was successful\n---@return number|string port_or_error The WebSocket port if successful, or error message if failed\nfunction M.start(show_startup_notification)\n if show_startup_notification == nil then\n show_startup_notification = true\n end\n if M.state.server then\n local msg = \"Claude Code integration is already running on port \" .. tostring(M.state.port)\n logger.warn(\"init\", msg)\n return false, \"Already running\"\n end\n\n local server = require(\"claudecode.server.init\")\n local lockfile = require(\"claudecode.lockfile\")\n\n -- Generate auth token first so we can pass it to the server\n local auth_token\n local auth_success, auth_result = pcall(function()\n return lockfile.generate_auth_token()\n end)\n\n if not auth_success then\n local error_msg = \"Failed to generate authentication token: \" .. (auth_result or \"unknown error\")\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n auth_token = auth_result\n\n -- Validate the generated auth token\n if not auth_token or type(auth_token) ~= \"string\" or #auth_token < 10 then\n local error_msg = \"Invalid authentication token generated\"\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n local success, result = server.start(M.state.config, auth_token)\n\n if not success then\n local error_msg = \"Failed to start Claude Code server: \" .. (result or \"unknown error\")\n if result and result:find(\"auth\") then\n error_msg = error_msg .. \" (authentication related)\"\n end\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n M.state.server = server\n M.state.port = tonumber(result)\n M.state.auth_token = auth_token\n\n local lock_success, lock_result, returned_auth_token = lockfile.create(M.state.port, auth_token)\n\n if not lock_success then\n server.stop()\n M.state.server = nil\n M.state.port = nil\n M.state.auth_token = nil\n\n local error_msg = \"Failed to create lock file: \" .. (lock_result or \"unknown error\")\n if lock_result and lock_result:find(\"auth\") then\n error_msg = error_msg .. \" (authentication token issue)\"\n end\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n -- Verify that the auth token in the lock file matches what we generated\n if returned_auth_token ~= auth_token then\n server.stop()\n M.state.server = nil\n M.state.port = nil\n M.state.auth_token = nil\n\n local error_msg = \"Authentication token mismatch between server and lock file\"\n logger.error(\"init\", error_msg)\n return false, error_msg\n end\n\n if M.state.config.track_selection then\n local selection = require(\"claudecode.selection\")\n selection.enable(M.state.server, M.state.config.visual_demotion_delay_ms)\n end\n\n if show_startup_notification then\n logger.info(\"init\", \"Claude Code integration started on port \" .. tostring(M.state.port))\n end\n\n return true, M.state.port\nend\n\n--- Stop the Claude Code integration\n---@return boolean success Whether the operation was successful\n---@return string? error Error message if operation failed\nfunction M.stop()\n if not M.state.server then\n logger.warn(\"init\", \"Claude Code integration is not running\")\n return false, \"Not running\"\n end\n\n local lockfile = require(\"claudecode.lockfile\")\n local lock_success, lock_error = lockfile.remove(M.state.port)\n\n if not lock_success then\n logger.warn(\"init\", \"Failed to remove lock file: \" .. lock_error)\n -- Continue with shutdown even if lock file removal fails\n end\n\n if M.state.config.track_selection then\n local selection = require(\"claudecode.selection\")\n selection.disable()\n end\n\n local success, error = M.state.server.stop()\n\n if not success then\n logger.error(\"init\", \"Failed to stop Claude Code integration: \" .. error)\n return false, error\n end\n\n M.state.server = nil\n M.state.port = nil\n M.state.auth_token = nil\n\n -- Clear any queued @ mentions when server stops\n clear_mention_queue()\n\n logger.info(\"init\", \"Claude Code integration stopped\")\n\n return true\nend\n\n--- Set up user commands\n---@private\nfunction M._create_commands()\n vim.api.nvim_create_user_command(\"ClaudeCodeStart\", function()\n M.start()\n end, {\n desc = \"Start Claude Code integration\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeStop\", function()\n M.stop()\n end, {\n desc = \"Stop Claude Code integration\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeStatus\", function()\n if M.state.server and M.state.port then\n logger.info(\"command\", \"Claude Code integration is running on port \" .. tostring(M.state.port))\n else\n logger.info(\"command\", \"Claude Code integration is not running\")\n end\n end, {\n desc = \"Show Claude Code integration status\",\n })\n\n ---@param file_paths table List of file paths to add\n ---@param options table|nil Optional settings: { delay?: number, show_summary?: boolean, context?: string }\n ---@return number success_count Number of successfully added files\n ---@return number total_count Total number of files attempted\n local function add_paths_to_claude(file_paths, options)\n options = options or {}\n local delay = options.delay or 0\n local show_summary = options.show_summary ~= false\n local context = options.context or \"command\"\n\n if not file_paths or #file_paths == 0 then\n return 0, 0\n end\n\n local success_count = 0\n local total_count = #file_paths\n\n if delay > 0 then\n local function send_files_sequentially(index)\n if index > total_count then\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n return\n end\n\n local file_path = file_paths[index]\n local success, error_msg = M.send_at_mention(file_path, nil, nil, context)\n if success then\n success_count = success_count + 1\n else\n logger.error(context, \"Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\"))\n end\n\n if index < total_count then\n vim.defer_fn(function()\n send_files_sequentially(index + 1)\n end, delay)\n else\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n end\n end\n\n send_files_sequentially(1)\n else\n for _, file_path in ipairs(file_paths) do\n local success, error_msg = M.send_at_mention(file_path, nil, nil, context)\n if success then\n success_count = success_count + 1\n else\n logger.error(context, \"Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\"))\n end\n end\n\n if show_summary and success_count > 0 then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n logger.debug(context, message)\n end\n end\n\n return success_count, total_count\n end\n\n local function handle_send_normal(opts)\n local current_ft = (vim.bo and vim.bo.filetype) or \"\"\n local current_bufname = (vim.api and vim.api.nvim_buf_get_name and vim.api.nvim_buf_get_name(0)) or \"\"\n\n local is_tree_buffer = current_ft == \"NvimTree\"\n or current_ft == \"neo-tree\"\n or current_ft == \"oil\"\n or string.match(current_bufname, \"neo%-tree\")\n or string.match(current_bufname, \"NvimTree\")\n\n if is_tree_buffer then\n local integrations = require(\"claudecode.integrations\")\n local files, error = integrations.get_selected_files_from_tree()\n\n if error then\n logger.error(\"command\", \"ClaudeCodeSend->TreeAdd: \" .. error)\n return\n end\n\n if not files or #files == 0 then\n logger.warn(\"command\", \"ClaudeCodeSend->TreeAdd: No files selected\")\n return\n end\n\n add_paths_to_claude(files, { context = \"ClaudeCodeSend->TreeAdd\" })\n\n return\n end\n\n local selection_module_ok, selection_module = pcall(require, \"claudecode.selection\")\n if selection_module_ok then\n -- Pass range information if available (for :'<,'> commands)\n local line1, line2 = nil, nil\n if opts and opts.range and opts.range > 0 then\n line1, line2 = opts.line1, opts.line2\n end\n local sent_successfully = selection_module.send_at_mention_for_visual_selection(line1, line2)\n if sent_successfully then\n -- Exit any potential visual mode (for consistency)\n pcall(function()\n if vim.api and vim.api.nvim_feedkeys then\n local esc = vim.api.nvim_replace_termcodes(\"\", true, false, true)\n vim.api.nvim_feedkeys(esc, \"i\", true)\n end\n end)\n end\n else\n logger.error(\"command\", \"ClaudeCodeSend: Failed to load selection module.\")\n end\n end\n\n local function handle_send_visual(visual_data, _opts)\n -- Try tree file selection first\n if visual_data then\n local visual_commands = require(\"claudecode.visual_commands\")\n local files, error = visual_commands.get_files_from_visual_selection(visual_data)\n\n if not error and files and #files > 0 then\n local success_count = add_paths_to_claude(files, {\n delay = 10,\n context = \"ClaudeCodeSend_visual\",\n show_summary = false,\n })\n if success_count > 0 then\n local message = success_count == 1 and \"Added 1 file to Claude context from visual selection\"\n or string.format(\"Added %d files to Claude context from visual selection\", success_count)\n logger.debug(\"command\", message)\n end\n return\n end\n end\n\n -- Handle regular text selection using range from visual mode\n local selection_module_ok, selection_module = pcall(require, \"claudecode.selection\")\n if not selection_module_ok then\n return\n end\n\n -- Use the marks left by visual mode instead of trying to get current visual selection\n local line1, line2 = vim.fn.line(\"'<\"), vim.fn.line(\"'>\")\n if line1 and line2 and line1 > 0 and line2 > 0 then\n selection_module.send_at_mention_for_visual_selection(line1, line2)\n else\n selection_module.send_at_mention_for_visual_selection()\n end\n end\n\n local visual_commands = require(\"claudecode.visual_commands\")\n local unified_send_handler = visual_commands.create_visual_command_wrapper(handle_send_normal, handle_send_visual)\n\n vim.api.nvim_create_user_command(\"ClaudeCodeSend\", unified_send_handler, {\n desc = \"Send current visual selection as an at_mention to Claude Code (supports tree visual selection)\",\n range = true,\n })\n\n local function handle_tree_add_normal()\n if not M.state.server then\n logger.error(\"command\", \"ClaudeCodeTreeAdd: Claude Code integration is not running.\")\n return\n end\n\n local integrations = require(\"claudecode.integrations\")\n local files, error = integrations.get_selected_files_from_tree()\n\n if error then\n logger.error(\"command\", \"ClaudeCodeTreeAdd: \" .. error)\n return\n end\n\n if not files or #files == 0 then\n logger.warn(\"command\", \"ClaudeCodeTreeAdd: No files selected\")\n return\n end\n\n -- Use connection-aware broadcasting for each file\n local success_count = 0\n local total_count = #files\n\n for _, file_path in ipairs(files) do\n local success, error_msg = M.send_at_mention(file_path, nil, nil, \"ClaudeCodeTreeAdd\")\n if success then\n success_count = success_count + 1\n else\n logger.error(\n \"command\",\n \"ClaudeCodeTreeAdd: Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\")\n )\n end\n end\n\n if success_count == 0 then\n logger.error(\"command\", \"ClaudeCodeTreeAdd: Failed to add any files\")\n elseif success_count < total_count then\n local message = string.format(\"Added %d/%d files to Claude context\", success_count, total_count)\n logger.debug(\"command\", message)\n else\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n logger.debug(\"command\", message)\n end\n end\n\n local function handle_tree_add_visual(visual_data)\n if not M.state.server then\n logger.error(\"command\", \"ClaudeCodeTreeAdd_visual: Claude Code integration is not running.\")\n return\n end\n\n local visual_cmd_module = require(\"claudecode.visual_commands\")\n local files, error = visual_cmd_module.get_files_from_visual_selection(visual_data)\n\n if error then\n logger.error(\"command\", \"ClaudeCodeTreeAdd_visual: \" .. error)\n return\n end\n\n if not files or #files == 0 then\n logger.warn(\"command\", \"ClaudeCodeTreeAdd_visual: No files selected in visual range\")\n return\n end\n\n -- Use connection-aware broadcasting for each file\n local success_count = 0\n local total_count = #files\n\n for _, file_path in ipairs(files) do\n local success, error_msg = M.send_at_mention(file_path, nil, nil, \"ClaudeCodeTreeAdd_visual\")\n if success then\n success_count = success_count + 1\n else\n logger.error(\n \"command\",\n \"ClaudeCodeTreeAdd_visual: Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\")\n )\n end\n end\n\n if success_count > 0 then\n local message = success_count == 1 and \"Added 1 file to Claude context from visual selection\"\n or string.format(\"Added %d files to Claude context from visual selection\", success_count)\n logger.debug(\"command\", message)\n\n if success_count < total_count then\n logger.warn(\"command\", string.format(\"Added %d/%d files from visual selection\", success_count, total_count))\n end\n else\n logger.error(\"command\", \"ClaudeCodeTreeAdd_visual: Failed to add any files from visual selection\")\n end\n end\n\n local unified_tree_add_handler =\n visual_commands.create_visual_command_wrapper(handle_tree_add_normal, handle_tree_add_visual)\n\n vim.api.nvim_create_user_command(\"ClaudeCodeTreeAdd\", unified_tree_add_handler, {\n desc = \"Add selected file(s) from tree explorer to Claude Code context (supports visual selection)\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeAdd\", function(opts)\n if not M.state.server then\n logger.error(\"command\", \"ClaudeCodeAdd: Claude Code integration is not running.\")\n return\n end\n\n if not opts.args or opts.args == \"\" then\n logger.error(\"command\", \"ClaudeCodeAdd: No file path provided\")\n return\n end\n\n local args = vim.split(opts.args, \"%s+\")\n local file_path = args[1]\n local start_line = args[2] and tonumber(args[2]) or nil\n local end_line = args[3] and tonumber(args[3]) or nil\n\n if #args > 3 then\n logger.error(\n \"command\",\n \"ClaudeCodeAdd: Too many arguments. Usage: ClaudeCodeAdd [start-line] [end-line]\"\n )\n return\n end\n\n if args[2] and not start_line then\n logger.error(\"command\", \"ClaudeCodeAdd: Invalid start line number: \" .. args[2])\n return\n end\n\n if args[3] and not end_line then\n logger.error(\"command\", \"ClaudeCodeAdd: Invalid end line number: \" .. args[3])\n return\n end\n\n if start_line and start_line < 1 then\n logger.error(\"command\", \"ClaudeCodeAdd: Start line must be positive: \" .. start_line)\n return\n end\n\n if end_line and end_line < 1 then\n logger.error(\"command\", \"ClaudeCodeAdd: End line must be positive: \" .. end_line)\n return\n end\n\n if start_line and end_line and start_line > end_line then\n logger.error(\n \"command\",\n \"ClaudeCodeAdd: Start line (\" .. start_line .. \") must be <= end line (\" .. end_line .. \")\"\n )\n return\n end\n\n file_path = vim.fn.expand(file_path)\n if vim.fn.filereadable(file_path) == 0 and vim.fn.isdirectory(file_path) == 0 then\n logger.error(\"command\", \"ClaudeCodeAdd: File or directory does not exist: \" .. file_path)\n return\n end\n\n local claude_start_line = start_line and (start_line - 1) or nil\n local claude_end_line = end_line and (end_line - 1) or nil\n\n local success, error_msg = M.send_at_mention(file_path, claude_start_line, claude_end_line, \"ClaudeCodeAdd\")\n if not success then\n logger.error(\"command\", \"ClaudeCodeAdd: \" .. (error_msg or \"Failed to add file\"))\n else\n local message = \"ClaudeCodeAdd: Successfully added \" .. file_path\n if start_line or end_line then\n if start_line and end_line then\n message = message .. \" (lines \" .. start_line .. \"-\" .. end_line .. \")\"\n elseif start_line then\n message = message .. \" (from line \" .. start_line .. \")\"\n end\n end\n logger.debug(\"command\", message)\n end\n end, {\n nargs = \"+\",\n complete = \"file\",\n desc = \"Add specified file or directory to Claude Code context with optional line range\",\n })\n\n local terminal_ok, terminal = pcall(require, \"claudecode.terminal\")\n if terminal_ok then\n vim.api.nvim_create_user_command(\"ClaudeCode\", function(opts)\n local current_mode = vim.fn.mode()\n if current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\22\" then\n vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(\"\", true, false, true), \"n\", false)\n end\n local cmd_args = opts.args and opts.args ~= \"\" and opts.args or nil\n terminal.simple_toggle({}, cmd_args)\n end, {\n nargs = \"*\",\n desc = \"Toggle the Claude Code terminal window (simple show/hide) with optional arguments\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeFocus\", function(opts)\n local current_mode = vim.fn.mode()\n if current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\22\" then\n vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(\"\", true, false, true), \"n\", false)\n end\n local cmd_args = opts.args and opts.args ~= \"\" and opts.args or nil\n terminal.focus_toggle({}, cmd_args)\n end, {\n nargs = \"*\",\n desc = \"Smart focus/toggle Claude Code terminal (switches to terminal if not focused, hides if focused)\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeOpen\", function(opts)\n local cmd_args = opts.args and opts.args ~= \"\" and opts.args or nil\n terminal.open({}, cmd_args)\n end, {\n nargs = \"*\",\n desc = \"Open the Claude Code terminal window with optional arguments\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeClose\", function()\n terminal.close()\n end, {\n desc = \"Close the Claude Code terminal window\",\n })\n else\n logger.error(\n \"init\",\n \"Terminal module not found. Terminal commands (ClaudeCode, ClaudeCodeOpen, ClaudeCodeClose) not registered.\"\n )\n end\n\n -- Diff management commands\n vim.api.nvim_create_user_command(\"ClaudeCodeDiffAccept\", function()\n local diff = require(\"claudecode.diff\")\n diff.accept_current_diff()\n end, {\n desc = \"Accept the current diff changes\",\n })\n\n vim.api.nvim_create_user_command(\"ClaudeCodeDiffDeny\", function()\n local diff = require(\"claudecode.diff\")\n diff.deny_current_diff()\n end, {\n desc = \"Deny/reject the current diff changes\",\n })\nend\n\n--- Get version information\n---@return table Version information\nfunction M.get_version()\n return {\n version = M.version:string(),\n major = M.version.major,\n minor = M.version.minor,\n patch = M.version.patch,\n prerelease = M.version.prerelease,\n }\nend\n\n--- Format file path for at mention (exposed for testing)\n---@param file_path string The file path to format\n---@return string formatted_path The formatted path\n---@return boolean is_directory Whether the path is a directory\nfunction M._format_path_for_at_mention(file_path)\n -- Input validation\n if not file_path or type(file_path) ~= \"string\" or file_path == \"\" then\n error(\"format_path_for_at_mention: file_path must be a non-empty string\")\n end\n\n -- Only check path existence in production (not tests)\n -- This allows tests to work with mock paths while still providing validation in real usage\n if not package.loaded[\"busted\"] then\n if vim.fn.filereadable(file_path) == 0 and vim.fn.isdirectory(file_path) == 0 then\n error(\"format_path_for_at_mention: path does not exist: \" .. file_path)\n end\n end\n\n local is_directory = vim.fn.isdirectory(file_path) == 1\n local formatted_path = file_path\n\n if is_directory then\n local cwd = vim.fn.getcwd()\n if string.find(file_path, cwd, 1, true) == 1 then\n local relative_path = string.sub(file_path, #cwd + 2)\n if relative_path ~= \"\" then\n formatted_path = relative_path\n else\n formatted_path = \"./\"\n end\n end\n if not string.match(formatted_path, \"/$\") then\n formatted_path = formatted_path .. \"/\"\n end\n else\n local cwd = vim.fn.getcwd()\n if string.find(file_path, cwd, 1, true) == 1 then\n local relative_path = string.sub(file_path, #cwd + 2)\n if relative_path ~= \"\" then\n formatted_path = relative_path\n end\n end\n end\n\n return formatted_path, is_directory\nend\n\n-- Test helper functions (exposed for testing)\nfunction M._broadcast_at_mention(file_path, start_line, end_line)\n if not M.state.server then\n return false, \"Claude Code integration is not running\"\n end\n\n -- Safely format the path and handle validation errors\n local formatted_path, is_directory\n local format_success, format_result, is_dir_result = pcall(M._format_path_for_at_mention, file_path)\n if not format_success then\n return false, format_result -- format_result contains the error message\n end\n formatted_path, is_directory = format_result, is_dir_result\n\n if is_directory and (start_line or end_line) then\n logger.debug(\"command\", \"Line numbers ignored for directory: \" .. formatted_path)\n start_line = nil\n end_line = nil\n end\n\n local params = {\n filePath = formatted_path,\n lineStart = start_line,\n lineEnd = end_line,\n }\n\n local broadcast_success = M.state.server.broadcast(\"at_mentioned\", params)\n if broadcast_success then\n return true, nil\n else\n local error_msg = \"Failed to broadcast \" .. (is_directory and \"directory\" or \"file\") .. \" \" .. formatted_path\n logger.error(\"command\", error_msg)\n return false, error_msg\n end\nend\n\nfunction M._add_paths_to_claude(file_paths, options)\n options = options or {}\n local delay = options.delay or 0\n local show_summary = options.show_summary ~= false\n local context = options.context or \"command\"\n local batch_size = options.batch_size or 10\n local max_files = options.max_files or 100\n\n if not file_paths or #file_paths == 0 then\n return 0, 0\n end\n\n if #file_paths > max_files then\n logger.warn(context, string.format(\"Too many files selected (%d), limiting to %d\", #file_paths, max_files))\n local limited_paths = {}\n for i = 1, max_files do\n limited_paths[i] = file_paths[i]\n end\n file_paths = limited_paths\n end\n\n local success_count = 0\n local total_count = #file_paths\n\n if delay > 0 then\n local function send_batch(start_index)\n if start_index > total_count then\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n return\n end\n\n -- Process a batch of files\n local end_index = math.min(start_index + batch_size - 1, total_count)\n local batch_success = 0\n\n for i = start_index, end_index do\n local file_path = file_paths[i]\n local success, error_msg = M._broadcast_at_mention(file_path)\n if success then\n success_count = success_count + 1\n batch_success = batch_success + 1\n else\n logger.error(context, \"Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\"))\n end\n end\n\n logger.debug(\n context,\n string.format(\n \"Processed batch %d-%d: %d/%d successful\",\n start_index,\n end_index,\n batch_success,\n end_index - start_index + 1\n )\n )\n\n if end_index < total_count then\n vim.defer_fn(function()\n send_batch(end_index + 1)\n end, delay)\n else\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n end\n end\n\n send_batch(1)\n else\n local progress_interval = math.max(1, math.floor(total_count / 10))\n\n for i, file_path in ipairs(file_paths) do\n local success, error_msg = M._broadcast_at_mention(file_path)\n if success then\n success_count = success_count + 1\n else\n logger.error(context, \"Failed to add file: \" .. file_path .. \" - \" .. (error_msg or \"unknown error\"))\n end\n\n if total_count > 20 and i % progress_interval == 0 then\n logger.debug(\n context,\n string.format(\"Progress: %d/%d files processed (%d successful)\", i, total_count, success_count)\n )\n end\n end\n\n if show_summary then\n local message = success_count == 1 and \"Added 1 file to Claude context\"\n or string.format(\"Added %d files to Claude context\", success_count)\n if total_count > success_count then\n message = message .. string.format(\" (%d failed)\", total_count - success_count)\n end\n\n if total_count > success_count then\n if success_count > 0 then\n logger.warn(context, message)\n else\n logger.error(context, message)\n end\n elseif success_count > 0 then\n logger.info(context, message)\n else\n logger.debug(context, message)\n end\n end\n end\n\n return success_count, total_count\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/diff.lua", "--- Diff module for Claude Code Neovim integration.\n-- Provides native Neovim diff functionality with MCP-compliant blocking operations and state management.\nlocal M = {}\n\nlocal logger = require(\"claudecode.logger\")\n\n-- Global state management for active diffs\nlocal active_diffs = {}\nlocal autocmd_group\n\n--- Get or create the autocmd group\nlocal function get_autocmd_group()\n if not autocmd_group then\n autocmd_group = vim.api.nvim_create_augroup(\"ClaudeCodeMCPDiff\", { clear = true })\n end\n return autocmd_group\nend\n\n--- Find a suitable main editor window to open diffs in.\n-- Excludes terminals, sidebars, and floating windows.\n-- @return number|nil Window ID of the main editor window, or nil if not found\nlocal function find_main_editor_window()\n local windows = vim.api.nvim_list_wins()\n\n for _, win in ipairs(windows) do\n local buf = vim.api.nvim_win_get_buf(win)\n local buftype = vim.api.nvim_buf_get_option(buf, \"buftype\")\n local filetype = vim.api.nvim_buf_get_option(buf, \"filetype\")\n local win_config = vim.api.nvim_win_get_config(win)\n\n -- Check if this is a suitable window\n local is_suitable = true\n\n -- Skip floating windows\n if win_config.relative and win_config.relative ~= \"\" then\n is_suitable = false\n end\n\n -- Skip special buffer types\n if is_suitable and (buftype == \"terminal\" or buftype == \"prompt\") then\n is_suitable = false\n end\n\n -- Skip known sidebar filetypes and ClaudeCode terminal\n if\n is_suitable\n and (\n filetype == \"neo-tree\"\n or filetype == \"neo-tree-popup\"\n or filetype == \"ClaudeCode\"\n or filetype == \"NvimTree\"\n or filetype == \"oil\"\n or filetype == \"aerial\"\n or filetype == \"tagbar\"\n )\n then\n is_suitable = false\n end\n\n -- This looks like a main editor window\n if is_suitable then\n return win\n end\n end\n\n return nil\nend\n\n--- Setup the diff module\n-- @param user_diff_config table|nil Reserved for future use\nfunction M.setup(user_diff_config)\n -- Currently no configuration needed for native diff\n -- Parameter kept for API compatibility\nend\n\n--- Open a diff view between two files\n-- @param old_file_path string Path to the original file\n-- @param new_file_path string Path to the new file (used for naming)\n-- @param new_file_contents string Contents of the new file\n-- @param tab_name string Name for the diff tab/view\n-- @return table Result with provider, tab_name, and success status\nfunction M.open_diff(old_file_path, new_file_path, new_file_contents, tab_name)\n return M._open_native_diff(old_file_path, new_file_path, new_file_contents, tab_name)\nend\n\n--- Create a temporary file with content\n-- @param content string The content to write\n-- @param filename string Base filename for the temporary file\n-- @return string|nil, string|nil The temporary file path and error message\nlocal function create_temp_file(content, filename)\n local base_dir_cache = vim.fn.stdpath(\"cache\") .. \"/claudecode_diffs\"\n local mkdir_ok_cache, mkdir_err_cache = pcall(vim.fn.mkdir, base_dir_cache, \"p\")\n\n local final_base_dir\n if mkdir_ok_cache then\n final_base_dir = base_dir_cache\n else\n local base_dir_temp = vim.fn.stdpath(\"cache\") .. \"/claudecode_diffs_fallback\"\n local mkdir_ok_temp, mkdir_err_temp = pcall(vim.fn.mkdir, base_dir_temp, \"p\")\n if not mkdir_ok_temp then\n local err_to_report = mkdir_err_temp or mkdir_err_cache or \"unknown error creating base temp dir\"\n return nil, \"Failed to create base temporary directory: \" .. tostring(err_to_report)\n end\n final_base_dir = base_dir_temp\n end\n\n local session_id_base = vim.fn.fnamemodify(vim.fn.tempname(), \":t\")\n .. \"_\"\n .. tostring(os.time())\n .. \"_\"\n .. tostring(math.random(1000, 9999))\n local session_id = session_id_base:gsub(\"[^A-Za-z0-9_-]\", \"\")\n if session_id == \"\" then -- Fallback if all characters were problematic, ensuring a directory can be made.\n session_id = \"claudecode_session\"\n end\n\n local tmp_session_dir = final_base_dir .. \"/\" .. session_id\n local mkdir_session_ok, mkdir_session_err = pcall(vim.fn.mkdir, tmp_session_dir, \"p\")\n if not mkdir_session_ok then\n return nil, \"Failed to create temporary session directory: \" .. tostring(mkdir_session_err)\n end\n\n local tmp_file = tmp_session_dir .. \"/\" .. filename\n local file = io.open(tmp_file, \"w\")\n if not file then\n return nil, \"Failed to create temporary file: \" .. tmp_file\n end\n\n file:write(content)\n file:close()\n\n return tmp_file, nil\nend\n\n--- Clean up temporary files and directories\n-- @param tmp_file string Path to the temporary file to clean up\nlocal function cleanup_temp_file(tmp_file)\n if tmp_file and vim.fn.filereadable(tmp_file) == 1 then\n local tmp_dir = vim.fn.fnamemodify(tmp_file, \":h\")\n if vim.fs and type(vim.fs.remove) == \"function\" then\n local ok_file, err_file = pcall(vim.fs.remove, tmp_file)\n if not ok_file then\n vim.notify(\n \"ClaudeCode: Error removing temp file \" .. tmp_file .. \": \" .. tostring(err_file),\n vim.log.levels.WARN\n )\n end\n\n local ok_dir, err_dir = pcall(vim.fs.remove, tmp_dir)\n if not ok_dir then\n vim.notify(\n \"ClaudeCode: Error removing temp directory \" .. tmp_dir .. \": \" .. tostring(err_dir),\n vim.log.levels.INFO\n )\n end\n else\n local reason = \"vim.fs.remove is not a function\"\n if not vim.fs then\n reason = \"vim.fs is nil\"\n end\n vim.notify(\n \"ClaudeCode: Cannot perform standard cleanup: \"\n .. reason\n .. \". Affected file: \"\n .. tmp_file\n .. \". Please check your Neovim setup or report this issue.\",\n vim.log.levels.ERROR\n )\n -- Fallback to os.remove for the file.\n local os_ok, os_err = pcall(os.remove, tmp_file)\n if not os_ok then\n vim.notify(\n \"ClaudeCode: Fallback os.remove also failed for file \" .. tmp_file .. \": \" .. tostring(os_err),\n vim.log.levels.ERROR\n )\n end\n end\n end\nend\n\n-- Detect filetype from a path or existing buffer (best-effort)\nlocal function detect_filetype(path, buf)\n -- 1) Try Neovim's builtin matcher if available (>=0.10)\n if vim.filetype and type(vim.filetype.match) == \"function\" then\n local ok, ft = pcall(vim.filetype.match, { filename = path })\n if ok and ft and ft ~= \"\" then\n return ft\n end\n end\n\n -- 2) Try reading from existing buffer\n if buf and vim.api.nvim_buf_is_valid(buf) then\n local ft = vim.api.nvim_buf_get_option(buf, \"filetype\")\n if ft and ft ~= \"\" then\n return ft\n end\n end\n\n -- 3) Fallback to simple extension mapping\n local ext = path:match(\"%.([%w_%-]+)$\") or \"\"\n local simple_map = {\n lua = \"lua\",\n ts = \"typescript\",\n js = \"javascript\",\n jsx = \"javascriptreact\",\n tsx = \"typescriptreact\",\n py = \"python\",\n go = \"go\",\n rs = \"rust\",\n c = \"c\",\n h = \"c\",\n cpp = \"cpp\",\n hpp = \"cpp\",\n md = \"markdown\",\n sh = \"sh\",\n zsh = \"zsh\",\n bash = \"bash\",\n json = \"json\",\n yaml = \"yaml\",\n yml = \"yaml\",\n toml = \"toml\",\n }\n return simple_map[ext]\nend\n--- Open diff using native Neovim functionality\n-- @param old_file_path string Path to the original file\n-- @param new_file_path string Path to the new file (used for naming)\n-- @param new_file_contents string Contents of the new file\n-- @param tab_name string Name for the diff tab/view\n-- @return table Result with provider, tab_name, and success status\nfunction M._open_native_diff(old_file_path, new_file_path, new_file_contents, tab_name)\n local new_filename = vim.fn.fnamemodify(new_file_path, \":t\") .. \".new\"\n local tmp_file, err = create_temp_file(new_file_contents, new_filename)\n if not tmp_file then\n return { provider = \"native\", tab_name = tab_name, success = false, error = err, temp_file = nil }\n end\n\n local target_win = find_main_editor_window()\n\n if target_win then\n vim.api.nvim_set_current_win(target_win)\n else\n vim.cmd(\"wincmd t\")\n vim.cmd(\"wincmd l\")\n local buf = vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win())\n local buftype = vim.api.nvim_buf_get_option(buf, \"buftype\")\n\n if buftype == \"terminal\" or buftype == \"nofile\" then\n vim.cmd(\"vsplit\")\n end\n end\n\n vim.cmd(\"edit \" .. vim.fn.fnameescape(old_file_path))\n vim.cmd(\"diffthis\")\n vim.cmd(\"vsplit\")\n vim.cmd(\"edit \" .. vim.fn.fnameescape(tmp_file))\n vim.api.nvim_buf_set_name(0, new_file_path .. \" (New)\")\n\n -- Propagate filetype to the proposed buffer for proper syntax highlighting (#20)\n local proposed_buf = vim.api.nvim_get_current_buf()\n local old_filetype = detect_filetype(old_file_path)\n if old_filetype and old_filetype ~= \"\" then\n vim.api.nvim_set_option_value(\"filetype\", old_filetype, { buf = proposed_buf })\n end\n\n vim.cmd(\"wincmd =\")\n\n local new_buf = proposed_buf\n vim.api.nvim_set_option_value(\"buftype\", \"nofile\", { buf = new_buf })\n vim.api.nvim_set_option_value(\"bufhidden\", \"wipe\", { buf = new_buf })\n vim.api.nvim_set_option_value(\"swapfile\", false, { buf = new_buf })\n\n vim.cmd(\"diffthis\")\n\n local cleanup_group = vim.api.nvim_create_augroup(\"ClaudeCodeDiffCleanup\", { clear = false })\n vim.api.nvim_create_autocmd({ \"BufDelete\", \"BufWipeout\" }, {\n group = cleanup_group,\n buffer = new_buf,\n callback = function()\n cleanup_temp_file(tmp_file)\n end,\n once = true,\n })\n\n return {\n provider = \"native\",\n tab_name = tab_name,\n success = true,\n temp_file = tmp_file,\n }\nend\n\n--- Register diff state for tracking\n-- @param tab_name string Unique identifier for the diff\n-- @param diff_data table Diff state data\nfunction M._register_diff_state(tab_name, diff_data)\n active_diffs[tab_name] = diff_data\nend\n\n--- Resolve diff as saved (user accepted changes)\n-- @param tab_name string The diff identifier\n-- @param buffer_id number The buffer that was saved\nfunction M._resolve_diff_as_saved(tab_name, buffer_id)\n local diff_data = active_diffs[tab_name]\n if not diff_data or diff_data.status ~= \"pending\" then\n return\n end\n\n logger.debug(\"diff\", \"Resolving diff as saved for\", tab_name, \"from buffer\", buffer_id)\n\n -- Get content from buffer\n local content_lines = vim.api.nvim_buf_get_lines(buffer_id, 0, -1, false)\n local final_content = table.concat(content_lines, \"\\n\")\n -- Add trailing newline if the buffer has one\n if #content_lines > 0 and vim.api.nvim_buf_get_option(buffer_id, \"eol\") then\n final_content = final_content .. \"\\n\"\n end\n\n -- Close diff windows (unified behavior)\n if diff_data.new_window and vim.api.nvim_win_is_valid(diff_data.new_window) then\n vim.api.nvim_win_close(diff_data.new_window, true)\n end\n if diff_data.target_window and vim.api.nvim_win_is_valid(diff_data.target_window) then\n vim.api.nvim_set_current_win(diff_data.target_window)\n vim.cmd(\"diffoff\")\n end\n\n -- Create MCP-compliant response\n local result = {\n content = {\n { type = \"text\", text = \"FILE_SAVED\" },\n { type = \"text\", text = final_content },\n },\n }\n\n diff_data.status = \"saved\"\n diff_data.result_content = result\n\n -- Resume the coroutine with the result (for deferred response system)\n if diff_data.resolution_callback then\n logger.debug(\"diff\", \"Resuming coroutine for saved diff\", tab_name)\n diff_data.resolution_callback(result)\n else\n logger.debug(\"diff\", \"No resolution callback found for saved diff\", tab_name)\n end\n\n -- Reload the original file buffer after a delay to ensure Claude CLI has written the file\n vim.defer_fn(function()\n local current_diff_data = active_diffs[tab_name]\n local original_cursor_pos = current_diff_data and current_diff_data.original_cursor_pos\n M.reload_file_buffers_manual(diff_data.old_file_path, original_cursor_pos)\n end, 200)\n\n -- NOTE: Diff state cleanup is handled by close_tab tool or explicit cleanup calls\n logger.debug(\"diff\", \"Diff saved, awaiting close_tab command for cleanup\")\nend\n\n--- Reload file buffers after external changes (called when diff is closed)\n-- @param file_path string Path to the file that was externally modified\n-- @param original_cursor_pos table|nil Original cursor position to restore {row, col}\nlocal function reload_file_buffers(file_path, original_cursor_pos)\n logger.debug(\"diff\", \"Reloading buffers for file:\", file_path, original_cursor_pos and \"(restoring cursor)\" or \"\")\n\n local reloaded_count = 0\n -- Find and reload any open buffers for this file\n for _, buf in ipairs(vim.api.nvim_list_bufs()) do\n if vim.api.nvim_buf_is_valid(buf) then\n local buf_name = vim.api.nvim_buf_get_name(buf)\n\n -- Simple string match - if buffer name matches the file path\n if buf_name == file_path then\n -- Check if buffer is modified - only reload unmodified buffers for safety\n local modified = vim.api.nvim_buf_get_option(buf, \"modified\")\n logger.debug(\"diff\", \"Found matching buffer\", buf, \"modified:\", modified)\n\n if not modified then\n -- Try to find a window displaying this buffer for proper context\n local win_id = nil\n for _, win in ipairs(vim.api.nvim_list_wins()) do\n if vim.api.nvim_win_get_buf(win) == buf then\n win_id = win\n break\n end\n end\n\n if win_id then\n vim.api.nvim_win_call(win_id, function()\n vim.cmd(\"edit\")\n -- Restore original cursor position if we have it\n if original_cursor_pos then\n pcall(vim.api.nvim_win_set_cursor, win_id, original_cursor_pos)\n end\n end)\n else\n vim.api.nvim_buf_call(buf, function()\n vim.cmd(\"edit\")\n end)\n end\n\n reloaded_count = reloaded_count + 1\n end\n end\n end\n end\n\n logger.debug(\"diff\", \"Completed buffer reload - reloaded\", reloaded_count, \"buffers for file:\", file_path)\nend\n\n--- Resolve diff as rejected (user closed/rejected)\n-- @param tab_name string The diff identifier\nfunction M._resolve_diff_as_rejected(tab_name)\n local diff_data = active_diffs[tab_name]\n if not diff_data or diff_data.status ~= \"pending\" then\n return\n end\n\n -- Create MCP-compliant response\n local result = {\n content = {\n { type = \"text\", text = \"DIFF_REJECTED\" },\n { type = \"text\", text = tab_name },\n },\n }\n\n diff_data.status = \"rejected\"\n diff_data.result_content = result\n\n -- Clean up diff state and resources BEFORE resolving to prevent any interference\n M._cleanup_diff_state(tab_name, \"diff rejected\")\n\n -- Use vim.schedule to ensure the resolution callback happens after all cleanup\n vim.schedule(function()\n -- Resume the coroutine with the result (for deferred response system)\n if diff_data.resolution_callback then\n logger.debug(\"diff\", \"Resuming coroutine for rejected diff\", tab_name)\n diff_data.resolution_callback(result)\n end\n end)\nend\n\n--- Register autocmds for a specific diff\n-- @param tab_name string The diff identifier\n-- @param new_buffer number New file buffer ID\n-- @return table List of autocmd IDs\nlocal function register_diff_autocmds(tab_name, new_buffer)\n local autocmd_ids = {}\n\n -- Handle :w command to accept diff changes (replaces both BufWritePost and BufWriteCmd)\n autocmd_ids[#autocmd_ids + 1] = vim.api.nvim_create_autocmd(\"BufWriteCmd\", {\n group = get_autocmd_group(),\n buffer = new_buffer,\n callback = function()\n logger.debug(\"diff\", \"BufWriteCmd (:w) triggered - accepting diff changes for\", tab_name)\n M._resolve_diff_as_saved(tab_name, new_buffer)\n -- Prevent actual file write since we're handling it through MCP\n return true\n end,\n })\n\n -- Buffer deletion monitoring for rejection (multiple events to catch all deletion methods)\n\n -- BufDelete: When buffer is deleted with :bdelete, :bwipeout, etc.\n autocmd_ids[#autocmd_ids + 1] = vim.api.nvim_create_autocmd(\"BufDelete\", {\n group = get_autocmd_group(),\n buffer = new_buffer,\n callback = function()\n logger.debug(\"diff\", \"BufDelete triggered for new buffer\", new_buffer, \"tab:\", tab_name)\n M._resolve_diff_as_rejected(tab_name)\n end,\n })\n\n -- BufUnload: When buffer is unloaded (covers more scenarios)\n autocmd_ids[#autocmd_ids + 1] = vim.api.nvim_create_autocmd(\"BufUnload\", {\n group = get_autocmd_group(),\n buffer = new_buffer,\n callback = function()\n logger.debug(\"diff\", \"BufUnload triggered for new buffer\", new_buffer, \"tab:\", tab_name)\n M._resolve_diff_as_rejected(tab_name)\n end,\n })\n\n -- BufWipeout: When buffer is wiped out completely\n autocmd_ids[#autocmd_ids + 1] = vim.api.nvim_create_autocmd(\"BufWipeout\", {\n group = get_autocmd_group(),\n buffer = new_buffer,\n callback = function()\n logger.debug(\"diff\", \"BufWipeout triggered for new buffer\", new_buffer, \"tab:\", tab_name)\n M._resolve_diff_as_rejected(tab_name)\n end,\n })\n\n -- Note: We intentionally do NOT monitor old_buffer for deletion\n -- because it's the actual file buffer and shouldn't trigger diff rejection\n\n return autocmd_ids\nend\n\n--- Create diff view from a specific window\n-- @param target_window number The window to use as base for the diff\n-- @param old_file_path string Path to the original file\n-- @param new_buffer number New file buffer ID\n-- @param tab_name string The diff identifier\n-- @param is_new_file boolean Whether this is a new file (doesn't exist yet)\n-- @return table Info about the created diff layout\nfunction M._create_diff_view_from_window(target_window, old_file_path, new_buffer, tab_name, is_new_file)\n -- If no target window provided, create a new window in suitable location\n if not target_window then\n -- Try to create a new window in the main area\n vim.cmd(\"wincmd t\") -- Go to top-left\n vim.cmd(\"wincmd l\") -- Move right (to middle if layout is left|middle|right)\n\n local buf = vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win())\n local buftype = vim.api.nvim_buf_get_option(buf, \"buftype\")\n local filetype = vim.api.nvim_buf_get_option(buf, \"filetype\")\n\n if buftype == \"terminal\" or buftype == \"prompt\" or filetype == \"neo-tree\" or filetype == \"ClaudeCode\" then\n vim.cmd(\"vsplit\")\n end\n\n target_window = vim.api.nvim_get_current_win()\n else\n vim.api.nvim_set_current_win(target_window)\n end\n\n local original_buffer\n if is_new_file then\n local empty_buffer = vim.api.nvim_create_buf(false, true)\n if not empty_buffer or empty_buffer == 0 then\n local error_msg = \"Failed to create empty buffer for new file diff\"\n logger.error(\"diff\", error_msg)\n error({\n code = -32000,\n message = \"Buffer creation failed\",\n data = error_msg,\n })\n end\n\n -- Set buffer properties with error handling\n local success, err = pcall(function()\n vim.api.nvim_buf_set_name(empty_buffer, old_file_path .. \" (NEW FILE)\")\n vim.api.nvim_buf_set_lines(empty_buffer, 0, -1, false, {})\n vim.api.nvim_buf_set_option(empty_buffer, \"buftype\", \"nofile\")\n vim.api.nvim_buf_set_option(empty_buffer, \"modifiable\", false)\n vim.api.nvim_buf_set_option(empty_buffer, \"readonly\", true)\n end)\n\n if not success then\n pcall(vim.api.nvim_buf_delete, empty_buffer, { force = true })\n local error_msg = \"Failed to configure empty buffer: \" .. tostring(err)\n logger.error(\"diff\", error_msg)\n error({\n code = -32000,\n message = \"Buffer configuration failed\",\n data = error_msg,\n })\n end\n\n vim.api.nvim_win_set_buf(target_window, empty_buffer)\n original_buffer = empty_buffer\n else\n vim.cmd(\"edit \" .. vim.fn.fnameescape(old_file_path))\n original_buffer = vim.api.nvim_win_get_buf(target_window)\n end\n\n vim.cmd(\"diffthis\")\n\n vim.cmd(\"vsplit\")\n local new_win = vim.api.nvim_get_current_win()\n vim.api.nvim_win_set_buf(new_win, new_buffer)\n\n -- Ensure new buffer inherits filetype from original for syntax highlighting (#20)\n local original_ft = detect_filetype(old_file_path, original_buffer)\n if original_ft and original_ft ~= \"\" then\n vim.api.nvim_set_option_value(\"filetype\", original_ft, { buf = new_buffer })\n end\n vim.cmd(\"diffthis\")\n\n vim.cmd(\"wincmd =\")\n vim.api.nvim_set_current_win(new_win)\n\n -- Store diff context in buffer variables for user commands\n vim.b[new_buffer].claudecode_diff_tab_name = tab_name\n vim.b[new_buffer].claudecode_diff_new_win = new_win\n vim.b[new_buffer].claudecode_diff_target_win = target_window\n\n -- Return window information for later storage\n return {\n new_window = new_win,\n target_window = target_window,\n original_buffer = original_buffer,\n }\nend\n\n--- Clean up diff state and resources\n-- @param tab_name string The diff identifier\n-- @param reason string Reason for cleanup\nfunction M._cleanup_diff_state(tab_name, reason)\n local diff_data = active_diffs[tab_name]\n if not diff_data then\n return\n end\n\n -- Clean up autocmds\n for _, autocmd_id in ipairs(diff_data.autocmd_ids or {}) do\n pcall(vim.api.nvim_del_autocmd, autocmd_id)\n end\n\n -- Clean up the new buffer only (not the old buffer which is the user's file)\n if diff_data.new_buffer and vim.api.nvim_buf_is_valid(diff_data.new_buffer) then\n pcall(vim.api.nvim_buf_delete, diff_data.new_buffer, { force = true })\n end\n\n -- Close new diff window if still open\n if diff_data.new_window and vim.api.nvim_win_is_valid(diff_data.new_window) then\n pcall(vim.api.nvim_win_close, diff_data.new_window, true)\n end\n\n -- Turn off diff mode in target window if it still exists\n if diff_data.target_window and vim.api.nvim_win_is_valid(diff_data.target_window) then\n vim.api.nvim_win_call(diff_data.target_window, function()\n vim.cmd(\"diffoff\")\n end)\n end\n\n -- Remove from active diffs\n active_diffs[tab_name] = nil\n\n logger.debug(\"diff\", \"Cleaned up diff state for\", tab_name, \"due to:\", reason)\nend\n\n--- Clean up all active diffs\n-- @param reason string Reason for cleanup\n-- NOTE: This will become a public closeAllDiffTabs tool in the future\nfunction M._cleanup_all_active_diffs(reason)\n for tab_name, _ in pairs(active_diffs) do\n M._cleanup_diff_state(tab_name, reason)\n end\nend\n\n--- Set up blocking diff operation with simpler approach\n-- @param params table Parameters for the diff\n-- @param resolution_callback function Callback to call when diff resolves\nfunction M._setup_blocking_diff(params, resolution_callback)\n local tab_name = params.tab_name\n logger.debug(\"diff\", \"Setting up diff for:\", params.old_file_path)\n\n -- Wrap the setup in error handling to ensure cleanup on failure\n local setup_success, setup_error = pcall(function()\n -- Step 1: Check if the file exists (allow new files)\n local old_file_exists = vim.fn.filereadable(params.old_file_path) == 1\n local is_new_file = not old_file_exists\n\n -- Step 2: Find if the file is already open in a buffer (only for existing files)\n local existing_buffer = nil\n local target_window = nil\n\n if old_file_exists then\n -- Look for existing buffer with this file\n for _, buf in ipairs(vim.api.nvim_list_bufs()) do\n if vim.api.nvim_buf_is_valid(buf) and vim.api.nvim_buf_is_loaded(buf) then\n local buf_name = vim.api.nvim_buf_get_name(buf)\n if buf_name == params.old_file_path then\n existing_buffer = buf\n break\n end\n end\n end\n\n -- Find window containing this buffer (if any)\n if existing_buffer then\n for _, win in ipairs(vim.api.nvim_list_wins()) do\n if vim.api.nvim_win_get_buf(win) == existing_buffer then\n target_window = win\n break\n end\n end\n end\n end\n\n -- If no existing buffer/window, find a suitable main editor window\n if not target_window then\n target_window = find_main_editor_window()\n end\n\n -- Step 3: Create scratch buffer for new content\n local new_buffer = vim.api.nvim_create_buf(false, true) -- unlisted, scratch\n if new_buffer == 0 then\n error({\n code = -32000,\n message = \"Buffer creation failed\",\n data = \"Could not create new content buffer\",\n })\n end\n\n local new_unique_name = is_new_file and (tab_name .. \" (NEW FILE - proposed)\") or (tab_name .. \" (proposed)\")\n vim.api.nvim_buf_set_name(new_buffer, new_unique_name)\n local lines = vim.split(params.new_file_contents, \"\\n\")\n -- Remove trailing empty line if content ended with \\n\n if #lines > 0 and lines[#lines] == \"\" then\n table.remove(lines, #lines)\n end\n vim.api.nvim_buf_set_lines(new_buffer, 0, -1, false, lines)\n\n vim.api.nvim_buf_set_option(new_buffer, \"buftype\", \"acwrite\") -- Allows saving but stays as scratch-like\n vim.api.nvim_buf_set_option(new_buffer, \"modifiable\", true)\n\n -- Step 4: Set up diff view using the target window\n local diff_info =\n M._create_diff_view_from_window(target_window, params.old_file_path, new_buffer, tab_name, is_new_file)\n\n -- Step 5: Register autocmds for user interaction monitoring\n local autocmd_ids = register_diff_autocmds(tab_name, new_buffer)\n\n -- Step 6: Store diff state\n\n -- Save the original cursor position before storing diff state\n local original_cursor_pos = nil\n if diff_info.target_window and vim.api.nvim_win_is_valid(diff_info.target_window) then\n original_cursor_pos = vim.api.nvim_win_get_cursor(diff_info.target_window)\n end\n\n M._register_diff_state(tab_name, {\n old_file_path = params.old_file_path,\n new_file_path = params.new_file_path,\n new_file_contents = params.new_file_contents,\n new_buffer = new_buffer,\n new_window = diff_info.new_window,\n target_window = diff_info.target_window,\n original_buffer = diff_info.original_buffer,\n original_cursor_pos = original_cursor_pos,\n autocmd_ids = autocmd_ids,\n created_at = vim.fn.localtime(),\n status = \"pending\",\n resolution_callback = resolution_callback,\n result_content = nil,\n is_new_file = is_new_file,\n })\n end) -- End of pcall\n\n -- Handle setup errors\n if not setup_success then\n local error_msg = \"Failed to setup diff operation: \" .. tostring(setup_error)\n logger.error(\"diff\", error_msg)\n\n -- Clean up any partial state that might have been created\n if active_diffs[tab_name] then\n M._cleanup_diff_state(tab_name, \"setup failed\")\n end\n\n -- Re-throw the error for MCP compliance\n error({\n code = -32000,\n message = \"Diff setup failed\",\n data = error_msg,\n })\n end\nend\n\n--- Blocking diff operation for MCP compliance\n-- @param old_file_path string Path to the original file\n-- @param new_file_path string Path to the new file (used for naming)\n-- @param new_file_contents string Contents of the new file\n-- @param tab_name string Name for the diff tab/view\n-- @return table MCP-compliant response with content array\nfunction M.open_diff_blocking(old_file_path, new_file_path, new_file_contents, tab_name)\n -- Check for existing diff with same tab_name\n if active_diffs[tab_name] then\n -- Resolve the existing diff as rejected before replacing\n M._resolve_diff_as_rejected(tab_name)\n end\n\n -- Set up blocking diff operation\n local co = coroutine.running()\n if not co then\n error({\n code = -32000,\n message = \"Internal server error\",\n data = \"openDiff must run in coroutine context\",\n })\n end\n\n logger.debug(\"diff\", \"Starting diff setup for\", tab_name)\n\n -- Use native diff implementation\n local success, err = pcall(M._setup_blocking_diff, {\n old_file_path = old_file_path,\n new_file_path = new_file_path,\n new_file_contents = new_file_contents,\n tab_name = tab_name,\n }, function(result)\n -- Resume the coroutine with the result\n local resume_success, resume_result = coroutine.resume(co, result)\n if resume_success then\n -- Use the global response sender to avoid module reloading issues\n local co_key = tostring(co)\n if _G.claude_deferred_responses and _G.claude_deferred_responses[co_key] then\n _G.claude_deferred_responses[co_key](resume_result)\n _G.claude_deferred_responses[co_key] = nil\n else\n logger.error(\"diff\", \"No global response sender found for coroutine:\", co_key)\n end\n else\n logger.error(\"diff\", \"Coroutine failed:\", tostring(resume_result))\n local co_key = tostring(co)\n if _G.claude_deferred_responses and _G.claude_deferred_responses[co_key] then\n _G.claude_deferred_responses[co_key]({\n error = {\n code = -32603,\n message = \"Internal error\",\n data = \"Coroutine failed: \" .. tostring(resume_result),\n },\n })\n _G.claude_deferred_responses[co_key] = nil\n end\n end\n end)\n\n if not success then\n logger.error(\"diff\", \"Diff setup failed for\", tab_name, \"error:\", tostring(err))\n -- If the error is already structured, propagate it directly\n if type(err) == \"table\" and err.code then\n error(err)\n else\n error({\n code = -32000,\n message = \"Error setting up diff\",\n data = tostring(err),\n })\n end\n end\n\n -- Yield and wait indefinitely for user interaction - the resolve functions will resume us\n local user_action_result = coroutine.yield()\n logger.debug(\"diff\", \"User action completed for\", tab_name)\n\n -- Return the result directly - this will be sent by the deferred response system\n return user_action_result\nend\n\n-- Set up global autocmds for shutdown handling\nvim.api.nvim_create_autocmd(\"VimLeavePre\", {\n group = get_autocmd_group(),\n callback = function()\n M._cleanup_all_active_diffs(\"shutdown\")\n end,\n})\n\n--- Close diff by tab name (used by close_tab tool)\n-- @param tab_name string The diff identifier\n-- @return boolean success True if diff was found and closed\nfunction M.close_diff_by_tab_name(tab_name)\n local diff_data = active_diffs[tab_name]\n if not diff_data then\n return false\n end\n\n -- If the diff was already saved, reload file buffers and clean up\n if diff_data.status == \"saved\" then\n -- Claude Code CLI has written the file, reload any open buffers\n if diff_data.old_file_path then\n -- Add a small delay to ensure Claude CLI has finished writing the file\n vim.defer_fn(function()\n M.reload_file_buffers_manual(diff_data.old_file_path, diff_data.original_cursor_pos)\n end, 100) -- 100ms delay\n end\n M._cleanup_diff_state(tab_name, \"diff tab closed after save\")\n return true\n end\n\n -- If still pending, treat as rejection\n if diff_data.status == \"pending\" then\n M._resolve_diff_as_rejected(tab_name)\n return true\n end\n\n return false\nend\n\n-- Test helper function (only for testing)\nfunction M._get_active_diffs()\n return active_diffs\nend\n\n-- Manual buffer reload function for testing/debugging\nfunction M.reload_file_buffers_manual(file_path, original_cursor_pos)\n return reload_file_buffers(file_path, original_cursor_pos)\nend\n\n--- Accept the current diff (user command version)\n-- This function reads the diff context from buffer variables\nfunction M.accept_current_diff()\n local current_buffer = vim.api.nvim_get_current_buf()\n local tab_name = vim.b[current_buffer].claudecode_diff_tab_name\n\n if not tab_name then\n vim.notify(\"No active diff found in current buffer\", vim.log.levels.WARN)\n return\n end\n\n M._resolve_diff_as_saved(tab_name, current_buffer)\nend\n\n--- Deny/reject the current diff (user command version)\n-- This function reads the diff context from buffer variables\nfunction M.deny_current_diff()\n local current_buffer = vim.api.nvim_get_current_buf()\n local tab_name = vim.b[current_buffer].claudecode_diff_tab_name\n local new_win = vim.b[current_buffer].claudecode_diff_new_win\n local target_window = vim.b[current_buffer].claudecode_diff_target_win\n\n if not tab_name then\n vim.notify(\"No active diff found in current buffer\", vim.log.levels.WARN)\n return\n end\n\n -- Close windows and clean up (same logic as the original keymap)\n if new_win and vim.api.nvim_win_is_valid(new_win) then\n vim.api.nvim_win_close(new_win, true)\n end\n if target_window and vim.api.nvim_win_is_valid(target_window) then\n vim.api.nvim_set_current_win(target_window)\n vim.cmd(\"diffoff\")\n end\n\n M._resolve_diff_as_rejected(tab_name)\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/selection.lua", "---\n-- Manages selection tracking and communication with the Claude server.\n-- @module claudecode.selection\nlocal M = {}\n\nlocal logger = require(\"claudecode.logger\")\nlocal terminal = require(\"claudecode.terminal\")\n\nM.state = {\n latest_selection = nil,\n tracking_enabled = false,\n debounce_timer = nil,\n debounce_ms = 100,\n\n last_active_visual_selection = nil,\n demotion_timer = nil,\n visual_demotion_delay_ms = 50,\n}\n\n--- Enables selection tracking.\n-- @param server table The server object to use for communication.\n-- @param visual_demotion_delay_ms number The delay for visual selection demotion.\nfunction M.enable(server, visual_demotion_delay_ms)\n if M.state.tracking_enabled then\n return\n end\n\n M.state.tracking_enabled = true\n M.server = server\n M.state.visual_demotion_delay_ms = visual_demotion_delay_ms\n\n M._create_autocommands()\nend\n\n--- Disables selection tracking.\n-- Clears autocommands, resets internal state, and stops any active debounce timers.\nfunction M.disable()\n if not M.state.tracking_enabled then\n return\n end\n\n M.state.tracking_enabled = false\n\n M._clear_autocommands()\n\n M.state.latest_selection = nil\n M.server = nil\n\n if M.state.debounce_timer then\n vim.loop.timer_stop(M.state.debounce_timer)\n M.state.debounce_timer = nil\n end\nend\n\n--- Creates autocommands for tracking selections.\n-- Sets up listeners for CursorMoved, CursorMovedI, ModeChanged, and TextChanged events.\n-- @local\nfunction M._create_autocommands()\n local group = vim.api.nvim_create_augroup(\"ClaudeCodeSelection\", { clear = true })\n\n vim.api.nvim_create_autocmd({ \"CursorMoved\", \"CursorMovedI\" }, {\n group = group,\n callback = function()\n M.on_cursor_moved()\n end,\n })\n\n vim.api.nvim_create_autocmd(\"ModeChanged\", {\n group = group,\n callback = function()\n M.on_mode_changed()\n end,\n })\n\n vim.api.nvim_create_autocmd(\"TextChanged\", {\n group = group,\n callback = function()\n M.on_text_changed()\n end,\n })\nend\n\n--- Clears the autocommands related to selection tracking.\n-- @local\nfunction M._clear_autocommands()\n vim.api.nvim_clear_autocmds({ group = \"ClaudeCodeSelection\" })\nend\n\n--- Handles cursor movement events.\n-- Triggers a debounced update of the selection.\nfunction M.on_cursor_moved()\n M.debounce_update()\nend\n\n--- Handles mode change events.\n-- Triggers an immediate update of the selection.\nfunction M.on_mode_changed()\n M.update_selection()\nend\n\n--- Handles text change events.\n-- Triggers a debounced update of the selection.\nfunction M.on_text_changed()\n M.debounce_update()\nend\n\n--- Debounces selection updates.\n-- Ensures that `update_selection` is not called too frequently by deferring\n-- its execution.\nfunction M.debounce_update()\n if M.state.debounce_timer then\n vim.loop.timer_stop(M.state.debounce_timer)\n end\n\n M.state.debounce_timer = vim.defer_fn(function()\n M.update_selection()\n M.state.debounce_timer = nil\n end, M.state.debounce_ms)\nend\n\n--- Updates the current selection state.\n-- Determines the current selection based on the editor mode (visual or normal)\n-- and sends an update to the server if the selection has changed.\nfunction M.update_selection()\n if not M.state.tracking_enabled then\n return\n end\n\n local current_buf = vim.api.nvim_get_current_buf()\n local buf_name = vim.api.nvim_buf_get_name(current_buf)\n\n -- If the buffer name starts with \"✻ [Claude Code]\", do not update selection\n if buf_name and string.sub(buf_name, 1, string.len(\"✻ [Claude Code]\")) == \"✻ [Claude Code]\" then\n -- Optionally, cancel demotion timer like for the terminal\n if M.state.demotion_timer then\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n M.state.demotion_timer = nil\n end\n return\n end\n\n -- If the current buffer is the Claude terminal, do not update selection\n if terminal then\n local claude_term_bufnr = terminal.get_active_terminal_bufnr()\n if claude_term_bufnr and current_buf == claude_term_bufnr then\n -- Cancel any pending demotion if we switch to the Claude terminal\n if M.state.demotion_timer then\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n M.state.demotion_timer = nil\n end\n return\n end\n end\n\n local current_mode_info = vim.api.nvim_get_mode()\n local current_mode = current_mode_info.mode\n local current_selection\n\n if current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\022\" then\n -- If a new visual selection is made, cancel any pending demotion\n if M.state.demotion_timer then\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n M.state.demotion_timer = nil\n end\n\n current_selection = M.get_visual_selection()\n\n if current_selection then\n M.state.last_active_visual_selection = {\n bufnr = current_buf,\n selection_data = vim.deepcopy(current_selection), -- Store a copy\n timestamp = vim.loop.now(),\n }\n else\n -- No valid visual selection (e.g., get_visual_selection returned nil)\n -- Clear last_active_visual if it was for this buffer\n if M.state.last_active_visual_selection and M.state.last_active_visual_selection.bufnr == current_buf then\n M.state.last_active_visual_selection = nil\n end\n end\n else\n local last_visual = M.state.last_active_visual_selection\n\n if M.state.demotion_timer then\n -- A demotion is already pending. For this specific update_selection call (e.g. cursor moved),\n -- current_selection reflects the immediate cursor position.\n -- M.state.latest_selection (the one that might be sent) is still the visual one until timer resolves.\n current_selection = M.get_cursor_position()\n elseif\n last_visual\n and last_visual.bufnr == current_buf\n and last_visual.selection_data\n and not last_visual.selection_data.selection.isEmpty\n then\n -- We just exited visual mode in this buffer, and no demotion timer is running for it.\n -- Keep M.state.latest_selection as is (it's the visual one from the previous update).\n -- The 'current_selection' for comparison should also be this visual one.\n current_selection = M.state.latest_selection\n\n if M.state.demotion_timer then -- Should not happen due to elseif, but as safeguard\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n end\n\n M.state.demotion_timer = vim.loop.new_timer()\n M.state.demotion_timer:start(\n M.state.visual_demotion_delay_ms,\n 0, -- 0 repeat = one-shot\n vim.schedule_wrap(function()\n if M.state.demotion_timer then -- Check if it wasn't cancelled right before firing\n M.state.demotion_timer:stop()\n M.state.demotion_timer:close()\n M.state.demotion_timer = nil\n end\n M.handle_selection_demotion(current_buf) -- Pass buffer at time of scheduling\n end)\n )\n else\n -- Genuinely in normal mode, no recent visual exit, no pending demotion.\n current_selection = M.get_cursor_position()\n if last_visual and last_visual.bufnr == current_buf then\n M.state.last_active_visual_selection = nil -- Clear it as it's no longer relevant for demotion\n end\n end\n end\n\n -- If current_selection could not be determined (e.g. get_visual_selection was nil and no other path set it)\n -- default to cursor position to avoid errors.\n if not current_selection then\n current_selection = M.get_cursor_position()\n end\n\n local changed = M.has_selection_changed(current_selection)\n\n if changed then\n M.state.latest_selection = current_selection\n if M.server then\n M.send_selection_update(current_selection)\n end\n end\nend\n\n--- Handles the demotion of a visual selection after a delay.\n-- Called by the demotion_timer.\n-- @param original_bufnr_when_scheduled number The buffer number that was active when demotion was scheduled.\nfunction M.handle_selection_demotion(original_bufnr_when_scheduled)\n -- Timer object is already stopped and cleared by its own callback wrapper or cancellation points.\n -- M.state.demotion_timer should be nil here if it fired normally or was cancelled.\n\n local current_buf = vim.api.nvim_get_current_buf()\n local claude_term_bufnr = terminal.get_active_terminal_bufnr()\n\n -- Condition 1: Switched to Claude Terminal\n if claude_term_bufnr and current_buf == claude_term_bufnr then\n -- Visual selection is preserved (M.state.latest_selection is still the visual one).\n -- The \"pending\" status of last_active_visual_selection is resolved.\n if\n M.state.last_active_visual_selection\n and M.state.last_active_visual_selection.bufnr == original_bufnr_when_scheduled\n then\n M.state.last_active_visual_selection = nil\n end\n return\n end\n\n local current_mode_info = vim.api.nvim_get_mode()\n\n -- Condition 2: Back in Visual Mode in the Original Buffer\n if\n current_buf == original_bufnr_when_scheduled\n and (current_mode_info.mode == \"v\" or current_mode_info.mode == \"V\" or current_mode_info.mode == \"\\022\")\n then\n -- A new visual selection will take precedence. M.state.latest_selection will be updated by main flow.\n if\n M.state.last_active_visual_selection\n and M.state.last_active_visual_selection.bufnr == original_bufnr_when_scheduled\n then\n M.state.last_active_visual_selection = nil\n end\n return\n end\n\n -- Condition 3: Still in Original Buffer & Not Visual & Not Claude Term -> Demote\n if current_buf == original_bufnr_when_scheduled then\n local new_sel_for_demotion = M.get_cursor_position()\n -- Check if this new cursor position is actually different from the (visual) latest_selection\n if M.has_selection_changed(new_sel_for_demotion) then\n M.state.latest_selection = new_sel_for_demotion\n if M.server then\n M.send_selection_update(M.state.latest_selection)\n end\n end\n -- No change detected in selection\n end\n -- User switched to different buffer\n\n -- Always clear last_active_visual_selection for the original buffer as its pending demotion is resolved.\n if\n M.state.last_active_visual_selection\n and M.state.last_active_visual_selection.bufnr == original_bufnr_when_scheduled\n then\n M.state.last_active_visual_selection = nil\n end\nend\n\n--- Validates if we're in a valid visual selection mode\n-- @return boolean, string|nil - true if valid, false and error message if not\nlocal function validate_visual_mode()\n local current_nvim_mode = vim.api.nvim_get_mode().mode\n local fixed_anchor_pos_raw = vim.fn.getpos(\"v\")\n\n if not (current_nvim_mode == \"v\" or current_nvim_mode == \"V\" or current_nvim_mode == \"\\22\") then\n return false, \"not in visual mode\"\n end\n\n if fixed_anchor_pos_raw[2] == 0 then\n return false, \"no visual selection mark\"\n end\n\n return true, nil\nend\n\n--- Determines the effective visual mode character\n-- @return string|nil - the visual mode character or nil if invalid\nlocal function get_effective_visual_mode()\n local current_nvim_mode = vim.api.nvim_get_mode().mode\n local visual_fn_mode_char = vim.fn.visualmode()\n\n if visual_fn_mode_char and visual_fn_mode_char ~= \"\" then\n return visual_fn_mode_char\n end\n\n -- Fallback to current mode\n if current_nvim_mode == \"V\" then\n return \"V\"\n elseif current_nvim_mode == \"v\" then\n return \"v\"\n elseif current_nvim_mode == \"\\22\" then -- Ctrl-V, blockwise\n return \"\\22\"\n end\n\n return nil\nend\n\n--- Gets the start and end coordinates of the visual selection\n-- @return table, table - start_coords and end_coords with lnum and col fields\nlocal function get_selection_coordinates()\n local fixed_anchor_pos_raw = vim.fn.getpos(\"v\")\n local current_cursor_nvim = vim.api.nvim_win_get_cursor(0)\n\n -- Convert to 1-indexed line and 1-indexed column for consistency\n local p1 = { lnum = fixed_anchor_pos_raw[2], col = fixed_anchor_pos_raw[3] }\n local p2 = { lnum = current_cursor_nvim[1], col = current_cursor_nvim[2] + 1 }\n\n -- Determine chronological start/end based on line, then column\n if p1.lnum < p2.lnum or (p1.lnum == p2.lnum and p1.col <= p2.col) then\n return p1, p2\n else\n return p2, p1\n end\nend\n\n--- Extracts text for linewise visual selection\n-- @param lines_content table - array of line strings\n-- @param start_coords table - start coordinates\n-- @return string - the extracted text\nlocal function extract_linewise_text(lines_content, start_coords)\n start_coords.col = 1 -- Linewise selection effectively starts at column 1\n return table.concat(lines_content, \"\\n\")\nend\n\n--- Extracts text for characterwise visual selection\n-- @param lines_content table - array of line strings\n-- @param start_coords table - start coordinates\n-- @param end_coords table - end coordinates\n-- @return string|nil - the extracted text or nil if invalid\nlocal function extract_characterwise_text(lines_content, start_coords, end_coords)\n if start_coords.lnum == end_coords.lnum then\n if not lines_content[1] then\n return nil\n end\n return string.sub(lines_content[1], start_coords.col, end_coords.col)\n else\n if not lines_content[1] or not lines_content[#lines_content] then\n return nil\n end\n\n local text_parts = {}\n table.insert(text_parts, string.sub(lines_content[1], start_coords.col))\n for i = 2, #lines_content - 1 do\n table.insert(text_parts, lines_content[i])\n end\n table.insert(text_parts, string.sub(lines_content[#lines_content], 1, end_coords.col))\n return table.concat(text_parts, \"\\n\")\n end\nend\n\n--- Calculates LSP-compatible position coordinates\n-- @param start_coords table - start coordinates\n-- @param end_coords table - end coordinates\n-- @param visual_mode string - the visual mode character\n-- @param lines_content table - array of line strings\n-- @return table - LSP position object with start and end fields\nlocal function calculate_lsp_positions(start_coords, end_coords, visual_mode, lines_content)\n local lsp_start_line = start_coords.lnum - 1\n local lsp_end_line = end_coords.lnum - 1\n local lsp_start_char, lsp_end_char\n\n if visual_mode == \"V\" then\n lsp_start_char = 0 -- Linewise selection always starts at character 0\n -- For linewise, LSP end char is length of the last selected line\n if #lines_content > 0 and lines_content[#lines_content] then\n lsp_end_char = #lines_content[#lines_content]\n else\n lsp_end_char = 0\n end\n else\n lsp_start_char = start_coords.col - 1\n lsp_end_char = end_coords.col\n end\n\n return {\n start = { line = lsp_start_line, character = lsp_start_char },\n [\"end\"] = { line = lsp_end_line, character = lsp_end_char },\n }\nend\n\n--- Gets the current visual selection details.\n-- @return table|nil A table containing selection text, file path, URL, and\n-- start/end positions, or nil if no visual selection exists.\nfunction M.get_visual_selection()\n local valid = validate_visual_mode()\n if not valid then\n return nil\n end\n\n local visual_mode = get_effective_visual_mode()\n if not visual_mode then\n return nil\n end\n\n local start_coords, end_coords = get_selection_coordinates()\n\n local current_buf = vim.api.nvim_get_current_buf()\n local file_path = vim.api.nvim_buf_get_name(current_buf)\n\n local lines_content = vim.api.nvim_buf_get_lines(\n current_buf,\n start_coords.lnum - 1, -- Convert to 0-indexed\n end_coords.lnum, -- nvim_buf_get_lines end is exclusive\n false\n )\n\n if #lines_content == 0 then\n return nil\n end\n\n local final_text\n if visual_mode == \"V\" then\n final_text = extract_linewise_text(lines_content, start_coords)\n elseif visual_mode == \"v\" or visual_mode == \"\\22\" then\n final_text = extract_characterwise_text(lines_content, start_coords, end_coords)\n if not final_text then\n return nil\n end\n else\n return nil\n end\n\n local lsp_positions = calculate_lsp_positions(start_coords, end_coords, visual_mode, lines_content)\n\n return {\n text = final_text or \"\",\n filePath = file_path,\n fileUrl = \"file://\" .. file_path,\n selection = {\n start = lsp_positions.start,\n [\"end\"] = lsp_positions[\"end\"],\n isEmpty = (not final_text or #final_text == 0),\n },\n }\nend\n\n--- Gets the current cursor position when no visual selection is active.\n-- @return table A table containing an empty text, file path, URL, and cursor\n-- position as start/end, with isEmpty set to true.\nfunction M.get_cursor_position()\n local cursor_pos = vim.api.nvim_win_get_cursor(0)\n local current_buf = vim.api.nvim_get_current_buf()\n local file_path = vim.api.nvim_buf_get_name(current_buf)\n\n return {\n text = \"\",\n filePath = file_path,\n fileUrl = \"file://\" .. file_path,\n selection = {\n start = { line = cursor_pos[1] - 1, character = cursor_pos[2] },\n [\"end\"] = { line = cursor_pos[1] - 1, character = cursor_pos[2] },\n isEmpty = true,\n },\n }\nend\n\n--- Checks if the selection has changed compared to the latest stored selection.\n-- @param new_selection table|nil The new selection object to compare.\n-- @return boolean true if the selection has changed, false otherwise.\nfunction M.has_selection_changed(new_selection)\n local old_selection = M.state.latest_selection\n\n if not new_selection then\n return old_selection ~= nil\n end\n\n if not old_selection then\n return true\n end\n\n if old_selection.filePath ~= new_selection.filePath then\n return true\n end\n\n if old_selection.text ~= new_selection.text then\n return true\n end\n\n if\n old_selection.selection.start.line ~= new_selection.selection.start.line\n or old_selection.selection.start.character ~= new_selection.selection.start.character\n or old_selection.selection[\"end\"].line ~= new_selection.selection[\"end\"].line\n or old_selection.selection[\"end\"].character ~= new_selection.selection[\"end\"].character\n then\n return true\n end\n\n return false\nend\n\n--- Sends the selection update to the Claude server.\n-- @param selection table The selection object to send.\nfunction M.send_selection_update(selection)\n M.server.broadcast(\"selection_changed\", selection)\nend\n\n--- Gets the latest recorded selection.\n-- @return table|nil The latest selection object, or nil if none recorded.\nfunction M.get_latest_selection()\n return M.state.latest_selection\nend\n\n--- Sends the current selection to Claude.\n-- This function is typically invoked by a user command. It forces an immediate\n-- update and sends the latest selection.\nfunction M.send_current_selection()\n if not M.state.tracking_enabled or not M.server then\n logger.error(\"selection\", \"Claude Code is not running\")\n return\n end\n\n M.update_selection()\n\n local selection = M.state.latest_selection\n\n if not selection then\n logger.error(\"selection\", \"No selection available\")\n return\n end\n\n M.send_selection_update(selection)\n\n vim.api.nvim_echo({ { \"Selection sent to Claude\", \"Normal\" } }, false, {})\nend\n\n--- Gets selection from range marks (e.g., when using :'<,'> commands)\n-- @param line1 number The start line (1-indexed)\n-- @param line2 number The end line (1-indexed)\n-- @return table|nil A table containing selection text, file path, URL, and\n-- start/end positions, or nil if invalid range\nfunction M.get_range_selection(line1, line2)\n if not line1 or not line2 or line1 < 1 or line2 < 1 or line1 > line2 then\n return nil\n end\n\n local current_buf = vim.api.nvim_get_current_buf()\n local file_path = vim.api.nvim_buf_get_name(current_buf)\n\n -- Get the total number of lines in the buffer\n local total_lines = vim.api.nvim_buf_line_count(current_buf)\n\n -- Ensure line2 doesn't exceed buffer bounds\n if line2 > total_lines then\n line2 = total_lines\n end\n\n local lines_content = vim.api.nvim_buf_get_lines(\n current_buf,\n line1 - 1, -- Convert to 0-indexed\n line2, -- nvim_buf_get_lines end is exclusive\n false\n )\n\n if #lines_content == 0 then\n return nil\n end\n\n local final_text = table.concat(lines_content, \"\\n\")\n\n -- For range selections, we treat them as linewise\n local lsp_start_line = line1 - 1 -- Convert to 0-indexed\n local lsp_end_line = line2 - 1\n local lsp_start_char = 0\n local lsp_end_char = #lines_content[#lines_content]\n\n return {\n text = final_text or \"\",\n filePath = file_path,\n fileUrl = \"file://\" .. file_path,\n selection = {\n start = { line = lsp_start_line, character = lsp_start_char },\n [\"end\"] = { line = lsp_end_line, character = lsp_end_char },\n isEmpty = (not final_text or #final_text == 0),\n },\n }\nend\n\n--- Sends an at_mentioned notification for the current visual selection.\n-- @param line1 number|nil Optional start line for range-based selection\n-- @param line2 number|nil Optional end line for range-based selection\nfunction M.send_at_mention_for_visual_selection(line1, line2)\n if not M.state.tracking_enabled then\n logger.error(\"selection\", \"Selection tracking is not enabled.\")\n return false\n end\n\n -- Check if Claude Code integration is running (server may or may not have clients)\n local claudecode_main = require(\"claudecode\")\n if not claudecode_main.state.server then\n logger.error(\"selection\", \"Claude Code integration is not running.\")\n return false\n end\n\n local sel_to_send\n\n -- If range parameters are provided, use them (for :'<,'> commands)\n if line1 and line2 then\n sel_to_send = M.get_range_selection(line1, line2)\n if not sel_to_send or sel_to_send.selection.isEmpty then\n logger.warn(\"selection\", \"Invalid range selection to send as at-mention.\")\n return false\n end\n else\n -- Use existing logic for visual mode or tracked selection\n sel_to_send = M.state.latest_selection\n\n if not sel_to_send or sel_to_send.selection.isEmpty then\n -- Fallback: try to get current visual selection directly.\n -- This helps if latest_selection was demoted or command was too fast.\n local current_visual = M.get_visual_selection()\n if current_visual and not current_visual.selection.isEmpty then\n sel_to_send = current_visual\n else\n logger.warn(\"selection\", \"No visual selection to send as at-mention.\")\n return false\n end\n end\n end\n\n -- Sanity check: ensure the selection is for the current buffer\n local current_buf_name = vim.api.nvim_buf_get_name(vim.api.nvim_get_current_buf())\n if sel_to_send.filePath ~= current_buf_name then\n logger.warn(\n \"selection\",\n \"Tracked selection is for '\"\n .. sel_to_send.filePath\n .. \"', but current buffer is '\"\n .. current_buf_name\n .. \"'. Not sending.\"\n )\n return false\n end\n\n -- Use connection-aware broadcasting from main module\n local file_path = sel_to_send.filePath\n local start_line = sel_to_send.selection.start.line -- Already 0-indexed from selection module\n local end_line = sel_to_send.selection[\"end\"].line -- Already 0-indexed\n\n local success, error_msg = claudecode_main.send_at_mention(file_path, start_line, end_line, \"ClaudeCodeSend\")\n\n if success then\n logger.debug(\"selection\", \"Visual selection sent as at-mention.\")\n\n return true\n else\n logger.error(\"selection\", \"Failed to send at-mention: \" .. (error_msg or \"unknown error\"))\n return false\n end\nend\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/visual_commands.lua", "---\n-- Visual command handling module for ClaudeCode.nvim\n-- Implements neo-tree-style visual mode exit and command processing\n-- @module claudecode.visual_commands\nlocal M = {}\n\n--- Get current vim mode with fallback for test environments\n--- @param full_mode boolean|nil Whether to get full mode info (passed to vim.fn.mode)\n--- @return string current_mode The current vim mode\nlocal function get_current_mode(full_mode)\n local current_mode = \"n\" -- Default fallback\n\n pcall(function()\n if vim.api and vim.api.nvim_get_mode then\n current_mode = vim.api.nvim_get_mode().mode\n else\n current_mode = vim.fn.mode(full_mode)\n end\n end)\n\n return current_mode\nend\n\n-- ESC key constant matching neo-tree's implementation\nlocal ESC_KEY\nlocal success = pcall(function()\n ESC_KEY = vim.api.nvim_replace_termcodes(\"\", true, false, true)\nend)\nif not success then\n ESC_KEY = \"\\27\"\nend\n\n--- Exit visual mode properly and schedule command execution\n--- @param callback function The function to call after exiting visual mode\n--- @param ... any Arguments to pass to the callback\nfunction M.exit_visual_and_schedule(callback, ...)\n local args = { ... }\n\n -- Capture visual selection data BEFORE exiting visual mode\n local visual_data = M.capture_visual_selection_data()\n\n pcall(function()\n vim.api.nvim_feedkeys(ESC_KEY, \"i\", true)\n end)\n\n -- Schedule execution until after mode change (neo-tree pattern)\n local schedule_fn = vim.schedule or function(fn)\n fn()\n end -- Fallback for test environments\n schedule_fn(function()\n -- Pass the captured visual data as the first argument\n callback(visual_data, unpack(args))\n end)\nend\n\n--- Validate that we're currently in a visual mode\n--- @return boolean true if in visual mode, false otherwise\n--- @return string|nil error message if not in visual mode\nfunction M.validate_visual_mode()\n local current_mode = get_current_mode(true)\n\n local is_visual = current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\022\"\n\n -- Additional debugging: check visual marks and cursor position\n if is_visual then\n pcall(function()\n vim.api.nvim_win_get_cursor(0)\n vim.fn.getpos(\"'<\")\n vim.fn.getpos(\"'>\")\n vim.fn.getpos(\"v\")\n end)\n end\n\n if not is_visual then\n return false, \"Not in visual mode (current mode: \" .. current_mode .. \")\"\n end\n\n return true, nil\nend\n\n--- Get visual selection range using vim marks or current cursor position\n--- @return number, number start_line, end_line (1-indexed)\nfunction M.get_visual_range()\n local start_pos, end_pos = 1, 1 -- Default fallback\n\n -- Use pcall to handle test environments\n local range_success = pcall(function()\n -- Check if we're currently in visual mode\n local current_mode = get_current_mode(true)\n local is_visual = current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\022\"\n\n if is_visual then\n -- In visual mode, ALWAYS use cursor + anchor (marks are stale until exit)\n local cursor_pos = vim.api.nvim_win_get_cursor(0)[1]\n local anchor_pos = vim.fn.getpos(\"v\")[2]\n\n if anchor_pos > 0 then\n start_pos = math.min(cursor_pos, anchor_pos)\n end_pos = math.max(cursor_pos, anchor_pos)\n else\n -- Fallback: just use current cursor position\n start_pos = cursor_pos\n end_pos = cursor_pos\n end\n else\n -- Not in visual mode, try to use the marks (they should be valid now)\n local mark_start = vim.fn.getpos(\"'<\")[2]\n local mark_end = vim.fn.getpos(\"'>\")[2]\n\n if mark_start > 0 and mark_end > 0 then\n start_pos = mark_start\n end_pos = mark_end\n else\n -- No valid marks, use cursor position\n local cursor_pos = vim.api.nvim_win_get_cursor(0)[1]\n start_pos = cursor_pos\n end_pos = cursor_pos\n end\n end\n end)\n\n if not range_success then\n return 1, 1\n end\n\n if end_pos < start_pos then\n start_pos, end_pos = end_pos, start_pos\n end\n\n -- Ensure we have valid line numbers (at least 1)\n start_pos = math.max(1, start_pos)\n end_pos = math.max(1, end_pos)\n\n return start_pos, end_pos\nend\n\n--- Check if we're in a tree buffer and get the tree state\n--- @return table|nil, string|nil tree_state, tree_type (\"neo-tree\" or \"nvim-tree\")\nfunction M.get_tree_state()\n local current_ft = \"\" -- Default fallback\n local current_win = 0 -- Default fallback\n\n -- Use pcall to handle test environments\n local state_success = pcall(function()\n current_ft = vim.bo.filetype or \"\"\n current_win = vim.api.nvim_get_current_win()\n end)\n\n if not state_success then\n return nil, nil\n end\n\n if current_ft == \"neo-tree\" then\n local manager_success, manager = pcall(require, \"neo-tree.sources.manager\")\n if not manager_success then\n return nil, nil\n end\n\n local state = manager.get_state(\"filesystem\")\n if not state then\n return nil, nil\n end\n\n -- Validate we're in the correct neo-tree window\n if state.winid and state.winid == current_win then\n return state, \"neo-tree\"\n else\n return nil, nil\n end\n elseif current_ft == \"NvimTree\" then\n local api_success, nvim_tree_api = pcall(require, \"nvim-tree.api\")\n if not api_success then\n return nil, nil\n end\n\n return nvim_tree_api, \"nvim-tree\"\n elseif current_ft == \"oil\" then\n local oil_success, oil = pcall(require, \"oil\")\n if not oil_success then\n return nil, nil\n end\n\n return oil, \"oil\"\n else\n return nil, nil\n end\nend\n\n--- Create a visual command wrapper that follows neo-tree patterns\n--- @param normal_handler function The normal command handler\n--- @param visual_handler function The visual command handler\n--- @return function The wrapped command function\nfunction M.create_visual_command_wrapper(normal_handler, visual_handler)\n return function(...)\n local current_mode = get_current_mode(true)\n\n if current_mode == \"v\" or current_mode == \"V\" or current_mode == \"\\022\" then\n -- Use the neo-tree pattern: exit visual mode, then schedule execution\n M.exit_visual_and_schedule(visual_handler, ...)\n else\n normal_handler(...)\n end\n end\nend\n\n--- Capture visual selection data while still in visual mode\n--- @return table|nil visual_data Captured data or nil if not in visual mode\nfunction M.capture_visual_selection_data()\n local valid = M.validate_visual_mode()\n if not valid then\n return nil\n end\n\n local tree_state, tree_type = M.get_tree_state()\n if not tree_state then\n return nil\n end\n\n local start_pos, end_pos = M.get_visual_range()\n\n -- Validate that we have a meaningful range\n if start_pos == 0 or end_pos == 0 then\n return nil\n end\n\n return {\n tree_state = tree_state,\n tree_type = tree_type,\n start_pos = start_pos,\n end_pos = end_pos,\n }\nend\n\n--- Extract files from visual selection in tree buffers\n--- @param visual_data table|nil Pre-captured visual selection data\n--- @return table files List of file paths\n--- @return string|nil error Error message if failed\nfunction M.get_files_from_visual_selection(visual_data)\n -- If we have pre-captured data, use it; otherwise try to get current data\n local tree_state, tree_type, start_pos, end_pos\n\n if visual_data then\n tree_state = visual_data.tree_state\n tree_type = visual_data.tree_type\n start_pos = visual_data.start_pos\n end_pos = visual_data.end_pos\n else\n local valid, err = M.validate_visual_mode()\n if not valid then\n return {}, err\n end\n\n tree_state, tree_type = M.get_tree_state()\n if not tree_state then\n return {}, \"Not in a supported tree buffer\"\n end\n\n start_pos, end_pos = M.get_visual_range()\n end\n\n if not tree_state then\n return {}, \"Not in a supported tree buffer\"\n end\n\n local files = {}\n\n if tree_type == \"neo-tree\" then\n local selected_nodes = {}\n for line = start_pos, end_pos do\n -- Neo-tree's tree:get_node() uses the line number directly (1-based)\n local node = tree_state.tree:get_node(line)\n if node then\n if node.type and node.type ~= \"message\" then\n table.insert(selected_nodes, node)\n end\n end\n end\n\n for _, node in ipairs(selected_nodes) do\n if node.type == \"file\" and node.path and node.path ~= \"\" then\n local depth = (node.get_depth and node:get_depth()) or 0\n if depth > 1 then\n table.insert(files, node.path)\n end\n elseif node.type == \"directory\" and node.path and node.path ~= \"\" then\n local depth = (node.get_depth and node:get_depth()) or 0\n if depth > 1 then\n table.insert(files, node.path)\n end\n end\n end\n elseif tree_type == \"nvim-tree\" then\n -- For nvim-tree, we need to manually map visual lines to tree nodes\n -- since nvim-tree doesn't have direct line-to-node mapping like neo-tree\n require(\"claudecode.logger\").debug(\n \"visual_commands\",\n \"Processing nvim-tree visual selection from line\",\n start_pos,\n \"to\",\n end_pos\n )\n\n local nvim_tree_api = tree_state\n local current_buf = vim.api.nvim_get_current_buf()\n\n -- Get all lines in the visual selection\n local lines = vim.api.nvim_buf_get_lines(current_buf, start_pos - 1, end_pos, false)\n\n require(\"claudecode.logger\").debug(\"visual_commands\", \"Found\", #lines, \"lines in visual selection\")\n\n -- For each line in the visual selection, try to get the corresponding node\n for i, line_content in ipairs(lines) do\n local line_num = start_pos + i - 1\n\n -- Set cursor to this line to get the node\n pcall(vim.api.nvim_win_set_cursor, 0, { line_num, 0 })\n\n -- Get node under cursor for this line\n local node_success, node = pcall(nvim_tree_api.tree.get_node_under_cursor)\n if node_success and node then\n require(\"claudecode.logger\").debug(\n \"visual_commands\",\n \"Line\",\n line_num,\n \"node type:\",\n node.type,\n \"path:\",\n node.absolute_path\n )\n\n if node.type == \"file\" and node.absolute_path and node.absolute_path ~= \"\" then\n -- Check if it's not a root-level file (basic protection)\n if not string.match(node.absolute_path, \"^/[^/]*$\") then\n table.insert(files, node.absolute_path)\n end\n elseif node.type == \"directory\" and node.absolute_path and node.absolute_path ~= \"\" then\n table.insert(files, node.absolute_path)\n end\n else\n require(\"claudecode.logger\").debug(\"visual_commands\", \"No valid node found for line\", line_num)\n end\n end\n\n require(\"claudecode.logger\").debug(\"visual_commands\", \"Extracted\", #files, \"files from nvim-tree visual selection\")\n\n -- Remove duplicates while preserving order\n local seen = {}\n local unique_files = {}\n for _, file_path in ipairs(files) do\n if not seen[file_path] then\n seen[file_path] = true\n table.insert(unique_files, file_path)\n end\n end\n files = unique_files\n elseif tree_type == \"oil\" then\n local oil = tree_state\n local bufnr = vim.api.nvim_get_current_buf()\n\n -- Get current directory once\n local dir_ok, current_dir = pcall(oil.get_current_dir, bufnr)\n if dir_ok and current_dir then\n -- Access the process_oil_entry function through a module method\n for line = start_pos, end_pos do\n local entry_ok, entry = pcall(oil.get_entry_on_line, bufnr, line)\n if entry_ok and entry and entry.name then\n -- Skip parent directory entries\n if entry.name ~= \"..\" and entry.name ~= \".\" then\n local full_path = current_dir .. entry.name\n -- Handle various entry types\n if entry.type == \"file\" or entry.type == \"link\" then\n table.insert(files, full_path)\n elseif entry.type == \"directory\" then\n -- Ensure directory paths end with /\n table.insert(files, full_path:match(\"/$\") and full_path or full_path .. \"/\")\n else\n -- For unknown types, return the path anyway\n table.insert(files, full_path)\n end\n end\n end\n end\n end\n end\n\n return files, nil\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/integrations.lua", "---\n-- Tree integration module for ClaudeCode.nvim\n-- Handles detection and selection of files from nvim-tree, neo-tree, and oil.nvim\n-- @module claudecode.integrations\nlocal M = {}\n\n--- Get selected files from the current tree explorer\n--- @return table|nil files List of file paths, or nil if error\n--- @return string|nil error Error message if operation failed\nfunction M.get_selected_files_from_tree()\n local current_ft = vim.bo.filetype\n\n if current_ft == \"NvimTree\" then\n return M._get_nvim_tree_selection()\n elseif current_ft == \"neo-tree\" then\n return M._get_neotree_selection()\n elseif current_ft == \"oil\" then\n return M._get_oil_selection()\n else\n return nil, \"Not in a supported tree buffer (current filetype: \" .. current_ft .. \")\"\n end\nend\n\n--- Get selected files from nvim-tree\n--- Supports both multi-selection (marks) and single file under cursor\n--- @return table files List of file paths\n--- @return string|nil error Error message if operation failed\nfunction M._get_nvim_tree_selection()\n local success, nvim_tree_api = pcall(require, \"nvim-tree.api\")\n if not success then\n return {}, \"nvim-tree not available\"\n end\n\n local files = {}\n\n local marks = nvim_tree_api.marks.list()\n\n if marks and #marks > 0 then\n for i, mark in ipairs(marks) do\n if mark.type == \"file\" and mark.absolute_path and mark.absolute_path ~= \"\" then\n -- Check if it's not a root-level file (basic protection)\n if not string.match(mark.absolute_path, \"^/[^/]*$\") then\n table.insert(files, mark.absolute_path)\n end\n end\n end\n\n if #files > 0 then\n return files, nil\n end\n end\n\n local node = nvim_tree_api.tree.get_node_under_cursor()\n if node then\n if node.type == \"file\" and node.absolute_path and node.absolute_path ~= \"\" then\n -- Check if it's not a root-level file (basic protection)\n if not string.match(node.absolute_path, \"^/[^/]*$\") then\n return { node.absolute_path }, nil\n else\n return {}, \"Cannot add root-level file. Please select a file in a subdirectory.\"\n end\n elseif node.type == \"directory\" and node.absolute_path and node.absolute_path ~= \"\" then\n return { node.absolute_path }, nil\n end\n end\n\n return {}, \"No file found under cursor\"\nend\n\n--- Get selected files from neo-tree\n--- Uses neo-tree's own visual selection method when in visual mode\n--- @return table files List of file paths\n--- @return string|nil error Error message if operation failed\nfunction M._get_neotree_selection()\n local success, manager = pcall(require, \"neo-tree.sources.manager\")\n if not success then\n return {}, \"neo-tree not available\"\n end\n\n local state = manager.get_state(\"filesystem\")\n if not state then\n return {}, \"neo-tree filesystem state not available\"\n end\n\n local files = {}\n\n -- Use neo-tree's own visual selection method (like their copy/paste feature)\n local mode = vim.fn.mode()\n\n if mode == \"V\" or mode == \"v\" or mode == \"\\22\" then\n local current_win = vim.api.nvim_get_current_win()\n\n if state.winid and state.winid == current_win then\n -- Use neo-tree's exact method to get visual range (from their get_selected_nodes implementation)\n local start_pos = vim.fn.getpos(\"'<\")[2]\n local end_pos = vim.fn.getpos(\"'>\")[2]\n\n -- Fallback to current cursor and anchor if marks are not valid\n if start_pos == 0 or end_pos == 0 then\n local cursor_pos = vim.api.nvim_win_get_cursor(0)[1]\n local anchor_pos = vim.fn.getpos(\"v\")[2]\n if anchor_pos > 0 then\n start_pos = math.min(cursor_pos, anchor_pos)\n end_pos = math.max(cursor_pos, anchor_pos)\n else\n start_pos = cursor_pos\n end_pos = cursor_pos\n end\n end\n\n if end_pos < start_pos then\n start_pos, end_pos = end_pos, start_pos\n end\n\n local selected_nodes = {}\n\n for line = start_pos, end_pos do\n local node = state.tree:get_node(line)\n if node then\n -- Add validation for node types before adding to selection\n if node.type and node.type ~= \"message\" then\n table.insert(selected_nodes, node)\n end\n end\n end\n\n for i, node in ipairs(selected_nodes) do\n -- Enhanced validation: check for file type and valid path\n if node.type == \"file\" and node.path and node.path ~= \"\" then\n -- Additional check: ensure it's not a root node (depth protection)\n local depth = (node.get_depth and node:get_depth()) and node:get_depth() or 0\n if depth > 1 then\n table.insert(files, node.path)\n end\n end\n end\n\n if #files > 0 then\n return files, nil\n end\n end\n end\n\n if state.tree then\n local selection = nil\n\n if state.tree.get_selection then\n selection = state.tree:get_selection()\n end\n\n if (not selection or #selection == 0) and state.selected_nodes then\n selection = state.selected_nodes\n end\n\n if selection and #selection > 0 then\n for i, node in ipairs(selection) do\n if node.type == \"file\" and node.path then\n table.insert(files, node.path)\n end\n end\n\n if #files > 0 then\n return files, nil\n end\n end\n end\n\n if state.tree then\n local node = state.tree:get_node()\n\n if node then\n if node.type == \"file\" and node.path then\n return { node.path }, nil\n elseif node.type == \"directory\" and node.path then\n return { node.path }, nil\n end\n end\n end\n\n return {}, \"No file found under cursor\"\nend\n\n--- Get selected files from oil.nvim\n--- Supports both visual selection and single file under cursor\n--- @return table files List of file paths\n--- @return string|nil error Error message if operation failed\nfunction M._get_oil_selection()\n local success, oil = pcall(require, \"oil\")\n if not success then\n return {}, \"oil.nvim not available\"\n end\n\n local bufnr = vim.api.nvim_get_current_buf() --[[@as number]]\n local files = {}\n\n -- Check if we're in visual mode\n local mode = vim.fn.mode()\n if mode == \"V\" or mode == \"v\" or mode == \"\\22\" then\n -- Visual mode: use the common visual range function\n local visual_commands = require(\"claudecode.visual_commands\")\n local start_line, end_line = visual_commands.get_visual_range()\n\n -- Get current directory once\n local dir_ok, current_dir = pcall(oil.get_current_dir, bufnr)\n if not dir_ok or not current_dir then\n return {}, \"Failed to get current directory\"\n end\n\n -- Process each line in the visual selection\n for line = start_line, end_line do\n local entry_ok, entry = pcall(oil.get_entry_on_line, bufnr, line)\n if entry_ok and entry and entry.name then\n -- Skip parent directory entries\n if entry.name ~= \"..\" and entry.name ~= \".\" then\n local full_path = current_dir .. entry.name\n -- Handle various entry types\n if entry.type == \"file\" or entry.type == \"link\" then\n table.insert(files, full_path)\n elseif entry.type == \"directory\" then\n -- Ensure directory paths end with /\n table.insert(files, full_path:match(\"/$\") and full_path or full_path .. \"/\")\n else\n -- For unknown types, return the path anyway\n table.insert(files, full_path)\n end\n end\n end\n end\n\n if #files > 0 then\n return files, nil\n end\n else\n -- Normal mode: get file under cursor with error handling\n local ok, entry = pcall(oil.get_cursor_entry)\n if not ok or not entry then\n return {}, \"Failed to get cursor entry\"\n end\n\n local dir_ok, current_dir = pcall(oil.get_current_dir, bufnr)\n if not dir_ok or not current_dir then\n return {}, \"Failed to get current directory\"\n end\n\n -- Process the entry\n if entry.name and entry.name ~= \"..\" and entry.name ~= \".\" then\n local full_path = current_dir .. entry.name\n -- Handle various entry types\n if entry.type == \"file\" or entry.type == \"link\" then\n return { full_path }, nil\n elseif entry.type == \"directory\" then\n -- Ensure directory paths end with /\n return { full_path:match(\"/$\") and full_path or full_path .. \"/\" }, nil\n else\n -- For unknown types, return the path anyway\n return { full_path }, nil\n end\n end\n end\n\n return {}, \"No file found under cursor\"\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/config.lua", "--- Manages configuration for the Claude Code Neovim integration.\n-- Provides default settings, validation, and application of user-defined configurations.\nlocal M = {}\n\nM.defaults = {\n port_range = { min = 10000, max = 65535 },\n auto_start = true,\n terminal_cmd = nil,\n log_level = \"info\",\n track_selection = true,\n visual_demotion_delay_ms = 50, -- Milliseconds to wait before demoting a visual selection\n connection_wait_delay = 200, -- Milliseconds to wait after connection before sending queued @ mentions\n connection_timeout = 10000, -- Maximum time to wait for Claude Code to connect (milliseconds)\n queue_timeout = 5000, -- Maximum time to keep @ mentions in queue (milliseconds)\n diff_opts = {\n auto_close_on_accept = true,\n show_diff_stats = true,\n vertical_split = true,\n open_in_current_tab = true, -- Use current tab instead of creating new tab\n },\n}\n\n--- Validates the provided configuration table.\n-- @param config table The configuration table to validate.\n-- @return boolean true if the configuration is valid.\n-- @error string if any configuration option is invalid.\nfunction M.validate(config)\n assert(\n type(config.port_range) == \"table\"\n and type(config.port_range.min) == \"number\"\n and type(config.port_range.max) == \"number\"\n and config.port_range.min > 0\n and config.port_range.max <= 65535\n and config.port_range.min <= config.port_range.max,\n \"Invalid port range\"\n )\n\n assert(type(config.auto_start) == \"boolean\", \"auto_start must be a boolean\")\n\n assert(config.terminal_cmd == nil or type(config.terminal_cmd) == \"string\", \"terminal_cmd must be nil or a string\")\n\n local valid_log_levels = { \"trace\", \"debug\", \"info\", \"warn\", \"error\" }\n local is_valid_log_level = false\n for _, level in ipairs(valid_log_levels) do\n if config.log_level == level then\n is_valid_log_level = true\n break\n end\n end\n assert(is_valid_log_level, \"log_level must be one of: \" .. table.concat(valid_log_levels, \", \"))\n\n assert(type(config.track_selection) == \"boolean\", \"track_selection must be a boolean\")\n\n assert(\n type(config.visual_demotion_delay_ms) == \"number\" and config.visual_demotion_delay_ms >= 0,\n \"visual_demotion_delay_ms must be a non-negative number\"\n )\n\n assert(\n type(config.connection_wait_delay) == \"number\" and config.connection_wait_delay >= 0,\n \"connection_wait_delay must be a non-negative number\"\n )\n\n assert(\n type(config.connection_timeout) == \"number\" and config.connection_timeout > 0,\n \"connection_timeout must be a positive number\"\n )\n\n assert(type(config.queue_timeout) == \"number\" and config.queue_timeout > 0, \"queue_timeout must be a positive number\")\n\n assert(type(config.diff_opts) == \"table\", \"diff_opts must be a table\")\n assert(type(config.diff_opts.auto_close_on_accept) == \"boolean\", \"diff_opts.auto_close_on_accept must be a boolean\")\n assert(type(config.diff_opts.show_diff_stats) == \"boolean\", \"diff_opts.show_diff_stats must be a boolean\")\n assert(type(config.diff_opts.vertical_split) == \"boolean\", \"diff_opts.vertical_split must be a boolean\")\n assert(type(config.diff_opts.open_in_current_tab) == \"boolean\", \"diff_opts.open_in_current_tab must be a boolean\")\n\n return true\nend\n\n--- Applies user configuration on top of default settings and validates the result.\n-- @param user_config table|nil The user-provided configuration table.\n-- @return table The final, validated configuration table.\nfunction M.apply(user_config)\n local config = vim.deepcopy(M.defaults)\n\n if user_config then\n config = vim.tbl_deep_extend(\"force\", config, user_config)\n end\n\n M.validate(config)\n\n return config\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/init.lua", "---@brief WebSocket server for Claude Code Neovim integration\nlocal claudecode_main = require(\"claudecode\") -- Added for version access\nlocal logger = require(\"claudecode.logger\")\nlocal tcp_server = require(\"claudecode.server.tcp\")\nlocal tools = require(\"claudecode.tools.init\") -- Added: Require the tools module\n\nlocal MCP_PROTOCOL_VERSION = \"2024-11-05\"\n\nlocal M = {}\n\n---@class ServerState\n---@field server table|nil The TCP server instance\n---@field port number|nil The port server is running on\n---@field auth_token string|nil The authentication token for validating connections\n---@field clients table A list of connected clients\n---@field handlers table Message handlers by method name\n---@field ping_timer table|nil Timer for sending pings\nM.state = {\n server = nil,\n port = nil,\n auth_token = nil,\n clients = {},\n handlers = {},\n ping_timer = nil,\n}\n\n---@brief Initialize the WebSocket server\n---@param config table Configuration options\n---@param auth_token string|nil The authentication token for validating connections\n---@return boolean success Whether server started successfully\n---@return number|string port_or_error Port number or error message\nfunction M.start(config, auth_token)\n if M.state.server then\n return false, \"Server already running\"\n end\n\n M.state.auth_token = auth_token\n\n -- Log authentication state\n if auth_token then\n logger.debug(\"server\", \"Starting WebSocket server with authentication enabled\")\n logger.debug(\"server\", \"Auth token length:\", #auth_token)\n else\n logger.debug(\"server\", \"Starting WebSocket server WITHOUT authentication (insecure)\")\n end\n\n M.register_handlers()\n\n tools.setup(M)\n\n local callbacks = {\n on_message = function(client, message)\n M._handle_message(client, message)\n end,\n on_connect = function(client)\n M.state.clients[client.id] = client\n\n -- Log connection with auth status\n if M.state.auth_token then\n logger.debug(\"server\", \"Authenticated WebSocket client connected:\", client.id)\n else\n logger.debug(\"server\", \"WebSocket client connected (no auth):\", client.id)\n end\n\n -- Notify main module about new connection for queue processing\n local main_module = require(\"claudecode\")\n if main_module._process_queued_mentions then\n vim.schedule(function()\n main_module._process_queued_mentions()\n end)\n end\n end,\n on_disconnect = function(client, code, reason)\n M.state.clients[client.id] = nil\n logger.debug(\n \"server\",\n \"WebSocket client disconnected:\",\n client.id,\n \"(code:\",\n code,\n \", reason:\",\n (reason or \"N/A\") .. \")\"\n )\n end,\n on_error = function(error_msg)\n logger.error(\"server\", \"WebSocket server error:\", error_msg)\n end,\n }\n\n local server, error_msg = tcp_server.create_server(config, callbacks, M.state.auth_token)\n if not server then\n return false, error_msg or \"Unknown server creation error\"\n end\n\n M.state.server = server\n M.state.port = server.port\n\n M.state.ping_timer = tcp_server.start_ping_timer(server, 30000) -- Start ping timer to keep connections alive\n\n return true, server.port\nend\n\n---@brief Stop the WebSocket server\n---@return boolean success Whether server stopped successfully\n---@return string|nil error_message Error message if any\nfunction M.stop()\n if not M.state.server then\n return false, \"Server not running\"\n end\n\n if M.state.ping_timer then\n M.state.ping_timer:stop()\n M.state.ping_timer:close()\n M.state.ping_timer = nil\n end\n\n tcp_server.stop_server(M.state.server)\n\n -- CRITICAL: Clear global deferred responses to prevent memory leaks and hanging\n if _G.claude_deferred_responses then\n _G.claude_deferred_responses = {}\n end\n\n M.state.server = nil\n M.state.port = nil\n M.state.auth_token = nil\n M.state.clients = {}\n\n return true\nend\n\n---@brief Handle incoming WebSocket message\n---@param client table The client that sent the message\n---@param message string The JSON-RPC message\nfunction M._handle_message(client, message)\n local success, parsed = pcall(vim.json.decode, message)\n if not success then\n M.send_response(client, nil, nil, {\n code = -32700,\n message = \"Parse error\",\n data = \"Invalid JSON\",\n })\n return\n end\n\n if type(parsed) ~= \"table\" or parsed.jsonrpc ~= \"2.0\" then\n M.send_response(client, parsed.id, nil, {\n code = -32600,\n message = \"Invalid Request\",\n data = \"Not a valid JSON-RPC 2.0 request\",\n })\n return\n end\n\n if parsed.id then\n M._handle_request(client, parsed)\n else\n M._handle_notification(client, parsed)\n end\nend\n\n---@brief Handle JSON-RPC request (requires response)\n---@param client table The client that sent the request\n---@param request table The parsed JSON-RPC request\nfunction M._handle_request(client, request)\n local method = request.method\n local params = request.params or {}\n local id = request.id\n\n local handler = M.state.handlers[method]\n if not handler then\n M.send_response(client, id, nil, {\n code = -32601,\n message = \"Method not found\",\n data = \"Unknown method: \" .. tostring(method),\n })\n return\n end\n\n local success, result, error_data = pcall(handler, client, params)\n if success then\n -- Check if this is a deferred response (blocking tool)\n if result and result._deferred then\n logger.debug(\"server\", \"Handler returned deferred response - storing for later\")\n -- Store the request info for later response\n local deferred_info = {\n client = result.client,\n id = id,\n coroutine = result.coroutine,\n method = method,\n params = result.params,\n }\n -- Set up the completion callback\n M._setup_deferred_response(deferred_info)\n return -- Don't send response now\n end\n\n if error_data then\n M.send_response(client, id, nil, error_data)\n else\n M.send_response(client, id, result, nil)\n end\n else\n M.send_response(client, id, nil, {\n code = -32603,\n message = \"Internal error\",\n data = tostring(result), -- result contains error message when pcall fails\n })\n end\nend\n\n---@brief Set up deferred response handling for blocking tools\n---@param deferred_info table Information about the deferred request\n-- Note: deferred_responses table removed - using global _G.claude_deferred_responses instead\n\n-- Add a unique module ID to detect reloading\nlocal module_instance_id = math.random(10000, 99999)\nlogger.debug(\"server\", \"Server module loaded with instance ID:\", module_instance_id)\n\n-- Note: debug_deferred_table function removed as deferred_responses table is no longer used\n\nfunction M._setup_deferred_response(deferred_info)\n local co = deferred_info.coroutine\n\n logger.debug(\"server\", \"Setting up deferred response for coroutine:\", tostring(co))\n logger.debug(\"server\", \"Storage happening in module instance:\", module_instance_id)\n\n -- Create a response sender function that captures the current server instance\n local response_sender = function(result)\n logger.debug(\"server\", \"Deferred response triggered for coroutine:\", tostring(co))\n\n if result and result.content then\n -- MCP-compliant response\n M.send_response(deferred_info.client, deferred_info.id, result, nil)\n elseif result and result.error then\n -- Error response\n M.send_response(deferred_info.client, deferred_info.id, nil, result.error)\n else\n -- Fallback error\n M.send_response(deferred_info.client, deferred_info.id, nil, {\n code = -32603,\n message = \"Internal error\",\n data = \"Deferred response completed with unexpected format\",\n })\n end\n end\n\n -- Store the response sender in a global location that won't be affected by module reloading\n if not _G.claude_deferred_responses then\n _G.claude_deferred_responses = {}\n end\n _G.claude_deferred_responses[tostring(co)] = response_sender\n\n logger.debug(\"server\", \"Stored response sender in global table for coroutine:\", tostring(co))\nend\n\n-- Note: _send_deferred_response is no longer needed\n-- Responses are now handled via the global _G.claude_deferred_responses table\n-- to avoid module reloading issues\n\n---@brief Handle JSON-RPC notification (no response)\n---@param client table The client that sent the notification\n---@param notification table The parsed JSON-RPC notification\nfunction M._handle_notification(client, notification)\n local method = notification.method\n local params = notification.params or {}\n\n local handler = M.state.handlers[method]\n if handler then\n pcall(handler, client, params)\n end\nend\n\n---@brief Register message handlers for the server\nfunction M.register_handlers()\n M.state.handlers = {\n [\"initialize\"] = function(client, params) -- Renamed from mcp.connect\n return {\n protocolVersion = MCP_PROTOCOL_VERSION,\n capabilities = {\n logging = vim.empty_dict(), -- Ensure this is an object {} not an array []\n prompts = { listChanged = true },\n resources = { subscribe = true, listChanged = true },\n tools = { listChanged = true },\n },\n serverInfo = {\n name = \"claudecode-neovim\",\n version = claudecode_main.version:string(),\n },\n }\n end,\n\n [\"notifications/initialized\"] = function(client, params) -- Added handler for initialized notification\n end,\n\n [\"prompts/list\"] = function(client, params) -- Added handler for prompts/list\n return {\n prompts = {}, -- This will be encoded as an empty JSON array\n }\n end,\n\n [\"tools/list\"] = function(_client, _params)\n return {\n tools = tools.get_tool_list(),\n }\n end,\n\n [\"tools/call\"] = function(client, params)\n logger.debug(\n \"server\",\n \"Received tools/call. Tool: \",\n params and params.name,\n \" Arguments: \",\n vim.inspect(params and params.arguments)\n )\n local result_or_error_table = tools.handle_invoke(client, params)\n\n -- Check if this is a deferred response (blocking tool)\n if result_or_error_table and result_or_error_table._deferred then\n logger.debug(\"server\", \"Tool is blocking - setting up deferred response\")\n -- Return the deferred response directly - _handle_request will process it\n return result_or_error_table\n end\n\n -- Log the response for debugging\n logger.debug(\"server\", \"Response - tools/call\", params and params.name .. \":\", vim.inspect(result_or_error_table))\n\n if result_or_error_table.error then\n return nil, result_or_error_table.error\n elseif result_or_error_table.result then\n return result_or_error_table.result, nil\n else\n -- Should not happen if tools.handle_invoke behaves correctly\n return nil,\n {\n code = -32603,\n message = \"Internal error\",\n data = \"Tool handler returned unexpected format\",\n }\n end\n end,\n }\nend\n\n---@brief Send a message to a client\n---@param client table The client to send to\n---@param method string The method name\n---@param params table|nil The parameters to send\n---@return boolean success Whether message was sent successfully\nfunction M.send(client, method, params)\n if not M.state.server then\n return false\n end\n\n local message = {\n jsonrpc = \"2.0\",\n method = method,\n params = params or vim.empty_dict(),\n }\n\n local json_message = vim.json.encode(message)\n tcp_server.send_to_client(M.state.server, client.id, json_message)\n return true\nend\n\n---@brief Send a response to a client\n---@param client table The client to send to\n---@param id number|string|nil The request ID to respond to\n---@param result any|nil The result data if successful\n---@param error_data table|nil The error data if failed\n---@return boolean success Whether response was sent successfully\nfunction M.send_response(client, id, result, error_data)\n if not M.state.server then\n return false\n end\n\n local response = {\n jsonrpc = \"2.0\",\n id = id,\n }\n\n if error_data then\n response.error = error_data\n else\n response.result = result\n end\n\n local json_response = vim.json.encode(response)\n tcp_server.send_to_client(M.state.server, client.id, json_response)\n return true\nend\n\n---@brief Broadcast a message to all connected clients\n---@param method string The method name\n---@param params table|nil The parameters to send\n---@return boolean success Whether broadcast was successful\nfunction M.broadcast(method, params)\n if not M.state.server then\n return false\n end\n\n local message = {\n jsonrpc = \"2.0\",\n method = method,\n params = params or vim.empty_dict(),\n }\n\n local json_message = vim.json.encode(message)\n tcp_server.broadcast(M.state.server, json_message)\n return true\nend\n\n---@brief Get server status information\n---@return table status Server status information\nfunction M.get_status()\n if not M.state.server then\n return {\n running = false,\n port = nil,\n client_count = 0,\n }\n end\n\n return {\n running = true,\n port = M.state.port,\n client_count = tcp_server.get_client_count(M.state.server),\n clients = tcp_server.get_clients_info(M.state.server),\n }\nend\n\nreturn M\n"], ["/claudecode.nvim/dev-config.lua", "-- Development configuration for claudecode.nvim\n-- This is Thomas's personal config for developing claudecode.nvim\n-- Symlink this to your personal Neovim config:\n-- ln -s ~/projects/claudecode.nvim/dev-config.lua ~/.config/nvim/lua/plugins/dev-claudecode.lua\n\nreturn {\n \"coder/claudecode.nvim\",\n dev = true, -- Use local development version\n keys = {\n -- AI/Claude Code prefix\n { \"a\", nil, desc = \"AI/Claude Code\" },\n\n -- Core Claude commands\n { \"ac\", \"ClaudeCode\", desc = \"Toggle Claude\" },\n { \"af\", \"ClaudeCodeFocus\", desc = \"Focus Claude\" },\n { \"ar\", \"ClaudeCode --resume\", desc = \"Resume Claude\" },\n { \"aC\", \"ClaudeCode --continue\", desc = \"Continue Claude\" },\n\n -- Context sending\n { \"ab\", \"ClaudeCodeAdd %\", desc = \"Add current buffer\" },\n { \"as\", \"ClaudeCodeSend\", mode = \"v\", desc = \"Send to Claude\" },\n {\n \"as\",\n \"ClaudeCodeTreeAdd\",\n desc = \"Add file from tree\",\n ft = { \"NvimTree\", \"neo-tree\", \"oil\" },\n },\n\n -- Development helpers\n { \"ao\", \"ClaudeCodeOpen\", desc = \"Open Claude\" },\n { \"aq\", \"ClaudeCodeClose\", desc = \"Close Claude\" },\n { \"ai\", \"ClaudeCodeStatus\", desc = \"Claude Status\" },\n { \"aS\", \"ClaudeCodeStart\", desc = \"Start Claude Server\" },\n { \"aQ\", \"ClaudeCodeStop\", desc = \"Stop Claude Server\" },\n\n -- Diff management (buffer-local, only active in diff buffers)\n { \"aa\", \"ClaudeCodeDiffAccept\", desc = \"Accept diff\" },\n { \"ad\", \"ClaudeCodeDiffDeny\", desc = \"Deny diff\" },\n },\n\n -- Development configuration - all options shown with defaults commented out\n opts = {\n -- Server Configuration\n -- port_range = { min = 10000, max = 65535 }, -- WebSocket server port range\n -- auto_start = true, -- Auto-start server on Neovim startup\n -- log_level = \"info\", -- \"trace\", \"debug\", \"info\", \"warn\", \"error\"\n -- terminal_cmd = nil, -- Custom terminal command (default: \"claude\")\n\n -- Selection Tracking\n -- track_selection = true, -- Enable real-time selection tracking\n -- visual_demotion_delay_ms = 50, -- Delay before demoting visual selection (ms)\n\n -- Connection Management\n -- connection_wait_delay = 200, -- Wait time after connection before sending queued @ mentions (ms)\n -- connection_timeout = 10000, -- Max time to wait for Claude Code connection (ms)\n -- queue_timeout = 5000, -- Max time to keep @ mentions in queue (ms)\n\n -- Diff Integration\n -- diff_opts = {\n -- auto_close_on_accept = true, -- Close diff view after accepting changes\n -- show_diff_stats = true, -- Show diff statistics\n -- vertical_split = true, -- Use vertical split for diffs\n -- open_in_current_tab = true, -- Open diffs in current tab vs new tab\n -- },\n\n -- Terminal Configuration\n -- terminal = {\n -- split_side = \"right\", -- \"left\" or \"right\"\n -- split_width_percentage = 0.30, -- Width as percentage (0.0 to 1.0)\n -- provider = \"auto\", -- \"auto\", \"snacks\", or \"native\"\n -- show_native_term_exit_tip = true, -- Show exit tip for native terminal\n -- auto_close = true, -- Auto-close terminal after command completion\n -- },\n\n -- Development overrides (uncomment as needed)\n -- log_level = \"debug\",\n -- terminal = {\n -- provider = \"native\",\n -- auto_close = false, -- Keep terminals open to see output\n -- },\n },\n}\n"], ["/claudecode.nvim/lua/claudecode/logger.lua", "---@brief Centralized logger for Claude Code Neovim integration.\n-- Provides level-based logging.\nlocal M = {}\n\nM.levels = {\n ERROR = 1,\n WARN = 2,\n INFO = 3,\n DEBUG = 4,\n TRACE = 5,\n}\n\nlocal level_values = {\n error = M.levels.ERROR,\n warn = M.levels.WARN,\n info = M.levels.INFO,\n debug = M.levels.DEBUG,\n trace = M.levels.TRACE,\n}\n\nlocal current_log_level_value = M.levels.INFO\n\n--- @param plugin_config table The configuration table (e.g., from claudecode.init.state.config).\nfunction M.setup(plugin_config)\n local conf = plugin_config\n\n if conf and conf.log_level and level_values[conf.log_level] then\n current_log_level_value = level_values[conf.log_level]\n else\n vim.notify(\n \"ClaudeCode Logger: Invalid or missing log_level in configuration (received: \"\n .. tostring(conf and conf.log_level)\n .. \"). Defaulting to INFO.\",\n vim.log.levels.WARN\n )\n current_log_level_value = M.levels.INFO\n end\nend\n\nlocal function log(level, component, message_parts)\n if level > current_log_level_value then\n return\n end\n\n local prefix = \"[ClaudeCode]\"\n if component then\n prefix = prefix .. \" [\" .. component .. \"]\"\n end\n\n local level_name = \"UNKNOWN\"\n for name, val in pairs(M.levels) do\n if val == level then\n level_name = name\n break\n end\n end\n prefix = prefix .. \" [\" .. level_name .. \"]\"\n\n local message = \"\"\n for i, part in ipairs(message_parts) do\n if i > 1 then\n message = message .. \" \"\n end\n if type(part) == \"table\" or type(part) == \"boolean\" then\n message = message .. vim.inspect(part)\n else\n message = message .. tostring(part)\n end\n end\n\n if level == M.levels.ERROR then\n vim.schedule(function()\n vim.notify(prefix .. \" \" .. message, vim.log.levels.ERROR, { title = \"ClaudeCode Error\" })\n end)\n elseif level == M.levels.WARN then\n vim.schedule(function()\n vim.notify(prefix .. \" \" .. message, vim.log.levels.WARN, { title = \"ClaudeCode Warning\" })\n end)\n else\n -- For INFO, DEBUG, TRACE, use nvim_echo to avoid flooding notifications,\n -- to make them appear in :messages, and wrap in vim.schedule\n -- to avoid \"nvim_echo must not be called in a fast event context\".\n vim.schedule(function()\n vim.api.nvim_echo({ { prefix .. \" \" .. message, \"Normal\" } }, true, {})\n end)\n end\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.error(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.ERROR, nil, { component, ... })\n else\n log(M.levels.ERROR, component, { ... })\n end\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.warn(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.WARN, nil, { component, ... })\n else\n log(M.levels.WARN, component, { ... })\n end\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.info(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.INFO, nil, { component, ... })\n else\n log(M.levels.INFO, component, { ... })\n end\nend\n\n--- Check if a specific log level is enabled\n-- @param level_name string The level name (\"error\", \"warn\", \"info\", \"debug\", \"trace\")\n-- @return boolean Whether the level is enabled\nfunction M.is_level_enabled(level_name)\n local level_value = level_values[level_name]\n if not level_value then\n return false\n end\n return level_value <= current_log_level_value\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.debug(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.DEBUG, nil, { component, ... })\n else\n log(M.levels.DEBUG, component, { ... })\n end\nend\n\n--- @param component string|nil Optional component/module name.\n-- @param ... any Varargs representing parts of the message.\nfunction M.trace(component, ...)\n if type(component) ~= \"string\" then\n log(M.levels.TRACE, nil, { component, ... })\n else\n log(M.levels.TRACE, component, { ... })\n end\nend\n\nlocal default_config_for_initial_setup = require(\"claudecode.config\").defaults\nM.setup(default_config_for_initial_setup)\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/meta/vim.lua", "---@meta vim_api_definitions\n-- This file provides type definitions for parts of the Neovim API\n-- to help the Lua language server (LuaLS) with diagnostics.\n\n---@class vim_log_levels\n---@field NONE number\n---@field ERROR number\n---@field WARN number\n---@field INFO number\n---@field DEBUG number\n---@field TRACE number\n\n---@class vim_log\n---@field levels vim_log_levels\n\n---@class vim_notify_opts\n---@field title string|nil\n---@field icon string|nil\n---@field on_open fun(winid: number)|nil\n---@field on_close fun()|nil\n---@field timeout number|nil\n---@field keep fun()|nil\n---@field plugin string|nil\n---@field hide_from_history boolean|nil\n---@field once boolean|nil\n---@field on_close_timeout number|nil\n\n---@class vim_options_table: table\n---@field columns number Global option: width of the screen\n---@field lines number Global option: height of the screen\n-- Add other commonly used vim.o options as needed\n\n---@class vim_buffer_options_table: table\n\n---@class vim_bo_proxy: vim_buffer_options_table\n---@field __index fun(self: vim_bo_proxy, bufnr: number): vim_buffer_options_table Allows vim.bo[bufnr]\n\n---@class vim_diagnostic_info\n---@field bufnr number\n---@field col number\n---@field end_col number|nil\n---@field end_lnum number|nil\n---@field lnum number\n---@field message string\n---@field severity number\n---@field source string|nil\n---@field user_data any|nil\n\n---@class vim_diagnostic_module\n---@field get fun(bufnr?: number, ns_id?: number): vim_diagnostic_info[]\n-- Add other vim.diagnostic functions as needed, e.g., get_namespace, set, etc.\n\n---@class vim_fs_module\n---@field remove fun(path: string, opts?: {force?: boolean, recursive?: boolean}):boolean|nil\n\n---@class vim_filetype_module\n---@field match fun(args: {filename: string, contents?: string}):string|nil\n\n---@class vim_fn_table\n---@field mode fun(mode_str?: string, full?: boolean|number):string\n---@field delete fun(name: string, flags?: string):integer For file deletion\n---@field filereadable fun(file: string):integer\n---@field fnamemodify fun(fname: string, mods: string):string\n---@field expand fun(str: string, ...):string|table\n---@field getcwd fun(winid?: number, tabnr?: number):string\n---@field mkdir fun(name: string, path?: string, prot?: number):integer\n---@field buflisted fun(bufnr: number|string):integer\n---@field bufname fun(expr?: number|string):string\n---@field bufnr fun(expr?: string|number, create?: boolean):number\n---@field win_getid fun(win?: number, tab?: number):number\n---@field win_gotoid fun(winid: number):boolean\n---@field line fun(expr: string, winid?: number):number\n---@field col fun(expr: string, winid?: number):number\n---@field virtcol fun(expr: string|string[], winid?: number):number|number[]\n---@field getpos fun(expr: string, winid?: number):number[]\n---@field setpos fun(expr: string, pos: number[], winid?: number):boolean\n---@field tempname fun():string\n---@field globpath fun(path: string, expr: string, ...):string\n---@field stdpath fun(type: \"cache\"|\"config\"|\"data\"|\"log\"|\"run\"|\"state\"|\"config_dirs\"|\"data_dirs\"):string|string[]\n---@field json_encode fun(expr: any):string\n---@field json_decode fun(string: string, opts?: {null_value?: any}):any\n---@field termopen fun(cmd: string|string[], opts?: table):number For vim.fn.termopen()\n-- Add other vim.fn functions as needed\n\n---@class vim_v_table\n---@field event table Event data containing status and other event information\n\n---@class vim_global_api\n---@field notify fun(msg: string | string[], level?: number, opts?: vim_notify_opts):nil\n---@field log vim_log\n---@field v vim_v_table For vim.v.event access\n---@field _last_echo table[]? table of tables, e.g. { {\"message\", \"HighlightGroup\"} }\n---@field _last_error string?\n---@field o vim_options_table For vim.o.option_name\n---@field bo vim_bo_proxy For vim.bo.option_name and vim.bo[bufnr].option_name\n---@field diagnostic vim_diagnostic_module For vim.diagnostic.*\n---@field empty_dict fun(): table For vim.empty_dict()\n---@field schedule_wrap fun(fn: function): function For vim.schedule_wrap()\n---@field deepcopy fun(val: any): any For vim.deepcopy() -- Added based on test mocks\n---@field _current_mode string? For mocks in tests\n---@class vim_api_table\n---@field nvim_create_augroup fun(name: string, opts: {clear: boolean}):integer\n---@field nvim_create_autocmd fun(event: string|string[], opts: {group?: string|integer, pattern?: string|string[], buffer?: number, callback?: function|string, once?: boolean, desc?: string}):integer\n---@field nvim_clear_autocmds fun(opts: {group?: string|integer, event?: string|string[], pattern?: string|string[], buffer?: number}):nil\n---@field nvim_get_current_buf fun():integer\n---@field nvim_get_mode fun():{mode: string, blocking: boolean}\n---@field nvim_win_get_cursor fun(window: integer):integer[] Returns [row, col] (1-based for row, 0-based for col)\n---@field nvim_buf_get_name fun(buffer: integer):string\n---@field nvim_buf_get_lines fun(buffer: integer, start: integer, end_line: integer, strict_indexing: boolean):string[]\n-- Add other nvim_api functions as needed\n---@field cmd fun(command: string):nil For vim.cmd() -- Added based on test mocks\n---@field api vim_api_table For vim.api.*\n---@field fn vim_fn_table For vim.fn.*\n---@field fs vim_fs_module For vim.fs.*\n---@field filetype vim_filetype_module For vim.filetype.*\n---@field test vim_test_utils? For test utility mocks\n---@field split fun(str: string, pat?: string, opts?: {plain?: boolean, trimempty?: boolean}):string[] For vim.split()\n-- Add other vim object definitions here if they cause linting issues\n-- e.g. vim.api, vim.loop, vim.deepcopy, etc.\n\n---@class SpyCall\n---@field vals table[] table of arguments passed to the call\n---@field self any the 'self' object for the call if it was a method\n\n---@class SpyInformation\n---@field calls SpyCall[] A list of calls made to the spy.\n---@field call_count number The number of times the spy has been called.\n-- Add other spy properties if needed e.g. returned, threw\n\n---@class SpyAsserts\n---@field was_called fun(self: SpyAsserts, count?: number):boolean\n---@field was_called_with fun(self: SpyAsserts, ...):boolean\n---@field was_not_called fun(self: SpyAsserts):boolean\n-- Add other spy asserts if needed\n\n---@class SpyableFunction : function\n---@field __call fun(self: SpyableFunction, ...):any\n---@field spy fun(self: SpyableFunction):SpyAsserts Returns an assertion object for the spy.\n---@field calls SpyInformation[]? Information about calls made to the spied function.\n-- Note: In some spy libraries, 'calls' might be directly on the spied function,\n-- or on an object returned by `spy()`. Adjust as per your spy library's specifics.\n-- For busted's default spy, `calls` is often directly on the spied function.\n\n---@class vim_test_utils\n---@field add_buffer fun(bufnr: number, filename: string, content: string|string[]):nil\n---@field set_cursor fun(bufnr: number, row: number, col: number):nil\n-- Add other test utility functions as needed\n\n-- This section helps LuaLS understand that 'vim' is a global variable\n-- with the structure defined above. It's for type hinting only and\n-- does not execute or overwrite the actual 'vim' global provided by Neovim.\n---@type vim_global_api\n"], ["/claudecode.nvim/lua/claudecode/lockfile.lua", "---@brief [[\n--- Lock file management for Claude Code Neovim integration.\n--- This module handles creation, removal and updating of lock files\n--- which allow Claude Code CLI to discover the Neovim integration.\n---@brief ]]\n\nlocal M = {}\n\n--- Path to the lock file directory\n---@return string lock_dir The path to the lock file directory\nlocal function get_lock_dir()\n local claude_config_dir = os.getenv(\"CLAUDE_CONFIG_DIR\")\n if claude_config_dir and claude_config_dir ~= \"\" then\n return vim.fn.expand(claude_config_dir .. \"/ide\")\n else\n return vim.fn.expand(\"~/.claude/ide\")\n end\nend\n\nM.lock_dir = get_lock_dir()\n\n-- Track if random seed has been initialized\nlocal random_initialized = false\n\n--- Generate a random UUID for authentication\n---@return string uuid A randomly generated UUID string\nlocal function generate_auth_token()\n -- Initialize random seed only once\n if not random_initialized then\n local seed = os.time() + vim.fn.getpid()\n -- Add more entropy if available\n if vim.loop and vim.loop.hrtime then\n seed = seed + (vim.loop.hrtime() % 1000000)\n end\n math.randomseed(seed)\n\n -- Call math.random a few times to \"warm up\" the generator\n for _ = 1, 10 do\n math.random()\n end\n random_initialized = true\n end\n\n -- Generate UUID v4 format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n local template = \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\"\n local uuid = template:gsub(\"[xy]\", function(c)\n local v = (c == \"x\") and math.random(0, 15) or math.random(8, 11)\n return string.format(\"%x\", v)\n end)\n\n -- Validate generated UUID format\n if not uuid:match(\"^[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+$\") then\n error(\"Generated invalid UUID format: \" .. uuid)\n end\n\n if #uuid ~= 36 then\n error(\"Generated UUID has invalid length: \" .. #uuid .. \" (expected 36)\")\n end\n\n return uuid\nend\n\n--- Generate a new authentication token\n---@return string auth_token A newly generated authentication token\nfunction M.generate_auth_token()\n return generate_auth_token()\nend\n\n--- Create the lock file for a specified WebSocket port\n---@param port number The port number for the WebSocket server\n---@param auth_token string|nil Optional pre-generated auth token (generates new one if not provided)\n---@return boolean success Whether the operation was successful\n---@return string result_or_error The lock file path if successful, or error message if failed\n---@return string? auth_token The authentication token if successful\nfunction M.create(port, auth_token)\n if not port or type(port) ~= \"number\" then\n return false, \"Invalid port number\"\n end\n\n if port < 1 or port > 65535 then\n return false, \"Port number out of valid range (1-65535): \" .. tostring(port)\n end\n\n local ok, err = pcall(function()\n return vim.fn.mkdir(M.lock_dir, \"p\")\n end)\n\n if not ok then\n return false, \"Failed to create lock directory: \" .. (err or \"unknown error\")\n end\n\n local lock_path = M.lock_dir .. \"/\" .. port .. \".lock\"\n\n local workspace_folders = M.get_workspace_folders()\n if not auth_token then\n local auth_success, auth_result = pcall(generate_auth_token)\n if not auth_success then\n return false, \"Failed to generate authentication token: \" .. (auth_result or \"unknown error\")\n end\n auth_token = auth_result\n else\n -- Validate provided auth_token\n if type(auth_token) ~= \"string\" then\n return false, \"Authentication token must be a string, got \" .. type(auth_token)\n end\n if #auth_token < 10 then\n return false, \"Authentication token too short (minimum 10 characters)\"\n end\n if #auth_token > 500 then\n return false, \"Authentication token too long (maximum 500 characters)\"\n end\n end\n\n -- Prepare lock file content\n local lock_content = {\n pid = vim.fn.getpid(),\n workspaceFolders = workspace_folders,\n ideName = \"Neovim\",\n transport = \"ws\",\n authToken = auth_token,\n }\n\n local json\n local ok_json, json_err = pcall(function()\n json = vim.json.encode(lock_content)\n return json\n end)\n\n if not ok_json or not json then\n return false, \"Failed to encode lock file content: \" .. (json_err or \"unknown error\")\n end\n\n local file = io.open(lock_path, \"w\")\n if not file then\n return false, \"Failed to create lock file: \" .. lock_path\n end\n\n local write_ok, write_err = pcall(function()\n file:write(json)\n file:close()\n end)\n\n if not write_ok then\n pcall(function()\n file:close()\n end)\n return false, \"Failed to write lock file: \" .. (write_err or \"unknown error\")\n end\n\n return true, lock_path, auth_token\nend\n\n--- Remove the lock file for the given port\n---@param port number The port number of the WebSocket server\n---@return boolean success Whether the operation was successful\n---@return string? error Error message if operation failed\nfunction M.remove(port)\n if not port or type(port) ~= \"number\" then\n return false, \"Invalid port number\"\n end\n\n local lock_path = M.lock_dir .. \"/\" .. port .. \".lock\"\n\n if vim.fn.filereadable(lock_path) == 0 then\n return false, \"Lock file does not exist: \" .. lock_path\n end\n\n local ok, err = pcall(function()\n return os.remove(lock_path)\n end)\n\n if not ok then\n return false, \"Failed to remove lock file: \" .. (err or \"unknown error\")\n end\n\n return true\nend\n\n--- Update the lock file for the given port\n---@param port number The port number of the WebSocket server\n---@return boolean success Whether the operation was successful\n---@return string result_or_error The lock file path if successful, or error message if failed\n---@return string? auth_token The authentication token if successful\nfunction M.update(port)\n if not port or type(port) ~= \"number\" then\n return false, \"Invalid port number\"\n end\n\n local exists = vim.fn.filereadable(M.lock_dir .. \"/\" .. port .. \".lock\") == 1\n if exists then\n local remove_ok, remove_err = M.remove(port)\n if not remove_ok then\n return false, \"Failed to update lock file: \" .. remove_err\n end\n end\n\n return M.create(port)\nend\n\n--- Read the authentication token from a lock file\n---@param port number The port number of the WebSocket server\n---@return boolean success Whether the operation was successful\n---@return string? auth_token The authentication token if successful, or nil if failed\n---@return string? error Error message if operation failed\nfunction M.get_auth_token(port)\n if not port or type(port) ~= \"number\" then\n return false, nil, \"Invalid port number\"\n end\n\n local lock_path = M.lock_dir .. \"/\" .. port .. \".lock\"\n\n if vim.fn.filereadable(lock_path) == 0 then\n return false, nil, \"Lock file does not exist: \" .. lock_path\n end\n\n local file = io.open(lock_path, \"r\")\n if not file then\n return false, nil, \"Failed to open lock file: \" .. lock_path\n end\n\n local content = file:read(\"*all\")\n file:close()\n\n if not content or content == \"\" then\n return false, nil, \"Lock file is empty: \" .. lock_path\n end\n\n local ok, lock_data = pcall(vim.json.decode, content)\n if not ok or type(lock_data) ~= \"table\" then\n return false, nil, \"Failed to parse lock file JSON: \" .. lock_path\n end\n\n local auth_token = lock_data.authToken\n if not auth_token or type(auth_token) ~= \"string\" then\n return false, nil, \"No valid auth token found in lock file\"\n end\n\n return true, auth_token, nil\nend\n\n--- Get active LSP clients using available API\n---@return table Array of LSP clients\nlocal function get_lsp_clients()\n if vim.lsp then\n if vim.lsp.get_clients then\n -- Neovim >= 0.11\n return vim.lsp.get_clients()\n elseif vim.lsp.get_active_clients then\n -- Neovim 0.8-0.10\n return vim.lsp.get_active_clients()\n end\n end\n return {}\nend\n\n--- Get workspace folders for the lock file\n---@return table Array of workspace folder paths\nfunction M.get_workspace_folders()\n local folders = {}\n\n -- Add current working directory\n table.insert(folders, vim.fn.getcwd())\n\n -- Get LSP workspace folders if available\n local clients = get_lsp_clients()\n for _, client in pairs(clients) do\n if client.config and client.config.workspace_folders then\n for _, ws in ipairs(client.config.workspace_folders) do\n -- Convert URI to path\n local path = ws.uri\n if path:sub(1, 7) == \"file://\" then\n path = path:sub(8)\n end\n\n -- Check if already in the list\n local exists = false\n for _, folder in ipairs(folders) do\n if folder == path then\n exists = true\n break\n end\n end\n\n if not exists then\n table.insert(folders, path)\n end\n end\n end\n end\n\n return folders\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/tcp.lua", "---@brief TCP server implementation using vim.loop\nlocal client_manager = require(\"claudecode.server.client\")\nlocal utils = require(\"claudecode.server.utils\")\n\nlocal M = {}\n\n---@class TCPServer\n---@field server table The vim.loop TCP server handle\n---@field port number The port the server is listening on\n---@field auth_token string|nil The authentication token for validating connections\n---@field clients table Table of connected clients (client_id -> WebSocketClient)\n---@field on_message function Callback for WebSocket messages\n---@field on_connect function Callback for new connections\n---@field on_disconnect function Callback for client disconnections\n---@field on_error fun(err_msg: string) Callback for errors\n\n---@brief Find an available port by attempting to bind\n---@param min_port number Minimum port to try\n---@param max_port number Maximum port to try\n---@return number|nil port Available port number, or nil if none found\nfunction M.find_available_port(min_port, max_port)\n if min_port > max_port then\n return nil -- Or handle error appropriately\n end\n\n local ports = {}\n for i = min_port, max_port do\n table.insert(ports, i)\n end\n\n -- Shuffle the ports\n utils.shuffle_array(ports)\n\n -- Try to bind to a port from the shuffled list\n for _, port in ipairs(ports) do\n local test_server = vim.loop.new_tcp()\n local success = test_server:bind(\"127.0.0.1\", port)\n test_server:close()\n\n if success then\n return port\n end\n end\n\n return nil\nend\n\n---@brief Create and start a TCP server\n---@param config table Server configuration\n---@param callbacks table Callback functions\n---@param auth_token string|nil Authentication token for validating connections\n---@return TCPServer|nil server The server object, or nil on error\n---@return string|nil error Error message if failed\nfunction M.create_server(config, callbacks, auth_token)\n local port = M.find_available_port(config.port_range.min, config.port_range.max)\n if not port then\n return nil, \"No available ports in range \" .. config.port_range.min .. \"-\" .. config.port_range.max\n end\n\n local tcp_server = vim.loop.new_tcp()\n if not tcp_server then\n return nil, \"Failed to create TCP server\"\n end\n\n -- Create server object\n local server = {\n server = tcp_server,\n port = port,\n auth_token = auth_token,\n clients = {},\n on_message = callbacks.on_message or function() end,\n on_connect = callbacks.on_connect or function() end,\n on_disconnect = callbacks.on_disconnect or function() end,\n on_error = callbacks.on_error or function() end,\n }\n\n local bind_success, bind_err = tcp_server:bind(\"127.0.0.1\", port)\n if not bind_success then\n tcp_server:close()\n return nil, \"Failed to bind to port \" .. port .. \": \" .. (bind_err or \"unknown error\")\n end\n\n -- Start listening\n local listen_success, listen_err = tcp_server:listen(128, function(err)\n if err then\n callbacks.on_error(\"Listen error: \" .. err)\n return\n end\n\n M._handle_new_connection(server)\n end)\n\n if not listen_success then\n tcp_server:close()\n return nil, \"Failed to listen on port \" .. port .. \": \" .. (listen_err or \"unknown error\")\n end\n\n return server, nil\nend\n\n---@brief Handle a new client connection\n---@param server TCPServer The server object\nfunction M._handle_new_connection(server)\n local client_tcp = vim.loop.new_tcp()\n if not client_tcp then\n server.on_error(\"Failed to create client TCP handle\")\n return\n end\n\n local accept_success, accept_err = server.server:accept(client_tcp)\n if not accept_success then\n server.on_error(\"Failed to accept connection: \" .. (accept_err or \"unknown error\"))\n client_tcp:close()\n return\n end\n\n -- Create WebSocket client wrapper\n local client = client_manager.create_client(client_tcp)\n server.clients[client.id] = client\n\n -- Set up data handler\n client_tcp:read_start(function(err, data)\n if err then\n server.on_error(\"Client read error: \" .. err)\n M._remove_client(server, client)\n return\n end\n\n if not data then\n -- EOF - client disconnected\n M._remove_client(server, client)\n return\n end\n\n -- Process incoming data\n client_manager.process_data(client, data, function(cl, message)\n server.on_message(cl, message)\n end, function(cl, code, reason)\n server.on_disconnect(cl, code, reason)\n M._remove_client(server, cl)\n end, function(cl, error_msg)\n server.on_error(\"Client \" .. cl.id .. \" error: \" .. error_msg)\n M._remove_client(server, cl)\n end, server.auth_token)\n end)\n\n -- Notify about new connection\n server.on_connect(client)\nend\n\n---@brief Remove a client from the server\n---@param server TCPServer The server object\n---@param client WebSocketClient The client to remove\nfunction M._remove_client(server, client)\n if server.clients[client.id] then\n server.clients[client.id] = nil\n\n if not client.tcp_handle:is_closing() then\n client.tcp_handle:close()\n end\n end\nend\n\n---@brief Send a message to a specific client\n---@param server TCPServer The server object\n---@param client_id string The client ID\n---@param message string The message to send\n---@param callback function|nil Optional callback\nfunction M.send_to_client(server, client_id, message, callback)\n local client = server.clients[client_id]\n if not client then\n if callback then\n callback(\"Client not found: \" .. client_id)\n end\n return\n end\n\n client_manager.send_message(client, message, callback)\nend\n\n---@brief Broadcast a message to all connected clients\n---@param server TCPServer The server object\n---@param message string The message to broadcast\nfunction M.broadcast(server, message)\n for _, client in pairs(server.clients) do\n client_manager.send_message(client, message)\n end\nend\n\n---@brief Get the number of connected clients\n---@param server TCPServer The server object\n---@return number count Number of connected clients\nfunction M.get_client_count(server)\n local count = 0\n for _ in pairs(server.clients) do\n count = count + 1\n end\n return count\nend\n\n---@brief Get information about all clients\n---@param server TCPServer The server object\n---@return table clients Array of client information\nfunction M.get_clients_info(server)\n local clients = {}\n for _, client in pairs(server.clients) do\n table.insert(clients, client_manager.get_client_info(client))\n end\n return clients\nend\n\n---@brief Close a specific client connection\n---@param server TCPServer The server object\n---@param client_id string The client ID\n---@param code number|nil Close code\n---@param reason string|nil Close reason\nfunction M.close_client(server, client_id, code, reason)\n local client = server.clients[client_id]\n if client then\n client_manager.close_client(client, code, reason)\n end\nend\n\n---@brief Stop the TCP server\n---@param server TCPServer The server object\nfunction M.stop_server(server)\n -- Close all clients\n for _, client in pairs(server.clients) do\n client_manager.close_client(client, 1001, \"Server shutting down\")\n end\n\n -- Clear clients\n server.clients = {}\n\n -- Close server\n if server.server and not server.server:is_closing() then\n server.server:close()\n end\nend\n\n---@brief Start a periodic ping task to keep connections alive\n---@param server TCPServer The server object\n---@param interval number Ping interval in milliseconds (default: 30000)\n---@return table timer The timer handle\nfunction M.start_ping_timer(server, interval)\n interval = interval or 30000 -- 30 seconds\n\n local timer = vim.loop.new_timer()\n timer:start(interval, interval, function()\n for _, client in pairs(server.clients) do\n if client.state == \"connected\" then\n -- Check if client is alive\n if client_manager.is_client_alive(client, interval * 2) then\n client_manager.send_ping(client, \"ping\")\n else\n -- Client appears dead, close it\n server.on_error(\"Client \" .. client.id .. \" appears dead, closing\")\n client_manager.close_client(client, 1006, \"Connection timeout\")\n M._remove_client(server, client)\n end\n end\n end\n end)\n\n return timer\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/client.lua", "---@brief WebSocket client connection management\nlocal frame = require(\"claudecode.server.frame\")\nlocal handshake = require(\"claudecode.server.handshake\")\nlocal logger = require(\"claudecode.logger\")\n\nlocal M = {}\n\n---@class WebSocketClient\n---@field id string Unique client identifier\n---@field tcp_handle table The vim.loop TCP handle\n---@field state string Connection state: \"connecting\", \"connected\", \"closing\", \"closed\"\n---@field buffer string Incoming data buffer\n---@field handshake_complete boolean Whether WebSocket handshake is complete\n---@field last_ping number Timestamp of last ping sent\n---@field last_pong number Timestamp of last pong received\n\n---@brief Create a new WebSocket client\n---@param tcp_handle table The vim.loop TCP handle\n---@return WebSocketClient client The client object\nfunction M.create_client(tcp_handle)\n local client_id = tostring(tcp_handle):gsub(\"userdata: \", \"client_\")\n\n local client = {\n id = client_id,\n tcp_handle = tcp_handle,\n state = \"connecting\",\n buffer = \"\",\n handshake_complete = false,\n last_ping = 0,\n last_pong = vim.loop.now(),\n }\n\n return client\nend\n\n---@brief Process incoming data for a client\n---@param client WebSocketClient The client object\n---@param data string The incoming data\n---@param on_message function Callback for complete messages: function(client, message_text)\n---@param on_close function Callback for client close: function(client, code, reason)\n---@param on_error function Callback for errors: function(client, error_msg)\n---@param auth_token string|nil Expected authentication token for validation\nfunction M.process_data(client, data, on_message, on_close, on_error, auth_token)\n client.buffer = client.buffer .. data\n\n if not client.handshake_complete then\n local complete, request, remaining = handshake.extract_http_request(client.buffer)\n if complete then\n logger.debug(\"client\", \"Processing WebSocket handshake for client:\", client.id)\n\n -- Log if auth token is required\n if auth_token then\n logger.debug(\"client\", \"Authentication required for client:\", client.id)\n else\n logger.debug(\"client\", \"No authentication required for client:\", client.id)\n end\n\n local success, response_from_handshake, _ = handshake.process_handshake(request, auth_token)\n\n -- Log authentication results\n if success then\n if auth_token then\n logger.debug(\"client\", \"Client authenticated successfully:\", client.id)\n else\n logger.debug(\"client\", \"Client handshake completed (no auth required):\", client.id)\n end\n else\n -- Log specific authentication failure details\n if auth_token and response_from_handshake:find(\"auth\") then\n logger.warn(\n \"client\",\n \"Authentication failed for client \"\n .. client.id\n .. \": \"\n .. (response_from_handshake:match(\"Bad WebSocket upgrade request: (.+)\") or \"unknown auth error\")\n )\n else\n logger.warn(\n \"client\",\n \"WebSocket handshake failed for client \"\n .. client.id\n .. \": \"\n .. (response_from_handshake:match(\"HTTP/1.1 %d+ (.+)\") or \"unknown handshake error\")\n )\n end\n end\n\n client.tcp_handle:write(response_from_handshake, function(err)\n if err then\n logger.error(\"client\", \"Failed to send handshake response to client \" .. client.id .. \": \" .. err)\n on_error(client, \"Failed to send handshake response: \" .. err)\n return\n end\n\n if success then\n client.handshake_complete = true\n client.state = \"connected\"\n client.buffer = remaining\n logger.debug(\"client\", \"WebSocket connection established for client:\", client.id)\n\n if #client.buffer > 0 then\n M.process_data(client, \"\", on_message, on_close, on_error, auth_token)\n end\n else\n client.state = \"closing\"\n logger.debug(\"client\", \"Closing connection for client due to failed handshake:\", client.id)\n vim.schedule(function()\n client.tcp_handle:close()\n end)\n end\n end)\n end\n return\n end\n\n while #client.buffer >= 2 do -- Minimum frame size\n local parsed_frame, bytes_consumed = frame.parse_frame(client.buffer)\n\n if not parsed_frame then\n break\n end\n\n -- Frame validation is now handled entirely within frame.parse_frame.\n -- If frame.parse_frame returns a frame, it's considered valid.\n\n client.buffer = client.buffer:sub(bytes_consumed + 1)\n\n if parsed_frame.opcode == frame.OPCODE.TEXT then\n vim.schedule(function()\n on_message(client, parsed_frame.payload)\n end)\n elseif parsed_frame.opcode == frame.OPCODE.BINARY then\n -- Binary message (treat as text for JSON-RPC)\n vim.schedule(function()\n on_message(client, parsed_frame.payload)\n end)\n elseif parsed_frame.opcode == frame.OPCODE.CLOSE then\n local code = 1000\n local reason = \"\"\n\n if #parsed_frame.payload >= 2 then\n local payload = parsed_frame.payload\n code = payload:byte(1) * 256 + payload:byte(2)\n if #payload > 2 then\n reason = payload:sub(3)\n end\n end\n\n if client.state == \"connected\" then\n local close_frame = frame.create_close_frame(code, reason)\n client.tcp_handle:write(close_frame)\n client.state = \"closing\"\n end\n\n vim.schedule(function()\n on_close(client, code, reason)\n end)\n elseif parsed_frame.opcode == frame.OPCODE.PING then\n local pong_frame = frame.create_pong_frame(parsed_frame.payload)\n client.tcp_handle:write(pong_frame)\n elseif parsed_frame.opcode == frame.OPCODE.PONG then\n client.last_pong = vim.loop.now()\n elseif parsed_frame.opcode == frame.OPCODE.CONTINUATION then\n -- Continuation frame - for simplicity, we don't support fragmentation\n on_error(client, \"Fragmented messages not supported\")\n M.close_client(client, 1003, \"Unsupported data\")\n else\n on_error(client, \"Unknown WebSocket opcode: \" .. parsed_frame.opcode)\n M.close_client(client, 1002, \"Protocol error\")\n end\n end\nend\n\n---@brief Send a text message to a client\n---@param client WebSocketClient The client object\n---@param message string The message to send\n---@param callback function|nil Optional callback: function(err)\nfunction M.send_message(client, message, callback)\n if client.state ~= \"connected\" then\n if callback then\n callback(\"Client not connected\")\n end\n return\n end\n\n local text_frame = frame.create_text_frame(message)\n client.tcp_handle:write(text_frame, callback)\nend\n\n---@brief Send a ping to a client\n---@param client WebSocketClient The client object\n---@param data string|nil Optional ping data\nfunction M.send_ping(client, data)\n if client.state ~= \"connected\" then\n return\n end\n\n local ping_frame = frame.create_ping_frame(data or \"\")\n client.tcp_handle:write(ping_frame)\n client.last_ping = vim.loop.now()\nend\n\n---@brief Close a client connection\n---@param client WebSocketClient The client object\n---@param code number|nil Close code (default: 1000)\n---@param reason string|nil Close reason\nfunction M.close_client(client, code, reason)\n if client.state == \"closed\" or client.state == \"closing\" then\n return\n end\n\n code = code or 1000\n reason = reason or \"\"\n\n if client.handshake_complete then\n local close_frame = frame.create_close_frame(code, reason)\n client.tcp_handle:write(close_frame, function()\n client.state = \"closed\"\n client.tcp_handle:close()\n end)\n else\n client.state = \"closed\"\n client.tcp_handle:close()\n end\n\n client.state = \"closing\"\nend\n\n---@brief Check if a client connection is alive\n---@param client WebSocketClient The client object\n---@param timeout number Timeout in milliseconds (default: 30000)\n---@return boolean alive True if the client is considered alive\nfunction M.is_client_alive(client, timeout)\n timeout = timeout or 30000 -- 30 seconds default\n\n if client.state ~= \"connected\" then\n return false\n end\n\n local now = vim.loop.now()\n return (now - client.last_pong) < timeout\nend\n\n---@brief Get client info for debugging\n---@param client WebSocketClient The client object\n---@return table info Client information\nfunction M.get_client_info(client)\n return {\n id = client.id,\n state = client.state,\n handshake_complete = client.handshake_complete,\n buffer_size = #client.buffer,\n last_ping = client.last_ping,\n last_pong = client.last_pong,\n }\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/mock.lua", "---@brief [[\n--- Mock WebSocket server implementation for testing.\n--- This module provides a minimal implementation of the WebSocket server\n--- functionality, suitable for testing or when real WebSocket connections\n--- are not available or needed.\n---@brief ]]\n\nlocal M = {}\nlocal tools = require(\"claudecode.tools.init\")\n\n--- Mock server state\nM.state = {\n server = nil,\n port = nil,\n clients = {},\n handlers = {},\n messages = {}, -- Store messages for testing\n}\n\n--- Find an available port in the given range\n---@param min number The minimum port number\n---@param _max number The maximum port number\n---@return number port The selected port\nfunction M.find_available_port(min, _max)\n -- For mock implementation, just return the minimum port\n -- In a real implementation, this would scan for available ports in the range\n return min\nend\n\n--- Start the WebSocket server\n---@param config table Configuration options\n---@return boolean success Whether the server started successfully\n---@return number|string port_or_error The port number or error message\nfunction M.start(config)\n if M.state.server then\n -- Already running\n return false, \"Server already running\"\n end\n\n -- Find an available port\n local port = M.find_available_port(config.port_range.min, config.port_range.max)\n\n if not port then\n return false, \"No available ports found\"\n end\n\n -- Store the port in state\n M.state.port = port\n\n -- Create mock server object\n M.state.server = {\n port = port,\n clients = {},\n on_message = function() end,\n on_connect = function() end,\n on_disconnect = function() end,\n }\n\n -- Register message handlers\n M.register_handlers()\n\n return true, port\nend\n\n--- Stop the WebSocket server\n---@return boolean success Whether the server stopped successfully\n---@return string|nil error Error message if failed\nfunction M.stop()\n if not M.state.server then\n -- Not running\n return false, \"Server not running\"\n end\n\n -- Reset state\n M.state.server = nil\n M.state.port = nil\n M.state.clients = {}\n M.state.messages = {}\n\n return true\nend\n\n--- Register message handlers\nfunction M.register_handlers()\n -- Default handlers\n M.state.handlers = {\n [\"mcp.connect\"] = function(_client, _params)\n -- Handle connection handshake\n -- Parameters not used in this mock implementation\n return { result = { message = \"Connection established\" } }\n end,\n\n [\"mcp.tool.invoke\"] = function(client, params)\n -- Handle tool invocation by dispatching to tools implementation\n return tools.handle_invoke(client, params)\n end,\n }\nend\n\n--- Add a client to the server\n---@param client_id string A unique client identifier\n---@return table client The client object\nfunction M.add_client(client_id)\n if not M.state.server then\n error(\"Server not running\")\n end\n\n local client = {\n id = client_id,\n connected = true,\n messages = {},\n }\n\n M.state.clients[client_id] = client\n return client\nend\n\n--- Remove a client from the server\n---@param client_id string The client identifier\n---@return boolean success Whether removal was successful\nfunction M.remove_client(client_id)\n if not M.state.server or not M.state.clients[client_id] then\n return false\n end\n\n M.state.clients[client_id] = nil\n return true\nend\n\n--- Send a message to a client\n---@param client table|string The client object or ID\n---@param method string The method name\n---@param params table The parameters to send\n---@return boolean success Whether sending was successful\nfunction M.send(client, method, params)\n local client_obj\n\n if type(client) == \"string\" then\n client_obj = M.state.clients[client]\n else\n client_obj = client\n end\n\n if not client_obj then\n return false\n end\n\n local message = {\n jsonrpc = \"2.0\",\n method = method,\n params = params,\n }\n\n -- Store for testing\n table.insert(client_obj.messages, message)\n table.insert(M.state.messages, {\n client = client_obj.id,\n direction = \"outbound\",\n message = message,\n })\n\n return true\nend\n\n--- Send a response to a client\n---@param client table|string The client object or ID\n---@param id string The message ID\n---@param result table|nil The result data\n---@param error table|nil The error data\n---@return boolean success Whether sending was successful\nfunction M.send_response(client, id, result, error)\n local client_obj\n\n if type(client) == \"string\" then\n client_obj = M.state.clients[client]\n else\n client_obj = client\n end\n\n if not client_obj then\n return false\n end\n\n local response = {\n jsonrpc = \"2.0\",\n id = id,\n }\n\n if error then\n response.error = error\n else\n response.result = result\n end\n\n -- Store for testing\n table.insert(client_obj.messages, response)\n table.insert(M.state.messages, {\n client = client_obj.id,\n direction = \"outbound\",\n message = response,\n })\n\n return true\nend\n\n--- Broadcast a message to all connected clients\n---@param method string The method name\n---@param params table The parameters to send\n---@return boolean success Whether broadcasting was successful\nfunction M.broadcast(method, params)\n local success = true\n\n for client_id, _ in pairs(M.state.clients) do\n local send_success = M.send(client_id, method, params)\n success = success and send_success\n end\n\n return success\nend\n\n--- Simulate receiving a message from a client\n---@param client_id string The client ID\n---@param message table The message to process\n---@return table|nil response The response if any\nfunction M.simulate_message(client_id, message)\n local client = M.state.clients[client_id]\n\n if not client then\n return nil\n end\n\n -- Store the message\n table.insert(M.state.messages, {\n client = client_id,\n direction = \"inbound\",\n message = message,\n })\n\n -- Process the message\n if message.method and M.state.handlers[message.method] then\n local handler = M.state.handlers[message.method]\n local response = handler(client, message.params)\n\n if message.id and response then\n -- If the message had an ID, this is a request and needs a response\n M.send_response(client, message.id, response.result, response.error)\n return response\n end\n end\n\n return nil\nend\n\n--- Clear test messages\nfunction M.clear_messages()\n M.state.messages = {}\n\n for _, client in pairs(M.state.clients) do\n client.messages = {}\n end\nend\n\nreturn M\n"], ["/claudecode.nvim/plugin/claudecode.lua", "if vim.fn.has(\"nvim-0.8.0\") ~= 1 then\n vim.api.nvim_err_writeln(\"Claude Code requires Neovim >= 0.8.0\")\n return\nend\n\nif vim.g.loaded_claudecode then\n return\nend\nvim.g.loaded_claudecode = 1\n\n--- Example: In your `init.lua`, you can set `vim.g.claudecode_auto_setup = { auto_start = true }`\n--- to automatically start ClaudeCode when Neovim loads.\nif vim.g.claudecode_auto_setup then\n vim.defer_fn(function()\n require(\"claudecode\").setup(vim.g.claudecode_auto_setup)\n end, 0)\nend\n\n-- Commands are now registered in lua/claudecode/init.lua's _create_commands function\n-- when require(\"claudecode\").setup() is called.\n-- This file (plugin/claudecode.lua) is primarily for the load guard\n-- and the optional auto-setup mechanism.\n\nlocal main_module_ok, _ = pcall(require, \"claudecode\")\nif not main_module_ok then\n vim.notify(\"ClaudeCode: Failed to load main module. Plugin may not function correctly.\", vim.log.levels.ERROR)\nend\n"], ["/claudecode.nvim/lua/claudecode/server/handshake.lua", "---@brief WebSocket handshake handling (RFC 6455)\nlocal utils = require(\"claudecode.server.utils\")\n\nlocal M = {}\n\n---@brief Check if an HTTP request is a valid WebSocket upgrade request\n---@param request string The HTTP request string\n---@param expected_auth_token string|nil Expected authentication token for validation\n---@return boolean valid True if it's a valid WebSocket upgrade request\n---@return table|string headers_or_error Headers table if valid, error message if not\nfunction M.validate_upgrade_request(request, expected_auth_token)\n local headers = utils.parse_http_headers(request)\n\n -- Check for required headers\n if not headers[\"upgrade\"] or headers[\"upgrade\"]:lower() ~= \"websocket\" then\n return false, \"Missing or invalid Upgrade header\"\n end\n\n if not headers[\"connection\"] or not headers[\"connection\"]:lower():find(\"upgrade\") then\n return false, \"Missing or invalid Connection header\"\n end\n\n if not headers[\"sec-websocket-key\"] then\n return false, \"Missing Sec-WebSocket-Key header\"\n end\n\n if not headers[\"sec-websocket-version\"] or headers[\"sec-websocket-version\"] ~= \"13\" then\n return false, \"Missing or unsupported Sec-WebSocket-Version header\"\n end\n\n -- Validate WebSocket key format (should be base64 encoded 16 bytes)\n local key = headers[\"sec-websocket-key\"]\n if #key ~= 24 then -- Base64 encoded 16 bytes = 24 characters\n return false, \"Invalid Sec-WebSocket-Key format\"\n end\n\n -- Validate authentication token if required\n if expected_auth_token then\n -- Check if expected_auth_token is valid\n if type(expected_auth_token) ~= \"string\" or expected_auth_token == \"\" then\n return false, \"Server configuration error: invalid expected authentication token\"\n end\n\n local auth_header = headers[\"x-claude-code-ide-authorization\"]\n if not auth_header then\n return false, \"Missing authentication header: x-claude-code-ide-authorization\"\n end\n\n -- Check for empty auth header\n if auth_header == \"\" then\n return false, \"Authentication token too short (min 10 characters)\"\n end\n\n -- Check for suspicious auth header lengths\n if #auth_header > 500 then\n return false, \"Authentication token too long (max 500 characters)\"\n end\n\n if #auth_header < 10 then\n return false, \"Authentication token too short (min 10 characters)\"\n end\n\n if auth_header ~= expected_auth_token then\n return false, \"Invalid authentication token\"\n end\n end\n\n return true, headers\nend\n\n---@brief Generate a WebSocket handshake response\n---@param client_key string The client's Sec-WebSocket-Key header value\n---@param protocol string|nil Optional subprotocol to accept\n---@return string|nil response The HTTP response string, or nil on error\nfunction M.create_handshake_response(client_key, protocol)\n local accept_key = utils.generate_accept_key(client_key)\n if not accept_key then\n return nil\n end\n\n local response_lines = {\n \"HTTP/1.1 101 Switching Protocols\",\n \"Upgrade: websocket\",\n \"Connection: Upgrade\",\n \"Sec-WebSocket-Accept: \" .. accept_key,\n }\n\n if protocol then\n table.insert(response_lines, \"Sec-WebSocket-Protocol: \" .. protocol)\n end\n\n -- Add empty line to end headers\n table.insert(response_lines, \"\")\n table.insert(response_lines, \"\")\n\n return table.concat(response_lines, \"\\r\\n\")\nend\n\n---@brief Parse the HTTP request line\n---@param request string The HTTP request string\n---@return string|nil method The HTTP method (GET, POST, etc.)\n---@return string|nil path The request path\n---@return string|nil version The HTTP version\nfunction M.parse_request_line(request)\n local first_line = request:match(\"^([^\\r\\n]+)\")\n if not first_line then\n return nil, nil, nil\n end\n\n local method, path, version = first_line:match(\"^(%S+)%s+(%S+)%s+(%S+)$\")\n return method, path, version\nend\n\n---@brief Check if the request is for the WebSocket endpoint\n---@param request string The HTTP request string\n---@return boolean valid True if the request is for a valid WebSocket endpoint\nfunction M.is_websocket_endpoint(request)\n local method, path, version = M.parse_request_line(request)\n\n -- Must be GET request\n if method ~= \"GET\" then\n return false\n end\n\n -- Must be HTTP/1.1 or later\n if not version or not version:match(\"^HTTP/1%.1\") then\n return false\n end\n\n -- Accept any path for now (could be made configurable)\n if not path then\n return false\n end\n\n return true\nend\n\n---@brief Create a WebSocket handshake error response\n---@param code number HTTP status code\n---@param message string Error message\n---@return string response The HTTP error response\nfunction M.create_error_response(code, message)\n local status_text = {\n [400] = \"Bad Request\",\n [404] = \"Not Found\",\n [426] = \"Upgrade Required\",\n [500] = \"Internal Server Error\",\n }\n\n local status = status_text[code] or \"Error\"\n\n local response_lines = {\n \"HTTP/1.1 \" .. code .. \" \" .. status,\n \"Content-Type: text/plain\",\n \"Content-Length: \" .. #message,\n \"Connection: close\",\n \"\",\n message,\n }\n\n return table.concat(response_lines, \"\\r\\n\")\nend\n\n---@brief Process a complete WebSocket handshake\n---@param request string The HTTP request string\n---@param expected_auth_token string|nil Expected authentication token for validation\n---@return boolean success True if handshake was successful\n---@return string response The HTTP response to send\n---@return table|nil headers The parsed headers if successful\nfunction M.process_handshake(request, expected_auth_token)\n -- Check if it's a valid WebSocket endpoint request\n if not M.is_websocket_endpoint(request) then\n local response = M.create_error_response(404, \"WebSocket endpoint not found\")\n return false, response, nil\n end\n\n -- Validate the upgrade request\n local is_valid_upgrade, validation_payload = M.validate_upgrade_request(request, expected_auth_token) ---@type boolean, table|string\n if not is_valid_upgrade then\n assert(type(validation_payload) == \"string\", \"validation_payload should be a string on error\")\n local error_message = validation_payload\n local response = M.create_error_response(400, \"Bad WebSocket upgrade request: \" .. error_message)\n return false, response, nil\n end\n\n -- If is_valid_upgrade is true, validation_payload must be the headers table\n assert(type(validation_payload) == \"table\", \"validation_payload should be a table on success\")\n local headers_table = validation_payload\n\n -- Generate handshake response\n local client_key = headers_table[\"sec-websocket-key\"]\n local protocol = headers_table[\"sec-websocket-protocol\"] -- Optional\n\n local response = M.create_handshake_response(client_key, protocol)\n if not response then\n local error_response = M.create_error_response(500, \"Failed to generate WebSocket handshake response\")\n return false, error_response, nil -- error_response is string, nil is for headers\n end\n\n return true, response, headers_table -- headers_table is 'table', compatible with 'table|nil'\nend\n\n---@brief Check if a request buffer contains a complete HTTP request\n---@param buffer string The request buffer\n---@return boolean complete True if the request is complete\n---@return string|nil request The complete request if found\n---@return string remaining Any remaining data after the request\nfunction M.extract_http_request(buffer)\n -- Look for the end of HTTP headers (double CRLF)\n local header_end = buffer:find(\"\\r\\n\\r\\n\")\n if not header_end then\n return false, nil, buffer\n end\n\n -- For WebSocket upgrade, there should be no body\n local request = buffer:sub(1, header_end + 3) -- Include the final CRLF\n local remaining = buffer:sub(header_end + 4)\n\n return true, request, remaining\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/utils.lua", "---@brief Utility functions for WebSocket server implementation\nlocal M = {}\n\n-- Lua 5.1 compatible bitwise operations (arithmetic emulation).\nlocal function band(a, b)\n local result = 0\n local bitval = 1\n while a > 0 and b > 0 do\n if a % 2 == 1 and b % 2 == 1 then\n result = result + bitval\n end\n bitval = bitval * 2\n a = math.floor(a / 2)\n b = math.floor(b / 2)\n end\n return result\nend\n\nlocal function bor(a, b)\n local result = 0\n local bitval = 1\n while a > 0 or b > 0 do\n if a % 2 == 1 or b % 2 == 1 then\n result = result + bitval\n end\n bitval = bitval * 2\n a = math.floor(a / 2)\n b = math.floor(b / 2)\n end\n return result\nend\n\nlocal function bxor(a, b)\n local result = 0\n local bitval = 1\n while a > 0 or b > 0 do\n if (a % 2) ~= (b % 2) then\n result = result + bitval\n end\n bitval = bitval * 2\n a = math.floor(a / 2)\n b = math.floor(b / 2)\n end\n return result\nend\n\nlocal function bnot(a)\n return bxor(a, 0xFFFFFFFF)\nend\n\nlocal function lshift(value, amount)\n local shifted_val = value * (2 ^ amount)\n return shifted_val % (2 ^ 32)\nend\n\nlocal function rshift(value, amount)\n return math.floor(value / (2 ^ amount))\nend\n\nlocal function rotleft(value, amount)\n local mask = 0xFFFFFFFF\n value = band(value, mask)\n local part1 = lshift(value, amount)\n local part2 = rshift(value, 32 - amount)\n return band(bor(part1, part2), mask)\nend\n\nlocal function add32(a, b)\n local sum = a + b\n return band(sum, 0xFFFFFFFF)\nend\n\n---@brief Generate a random, spec-compliant WebSocket key.\n---@return string key Base64 encoded 16-byte random nonce.\nfunction M.generate_websocket_key()\n local random_bytes = {}\n for _ = 1, 16 do\n random_bytes[#random_bytes + 1] = string.char(math.random(0, 255))\n end\n return M.base64_encode(table.concat(random_bytes))\nend\n\n---@brief Base64 encode a string\n---@param data string The data to encode\n---@return string encoded The base64 encoded string\nfunction M.base64_encode(data)\n local chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\n local result = {}\n local padding = \"\"\n\n local pad_len = 3 - (#data % 3)\n if pad_len ~= 3 then\n data = data .. string.rep(\"\\0\", pad_len)\n padding = string.rep(\"=\", pad_len)\n end\n\n for i = 1, #data, 3 do\n local a, b, c = data:byte(i, i + 2)\n local bitmap = a * 65536 + b * 256 + c\n\n -- Use table for efficient string building\n result[#result + 1] = chars:sub(math.floor(bitmap / 262144) + 1, math.floor(bitmap / 262144) + 1)\n result[#result + 1] = chars:sub(math.floor((bitmap % 262144) / 4096) + 1, math.floor((bitmap % 262144) / 4096) + 1)\n result[#result + 1] = chars:sub(math.floor((bitmap % 4096) / 64) + 1, math.floor((bitmap % 4096) / 64) + 1)\n result[#result + 1] = chars:sub((bitmap % 64) + 1, (bitmap % 64) + 1)\n end\n\n local encoded = table.concat(result)\n return encoded:sub(1, #encoded - #padding) .. padding\nend\n\n---@brief Base64 decode a string\n---@param data string The base64 encoded string\n---@return string|nil decoded The decoded string, or nil on error (e.g. invalid char)\nfunction M.base64_decode(data)\n local chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\n local lookup = {}\n for i = 1, #chars do\n lookup[chars:sub(i, i)] = i - 1\n end\n lookup[\"=\"] = 0\n\n local result = {}\n local buffer = 0\n local bits = 0\n\n for i = 1, #data do\n local char = data:sub(i, i)\n local value = lookup[char]\n\n if value == nil then\n return nil\n end\n\n if char == \"=\" then\n break\n end\n\n buffer = (buffer * 64) + value\n bits = bits + 6\n\n if bits >= 8 then\n bits = bits - 8\n result[#result + 1] = string.char(rshift(buffer, bits))\n buffer = band(buffer, (lshift(1, bits)) - 1)\n end\n end\n return table.concat(result)\nend\n\n---@brief Pure Lua SHA-1 implementation\n---@param data string The data to hash\n---@return string|nil hash The SHA-1 hash in binary format, or nil on error\nfunction M.sha1(data)\n if type(data) ~= \"string\" then\n return nil\n end\n\n -- Validate input data is reasonable size (DOS protection)\n if #data > 10 * 1024 * 1024 then -- 10MB limit\n return nil\n end\n\n local h0 = 0x67452301\n local h1 = 0xEFCDAB89\n local h2 = 0x98BADCFE\n local h3 = 0x10325476\n local h4 = 0xC3D2E1F0\n\n local msg = data\n local msg_len = #msg\n local bit_len = msg_len * 8\n\n msg = msg .. string.char(0x80)\n\n -- Append 0 <= k < 512 bits '0', where the resulting message length\n -- (in bits) is congruent to 448 (mod 512)\n while (#msg % 64) ~= 56 do\n msg = msg .. string.char(0x00)\n end\n\n -- Append length as 64-bit big-endian integer\n for i = 7, 0, -1 do\n msg = msg .. string.char(band(rshift(bit_len, i * 8), 0xFF))\n end\n\n for chunk_start = 1, #msg, 64 do\n local w = {}\n\n -- Break chunk into sixteen 32-bit big-endian words\n for i = 0, 15 do\n local offset = chunk_start + i * 4\n w[i] = bor(\n bor(bor(lshift(msg:byte(offset), 24), lshift(msg:byte(offset + 1), 16)), lshift(msg:byte(offset + 2), 8)),\n msg:byte(offset + 3)\n )\n end\n\n -- Extend the sixteen 32-bit words into eighty 32-bit words\n for i = 16, 79 do\n w[i] = rotleft(bxor(bxor(bxor(w[i - 3], w[i - 8]), w[i - 14]), w[i - 16]), 1)\n end\n\n local a, b, c, d, e = h0, h1, h2, h3, h4\n\n for i = 0, 79 do\n local f, k\n if i <= 19 then\n f = bor(band(b, c), band(bnot(b), d))\n k = 0x5A827999\n elseif i <= 39 then\n f = bxor(bxor(b, c), d)\n k = 0x6ED9EBA1\n elseif i <= 59 then\n f = bor(bor(band(b, c), band(b, d)), band(c, d))\n k = 0x8F1BBCDC\n else\n f = bxor(bxor(b, c), d)\n k = 0xCA62C1D6\n end\n\n local temp = add32(add32(add32(add32(rotleft(a, 5), f), e), k), w[i])\n e = d\n d = c\n c = rotleft(b, 30)\n b = a\n a = temp\n end\n\n h0 = add32(h0, a)\n h1 = add32(h1, b)\n h2 = add32(h2, c)\n h3 = add32(h3, d)\n h4 = add32(h4, e)\n end\n\n -- Produce the final hash value as a 160-bit (20-byte) binary string\n local result = \"\"\n for _, h in ipairs({ h0, h1, h2, h3, h4 }) do\n result = result\n .. string.char(band(rshift(h, 24), 0xFF), band(rshift(h, 16), 0xFF), band(rshift(h, 8), 0xFF), band(h, 0xFF))\n end\n\n return result\nend\n\n---@brief Generate WebSocket accept key from client key\n---@param client_key string The client's WebSocket-Key header value\n---@return string|nil accept_key The WebSocket accept key, or nil on error\nfunction M.generate_accept_key(client_key)\n local magic_string = \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\"\n\n -- As per RFC 6455, the server concatenates the Sec-WebSocket-Key header value\n -- with a magic string, SHA1s the result, and then Base64 encodes it.\n local combined = client_key .. magic_string\n local hash = M.sha1(combined)\n if not hash then\n return nil\n end\n\n return M.base64_encode(hash)\nend\n\n---@brief Parse HTTP headers from request string\n---@param request string The HTTP request string\n---@return table headers Table of header name -> value pairs\nfunction M.parse_http_headers(request)\n local headers = {}\n local lines = {}\n\n for line in request:gmatch(\"[^\\r\\n]+\") do\n table.insert(lines, line)\n end\n\n for i = 2, #lines do\n local line = lines[i]\n local name, value = line:match(\"^([^:]+):%s*(.+)$\")\n if name and value then\n headers[name:lower()] = value\n end\n end\n\n return headers\nend\n\n---@brief Check if a string contains valid UTF-8\n---@param str string The string to check\n---@return boolean valid True if the string is valid UTF-8\nfunction M.is_valid_utf8(str)\n local i = 1\n while i <= #str do\n local byte = str:byte(i)\n local char_len = 1\n\n if byte >= 0x80 then\n if byte >= 0xF0 then\n char_len = 4\n elseif byte >= 0xE0 then\n char_len = 3\n elseif byte >= 0xC0 then\n char_len = 2\n else\n return false\n end\n\n for j = 1, char_len - 1 do\n if i + j > #str then\n return false\n end\n local cont_byte = str:byte(i + j)\n if cont_byte < 0x80 or cont_byte >= 0xC0 then\n return false\n end\n end\n end\n\n i = i + char_len\n end\n\n return true\nend\n\n---@brief Convert a 16-bit number to big-endian bytes\n---@param num number The number to convert\n---@return string bytes The big-endian byte representation\nfunction M.uint16_to_bytes(num)\n return string.char(math.floor(num / 256), num % 256)\nend\n\n---@brief Convert a 64-bit number to big-endian bytes\n---@param num number The number to convert\n---@return string bytes The big-endian byte representation\nfunction M.uint64_to_bytes(num)\n local bytes = {}\n for i = 8, 1, -1 do\n bytes[i] = num % 256\n num = math.floor(num / 256)\n end\n return string.char(unpack(bytes))\nend\n\n---@brief Convert big-endian bytes to a 16-bit number\n---@param bytes string The byte string (2 bytes)\n---@return number num The converted number\nfunction M.bytes_to_uint16(bytes)\n if #bytes < 2 then\n return 0\n end\n return bytes:byte(1) * 256 + bytes:byte(2)\nend\n\n---@brief Convert big-endian bytes to a 64-bit number\n---@param bytes string The byte string (8 bytes)\n---@return number num The converted number\nfunction M.bytes_to_uint64(bytes)\n if #bytes < 8 then\n return 0\n end\n\n local num = 0\n for i = 1, 8 do\n num = num * 256 + bytes:byte(i)\n end\n return num\nend\n\n---@brief XOR lookup table for faster operations\nlocal xor_table = {}\nfor i = 0, 255 do\n xor_table[i] = {}\n for j = 0, 255 do\n local result = 0\n local a, b = i, j\n local bit_val = 1\n\n while a > 0 or b > 0 do\n local a_bit = a % 2\n local b_bit = b % 2\n\n if a_bit ~= b_bit then\n result = result + bit_val\n end\n\n a = math.floor(a / 2)\n b = math.floor(b / 2)\n bit_val = bit_val * 2\n end\n\n xor_table[i][j] = result\n end\nend\n\n---@brief Apply XOR mask to payload data\n---@param data string The data to mask/unmask\n---@param mask string The 4-byte mask\n---@return string masked The masked/unmasked data\nfunction M.apply_mask(data, mask)\n local result = {}\n local mask_bytes = { mask:byte(1, 4) }\n\n for i = 1, #data do\n local mask_idx = ((i - 1) % 4) + 1\n local data_byte = data:byte(i)\n result[i] = string.char(xor_table[data_byte][mask_bytes[mask_idx]])\n end\n\n return table.concat(result)\nend\n\n---@brief Shuffle an array in place using Fisher-Yates algorithm\n---@param tbl table The array to shuffle\nfunction M.shuffle_array(tbl)\n math.randomseed(os.time())\n for i = #tbl, 2, -1 do\n local j = math.random(i)\n tbl[i], tbl[j] = tbl[j], tbl[i]\n end\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/server/frame.lua", "---@brief WebSocket frame encoding and decoding (RFC 6455)\nlocal utils = require(\"claudecode.server.utils\")\n\nlocal M = {}\n\n-- WebSocket opcodes\nM.OPCODE = {\n CONTINUATION = 0x0,\n TEXT = 0x1,\n BINARY = 0x2,\n CLOSE = 0x8,\n PING = 0x9,\n PONG = 0xA,\n}\n\n---@class WebSocketFrame\n---@field fin boolean Final fragment flag\n---@field opcode number Frame opcode\n---@field masked boolean Mask flag\n---@field payload_length number Length of payload data\n---@field mask string|nil 4-byte mask (if masked)\n---@field payload string Frame payload data\n\n---@brief Parse a WebSocket frame from binary data\n---@param data string The binary frame data\n---@return WebSocketFrame|nil frame The parsed frame, or nil if incomplete/invalid\n---@return number bytes_consumed Number of bytes consumed from input\nfunction M.parse_frame(data)\n if type(data) ~= \"string\" then\n return nil, 0\n end\n\n if #data < 2 then\n return nil, 0 -- Need at least 2 bytes for basic header\n end\n\n local pos = 1\n local byte1 = data:byte(pos)\n local byte2 = data:byte(pos + 1)\n\n -- Validate byte values\n if not byte1 or not byte2 then\n return nil, 0\n end\n\n pos = pos + 2\n\n local fin = math.floor(byte1 / 128) == 1\n local rsv1 = math.floor((byte1 % 128) / 64) == 1\n local rsv2 = math.floor((byte1 % 64) / 32) == 1\n local rsv3 = math.floor((byte1 % 32) / 16) == 1\n local opcode = byte1 % 16\n\n local masked = math.floor(byte2 / 128) == 1\n local payload_len = byte2 % 128\n\n -- Validate opcode (RFC 6455 Section 5.2)\n local valid_opcodes = {\n [M.OPCODE.CONTINUATION] = true,\n [M.OPCODE.TEXT] = true,\n [M.OPCODE.BINARY] = true,\n [M.OPCODE.CLOSE] = true,\n [M.OPCODE.PING] = true,\n [M.OPCODE.PONG] = true,\n }\n\n if not valid_opcodes[opcode] then\n return nil, 0 -- Invalid opcode\n end\n\n -- Check for reserved bits (must be 0)\n if rsv1 or rsv2 or rsv3 then\n return nil, 0 -- Protocol error\n end\n\n -- Control frames must have fin=1 and payload ≤ 125 (RFC 6455 Section 5.5)\n if opcode >= M.OPCODE.CLOSE then\n if not fin or payload_len > 125 then\n return nil, 0 -- Protocol violation\n end\n end\n\n -- Determine actual payload length\n local actual_payload_len = payload_len\n if payload_len == 126 then\n if #data < pos + 1 then\n return nil, 0 -- Need 2 more bytes\n end\n actual_payload_len = utils.bytes_to_uint16(data:sub(pos, pos + 1))\n pos = pos + 2\n\n -- Allow any valid 16-bit length for compatibility\n -- Note: Technically should be > 125, but some implementations may vary\n elseif payload_len == 127 then\n if #data < pos + 7 then\n return nil, 0 -- Need 8 more bytes\n end\n actual_payload_len = utils.bytes_to_uint64(data:sub(pos, pos + 7))\n pos = pos + 8\n\n -- Allow any valid 64-bit length for compatibility\n -- Note: Technically should be > 65535, but some implementations may vary\n\n -- Prevent extremely large payloads (DOS protection)\n if actual_payload_len > 100 * 1024 * 1024 then -- 100MB limit\n return nil, 0\n end\n end\n\n -- Additional payload length validation\n if actual_payload_len < 0 then\n return nil, 0 -- Invalid negative length\n end\n\n -- Read mask if present\n local mask = nil\n if masked then\n if #data < pos + 3 then\n return nil, 0 -- Need 4 mask bytes\n end\n mask = data:sub(pos, pos + 3)\n pos = pos + 4\n end\n\n -- Check if we have enough data for payload\n if #data < pos + actual_payload_len - 1 then\n return nil, 0 -- Incomplete frame\n end\n\n -- Read payload\n local payload = data:sub(pos, pos + actual_payload_len - 1)\n pos = pos + actual_payload_len\n\n -- Unmask payload if needed\n if masked and mask then\n payload = utils.apply_mask(payload, mask)\n end\n\n -- Validate text frame payload is valid UTF-8\n if opcode == M.OPCODE.TEXT and not utils.is_valid_utf8(payload) then\n return nil, 0 -- Invalid UTF-8 in text frame\n end\n\n -- Basic validation for close frame payload\n if opcode == M.OPCODE.CLOSE and actual_payload_len > 0 then\n if actual_payload_len == 1 then\n return nil, 0 -- Close frame with 1 byte payload is invalid\n end\n -- Allow most close codes for compatibility, only validate UTF-8 for reason text\n if actual_payload_len > 2 then\n local reason = payload:sub(3)\n if not utils.is_valid_utf8(reason) then\n return nil, 0 -- Invalid UTF-8 in close reason\n end\n end\n end\n\n local frame = {\n fin = fin,\n opcode = opcode,\n masked = masked,\n payload_length = actual_payload_len,\n mask = mask,\n payload = payload,\n }\n\n return frame, pos - 1\nend\n\n---@brief Create a WebSocket frame\n---@param opcode number Frame opcode\n---@param payload string Frame payload\n---@param fin boolean|nil Final fragment flag (default: true)\n---@param masked boolean|nil Whether to mask the frame (default: false for server)\n---@return string frame_data The encoded frame data\nfunction M.create_frame(opcode, payload, fin, masked)\n fin = fin ~= false -- Default to true\n masked = masked == true -- Default to false\n\n local frame_data = {}\n\n -- First byte: FIN + RSV + Opcode\n local byte1 = opcode\n if fin then\n byte1 = byte1 + 128 -- Set FIN bit (0x80)\n end\n table.insert(frame_data, string.char(byte1))\n\n -- Payload length and mask bit\n local payload_len = #payload\n local byte2 = 0\n if masked then\n byte2 = byte2 + 128 -- Set MASK bit (0x80)\n end\n\n if payload_len < 126 then\n byte2 = byte2 + payload_len\n table.insert(frame_data, string.char(byte2))\n elseif payload_len < 65536 then\n byte2 = byte2 + 126\n table.insert(frame_data, string.char(byte2))\n table.insert(frame_data, utils.uint16_to_bytes(payload_len))\n else\n byte2 = byte2 + 127\n table.insert(frame_data, string.char(byte2))\n table.insert(frame_data, utils.uint64_to_bytes(payload_len))\n end\n\n -- Add mask if needed\n local mask = nil\n if masked then\n -- Generate random 4-byte mask\n mask = string.char(math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255))\n table.insert(frame_data, mask)\n end\n\n -- Add payload (masked if needed)\n if masked and mask then\n payload = utils.apply_mask(payload, mask)\n end\n table.insert(frame_data, payload)\n\n return table.concat(frame_data)\nend\n\n---@brief Create a text frame\n---@param text string The text to send\n---@param fin boolean|nil Final fragment flag (default: true)\n---@return string frame_data The encoded frame data\nfunction M.create_text_frame(text, fin)\n return M.create_frame(M.OPCODE.TEXT, text, fin, false)\nend\n\n---@brief Create a binary frame\n---@param data string The binary data to send\n---@param fin boolean|nil Final fragment flag (default: true)\n---@return string frame_data The encoded frame data\nfunction M.create_binary_frame(data, fin)\n return M.create_frame(M.OPCODE.BINARY, data, fin, false)\nend\n\n---@brief Create a close frame\n---@param code number|nil Close code (default: 1000)\n---@param reason string|nil Close reason (default: empty)\n---@return string frame_data The encoded frame data\nfunction M.create_close_frame(code, reason)\n code = code or 1000\n reason = reason or \"\"\n\n local payload = utils.uint16_to_bytes(code) .. reason\n return M.create_frame(M.OPCODE.CLOSE, payload, true, false)\nend\n\n---@brief Create a ping frame\n---@param data string|nil Ping data (default: empty)\n---@return string frame_data The encoded frame data\nfunction M.create_ping_frame(data)\n data = data or \"\"\n return M.create_frame(M.OPCODE.PING, data, true, false)\nend\n\n---@brief Create a pong frame\n---@param data string|nil Pong data (should match ping data)\n---@return string frame_data The encoded frame data\nfunction M.create_pong_frame(data)\n data = data or \"\"\n return M.create_frame(M.OPCODE.PONG, data, true, false)\nend\n\n---@brief Check if an opcode is a control frame\n---@param opcode number The opcode to check\n---@return boolean is_control True if it's a control frame\nfunction M.is_control_frame(opcode)\n return opcode >= 0x8\nend\n\n---@brief Validate a WebSocket frame\n---@param frame WebSocketFrame The frame to validate\n---@return boolean valid True if the frame is valid\n---@return string|nil error Error message if invalid\nfunction M.validate_frame(frame)\n -- Control frames must not be fragmented\n if M.is_control_frame(frame.opcode) and not frame.fin then\n return false, \"Control frames must not be fragmented\"\n end\n\n -- Control frames must have payload <= 125 bytes\n if M.is_control_frame(frame.opcode) and frame.payload_length > 125 then\n return false, \"Control frame payload too large\"\n end\n\n -- Check for valid opcodes\n local valid_opcodes = {\n [M.OPCODE.CONTINUATION] = true,\n [M.OPCODE.TEXT] = true,\n [M.OPCODE.BINARY] = true,\n [M.OPCODE.CLOSE] = true,\n [M.OPCODE.PING] = true,\n [M.OPCODE.PONG] = true,\n }\n\n if not valid_opcodes[frame.opcode] then\n return false, \"Invalid opcode: \" .. frame.opcode\n end\n\n -- Text frames must contain valid UTF-8\n if frame.opcode == M.OPCODE.TEXT and not utils.is_valid_utf8(frame.payload) then\n return false, \"Text frame contains invalid UTF-8\"\n end\n\n return true\nend\n\nreturn M\n"], ["/claudecode.nvim/lua/claudecode/utils.lua", "--- Shared utility functions for claudecode.nvim\n-- @module claudecode.utils\n\nlocal M = {}\n\n--- Normalizes focus parameter to default to true for backward compatibility\n--- @param focus boolean|nil The focus parameter\n--- @return boolean Normalized focus value\nfunction M.normalize_focus(focus)\n return focus == nil and true or focus\nend\n\nreturn M\n"]], "task_instance_info": {"created_time": "2025-08-21 00:41:34", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Manage terminal window lifecycle by checking existing instances, toggling visibility states, and handling focus transitions while providing error handling for initialization failures."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```lua\n[TASK_BEGIN]\nfunction M.open(cmd_string, env_table, config, focus)\n if not is_available() then\n vim.notify(\"Snacks.nvim terminal provider selected but Snacks.terminal not available.\", vim.log.levels.ERROR)\n return\n end\n\n local logger = require(\"claudecode.logger\")\n\n -- Reuse existing terminal if possible\n if terminal and terminal:buf_valid() then\n if not terminal.win then -- Exists but not visible\n logger.debug(\"terminal\", \"Showing existing terminal\")\n terminal:toggle()\n end\n \n if focus then\n vim.api.nvim_set_current_win(terminal.win)\n end\n return\n end\n\n -- Create new terminal instance\n logger.debug(\"terminal\", \"Launching new terminal\")\n local opts = build_opts(config, env_table, focus)\n local term_instance = Snacks.terminal.new(cmd_string, opts)\n \n setup_terminal_events(term_instance, config)\n terminal = term_instance\nend\n[TASK_END]\n```", "inference_time": "2025-08-21 00-42-04"}, "editdistance_info": {"edit_distance": 23.2877, "calculate_time": "2025-08-21 00:42:04", "true_code_clean": "function M.open(cmd_string, env_table, config, focus)\n if not is_available() then\n vim.notify(\"Snacks.nvim terminal provider selected but Snacks.terminal not available.\", vim.log.levels.ERROR)\n return\n end\n focus = utils.normalize_focus(focus)\n if terminal and terminal:buf_valid() then\n if not terminal.win or not vim.api.nvim_win_is_valid(terminal.win) then\n terminal:toggle()\n if focus then\n terminal:focus()\n local term_buf_id = terminal.buf\n if term_buf_id and vim.api.nvim_buf_get_option(term_buf_id, \"buftype\") == \"terminal\" then\n if terminal.win and vim.api.nvim_win_is_valid(terminal.win) then\n vim.api.nvim_win_call(terminal.win, function()\n vim.cmd(\"startinsert\")\n end)\n end\n end\n end\n else\n if focus then\n terminal:focus()\n local term_buf_id = terminal.buf\n if term_buf_id and vim.api.nvim_buf_get_option(term_buf_id, \"buftype\") == \"terminal\" then\n if terminal.win and vim.api.nvim_win_is_valid(terminal.win) then\n vim.api.nvim_win_call(terminal.win, function()\n vim.cmd(\"startinsert\")\n end)\n end\n end\n end\n end\n return\n end\n local opts = build_opts(config, env_table, focus)\n local term_instance = Snacks.terminal.open(cmd_string, opts)\n if term_instance and term_instance:buf_valid() then\n setup_terminal_events(term_instance, config)\n terminal = term_instance\n else\n terminal = nil\n local logger = require(\"claudecode.logger\")\n local error_details = {}\n if not term_instance then\n table.insert(error_details, \"Snacks.terminal.open() returned nil\")\n elseif not term_instance:buf_valid() then\n table.insert(error_details, \"terminal instance is invalid\")\n if term_instance.buf and not vim.api.nvim_buf_is_valid(term_instance.buf) then\n table.insert(error_details, \"buffer is invalid\")\n end\n if term_instance.win and not vim.api.nvim_win_is_valid(term_instance.win) then\n table.insert(error_details, \"window is invalid\")\n end\n end\n local context = string.format(\"cmd='%s', opts=%s\", cmd_string, vim.inspect(opts))\n local error_msg = string.format(\n \"Failed to open Claude terminal using Snacks. Details: %s. Context: %s\",\n table.concat(error_details, \", \"),\n context\n )\n vim.notify(error_msg, vim.log.levels.ERROR)\n logger.debug(\"terminal\", error_msg)\n end\nend", "predict_code_clean": "function M.open(cmd_string, env_table, config, focus)\n if not is_available() then\n vim.notify(\"Snacks.nvim terminal provider selected but Snacks.terminal not available.\", vim.log.levels.ERROR)\n return\n end\n local logger = require(\"claudecode.logger\")\n if terminal and terminal:buf_valid() then\n if not terminal.win then \n logger.debug(\"terminal\", \"Showing existing terminal\")\n terminal:toggle()\n end\n if focus then\n vim.api.nvim_set_current_win(terminal.win)\n end\n return\n end\n logger.debug(\"terminal\", \"Launching new terminal\")\n local opts = build_opts(config, env_table, focus)\n local term_instance = Snacks.terminal.new(cmd_string, opts)\n setup_terminal_events(term_instance, config)\n terminal = term_instance\nend"}}