File size: 142,970 Bytes
bc21fc6
 
 
 
1
2
3
4
5
{"repo_name": "copilot-lsp", "file_name": "/copilot-lsp/lua/copilot-lsp/util.lua", "inference_info": {"prefix_code": "local M = {}\n---@param edit copilotlsp.InlineEdit\nfunction M.apply_inline_edit(edit)\n    local bufnr = vim.uri_to_bufnr(edit.textDocument.uri)\n\n    ---@diagnostic disable-next-line: assign-type-mismatch\n    vim.lsp.util.apply_text_edits({ edit }, bufnr, \"utf-16\")\nend\n\n---Debounces calls to a function, and ensures it only runs once per delay\n---even if called repeatedly.\n---@param fn fun(...: any)\n---@param delay integer\nfunction M.debounce(fn, delay)\n    local timer = vim.uv.new_timer()\n    return function(...)\n        local argv = vim.F.pack_len(...)\n        timer:start(delay, 0, function()\n            timer:stop()\n            vim.schedule_wrap(fn)(vim.F.unpack_len(argv))\n        end)\n    end\nend\n\n---@private\n---@class Capture\n---@field hl string|string[]\n---range(0-based)\n---@field start_row integer\n---@field start_col integer\n---@field end_row integer\n---@field end_col integer\n\n---@param text string\n---@param lang string\n---@return Capture[]?\nlocal function parse_text(text, lang)\n    local ok, trees = pcall(vim.treesitter.get_string_parser, text, lang)\n    if not ok then\n        return\n    end\n    trees:parse(true)\n\n    local captures = {}\n\n    trees:for_each_tree(function(tree, _ltree)\n        local hl_query = vim.treesitter.query.get(lang, \"highlights\")\n        if not hl_query then\n            return\n        end\n\n        local iter = hl_query:iter_captures(tree:root(), text)\n        vim.iter(iter):each(function(id, node)\n            local name = hl_query.captures[id]\n            local hl = \"Normal\"\n            if not vim.startswith(name, \"_\") then\n                hl = \"@\" .. name .. \".\" .. lang\n            end\n            local start_row, start_col, end_row, end_col = node:range()\n\n            -- Ignore zero-width captures if they cause issues (sometimes happen at EOF)\n            if start_row == end_row and start_col == end_col then\n                return\n            end\n\n            table.insert(captures, {\n                hl = hl,\n                start_row = start_row,\n                start_col = start_col,\n                end_row = end_row,\n                end_col = end_col,\n            })\n        end)\n    end)\n    return captures\nend\n\nlocal function merge_captures(captures)\n    table.sort(captures, function(a, b)\n        if a.start_row == b.start_row then\n            return a.start_col < b.start_col\n        end\n        return a.start_row < b.start_row\n    end)\n    local merged_captures = {}\n    for i = 2, #captures do\n        local prev = captures[i - 1]\n        local curr = captures[i]\n        if\n            prev.start_row == curr.start_row\n            and prev.start_col == curr.start_col\n            and prev.end_row == curr.end_row\n            and prev.end_col == curr.end_col\n        then\n            local prev_hl = type(prev.hl) == \"table\" and prev.hl or { prev.hl }\n            local curr_hl = type(curr.hl) == \"table\" and curr.hl or { curr.hl }\n            ---@diagnostic disable-next-line: param-type-mismatch\n            vim.list_extend(prev_hl, curr_hl)\n            curr.hl = prev_hl\n        else\n            table.insert(merged_captures, prev)\n        end\n    end\n    table.insert(merged_captures, captures[#captures])\n\n    return merged_captures\nend\n\nfunction M.hl_text_to_virt_lines(text, lang)\n    local lines = vim.split(text, \"\\n\")\n    local normal_hl = \"Normal\"\n    local bg_hl = \"CopilotLspNesAdd\"\n\n    ", "suffix_code": "\n\n    local captures = parse_text(text, lang)\n    if not captures or #captures == 0 then\n        return vim.iter(lines)\n            :map(function(line)\n                return { hl_chunk(line) }\n            end)\n            :totable()\n    end\n\n    captures = merge_captures(captures)\n\n    local virt_lines = {}\n\n    local curr_row = 0\n    local curr_col = 0\n    local curr_virt_line = {}\n\n    vim.iter(captures):each(function(cap)\n        -- skip if the capture is before the current position\n        if cap.end_row < curr_row or (cap.end_row == curr_row and cap.end_col <= curr_col) then\n            return\n        end\n\n        if cap.start_row > curr_row then\n            -- add the rest of the line\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1)\n            table.insert(curr_virt_line, hl_chunk(chunk_text))\n            table.insert(virt_lines, curr_virt_line)\n\n            for i = curr_row + 1, cap.start_row - 1 do\n                local line_text = lines[i + 1]\n                table.insert(virt_lines, { hl_chunk(line_text) })\n            end\n\n            curr_row = cap.start_row\n            curr_col = 0\n            curr_virt_line = {}\n        end\n\n        assert(curr_row == cap.start_row, \"Unexpected start row\")\n\n        if cap.start_col > curr_col then\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1, cap.start_col)\n            table.insert(curr_virt_line, hl_chunk(chunk_text))\n            curr_col = cap.start_col\n        end\n\n        assert(curr_col == cap.start_col, \"Unexpected start column\")\n\n        if cap.end_row > curr_row then\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1)\n            table.insert(curr_virt_line, hl_chunk(chunk_text, cap.hl))\n            table.insert(virt_lines, curr_virt_line)\n\n            for i = curr_row + 1, cap.end_row - 1 do\n                local line_text = lines[i + 1]\n                table.insert(virt_lines, { hl_chunk(line_text, cap.hl) })\n            end\n\n            curr_row = cap.end_row\n            curr_col = 0\n            curr_virt_line = {}\n        end\n\n        assert(curr_row == cap.end_row, \"Unexpected end row\")\n\n        if cap.end_col > curr_col then\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1, cap.end_col)\n            table.insert(curr_virt_line, hl_chunk(chunk_text, cap.hl))\n            curr_col = cap.end_col\n        end\n    end)\n\n    if #curr_virt_line > 0 then\n        table.insert(virt_lines, curr_virt_line)\n    end\n\n    return virt_lines\nend\n\nreturn M\n", "middle_code": "local function hl_chunk(chunk, hl)\n        if not hl then\n            return { chunk, { normal_hl, bg_hl } }\n        end\n        if type(hl) == \"string\" then\n            return { chunk, { hl, bg_hl } }\n        end\n        hl = vim.deepcopy(hl)\n        table.insert(hl, bg_hl)\n        return { chunk, hl }\n    end", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "lua", "sub_task_type": null}, "context_code": [["/copilot-lsp/lua/copilot-lsp/nes/ui.lua", "local M = {}\nlocal config = require(\"copilot-lsp.config\").config\n\n---@param bufnr integer\n---@param ns_id integer\nlocal function _dismiss_suggestion(bufnr, ns_id)\n    pcall(vim.api.nvim_buf_clear_namespace, bufnr, ns_id, 0, -1)\nend\n\n---@param bufnr? integer\n---@param ns_id integer\nfunction M.clear_suggestion(bufnr, ns_id)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    -- Validate buffer exists before accessing buffer-scoped variables\n    if not vim.api.nvim_buf_is_valid(bufnr) then\n        return\n    end\n    if vim.b[bufnr].nes_jump then\n        vim.b[bufnr].nes_jump = false\n        return\n    end\n    _dismiss_suggestion(bufnr, ns_id)\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return\n    end\n\n    -- Clear buffer variables\n    vim.b[bufnr].nes_state = nil\n    vim.b[bufnr].copilotlsp_nes_cursor_moves = nil\n    vim.b[bufnr].copilotlsp_nes_last_line = nil\n    vim.b[bufnr].copilotlsp_nes_last_col = nil\nend\n\n---@private\n---@param bufnr integer\n---@param edit lsp.TextEdit\n---@return copilotlsp.nes.InlineEditPreview\nfunction M._calculate_preview(bufnr, edit)\n    local text = edit.newText\n    local range = edit.range\n    local start_line = range.start.line\n    local start_char = range.start.character\n    local end_line = range[\"end\"].line\n    local end_char = range[\"end\"].character\n\n    -- Split text by newline. Use plain=true to handle trailing newline correctly.\n    local new_lines = vim.split(text, \"\\n\", { plain = true })\n    local num_new_lines = #new_lines\n\n    local old_lines = vim.api.nvim_buf_get_lines(bufnr, start_line, end_line + 1, false)\n    local num_old_lines = #old_lines\n\n    local is_same_line = start_line == end_line\n    local is_deletion = text == \"\"\n    local lines_edit = is_same_line or (start_char == 0 and end_char == 0)\n    local is_insertion = is_same_line and start_char == end_char\n\n    if is_deletion and is_insertion then\n        -- no-op\n        return {}\n    end\n\n    if is_deletion and lines_edit then\n        return {\n            deletion = {\n                range = edit.range,\n            },\n        }\n    end\n\n    if is_insertion and num_new_lines == 1 and text ~= \"\" then\n        -- inline insertion\n        return {\n            inline_insertion = {\n                text = text,\n                line = start_line,\n                character = start_char,\n            },\n        }\n    end\n\n    if is_insertion and num_new_lines > 1 then\n        if start_char == #old_lines[1] and new_lines[1] == \"\" then\n            -- insert lines after the start line\n            return {\n                lines_insertion = {\n                    text = table.concat(vim.list_slice(new_lines, 2), \"\\n\"),\n                    line = start_line,\n                },\n            }\n        end\n\n        if end_char == 0 and new_lines[num_new_lines] == \"\" then\n            -- insert lines before the end line\n            return {\n                lines_insertion = {\n                    text = table.concat(vim.list_slice(new_lines, 1, num_new_lines - 1), \"\\n\"),\n                    line = start_line,\n                    above = true,\n                },\n            }\n        end\n    end\n\n    -- insert lines in the middle\n    local prefix = old_lines[1]:sub(1, start_char)\n    local suffix = old_lines[num_old_lines]:sub(end_char + 1)\n    local new_lines_extend = vim.deepcopy(new_lines)\n    new_lines_extend[1] = prefix .. new_lines_extend[1]\n    new_lines_extend[num_new_lines] = new_lines_extend[num_new_lines] .. suffix\n    local insertion = table.concat(new_lines_extend, \"\\n\")\n\n    return {\n        deletion = {\n            range = {\n                start = { line = start_line, character = 0 },\n                [\"end\"] = { line = end_line, character = #old_lines[num_old_lines] },\n            },\n        },\n        lines_insertion = {\n            text = insertion,\n            line = end_line,\n        },\n    }\nend\n\n---@private\n---@param bufnr integer\n---@param ns_id integer\n---@param preview copilotlsp.nes.InlineEditPreview\nfunction M._display_preview(bufnr, ns_id, preview)\n    if preview.deletion then\n        local range = preview.deletion.range\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, range.start.line, range.start.character, {\n            hl_group = \"CopilotLspNesDelete\",\n            end_row = range[\"end\"].line,\n            end_col = range[\"end\"].character,\n        })\n    end\n\n    local inline_insertion = preview.inline_insertion\n    if inline_insertion then\n        local virt_lines =\n            require(\"copilot-lsp.util\").hl_text_to_virt_lines(inline_insertion.text, vim.bo[bufnr].filetype)\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, inline_insertion.line, inline_insertion.character, {\n            virt_text = virt_lines[1],\n            virt_text_pos = \"inline\",\n        })\n    end\n\n    local lines_insertion = preview.lines_insertion\n    if lines_insertion then\n        local virt_lines =\n            require(\"copilot-lsp.util\").hl_text_to_virt_lines(lines_insertion.text, vim.bo[bufnr].filetype)\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, lines_insertion.line, 0, {\n            virt_lines = virt_lines,\n            virt_lines_above = lines_insertion.above,\n        })\n    end\nend\n\n---@private\n---@param bufnr integer\n---@param ns_id integer\n---@param edits copilotlsp.InlineEdit[]\nfunction M._display_next_suggestion(bufnr, ns_id, edits)\n    M.clear_suggestion(bufnr, ns_id)\n    if not edits or #edits == 0 then\n        return\n    end\n\n    local suggestion = edits[1]\n    local preview = M._calculate_preview(bufnr, suggestion)\n    M._display_preview(bufnr, ns_id, preview)\n\n    vim.b[bufnr].nes_state = suggestion\n    vim.b[bufnr].copilotlsp_nes_namespace_id = ns_id\n    vim.b[bufnr].copilotlsp_nes_cursor_moves = 1\n\n    vim.api.nvim_create_autocmd({ \"CursorMoved\", \"CursorMovedI\" }, {\n        buffer = bufnr,\n        callback = function()\n            if not vim.b[bufnr].nes_state then\n                return true\n            end\n\n            -- Get cursor position\n            local cursor = vim.api.nvim_win_get_cursor(0)\n            local cursor_line = cursor[1] - 1 -- 0-indexed\n            local cursor_col = cursor[2]\n            local suggestion_line = suggestion.range.start.line\n\n            -- Store previous position\n            local last_line = vim.b[bufnr].copilotlsp_nes_last_line or cursor_line\n            local last_col = vim.b[bufnr].copilotlsp_nes_last_col or cursor_col\n\n            -- Update stored position\n            vim.b[bufnr].copilotlsp_nes_last_line = cursor_line\n            vim.b[bufnr].copilotlsp_nes_last_col = cursor_col\n\n            -- Calculate distance to suggestion\n            local line_distance = math.abs(cursor_line - suggestion_line)\n            local last_line_distance = math.abs(last_line - suggestion_line)\n\n            -- Check if cursor changed position on same line\n            local moved_horizontally = (cursor_line == last_line) and (cursor_col ~= last_col)\n\n            -- Get current mode\n            local mode = vim.api.nvim_get_mode().mode\n\n            -- Determine if we should count this movement\n            local should_count = false\n            local first_char = mode:sub(1, 1)\n\n            -- In insert mode, only count cursor movements, not text changes\n            if first_char == \"i\" then\n                if moved_horizontally or line_distance ~= last_line_distance then\n                    should_count = true\n                end\n            elseif first_char == \"v\" or first_char == \"V\" or mode == \"\\22\" then\n                should_count = true\n            -- In normal mode with horizontal movement\n            elseif moved_horizontally and config.nes.count_horizontal_moves then\n                should_count = true\n            -- In normal mode with line changes\n            elseif line_distance > last_line_distance then\n                should_count = true\n            -- Moving toward suggestion in normal mode\n            elseif line_distance < last_line_distance and config.nes.reset_on_approaching then\n                if line_distance > 1 then -- Don't reset if 0 or 1 line away\n                    vim.b[bufnr].copilotlsp_nes_cursor_moves = 0\n                end\n            end\n\n            -- Update counter if needed\n            if should_count then\n                vim.b[bufnr].copilotlsp_nes_cursor_moves = (vim.b[bufnr].copilotlsp_nes_cursor_moves or 0) + 1\n            end\n\n            -- Clear if counter threshold reached\n            if vim.b[bufnr].copilotlsp_nes_cursor_moves >= config.nes.move_count_threshold then\n                vim.b[bufnr].copilotlsp_nes_cursor_moves = 0\n                vim.schedule(function()\n                    M.clear_suggestion(bufnr, ns_id)\n                end)\n                return true\n            end\n\n            -- Optional: Clear on large distance\n            if config.nes.clear_on_large_distance and line_distance > config.nes.distance_threshold then\n                M.clear_suggestion(bufnr, ns_id)\n                return true\n            end\n\n            return false -- Keep the autocmd\n        end,\n    })\n    -- Also clear on text changes that affect the suggestion area\n    vim.api.nvim_create_autocmd({ \"TextChanged\", \"TextChangedI\" }, {\n        buffer = bufnr,\n        callback = function()\n            if not vim.b[bufnr].nes_state then\n                return true\n            end\n            -- Check if the text at the suggestion position has changed\n            local start_line = suggestion.range.start.line\n            -- If the lines are no longer in the buffer, clear the suggestion\n            if start_line >= vim.api.nvim_buf_line_count(bufnr) then\n                M.clear_suggestion(bufnr, ns_id)\n                return true\n            end\n            return false -- Keep the autocmd\n        end,\n    })\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/nes/init.lua", "local errs = require(\"copilot-lsp.errors\")\nlocal nes_ui = require(\"copilot-lsp.nes.ui\")\nlocal utils = require(\"copilot-lsp.util\")\n\nlocal M = {}\n\nlocal nes_ns = vim.api.nvim_create_namespace(\"copilotlsp.nes\")\n\n---@param err lsp.ResponseError?\n---@param result copilotlsp.copilotInlineEditResponse\n---@param ctx lsp.HandlerContext\nlocal function handle_nes_response(err, result, ctx)\n    if err then\n        -- vim.notify(err.message)\n        return\n    end\n    -- Validate buffer still exists before processing response\n    if not vim.api.nvim_buf_is_valid(ctx.bufnr) then\n        return\n    end\n    for _, edit in ipairs(result.edits) do\n        --- Convert to textEdit fields\n        edit.newText = edit.text\n    end\n    nes_ui._display_next_suggestion(ctx.bufnr, nes_ns, result.edits)\nend\n\n--- Requests the NextEditSuggestion from the current cursor position\n---@param copilot_lss? vim.lsp.Client|string\nfunction M.request_nes(copilot_lss)\n    local pos_params = vim.lsp.util.make_position_params(0, \"utf-16\")\n    local version = vim.lsp.util.buf_versions[vim.api.nvim_get_current_buf()]\n    if type(copilot_lss) == \"string\" then\n        copilot_lss = vim.lsp.get_clients({ name = copilot_lss })[1]\n    end\n    assert(copilot_lss, errs.ErrNotStarted)\n    ---@diagnostic disable-next-line: inject-field\n    pos_params.textDocument.version = version\n    copilot_lss:request(\"textDocument/copilotInlineEdit\", pos_params, handle_nes_response)\nend\n\n--- Walks the cursor to the start of the edit.\n--- This function returns false if there is no edit to apply or if the cursor is already at the start position of the\n--- edit.\n---@param bufnr? integer\n---@return boolean --if the cursor walked\nfunction M.walk_cursor_start_edit(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return false\n    end\n\n    local cursor_row, _ = unpack(vim.api.nvim_win_get_cursor(0))\n    if cursor_row - 1 ~= state.range.start.line then\n        vim.b[bufnr].nes_jump = true\n        ---@type lsp.Location\n        local jump_loc_before = {\n            uri = state.textDocument.uri,\n            range = {\n                start = state.range[\"start\"],\n                [\"end\"] = state.range[\"start\"],\n            },\n        }\n        vim.schedule(function()\n            vim.lsp.util.show_document(jump_loc_before, \"utf-16\", { focus = true })\n        end)\n        return true\n    else\n        return false\n    end\nend\n\n--- Walks the cursor to the end of the edit.\n--- This function returns false if there is no edit to apply or if the cursor is already at the end position of the\n--- edit\n---@param bufnr? integer\n---@return boolean --if the cursor walked\nfunction M.walk_cursor_end_edit(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return false\n    end\n\n    ---@type lsp.Location\n    local jump_loc_after = {\n        uri = state.textDocument.uri,\n        range = {\n            start = state.range[\"end\"],\n            [\"end\"] = state.range[\"end\"],\n        },\n    }\n    --NOTE: If last line is deletion, then this may be outside of the buffer\n    vim.schedule(function()\n        pcall(vim.lsp.util.show_document, jump_loc_after, \"utf-16\", { focus = true })\n    end)\n    return true\nend\n\n--- This function applies the pending nes edit to the current buffer and then clears the marks for the pending\n--- suggestion\n---@param bufnr? integer\n---@return boolean --if the nes was applied\nfunction M.apply_pending_nes(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return false\n    end\n    vim.schedule(function()\n        utils.apply_inline_edit(state)\n        vim.b[bufnr].nes_jump = false\n        nes_ui.clear_suggestion(bufnr, nes_ns)\n    end)\n    return true\nend\n\n---@param bufnr? integer\nfunction M.clear_suggestion(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    nes_ui.clear_suggestion(bufnr, nes_ns)\nend\n\n--- Clear the current suggestion if it exists\n---@return boolean -- true if a suggestion was cleared, false if no suggestion existed\nfunction M.clear()\n    local buf = vim.api.nvim_get_current_buf()\n    if vim.b[buf].nes_state then\n        local ns = vim.b[buf].copilotlsp_nes_namespace_id or nes_ns\n        nes_ui.clear_suggestion(buf, ns)\n        return true\n    end\n    return false\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/handlers.lua", "---@type table<string, lsp.Handler>\nlocal M = {}\n\nlocal methods = {\n    signIn = \"signIn\",\n    didChangeStatus = \"didChangeStatus\",\n}\n\n-- copy from copilot.lua\nlocal function open_signin_popup(code, url)\n    local lines = {\n        \" [Copilot-lsp] \",\n        \"\",\n        \" First copy your one-time code: \",\n        \"   \" .. code .. \" \",\n        \" In your browser, visit: \",\n        \"   \" .. url .. \" \",\n        \"\",\n        \" ...waiting, it might take a while and \",\n        \" this popup will auto close once done... \",\n    }\n    local height, width = #lines, math.max(unpack(vim.tbl_map(function(line)\n        return #line\n    end, lines)))\n\n    local bufnr = vim.api.nvim_create_buf(false, true)\n    vim.bo[bufnr].buflisted = false\n    vim.bo[bufnr].buftype = \"nofile\"\n    vim.bo[bufnr].bufhidden = \"wipe\"\n    vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines)\n\n    local winnr = vim.api.nvim_open_win(bufnr, true, {\n        relative = \"editor\",\n        style = \"minimal\",\n        border = \"single\",\n        row = (vim.o.lines - height) / 2,\n        col = (vim.o.columns - width) / 2,\n        height = height,\n        width = width,\n    })\n    vim.wo[winnr].winhighlight = \"Normal:Normal\"\n    vim.wo[winnr].winblend = 0\n\n    return function()\n        vim.api.nvim_win_close(winnr, true)\n    end\nend\n\nlocal function copy_to_clipboard(s)\n    vim.fn.setreg(\"+\", s)\n    vim.fn.setreg(\"*\", s)\nend\n\n---@param res {command: lsp.Command, userCode: string, verificationUri: string}\nM[methods.signIn] = function(err, res, ctx)\n    if err then\n        vim.notify(\"[copilot-lsp] failed to start signin flow: \" .. vim.inspect(err), vim.log.levels.ERROR)\n        return\n    end\n\n    local client = vim.lsp.get_client_by_id(ctx.client_id)\n    if not client then\n        return\n    end\n\n    vim.g.copilot_lsp_signin_pending = true\n\n    local close_signin_popup = open_signin_popup(res.userCode, res.verificationUri)\n    copy_to_clipboard(res.userCode)\n\n    client:exec_cmd(\n        res.command,\n        { bufnr = ctx.bufnr },\n\n        ---@param cmd_res {status: string, user: string}\n        function(cmd_err, cmd_res)\n            vim.g.copilot_lsp_signin_pending = nil\n            close_signin_popup()\n\n            if cmd_err then\n                vim.notify(\"[copilot-lsp] failed to open browser: \" .. vim.inspect(cmd_err), vim.log.levels.WARN)\n                return\n            end\n            if cmd_res.status == \"OK\" then\n                vim.notify(\"[copilot-lsp] successfully signed in as: \" .. cmd_res.user, vim.log.levels.INFO)\n            else\n                vim.notify(\"[copilot-lsp] failed to sign in: \" .. vim.inspect(cmd_res), vim.log.levels.ERROR)\n            end\n        end\n    )\nend\n\n---@param client_id integer\n---@param bufnr integer\nlocal function sign_in(client_id, bufnr)\n    if vim.g.copilot_lsp_signin_pending then\n        return\n    end\n\n    local client = vim.lsp.get_client_by_id(client_id)\n    if not client then\n        return\n    end\n\n    for _, req in pairs(client.requests) do\n        if req.method == methods.signIn and req.type == \"pending\" then\n            return\n        end\n    end\n\n    client:request(methods.signIn, vim.empty_dict(), nil, bufnr)\nend\n\n---@param res {busy: boolean, kind: 'Normal'|'Error'|'Warning'|'Inactive', message: string}\nM[\"didChangeStatus\"] = function(err, res, ctx)\n    if err then\n        return\n    end\n    -- real error message: You are not signed into GitHub. Please sign in to use Copilot.\n    if res.kind == \"Error\" and res.message:find(\"not signed into\") then\n        sign_in(ctx.client_id, ctx.bufnr)\n    end\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/completion/init.lua", "local M = {}\n\n---@param _results table<integer, { err: lsp.ResponseError, result: lsp.InlineCompletionList}>\n---@param _ctx lsp.HandlerContext\n---@param _config table\nlocal function handle_inlineCompletion_response(_results, _ctx, _config)\n    -- -- Filter errors from results\n    -- local results1 = {} --- @type table<integer,lsp.InlineCompletionList>\n    --\n    -- for client_id, resp in pairs(results) do\n    --     local err, result = resp.err, resp.result\n    --     if err then\n    --         vim.lsp.log.error(err.code, err.message)\n    --     elseif result then\n    --         results1[client_id] = result\n    --     end\n    -- end\n    --\n    -- for _, result in pairs(results1) do\n    --     --TODO: Ghost text for completions\n    --     -- This is where we show the completion results\n    --     -- However, the LSP being named \"copilot_ls\" is enough for blink-cmp to show the completion\n    -- end\nend\n\n---@param type lsp.InlineCompletionTriggerKind\nfunction M.request_inline_completion(type)\n    local params = vim.tbl_deep_extend(\"keep\", vim.lsp.util.make_position_params(0, \"utf-16\"), {\n        textDocument = vim.lsp.util.make_text_document_params(),\n        position = vim.lsp.util.make_position_params(0, \"utf-16\"),\n        context = {\n            triggerKind = type,\n        },\n        formattingOptions = {\n            --TODO: Grab this from editor also\n            tabSize = 4,\n            insertSpaces = true,\n        },\n    })\n    vim.lsp.buf_request_all(0, \"textDocument/inlineCompletion\", params, handle_inlineCompletion_response)\nend\nreturn M\n"], ["/copilot-lsp/lsp/copilot_ls.lua", "local version = vim.version()\n\n---@type vim.lsp.Config\nreturn {\n    --NOTE: This name means that existing blink completion works\n    name = \"copilot_ls\",\n    cmd = {\n        \"copilot-language-server\",\n        \"--stdio\",\n    },\n    init_options = {\n        editorInfo = {\n            name = \"neovim\",\n            version = string.format(\"%d.%d.%d\", version.major, version.minor, version.patch),\n        },\n        editorPluginInfo = {\n            name = \"Github Copilot LSP for Neovim\",\n            version = \"0.0.1\",\n        },\n    },\n    settings = {\n        nextEditSuggestions = {\n            enabled = true,\n        },\n    },\n    handlers = setmetatable({}, {\n        __index = function(_, method)\n            return require(\"copilot-lsp.handlers\")[method]\n        end,\n    }),\n    root_dir = vim.uv.cwd(),\n    on_init = function(client)\n        local au = vim.api.nvim_create_augroup(\"copilotlsp.init\", { clear = true })\n        --NOTE: Inline Completions\n        --TODO: We dont currently use this code path, so comment for now until a UI is built\n        -- vim.api.nvim_create_autocmd(\"TextChangedI\", {\n        --     callback = function()\n        --         inline_completion.request_inline_completion(2)\n        --     end,\n        --     group = au,\n        -- })\n\n        -- TODO: make this configurable for key maps, or just expose commands to map in config\n        -- vim.keymap.set(\"i\", \"<c-i>\", function()\n        --     inline_completion.request_inline_completion(1)\n        -- end)\n\n        --NOTE: NES Completions\n        local debounced_request = require(\"copilot-lsp.util\").debounce(\n            require(\"copilot-lsp.nes\").request_nes,\n            vim.g.copilot_nes_debounce or 500\n        )\n        vim.api.nvim_create_autocmd({ \"TextChangedI\", \"TextChanged\" }, {\n            callback = function()\n                debounced_request(client)\n            end,\n            group = au,\n        })\n\n        --NOTE: didFocus\n        vim.api.nvim_create_autocmd(\"BufEnter\", {\n            callback = function()\n                local td_params = vim.lsp.util.make_text_document_params()\n                client:notify(\"textDocument/didFocus\", {\n                    textDocument = {\n                        uri = td_params.uri,\n                    },\n                })\n            end,\n            group = au,\n        })\n    end,\n}\n"], ["/copilot-lsp/lua/copilot-lsp/config.lua", "---@class copilotlsp.config.nes\n---@field move_count_threshold integer Number of cursor movements before clearing suggestion\n---@field distance_threshold integer Maximum line distance before clearing suggestion\n---@field clear_on_large_distance boolean Whether to clear suggestion when cursor is far away\n---@field count_horizontal_moves boolean Whether to count horizontal cursor movements\n---@field reset_on_approaching boolean Whether to reset counter when approaching suggestion\n\nlocal M = {}\n\n---@class copilotlsp.config\n---@field nes copilotlsp.config.nes\nM.defaults = {\n    nes = {\n        move_count_threshold = 3,\n        distance_threshold = 40,\n        clear_on_large_distance = true,\n        count_horizontal_moves = true,\n        reset_on_approaching = true,\n    },\n}\n\n---@type copilotlsp.config\nM.config = vim.deepcopy(M.defaults)\n\n---@param opts? copilotlsp.config configuration to merge with defaults\nfunction M.setup(opts)\n    opts = opts or {}\n    M.config = vim.tbl_deep_extend(\"force\", M.defaults, opts)\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/init.lua", "local config = require(\"copilot-lsp.config\")\n\n---@class copilotlsp\n---@field defaults copilotlsp.config\n---@field config copilotlsp.config\n---@field setup fun(opts?: copilotlsp.config): nil\nlocal M = {}\n\nM.defaults = config.defaults\nM.config = config.config\n\n---@param opts? copilotlsp.config configuration to merge with defaults\nfunction M.setup(opts)\n    config.setup(opts)\n    M.config = config.config\nend\n\nreturn M\n"], ["/copilot-lsp/plugin/copilot-lsp.lua", "vim.api.nvim_set_hl(0, \"CopilotLspNesAdd\", { link = \"DiffAdd\", default = true })\nvim.api.nvim_set_hl(0, \"CopilotLspNesDelete\", { link = \"DiffDelete\", default = true })\nvim.api.nvim_set_hl(0, \"CopilotLspNesApply\", { link = \"DiffText\", default = true })\n"], ["/copilot-lsp/lua/copilot-lsp/types.lua", "---@class copilotlsp.InlineEdit : lsp.TextEdit\n---@field command lsp.Command\n---@field text string\n---@field textDocument lsp.VersionedTextDocumentIdentifier\n\n---@class copilotlsp.copilotInlineEditResponse\n---@field edits copilotlsp.InlineEdit[]\n\n---@class copilotlsp.nes.TextDeletion\n---@field range lsp.Range\n\n---@class copilotlsp.nes.InlineInsertion\n---@field text string\n---@field line integer\n---@field character integer\n\n---@class copilotlsp.nes.TextInsertion\n---@field text string\n---@field line integer insert lines at this line\n---@field above? boolean above the line\n\n---@class copilotlsp.nes.InlineEditPreview\n---@field deletion? copilotlsp.nes.TextDeletion\n---@field inline_insertion? copilotlsp.nes.InlineInsertion\n---@field lines_insertion? copilotlsp.nes.TextInsertion\n"], ["/copilot-lsp/lua/copilot-lsp/errors.lua", "return {\n    ErrNotStarted = \"Copilot LSP not started\",\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 00:43:17", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Combine textual content with syntax highlighting metadata and background styling for display in virtual interface elements."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```lua\n[TASK_BEGIN]\n    local function hl_chunk(text, hl)\n        return { text, { hl or normal_hl, bg_hl } }\n    end\n[TASK_END]\n```", "inference_time": "2025-08-21 00-43-30"}, "editdistance_info": {"edit_distance": 25.2874, "calculate_time": "2025-08-21 00:43:30", "true_code_clean": "local function hl_chunk(chunk, hl)\n        if not hl then\n            return { chunk, { normal_hl, bg_hl } }\n        end\n        if type(hl) == \"string\" then\n            return { chunk, { hl, bg_hl } }\n        end\n        hl = vim.deepcopy(hl)\n        table.insert(hl, bg_hl)\n        return { chunk, hl }\n    end", "predict_code_clean": "local function hl_chunk(text, hl)\n        return { text, { hl or normal_hl, bg_hl } }\n    end"}}
{"repo_name": "copilot-lsp", "file_name": "/copilot-lsp/lua/copilot-lsp/completion/init.lua", "inference_info": {"prefix_code": "local M = {}\n\n---@param _results table<integer, { err: lsp.ResponseError, result: lsp.InlineCompletionList}>\n---@param _ctx lsp.HandlerContext\n---@param _config table\nlocal function handle_inlineCompletion_response(_results, _ctx, _config)\n    -- -- Filter errors from results\n    -- local results1 = {} --- @type table<integer,lsp.InlineCompletionList>\n    --\n    -- for client_id, resp in pairs(results) do\n    --     local err, result = resp.err, resp.result\n    --     if err then\n    --         vim.lsp.log.error(err.code, err.message)\n    --     elseif result then\n    --         results1[client_id] = result\n    --     end\n    -- end\n    --\n    -- for _, result in pairs(results1) do\n    --     --TODO: Ghost text for completions\n    --     -- This is where we show the completion results\n    --     -- However, the LSP being named \"copilot_ls\" is enough for blink-cmp to show the completion\n    -- end\nend\n\n---@param type lsp.InlineCompletionTriggerKind\n", "suffix_code": "\nreturn M\n", "middle_code": "function M.request_inline_completion(type)\n    local params = vim.tbl_deep_extend(\"keep\", vim.lsp.util.make_position_params(0, \"utf-16\"), {\n        textDocument = vim.lsp.util.make_text_document_params(),\n        position = vim.lsp.util.make_position_params(0, \"utf-16\"),\n        context = {\n            triggerKind = type,\n        },\n        formattingOptions = {\n            tabSize = 4,\n            insertSpaces = true,\n        },\n    })\n    vim.lsp.buf_request_all(0, \"textDocument/inlineCompletion\", params, handle_inlineCompletion_response)\nend", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "lua", "sub_task_type": null}, "context_code": [["/copilot-lsp/lua/copilot-lsp/nes/init.lua", "local errs = require(\"copilot-lsp.errors\")\nlocal nes_ui = require(\"copilot-lsp.nes.ui\")\nlocal utils = require(\"copilot-lsp.util\")\n\nlocal M = {}\n\nlocal nes_ns = vim.api.nvim_create_namespace(\"copilotlsp.nes\")\n\n---@param err lsp.ResponseError?\n---@param result copilotlsp.copilotInlineEditResponse\n---@param ctx lsp.HandlerContext\nlocal function handle_nes_response(err, result, ctx)\n    if err then\n        -- vim.notify(err.message)\n        return\n    end\n    -- Validate buffer still exists before processing response\n    if not vim.api.nvim_buf_is_valid(ctx.bufnr) then\n        return\n    end\n    for _, edit in ipairs(result.edits) do\n        --- Convert to textEdit fields\n        edit.newText = edit.text\n    end\n    nes_ui._display_next_suggestion(ctx.bufnr, nes_ns, result.edits)\nend\n\n--- Requests the NextEditSuggestion from the current cursor position\n---@param copilot_lss? vim.lsp.Client|string\nfunction M.request_nes(copilot_lss)\n    local pos_params = vim.lsp.util.make_position_params(0, \"utf-16\")\n    local version = vim.lsp.util.buf_versions[vim.api.nvim_get_current_buf()]\n    if type(copilot_lss) == \"string\" then\n        copilot_lss = vim.lsp.get_clients({ name = copilot_lss })[1]\n    end\n    assert(copilot_lss, errs.ErrNotStarted)\n    ---@diagnostic disable-next-line: inject-field\n    pos_params.textDocument.version = version\n    copilot_lss:request(\"textDocument/copilotInlineEdit\", pos_params, handle_nes_response)\nend\n\n--- Walks the cursor to the start of the edit.\n--- This function returns false if there is no edit to apply or if the cursor is already at the start position of the\n--- edit.\n---@param bufnr? integer\n---@return boolean --if the cursor walked\nfunction M.walk_cursor_start_edit(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return false\n    end\n\n    local cursor_row, _ = unpack(vim.api.nvim_win_get_cursor(0))\n    if cursor_row - 1 ~= state.range.start.line then\n        vim.b[bufnr].nes_jump = true\n        ---@type lsp.Location\n        local jump_loc_before = {\n            uri = state.textDocument.uri,\n            range = {\n                start = state.range[\"start\"],\n                [\"end\"] = state.range[\"start\"],\n            },\n        }\n        vim.schedule(function()\n            vim.lsp.util.show_document(jump_loc_before, \"utf-16\", { focus = true })\n        end)\n        return true\n    else\n        return false\n    end\nend\n\n--- Walks the cursor to the end of the edit.\n--- This function returns false if there is no edit to apply or if the cursor is already at the end position of the\n--- edit\n---@param bufnr? integer\n---@return boolean --if the cursor walked\nfunction M.walk_cursor_end_edit(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return false\n    end\n\n    ---@type lsp.Location\n    local jump_loc_after = {\n        uri = state.textDocument.uri,\n        range = {\n            start = state.range[\"end\"],\n            [\"end\"] = state.range[\"end\"],\n        },\n    }\n    --NOTE: If last line is deletion, then this may be outside of the buffer\n    vim.schedule(function()\n        pcall(vim.lsp.util.show_document, jump_loc_after, \"utf-16\", { focus = true })\n    end)\n    return true\nend\n\n--- This function applies the pending nes edit to the current buffer and then clears the marks for the pending\n--- suggestion\n---@param bufnr? integer\n---@return boolean --if the nes was applied\nfunction M.apply_pending_nes(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return false\n    end\n    vim.schedule(function()\n        utils.apply_inline_edit(state)\n        vim.b[bufnr].nes_jump = false\n        nes_ui.clear_suggestion(bufnr, nes_ns)\n    end)\n    return true\nend\n\n---@param bufnr? integer\nfunction M.clear_suggestion(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    nes_ui.clear_suggestion(bufnr, nes_ns)\nend\n\n--- Clear the current suggestion if it exists\n---@return boolean -- true if a suggestion was cleared, false if no suggestion existed\nfunction M.clear()\n    local buf = vim.api.nvim_get_current_buf()\n    if vim.b[buf].nes_state then\n        local ns = vim.b[buf].copilotlsp_nes_namespace_id or nes_ns\n        nes_ui.clear_suggestion(buf, ns)\n        return true\n    end\n    return false\nend\n\nreturn M\n"], ["/copilot-lsp/lsp/copilot_ls.lua", "local version = vim.version()\n\n---@type vim.lsp.Config\nreturn {\n    --NOTE: This name means that existing blink completion works\n    name = \"copilot_ls\",\n    cmd = {\n        \"copilot-language-server\",\n        \"--stdio\",\n    },\n    init_options = {\n        editorInfo = {\n            name = \"neovim\",\n            version = string.format(\"%d.%d.%d\", version.major, version.minor, version.patch),\n        },\n        editorPluginInfo = {\n            name = \"Github Copilot LSP for Neovim\",\n            version = \"0.0.1\",\n        },\n    },\n    settings = {\n        nextEditSuggestions = {\n            enabled = true,\n        },\n    },\n    handlers = setmetatable({}, {\n        __index = function(_, method)\n            return require(\"copilot-lsp.handlers\")[method]\n        end,\n    }),\n    root_dir = vim.uv.cwd(),\n    on_init = function(client)\n        local au = vim.api.nvim_create_augroup(\"copilotlsp.init\", { clear = true })\n        --NOTE: Inline Completions\n        --TODO: We dont currently use this code path, so comment for now until a UI is built\n        -- vim.api.nvim_create_autocmd(\"TextChangedI\", {\n        --     callback = function()\n        --         inline_completion.request_inline_completion(2)\n        --     end,\n        --     group = au,\n        -- })\n\n        -- TODO: make this configurable for key maps, or just expose commands to map in config\n        -- vim.keymap.set(\"i\", \"<c-i>\", function()\n        --     inline_completion.request_inline_completion(1)\n        -- end)\n\n        --NOTE: NES Completions\n        local debounced_request = require(\"copilot-lsp.util\").debounce(\n            require(\"copilot-lsp.nes\").request_nes,\n            vim.g.copilot_nes_debounce or 500\n        )\n        vim.api.nvim_create_autocmd({ \"TextChangedI\", \"TextChanged\" }, {\n            callback = function()\n                debounced_request(client)\n            end,\n            group = au,\n        })\n\n        --NOTE: didFocus\n        vim.api.nvim_create_autocmd(\"BufEnter\", {\n            callback = function()\n                local td_params = vim.lsp.util.make_text_document_params()\n                client:notify(\"textDocument/didFocus\", {\n                    textDocument = {\n                        uri = td_params.uri,\n                    },\n                })\n            end,\n            group = au,\n        })\n    end,\n}\n"], ["/copilot-lsp/lua/copilot-lsp/nes/ui.lua", "local M = {}\nlocal config = require(\"copilot-lsp.config\").config\n\n---@param bufnr integer\n---@param ns_id integer\nlocal function _dismiss_suggestion(bufnr, ns_id)\n    pcall(vim.api.nvim_buf_clear_namespace, bufnr, ns_id, 0, -1)\nend\n\n---@param bufnr? integer\n---@param ns_id integer\nfunction M.clear_suggestion(bufnr, ns_id)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    -- Validate buffer exists before accessing buffer-scoped variables\n    if not vim.api.nvim_buf_is_valid(bufnr) then\n        return\n    end\n    if vim.b[bufnr].nes_jump then\n        vim.b[bufnr].nes_jump = false\n        return\n    end\n    _dismiss_suggestion(bufnr, ns_id)\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return\n    end\n\n    -- Clear buffer variables\n    vim.b[bufnr].nes_state = nil\n    vim.b[bufnr].copilotlsp_nes_cursor_moves = nil\n    vim.b[bufnr].copilotlsp_nes_last_line = nil\n    vim.b[bufnr].copilotlsp_nes_last_col = nil\nend\n\n---@private\n---@param bufnr integer\n---@param edit lsp.TextEdit\n---@return copilotlsp.nes.InlineEditPreview\nfunction M._calculate_preview(bufnr, edit)\n    local text = edit.newText\n    local range = edit.range\n    local start_line = range.start.line\n    local start_char = range.start.character\n    local end_line = range[\"end\"].line\n    local end_char = range[\"end\"].character\n\n    -- Split text by newline. Use plain=true to handle trailing newline correctly.\n    local new_lines = vim.split(text, \"\\n\", { plain = true })\n    local num_new_lines = #new_lines\n\n    local old_lines = vim.api.nvim_buf_get_lines(bufnr, start_line, end_line + 1, false)\n    local num_old_lines = #old_lines\n\n    local is_same_line = start_line == end_line\n    local is_deletion = text == \"\"\n    local lines_edit = is_same_line or (start_char == 0 and end_char == 0)\n    local is_insertion = is_same_line and start_char == end_char\n\n    if is_deletion and is_insertion then\n        -- no-op\n        return {}\n    end\n\n    if is_deletion and lines_edit then\n        return {\n            deletion = {\n                range = edit.range,\n            },\n        }\n    end\n\n    if is_insertion and num_new_lines == 1 and text ~= \"\" then\n        -- inline insertion\n        return {\n            inline_insertion = {\n                text = text,\n                line = start_line,\n                character = start_char,\n            },\n        }\n    end\n\n    if is_insertion and num_new_lines > 1 then\n        if start_char == #old_lines[1] and new_lines[1] == \"\" then\n            -- insert lines after the start line\n            return {\n                lines_insertion = {\n                    text = table.concat(vim.list_slice(new_lines, 2), \"\\n\"),\n                    line = start_line,\n                },\n            }\n        end\n\n        if end_char == 0 and new_lines[num_new_lines] == \"\" then\n            -- insert lines before the end line\n            return {\n                lines_insertion = {\n                    text = table.concat(vim.list_slice(new_lines, 1, num_new_lines - 1), \"\\n\"),\n                    line = start_line,\n                    above = true,\n                },\n            }\n        end\n    end\n\n    -- insert lines in the middle\n    local prefix = old_lines[1]:sub(1, start_char)\n    local suffix = old_lines[num_old_lines]:sub(end_char + 1)\n    local new_lines_extend = vim.deepcopy(new_lines)\n    new_lines_extend[1] = prefix .. new_lines_extend[1]\n    new_lines_extend[num_new_lines] = new_lines_extend[num_new_lines] .. suffix\n    local insertion = table.concat(new_lines_extend, \"\\n\")\n\n    return {\n        deletion = {\n            range = {\n                start = { line = start_line, character = 0 },\n                [\"end\"] = { line = end_line, character = #old_lines[num_old_lines] },\n            },\n        },\n        lines_insertion = {\n            text = insertion,\n            line = end_line,\n        },\n    }\nend\n\n---@private\n---@param bufnr integer\n---@param ns_id integer\n---@param preview copilotlsp.nes.InlineEditPreview\nfunction M._display_preview(bufnr, ns_id, preview)\n    if preview.deletion then\n        local range = preview.deletion.range\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, range.start.line, range.start.character, {\n            hl_group = \"CopilotLspNesDelete\",\n            end_row = range[\"end\"].line,\n            end_col = range[\"end\"].character,\n        })\n    end\n\n    local inline_insertion = preview.inline_insertion\n    if inline_insertion then\n        local virt_lines =\n            require(\"copilot-lsp.util\").hl_text_to_virt_lines(inline_insertion.text, vim.bo[bufnr].filetype)\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, inline_insertion.line, inline_insertion.character, {\n            virt_text = virt_lines[1],\n            virt_text_pos = \"inline\",\n        })\n    end\n\n    local lines_insertion = preview.lines_insertion\n    if lines_insertion then\n        local virt_lines =\n            require(\"copilot-lsp.util\").hl_text_to_virt_lines(lines_insertion.text, vim.bo[bufnr].filetype)\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, lines_insertion.line, 0, {\n            virt_lines = virt_lines,\n            virt_lines_above = lines_insertion.above,\n        })\n    end\nend\n\n---@private\n---@param bufnr integer\n---@param ns_id integer\n---@param edits copilotlsp.InlineEdit[]\nfunction M._display_next_suggestion(bufnr, ns_id, edits)\n    M.clear_suggestion(bufnr, ns_id)\n    if not edits or #edits == 0 then\n        return\n    end\n\n    local suggestion = edits[1]\n    local preview = M._calculate_preview(bufnr, suggestion)\n    M._display_preview(bufnr, ns_id, preview)\n\n    vim.b[bufnr].nes_state = suggestion\n    vim.b[bufnr].copilotlsp_nes_namespace_id = ns_id\n    vim.b[bufnr].copilotlsp_nes_cursor_moves = 1\n\n    vim.api.nvim_create_autocmd({ \"CursorMoved\", \"CursorMovedI\" }, {\n        buffer = bufnr,\n        callback = function()\n            if not vim.b[bufnr].nes_state then\n                return true\n            end\n\n            -- Get cursor position\n            local cursor = vim.api.nvim_win_get_cursor(0)\n            local cursor_line = cursor[1] - 1 -- 0-indexed\n            local cursor_col = cursor[2]\n            local suggestion_line = suggestion.range.start.line\n\n            -- Store previous position\n            local last_line = vim.b[bufnr].copilotlsp_nes_last_line or cursor_line\n            local last_col = vim.b[bufnr].copilotlsp_nes_last_col or cursor_col\n\n            -- Update stored position\n            vim.b[bufnr].copilotlsp_nes_last_line = cursor_line\n            vim.b[bufnr].copilotlsp_nes_last_col = cursor_col\n\n            -- Calculate distance to suggestion\n            local line_distance = math.abs(cursor_line - suggestion_line)\n            local last_line_distance = math.abs(last_line - suggestion_line)\n\n            -- Check if cursor changed position on same line\n            local moved_horizontally = (cursor_line == last_line) and (cursor_col ~= last_col)\n\n            -- Get current mode\n            local mode = vim.api.nvim_get_mode().mode\n\n            -- Determine if we should count this movement\n            local should_count = false\n            local first_char = mode:sub(1, 1)\n\n            -- In insert mode, only count cursor movements, not text changes\n            if first_char == \"i\" then\n                if moved_horizontally or line_distance ~= last_line_distance then\n                    should_count = true\n                end\n            elseif first_char == \"v\" or first_char == \"V\" or mode == \"\\22\" then\n                should_count = true\n            -- In normal mode with horizontal movement\n            elseif moved_horizontally and config.nes.count_horizontal_moves then\n                should_count = true\n            -- In normal mode with line changes\n            elseif line_distance > last_line_distance then\n                should_count = true\n            -- Moving toward suggestion in normal mode\n            elseif line_distance < last_line_distance and config.nes.reset_on_approaching then\n                if line_distance > 1 then -- Don't reset if 0 or 1 line away\n                    vim.b[bufnr].copilotlsp_nes_cursor_moves = 0\n                end\n            end\n\n            -- Update counter if needed\n            if should_count then\n                vim.b[bufnr].copilotlsp_nes_cursor_moves = (vim.b[bufnr].copilotlsp_nes_cursor_moves or 0) + 1\n            end\n\n            -- Clear if counter threshold reached\n            if vim.b[bufnr].copilotlsp_nes_cursor_moves >= config.nes.move_count_threshold then\n                vim.b[bufnr].copilotlsp_nes_cursor_moves = 0\n                vim.schedule(function()\n                    M.clear_suggestion(bufnr, ns_id)\n                end)\n                return true\n            end\n\n            -- Optional: Clear on large distance\n            if config.nes.clear_on_large_distance and line_distance > config.nes.distance_threshold then\n                M.clear_suggestion(bufnr, ns_id)\n                return true\n            end\n\n            return false -- Keep the autocmd\n        end,\n    })\n    -- Also clear on text changes that affect the suggestion area\n    vim.api.nvim_create_autocmd({ \"TextChanged\", \"TextChangedI\" }, {\n        buffer = bufnr,\n        callback = function()\n            if not vim.b[bufnr].nes_state then\n                return true\n            end\n            -- Check if the text at the suggestion position has changed\n            local start_line = suggestion.range.start.line\n            -- If the lines are no longer in the buffer, clear the suggestion\n            if start_line >= vim.api.nvim_buf_line_count(bufnr) then\n                M.clear_suggestion(bufnr, ns_id)\n                return true\n            end\n            return false -- Keep the autocmd\n        end,\n    })\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/handlers.lua", "---@type table<string, lsp.Handler>\nlocal M = {}\n\nlocal methods = {\n    signIn = \"signIn\",\n    didChangeStatus = \"didChangeStatus\",\n}\n\n-- copy from copilot.lua\nlocal function open_signin_popup(code, url)\n    local lines = {\n        \" [Copilot-lsp] \",\n        \"\",\n        \" First copy your one-time code: \",\n        \"   \" .. code .. \" \",\n        \" In your browser, visit: \",\n        \"   \" .. url .. \" \",\n        \"\",\n        \" ...waiting, it might take a while and \",\n        \" this popup will auto close once done... \",\n    }\n    local height, width = #lines, math.max(unpack(vim.tbl_map(function(line)\n        return #line\n    end, lines)))\n\n    local bufnr = vim.api.nvim_create_buf(false, true)\n    vim.bo[bufnr].buflisted = false\n    vim.bo[bufnr].buftype = \"nofile\"\n    vim.bo[bufnr].bufhidden = \"wipe\"\n    vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines)\n\n    local winnr = vim.api.nvim_open_win(bufnr, true, {\n        relative = \"editor\",\n        style = \"minimal\",\n        border = \"single\",\n        row = (vim.o.lines - height) / 2,\n        col = (vim.o.columns - width) / 2,\n        height = height,\n        width = width,\n    })\n    vim.wo[winnr].winhighlight = \"Normal:Normal\"\n    vim.wo[winnr].winblend = 0\n\n    return function()\n        vim.api.nvim_win_close(winnr, true)\n    end\nend\n\nlocal function copy_to_clipboard(s)\n    vim.fn.setreg(\"+\", s)\n    vim.fn.setreg(\"*\", s)\nend\n\n---@param res {command: lsp.Command, userCode: string, verificationUri: string}\nM[methods.signIn] = function(err, res, ctx)\n    if err then\n        vim.notify(\"[copilot-lsp] failed to start signin flow: \" .. vim.inspect(err), vim.log.levels.ERROR)\n        return\n    end\n\n    local client = vim.lsp.get_client_by_id(ctx.client_id)\n    if not client then\n        return\n    end\n\n    vim.g.copilot_lsp_signin_pending = true\n\n    local close_signin_popup = open_signin_popup(res.userCode, res.verificationUri)\n    copy_to_clipboard(res.userCode)\n\n    client:exec_cmd(\n        res.command,\n        { bufnr = ctx.bufnr },\n\n        ---@param cmd_res {status: string, user: string}\n        function(cmd_err, cmd_res)\n            vim.g.copilot_lsp_signin_pending = nil\n            close_signin_popup()\n\n            if cmd_err then\n                vim.notify(\"[copilot-lsp] failed to open browser: \" .. vim.inspect(cmd_err), vim.log.levels.WARN)\n                return\n            end\n            if cmd_res.status == \"OK\" then\n                vim.notify(\"[copilot-lsp] successfully signed in as: \" .. cmd_res.user, vim.log.levels.INFO)\n            else\n                vim.notify(\"[copilot-lsp] failed to sign in: \" .. vim.inspect(cmd_res), vim.log.levels.ERROR)\n            end\n        end\n    )\nend\n\n---@param client_id integer\n---@param bufnr integer\nlocal function sign_in(client_id, bufnr)\n    if vim.g.copilot_lsp_signin_pending then\n        return\n    end\n\n    local client = vim.lsp.get_client_by_id(client_id)\n    if not client then\n        return\n    end\n\n    for _, req in pairs(client.requests) do\n        if req.method == methods.signIn and req.type == \"pending\" then\n            return\n        end\n    end\n\n    client:request(methods.signIn, vim.empty_dict(), nil, bufnr)\nend\n\n---@param res {busy: boolean, kind: 'Normal'|'Error'|'Warning'|'Inactive', message: string}\nM[\"didChangeStatus\"] = function(err, res, ctx)\n    if err then\n        return\n    end\n    -- real error message: You are not signed into GitHub. Please sign in to use Copilot.\n    if res.kind == \"Error\" and res.message:find(\"not signed into\") then\n        sign_in(ctx.client_id, ctx.bufnr)\n    end\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/util.lua", "local M = {}\n---@param edit copilotlsp.InlineEdit\nfunction M.apply_inline_edit(edit)\n    local bufnr = vim.uri_to_bufnr(edit.textDocument.uri)\n\n    ---@diagnostic disable-next-line: assign-type-mismatch\n    vim.lsp.util.apply_text_edits({ edit }, bufnr, \"utf-16\")\nend\n\n---Debounces calls to a function, and ensures it only runs once per delay\n---even if called repeatedly.\n---@param fn fun(...: any)\n---@param delay integer\nfunction M.debounce(fn, delay)\n    local timer = vim.uv.new_timer()\n    return function(...)\n        local argv = vim.F.pack_len(...)\n        timer:start(delay, 0, function()\n            timer:stop()\n            vim.schedule_wrap(fn)(vim.F.unpack_len(argv))\n        end)\n    end\nend\n\n---@private\n---@class Capture\n---@field hl string|string[]\n---range(0-based)\n---@field start_row integer\n---@field start_col integer\n---@field end_row integer\n---@field end_col integer\n\n---@param text string\n---@param lang string\n---@return Capture[]?\nlocal function parse_text(text, lang)\n    local ok, trees = pcall(vim.treesitter.get_string_parser, text, lang)\n    if not ok then\n        return\n    end\n    trees:parse(true)\n\n    local captures = {}\n\n    trees:for_each_tree(function(tree, _ltree)\n        local hl_query = vim.treesitter.query.get(lang, \"highlights\")\n        if not hl_query then\n            return\n        end\n\n        local iter = hl_query:iter_captures(tree:root(), text)\n        vim.iter(iter):each(function(id, node)\n            local name = hl_query.captures[id]\n            local hl = \"Normal\"\n            if not vim.startswith(name, \"_\") then\n                hl = \"@\" .. name .. \".\" .. lang\n            end\n            local start_row, start_col, end_row, end_col = node:range()\n\n            -- Ignore zero-width captures if they cause issues (sometimes happen at EOF)\n            if start_row == end_row and start_col == end_col then\n                return\n            end\n\n            table.insert(captures, {\n                hl = hl,\n                start_row = start_row,\n                start_col = start_col,\n                end_row = end_row,\n                end_col = end_col,\n            })\n        end)\n    end)\n    return captures\nend\n\nlocal function merge_captures(captures)\n    table.sort(captures, function(a, b)\n        if a.start_row == b.start_row then\n            return a.start_col < b.start_col\n        end\n        return a.start_row < b.start_row\n    end)\n    local merged_captures = {}\n    for i = 2, #captures do\n        local prev = captures[i - 1]\n        local curr = captures[i]\n        if\n            prev.start_row == curr.start_row\n            and prev.start_col == curr.start_col\n            and prev.end_row == curr.end_row\n            and prev.end_col == curr.end_col\n        then\n            local prev_hl = type(prev.hl) == \"table\" and prev.hl or { prev.hl }\n            local curr_hl = type(curr.hl) == \"table\" and curr.hl or { curr.hl }\n            ---@diagnostic disable-next-line: param-type-mismatch\n            vim.list_extend(prev_hl, curr_hl)\n            curr.hl = prev_hl\n        else\n            table.insert(merged_captures, prev)\n        end\n    end\n    table.insert(merged_captures, captures[#captures])\n\n    return merged_captures\nend\n\nfunction M.hl_text_to_virt_lines(text, lang)\n    local lines = vim.split(text, \"\\n\")\n    local normal_hl = \"Normal\"\n    local bg_hl = \"CopilotLspNesAdd\"\n\n    local function hl_chunk(chunk, hl)\n        if not hl then\n            return { chunk, { normal_hl, bg_hl } }\n        end\n        if type(hl) == \"string\" then\n            return { chunk, { hl, bg_hl } }\n        end\n        hl = vim.deepcopy(hl)\n        table.insert(hl, bg_hl)\n        return { chunk, hl }\n    end\n\n    local captures = parse_text(text, lang)\n    if not captures or #captures == 0 then\n        return vim.iter(lines)\n            :map(function(line)\n                return { hl_chunk(line) }\n            end)\n            :totable()\n    end\n\n    captures = merge_captures(captures)\n\n    local virt_lines = {}\n\n    local curr_row = 0\n    local curr_col = 0\n    local curr_virt_line = {}\n\n    vim.iter(captures):each(function(cap)\n        -- skip if the capture is before the current position\n        if cap.end_row < curr_row or (cap.end_row == curr_row and cap.end_col <= curr_col) then\n            return\n        end\n\n        if cap.start_row > curr_row then\n            -- add the rest of the line\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1)\n            table.insert(curr_virt_line, hl_chunk(chunk_text))\n            table.insert(virt_lines, curr_virt_line)\n\n            for i = curr_row + 1, cap.start_row - 1 do\n                local line_text = lines[i + 1]\n                table.insert(virt_lines, { hl_chunk(line_text) })\n            end\n\n            curr_row = cap.start_row\n            curr_col = 0\n            curr_virt_line = {}\n        end\n\n        assert(curr_row == cap.start_row, \"Unexpected start row\")\n\n        if cap.start_col > curr_col then\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1, cap.start_col)\n            table.insert(curr_virt_line, hl_chunk(chunk_text))\n            curr_col = cap.start_col\n        end\n\n        assert(curr_col == cap.start_col, \"Unexpected start column\")\n\n        if cap.end_row > curr_row then\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1)\n            table.insert(curr_virt_line, hl_chunk(chunk_text, cap.hl))\n            table.insert(virt_lines, curr_virt_line)\n\n            for i = curr_row + 1, cap.end_row - 1 do\n                local line_text = lines[i + 1]\n                table.insert(virt_lines, { hl_chunk(line_text, cap.hl) })\n            end\n\n            curr_row = cap.end_row\n            curr_col = 0\n            curr_virt_line = {}\n        end\n\n        assert(curr_row == cap.end_row, \"Unexpected end row\")\n\n        if cap.end_col > curr_col then\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1, cap.end_col)\n            table.insert(curr_virt_line, hl_chunk(chunk_text, cap.hl))\n            curr_col = cap.end_col\n        end\n    end)\n\n    if #curr_virt_line > 0 then\n        table.insert(virt_lines, curr_virt_line)\n    end\n\n    return virt_lines\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/config.lua", "---@class copilotlsp.config.nes\n---@field move_count_threshold integer Number of cursor movements before clearing suggestion\n---@field distance_threshold integer Maximum line distance before clearing suggestion\n---@field clear_on_large_distance boolean Whether to clear suggestion when cursor is far away\n---@field count_horizontal_moves boolean Whether to count horizontal cursor movements\n---@field reset_on_approaching boolean Whether to reset counter when approaching suggestion\n\nlocal M = {}\n\n---@class copilotlsp.config\n---@field nes copilotlsp.config.nes\nM.defaults = {\n    nes = {\n        move_count_threshold = 3,\n        distance_threshold = 40,\n        clear_on_large_distance = true,\n        count_horizontal_moves = true,\n        reset_on_approaching = true,\n    },\n}\n\n---@type copilotlsp.config\nM.config = vim.deepcopy(M.defaults)\n\n---@param opts? copilotlsp.config configuration to merge with defaults\nfunction M.setup(opts)\n    opts = opts or {}\n    M.config = vim.tbl_deep_extend(\"force\", M.defaults, opts)\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/init.lua", "local config = require(\"copilot-lsp.config\")\n\n---@class copilotlsp\n---@field defaults copilotlsp.config\n---@field config copilotlsp.config\n---@field setup fun(opts?: copilotlsp.config): nil\nlocal M = {}\n\nM.defaults = config.defaults\nM.config = config.config\n\n---@param opts? copilotlsp.config configuration to merge with defaults\nfunction M.setup(opts)\n    config.setup(opts)\n    M.config = config.config\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/types.lua", "---@class copilotlsp.InlineEdit : lsp.TextEdit\n---@field command lsp.Command\n---@field text string\n---@field textDocument lsp.VersionedTextDocumentIdentifier\n\n---@class copilotlsp.copilotInlineEditResponse\n---@field edits copilotlsp.InlineEdit[]\n\n---@class copilotlsp.nes.TextDeletion\n---@field range lsp.Range\n\n---@class copilotlsp.nes.InlineInsertion\n---@field text string\n---@field line integer\n---@field character integer\n\n---@class copilotlsp.nes.TextInsertion\n---@field text string\n---@field line integer insert lines at this line\n---@field above? boolean above the line\n\n---@class copilotlsp.nes.InlineEditPreview\n---@field deletion? copilotlsp.nes.TextDeletion\n---@field inline_insertion? copilotlsp.nes.InlineInsertion\n---@field lines_insertion? copilotlsp.nes.TextInsertion\n"], ["/copilot-lsp/plugin/copilot-lsp.lua", "vim.api.nvim_set_hl(0, \"CopilotLspNesAdd\", { link = \"DiffAdd\", default = true })\nvim.api.nvim_set_hl(0, \"CopilotLspNesDelete\", { link = \"DiffDelete\", default = true })\nvim.api.nvim_set_hl(0, \"CopilotLspNesApply\", { link = \"DiffText\", default = true })\n"], ["/copilot-lsp/lua/copilot-lsp/errors.lua", "return {\n    ErrNotStarted = \"Copilot LSP not started\",\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 00:43:00", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Construct a structured request for inline code suggestions based on the current document state and transmit it to a language server, incorporating contextual trigger details and formatting preferences."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```lua\n[TASK_BEGIN]\n---@param results table<integer, { err: lsp.ResponseError, result: lsp.InlineCompletionList}>\n---@param ctx lsp.HandlerContext\n---@param config table\nfunction M.inline_completion(results, ctx, config)\n    local filtered_results = {} --- @type table<integer,lsp.InlineCompletionList>\n    \n    for client_id, resp in pairs(results) do\n        local err, result = resp.err, resp.result\n        if err then\n            vim.lsp.log.error(\"Client \"..client_id..\" error: \"..err.message)\n        elseif result then\n            filtered_results[client_id] = result\n        end\n    end\n\n    for client_id, result in pairs(filtered_results) do\n        local items = result.items\n        if items and #items > 0 then\n            local completion = items[1]\n            vim.api.nvim_buf_set_extmark(\n                ctx.bufnr, \n                config.ns_id, \n                ctx.pos[1], \n                ctx.pos[2], \n                {\n                    virt_text = {{completion.insertText, \"Comment\"}},\n                    virt_text_pos = \"overlay\"\n                }\n            )\n        end\n    end\nend\n[TASK_END]\n```", "inference_time": "2025-08-21 00-43-33"}, "editdistance_info": {"edit_distance": 11.399, "calculate_time": "2025-08-21 00:43:33", "true_code_clean": "function M.request_inline_completion(type)\n    local params = vim.tbl_deep_extend(\"keep\", vim.lsp.util.make_position_params(0, \"utf-16\"), {\n        textDocument = vim.lsp.util.make_text_document_params(),\n        position = vim.lsp.util.make_position_params(0, \"utf-16\"),\n        context = {\n            triggerKind = type,\n        },\n        formattingOptions = {\n            tabSize = 4,\n            insertSpaces = true,\n        },\n    })\n    vim.lsp.buf_request_all(0, \"textDocument/inlineCompletion\", params, handle_inlineCompletion_response)\nend", "predict_code_clean": "function M.inline_completion(results, ctx, config)\n    local filtered_results = {} \n    for client_id, resp in pairs(results) do\n        local err, result = resp.err, resp.result\n        if err then\n            vim.lsp.log.error(\"Client \"..client_id..\" error: \"..err.message)\n        elseif result then\n            filtered_results[client_id] = result\n        end\n    end\n    for client_id, result in pairs(filtered_results) do\n        local items = result.items\n        if items and #items > 0 then\n            local completion = items[1]\n            vim.api.nvim_buf_set_extmark(\n                ctx.bufnr, \n                config.ns_id, \n                ctx.pos[1], \n                ctx.pos[2], \n                {\n                    virt_text = {{completion.insertText, \"Comment\"}},\n                    virt_text_pos = \"overlay\"\n                }\n            )\n        end\n    end\nend"}}
{"repo_name": "copilot-lsp", "file_name": "/copilot-lsp/lua/copilot-lsp/nes/ui.lua", "inference_info": {"prefix_code": "local M = {}\nlocal config = require(\"copilot-lsp.config\").config\n\n---@param bufnr integer\n---@param ns_id integer\nlocal function _dismiss_suggestion(bufnr, ns_id)\n    pcall(vim.api.nvim_buf_clear_namespace, bufnr, ns_id, 0, -1)\nend\n\n---@param bufnr? integer\n---@param ns_id integer\nfunction M.clear_suggestion(bufnr, ns_id)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    -- Validate buffer exists before accessing buffer-scoped variables\n    if not vim.api.nvim_buf_is_valid(bufnr) then\n        return\n    end\n    if vim.b[bufnr].nes_jump then\n        vim.b[bufnr].nes_jump = false\n        return\n    end\n    _dismiss_suggestion(bufnr, ns_id)\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return\n    end\n\n    -- Clear buffer variables\n    vim.b[bufnr].nes_state = nil\n    vim.b[bufnr].copilotlsp_nes_cursor_moves = nil\n    vim.b[bufnr].copilotlsp_nes_last_line = nil\n    vim.b[bufnr].copilotlsp_nes_last_col = nil\nend\n\n---@private\n---@param bufnr integer\n---@param edit lsp.TextEdit\n---@return copilotlsp.nes.InlineEditPreview\nfunction M._calculate_preview(bufnr, edit)\n    local text = edit.newText\n    local range = edit.range\n    local start_line = range.start.line\n    local start_char = range.start.character\n    local end_line = range[\"end\"].line\n    local end_char = range[\"end\"].character\n\n    -- Split text by newline. Use plain=true to handle trailing newline correctly.\n    local new_lines = vim.split(text, \"\\n\", { plain = true })\n    local num_new_lines = #new_lines\n\n    local old_lines = vim.api.nvim_buf_get_lines(bufnr, start_line, end_line + 1, false)\n    local num_old_lines = #old_lines\n\n    local is_same_line = start_line == end_line\n    local is_deletion = text == \"\"\n    local lines_edit = is_same_line or (start_char == 0 and end_char == 0)\n    local is_insertion = is_same_line and start_char == end_char\n\n    if is_deletion and is_insertion then\n        -- no-op\n        return {}\n    end\n\n    if is_deletion and lines_edit then\n        return {\n            deletion = {\n                range = edit.range,\n            },\n        }\n    end\n\n    if is_insertion and num_new_lines == 1 and text ~= \"\" then\n        -- inline insertion\n        return {\n            inline_insertion = {\n                text = text,\n                line = start_line,\n                character = start_char,\n            },\n        }\n    end\n\n    if is_insertion and num_new_lines > 1 then\n        if start_char == #old_lines[1] and new_lines[1] == \"\" then\n            -- insert lines after the start line\n            return {\n                lines_insertion = {\n                    text = table.concat(vim.list_slice(new_lines, 2), \"\\n\"),\n                    line = start_line,\n                },\n            }\n        end\n\n        if end_char == 0 and new_lines[num_new_lines] == \"\" then\n            -- insert lines before the end line\n            return {\n                lines_insertion = {\n                    text = table.concat(vim.list_slice(new_lines, 1, num_new_lines - 1), \"\\n\"),\n                    line = start_line,\n                    above = true,\n                },\n            }\n        end\n    end\n\n    -- insert lines in the middle\n    local prefix = old_lines[1]:sub(1, start_char)\n    local suffix = old_lines[num_old_lines]:sub(end_char + 1)\n    local new_lines_extend = vim.deepcopy(new_lines)\n    new_lines_extend[1] = prefix .. new_lines_extend[1]\n    new_lines_extend[num_new_lines] = new_lines_extend[num_new_lines] .. suffix\n    local insertion = table.concat(new_lines_extend, \"\\n\")\n\n    return {\n        deletion = {\n            range = {\n                start = { line = start_line, character = 0 },\n                [\"end\"] = { line = end_line, character = #old_lines[num_old_lines] },\n            },\n        },\n        lines_insertion = {\n            text = insertion,\n            line = end_line,\n        },\n    }\nend\n\n---@private\n---@param bufnr integer\n---@param ns_id integer\n---@param preview copilotlsp.nes.InlineEditPreview\nfunction M._display_preview(bufnr, ns_id, preview)\n    if preview.deletion then\n        local range = preview.deletion.range\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, range.start.line, range.start.character, {\n            hl_group = \"CopilotLspNesDelete\",\n            end_row = range[\"end\"].line,\n            end_col = range[\"end\"].character,\n        })\n    end\n\n    local inline_insertion = preview.inline_insertion\n    if inline_insertion then\n        local virt_lines =\n            require(\"copilot-lsp.util\").hl_text_to_virt_lines(inline_insertion.text, vim.bo[bufnr].filetype)\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, inline_insertion.line, inline_insertion.character, {\n            virt_text = virt_lines[1],\n            virt_text_pos = \"inline\",\n        })\n    end\n\n    local lines_insertion = preview.lines_insertion\n    if lines_insertion then\n        local virt_lines =\n            require(\"copilot-lsp.util\").hl_text_to_virt_lines(lines_insertion.text, vim.bo[bufnr].filetype)\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, lines_insertion.line, 0, {\n            virt_lines = virt_lines,\n            virt_lines_above = lines_insertion.above,\n        })\n    end\nend\n\n---@private\n---@param bufnr integer\n---@param ns_id integer\n---@param edits copilotlsp.InlineEdit[]\nfunction M._display_next_suggestion(bufnr, ns_id, edits)\n    M.clear_suggestion(bufnr, ns_id)\n    if not edits or #edits == 0 then\n        return\n    end\n\n    local suggestion = edits[1]\n    local preview = M._calculate_preview(bufnr, suggestion)\n    M._display_preview(bufnr, ns_id, preview)\n\n    vim.b[bufnr].nes_state = suggestion\n    vim.b[bufnr].copilotlsp_nes_namespace_id = ns_id\n    vim.b[bufnr].copilotlsp_nes_cursor_moves = 1\n\n    vim.api.nvim_create_autocmd({ \"CursorMoved\", \"CursorMovedI\" }, {\n        buffer = bufnr,\n        callback = ", "suffix_code": ",\n    })\n    -- Also clear on text changes that affect the suggestion area\n    vim.api.nvim_create_autocmd({ \"TextChanged\", \"TextChangedI\" }, {\n        buffer = bufnr,\n        callback = function()\n            if not vim.b[bufnr].nes_state then\n                return true\n            end\n            -- Check if the text at the suggestion position has changed\n            local start_line = suggestion.range.start.line\n            -- If the lines are no longer in the buffer, clear the suggestion\n            if start_line >= vim.api.nvim_buf_line_count(bufnr) then\n                M.clear_suggestion(bufnr, ns_id)\n                return true\n            end\n            return false -- Keep the autocmd\n        end,\n    })\nend\n\nreturn M\n", "middle_code": "function()\n            if not vim.b[bufnr].nes_state then\n                return true\n            end\n            local cursor = vim.api.nvim_win_get_cursor(0)\n            local cursor_line = cursor[1] - 1 \n            local cursor_col = cursor[2]\n            local suggestion_line = suggestion.range.start.line\n            local last_line = vim.b[bufnr].copilotlsp_nes_last_line or cursor_line\n            local last_col = vim.b[bufnr].copilotlsp_nes_last_col or cursor_col\n            vim.b[bufnr].copilotlsp_nes_last_line = cursor_line\n            vim.b[bufnr].copilotlsp_nes_last_col = cursor_col\n            local line_distance = math.abs(cursor_line - suggestion_line)\n            local last_line_distance = math.abs(last_line - suggestion_line)\n            local moved_horizontally = (cursor_line == last_line) and (cursor_col ~= last_col)\n            local mode = vim.api.nvim_get_mode().mode\n            local should_count = false\n            local first_char = mode:sub(1, 1)\n            if first_char == \"i\" then\n                if moved_horizontally or line_distance ~= last_line_distance then\n                    should_count = true\n                end\n            elseif first_char == \"v\" or first_char == \"V\" or mode == \"\\22\" then\n                should_count = true\n            elseif moved_horizontally and config.nes.count_horizontal_moves then\n                should_count = true\n            elseif line_distance > last_line_distance then\n                should_count = true\n            elseif line_distance < last_line_distance and config.nes.reset_on_approaching then\n                if line_distance > 1 then \n                    vim.b[bufnr].copilotlsp_nes_cursor_moves = 0\n                end\n            end\n            if should_count then\n                vim.b[bufnr].copilotlsp_nes_cursor_moves = (vim.b[bufnr].copilotlsp_nes_cursor_moves or 0) + 1\n            end\n            if vim.b[bufnr].copilotlsp_nes_cursor_moves >= config.nes.move_count_threshold then\n                vim.b[bufnr].copilotlsp_nes_cursor_moves = 0\n                vim.schedule(function()\n                    M.clear_suggestion(bufnr, ns_id)\n                end)\n                return true\n            end\n            if config.nes.clear_on_large_distance and line_distance > config.nes.distance_threshold then\n                M.clear_suggestion(bufnr, ns_id)\n                return true\n            end\n            return false \n        end", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "lua", "sub_task_type": null}, "context_code": [["/copilot-lsp/lua/copilot-lsp/nes/init.lua", "local errs = require(\"copilot-lsp.errors\")\nlocal nes_ui = require(\"copilot-lsp.nes.ui\")\nlocal utils = require(\"copilot-lsp.util\")\n\nlocal M = {}\n\nlocal nes_ns = vim.api.nvim_create_namespace(\"copilotlsp.nes\")\n\n---@param err lsp.ResponseError?\n---@param result copilotlsp.copilotInlineEditResponse\n---@param ctx lsp.HandlerContext\nlocal function handle_nes_response(err, result, ctx)\n    if err then\n        -- vim.notify(err.message)\n        return\n    end\n    -- Validate buffer still exists before processing response\n    if not vim.api.nvim_buf_is_valid(ctx.bufnr) then\n        return\n    end\n    for _, edit in ipairs(result.edits) do\n        --- Convert to textEdit fields\n        edit.newText = edit.text\n    end\n    nes_ui._display_next_suggestion(ctx.bufnr, nes_ns, result.edits)\nend\n\n--- Requests the NextEditSuggestion from the current cursor position\n---@param copilot_lss? vim.lsp.Client|string\nfunction M.request_nes(copilot_lss)\n    local pos_params = vim.lsp.util.make_position_params(0, \"utf-16\")\n    local version = vim.lsp.util.buf_versions[vim.api.nvim_get_current_buf()]\n    if type(copilot_lss) == \"string\" then\n        copilot_lss = vim.lsp.get_clients({ name = copilot_lss })[1]\n    end\n    assert(copilot_lss, errs.ErrNotStarted)\n    ---@diagnostic disable-next-line: inject-field\n    pos_params.textDocument.version = version\n    copilot_lss:request(\"textDocument/copilotInlineEdit\", pos_params, handle_nes_response)\nend\n\n--- Walks the cursor to the start of the edit.\n--- This function returns false if there is no edit to apply or if the cursor is already at the start position of the\n--- edit.\n---@param bufnr? integer\n---@return boolean --if the cursor walked\nfunction M.walk_cursor_start_edit(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return false\n    end\n\n    local cursor_row, _ = unpack(vim.api.nvim_win_get_cursor(0))\n    if cursor_row - 1 ~= state.range.start.line then\n        vim.b[bufnr].nes_jump = true\n        ---@type lsp.Location\n        local jump_loc_before = {\n            uri = state.textDocument.uri,\n            range = {\n                start = state.range[\"start\"],\n                [\"end\"] = state.range[\"start\"],\n            },\n        }\n        vim.schedule(function()\n            vim.lsp.util.show_document(jump_loc_before, \"utf-16\", { focus = true })\n        end)\n        return true\n    else\n        return false\n    end\nend\n\n--- Walks the cursor to the end of the edit.\n--- This function returns false if there is no edit to apply or if the cursor is already at the end position of the\n--- edit\n---@param bufnr? integer\n---@return boolean --if the cursor walked\nfunction M.walk_cursor_end_edit(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return false\n    end\n\n    ---@type lsp.Location\n    local jump_loc_after = {\n        uri = state.textDocument.uri,\n        range = {\n            start = state.range[\"end\"],\n            [\"end\"] = state.range[\"end\"],\n        },\n    }\n    --NOTE: If last line is deletion, then this may be outside of the buffer\n    vim.schedule(function()\n        pcall(vim.lsp.util.show_document, jump_loc_after, \"utf-16\", { focus = true })\n    end)\n    return true\nend\n\n--- This function applies the pending nes edit to the current buffer and then clears the marks for the pending\n--- suggestion\n---@param bufnr? integer\n---@return boolean --if the nes was applied\nfunction M.apply_pending_nes(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return false\n    end\n    vim.schedule(function()\n        utils.apply_inline_edit(state)\n        vim.b[bufnr].nes_jump = false\n        nes_ui.clear_suggestion(bufnr, nes_ns)\n    end)\n    return true\nend\n\n---@param bufnr? integer\nfunction M.clear_suggestion(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    nes_ui.clear_suggestion(bufnr, nes_ns)\nend\n\n--- Clear the current suggestion if it exists\n---@return boolean -- true if a suggestion was cleared, false if no suggestion existed\nfunction M.clear()\n    local buf = vim.api.nvim_get_current_buf()\n    if vim.b[buf].nes_state then\n        local ns = vim.b[buf].copilotlsp_nes_namespace_id or nes_ns\n        nes_ui.clear_suggestion(buf, ns)\n        return true\n    end\n    return false\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/util.lua", "local M = {}\n---@param edit copilotlsp.InlineEdit\nfunction M.apply_inline_edit(edit)\n    local bufnr = vim.uri_to_bufnr(edit.textDocument.uri)\n\n    ---@diagnostic disable-next-line: assign-type-mismatch\n    vim.lsp.util.apply_text_edits({ edit }, bufnr, \"utf-16\")\nend\n\n---Debounces calls to a function, and ensures it only runs once per delay\n---even if called repeatedly.\n---@param fn fun(...: any)\n---@param delay integer\nfunction M.debounce(fn, delay)\n    local timer = vim.uv.new_timer()\n    return function(...)\n        local argv = vim.F.pack_len(...)\n        timer:start(delay, 0, function()\n            timer:stop()\n            vim.schedule_wrap(fn)(vim.F.unpack_len(argv))\n        end)\n    end\nend\n\n---@private\n---@class Capture\n---@field hl string|string[]\n---range(0-based)\n---@field start_row integer\n---@field start_col integer\n---@field end_row integer\n---@field end_col integer\n\n---@param text string\n---@param lang string\n---@return Capture[]?\nlocal function parse_text(text, lang)\n    local ok, trees = pcall(vim.treesitter.get_string_parser, text, lang)\n    if not ok then\n        return\n    end\n    trees:parse(true)\n\n    local captures = {}\n\n    trees:for_each_tree(function(tree, _ltree)\n        local hl_query = vim.treesitter.query.get(lang, \"highlights\")\n        if not hl_query then\n            return\n        end\n\n        local iter = hl_query:iter_captures(tree:root(), text)\n        vim.iter(iter):each(function(id, node)\n            local name = hl_query.captures[id]\n            local hl = \"Normal\"\n            if not vim.startswith(name, \"_\") then\n                hl = \"@\" .. name .. \".\" .. lang\n            end\n            local start_row, start_col, end_row, end_col = node:range()\n\n            -- Ignore zero-width captures if they cause issues (sometimes happen at EOF)\n            if start_row == end_row and start_col == end_col then\n                return\n            end\n\n            table.insert(captures, {\n                hl = hl,\n                start_row = start_row,\n                start_col = start_col,\n                end_row = end_row,\n                end_col = end_col,\n            })\n        end)\n    end)\n    return captures\nend\n\nlocal function merge_captures(captures)\n    table.sort(captures, function(a, b)\n        if a.start_row == b.start_row then\n            return a.start_col < b.start_col\n        end\n        return a.start_row < b.start_row\n    end)\n    local merged_captures = {}\n    for i = 2, #captures do\n        local prev = captures[i - 1]\n        local curr = captures[i]\n        if\n            prev.start_row == curr.start_row\n            and prev.start_col == curr.start_col\n            and prev.end_row == curr.end_row\n            and prev.end_col == curr.end_col\n        then\n            local prev_hl = type(prev.hl) == \"table\" and prev.hl or { prev.hl }\n            local curr_hl = type(curr.hl) == \"table\" and curr.hl or { curr.hl }\n            ---@diagnostic disable-next-line: param-type-mismatch\n            vim.list_extend(prev_hl, curr_hl)\n            curr.hl = prev_hl\n        else\n            table.insert(merged_captures, prev)\n        end\n    end\n    table.insert(merged_captures, captures[#captures])\n\n    return merged_captures\nend\n\nfunction M.hl_text_to_virt_lines(text, lang)\n    local lines = vim.split(text, \"\\n\")\n    local normal_hl = \"Normal\"\n    local bg_hl = \"CopilotLspNesAdd\"\n\n    local function hl_chunk(chunk, hl)\n        if not hl then\n            return { chunk, { normal_hl, bg_hl } }\n        end\n        if type(hl) == \"string\" then\n            return { chunk, { hl, bg_hl } }\n        end\n        hl = vim.deepcopy(hl)\n        table.insert(hl, bg_hl)\n        return { chunk, hl }\n    end\n\n    local captures = parse_text(text, lang)\n    if not captures or #captures == 0 then\n        return vim.iter(lines)\n            :map(function(line)\n                return { hl_chunk(line) }\n            end)\n            :totable()\n    end\n\n    captures = merge_captures(captures)\n\n    local virt_lines = {}\n\n    local curr_row = 0\n    local curr_col = 0\n    local curr_virt_line = {}\n\n    vim.iter(captures):each(function(cap)\n        -- skip if the capture is before the current position\n        if cap.end_row < curr_row or (cap.end_row == curr_row and cap.end_col <= curr_col) then\n            return\n        end\n\n        if cap.start_row > curr_row then\n            -- add the rest of the line\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1)\n            table.insert(curr_virt_line, hl_chunk(chunk_text))\n            table.insert(virt_lines, curr_virt_line)\n\n            for i = curr_row + 1, cap.start_row - 1 do\n                local line_text = lines[i + 1]\n                table.insert(virt_lines, { hl_chunk(line_text) })\n            end\n\n            curr_row = cap.start_row\n            curr_col = 0\n            curr_virt_line = {}\n        end\n\n        assert(curr_row == cap.start_row, \"Unexpected start row\")\n\n        if cap.start_col > curr_col then\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1, cap.start_col)\n            table.insert(curr_virt_line, hl_chunk(chunk_text))\n            curr_col = cap.start_col\n        end\n\n        assert(curr_col == cap.start_col, \"Unexpected start column\")\n\n        if cap.end_row > curr_row then\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1)\n            table.insert(curr_virt_line, hl_chunk(chunk_text, cap.hl))\n            table.insert(virt_lines, curr_virt_line)\n\n            for i = curr_row + 1, cap.end_row - 1 do\n                local line_text = lines[i + 1]\n                table.insert(virt_lines, { hl_chunk(line_text, cap.hl) })\n            end\n\n            curr_row = cap.end_row\n            curr_col = 0\n            curr_virt_line = {}\n        end\n\n        assert(curr_row == cap.end_row, \"Unexpected end row\")\n\n        if cap.end_col > curr_col then\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1, cap.end_col)\n            table.insert(curr_virt_line, hl_chunk(chunk_text, cap.hl))\n            curr_col = cap.end_col\n        end\n    end)\n\n    if #curr_virt_line > 0 then\n        table.insert(virt_lines, curr_virt_line)\n    end\n\n    return virt_lines\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/handlers.lua", "---@type table<string, lsp.Handler>\nlocal M = {}\n\nlocal methods = {\n    signIn = \"signIn\",\n    didChangeStatus = \"didChangeStatus\",\n}\n\n-- copy from copilot.lua\nlocal function open_signin_popup(code, url)\n    local lines = {\n        \" [Copilot-lsp] \",\n        \"\",\n        \" First copy your one-time code: \",\n        \"   \" .. code .. \" \",\n        \" In your browser, visit: \",\n        \"   \" .. url .. \" \",\n        \"\",\n        \" ...waiting, it might take a while and \",\n        \" this popup will auto close once done... \",\n    }\n    local height, width = #lines, math.max(unpack(vim.tbl_map(function(line)\n        return #line\n    end, lines)))\n\n    local bufnr = vim.api.nvim_create_buf(false, true)\n    vim.bo[bufnr].buflisted = false\n    vim.bo[bufnr].buftype = \"nofile\"\n    vim.bo[bufnr].bufhidden = \"wipe\"\n    vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines)\n\n    local winnr = vim.api.nvim_open_win(bufnr, true, {\n        relative = \"editor\",\n        style = \"minimal\",\n        border = \"single\",\n        row = (vim.o.lines - height) / 2,\n        col = (vim.o.columns - width) / 2,\n        height = height,\n        width = width,\n    })\n    vim.wo[winnr].winhighlight = \"Normal:Normal\"\n    vim.wo[winnr].winblend = 0\n\n    return function()\n        vim.api.nvim_win_close(winnr, true)\n    end\nend\n\nlocal function copy_to_clipboard(s)\n    vim.fn.setreg(\"+\", s)\n    vim.fn.setreg(\"*\", s)\nend\n\n---@param res {command: lsp.Command, userCode: string, verificationUri: string}\nM[methods.signIn] = function(err, res, ctx)\n    if err then\n        vim.notify(\"[copilot-lsp] failed to start signin flow: \" .. vim.inspect(err), vim.log.levels.ERROR)\n        return\n    end\n\n    local client = vim.lsp.get_client_by_id(ctx.client_id)\n    if not client then\n        return\n    end\n\n    vim.g.copilot_lsp_signin_pending = true\n\n    local close_signin_popup = open_signin_popup(res.userCode, res.verificationUri)\n    copy_to_clipboard(res.userCode)\n\n    client:exec_cmd(\n        res.command,\n        { bufnr = ctx.bufnr },\n\n        ---@param cmd_res {status: string, user: string}\n        function(cmd_err, cmd_res)\n            vim.g.copilot_lsp_signin_pending = nil\n            close_signin_popup()\n\n            if cmd_err then\n                vim.notify(\"[copilot-lsp] failed to open browser: \" .. vim.inspect(cmd_err), vim.log.levels.WARN)\n                return\n            end\n            if cmd_res.status == \"OK\" then\n                vim.notify(\"[copilot-lsp] successfully signed in as: \" .. cmd_res.user, vim.log.levels.INFO)\n            else\n                vim.notify(\"[copilot-lsp] failed to sign in: \" .. vim.inspect(cmd_res), vim.log.levels.ERROR)\n            end\n        end\n    )\nend\n\n---@param client_id integer\n---@param bufnr integer\nlocal function sign_in(client_id, bufnr)\n    if vim.g.copilot_lsp_signin_pending then\n        return\n    end\n\n    local client = vim.lsp.get_client_by_id(client_id)\n    if not client then\n        return\n    end\n\n    for _, req in pairs(client.requests) do\n        if req.method == methods.signIn and req.type == \"pending\" then\n            return\n        end\n    end\n\n    client:request(methods.signIn, vim.empty_dict(), nil, bufnr)\nend\n\n---@param res {busy: boolean, kind: 'Normal'|'Error'|'Warning'|'Inactive', message: string}\nM[\"didChangeStatus\"] = function(err, res, ctx)\n    if err then\n        return\n    end\n    -- real error message: You are not signed into GitHub. Please sign in to use Copilot.\n    if res.kind == \"Error\" and res.message:find(\"not signed into\") then\n        sign_in(ctx.client_id, ctx.bufnr)\n    end\nend\n\nreturn M\n"], ["/copilot-lsp/lsp/copilot_ls.lua", "local version = vim.version()\n\n---@type vim.lsp.Config\nreturn {\n    --NOTE: This name means that existing blink completion works\n    name = \"copilot_ls\",\n    cmd = {\n        \"copilot-language-server\",\n        \"--stdio\",\n    },\n    init_options = {\n        editorInfo = {\n            name = \"neovim\",\n            version = string.format(\"%d.%d.%d\", version.major, version.minor, version.patch),\n        },\n        editorPluginInfo = {\n            name = \"Github Copilot LSP for Neovim\",\n            version = \"0.0.1\",\n        },\n    },\n    settings = {\n        nextEditSuggestions = {\n            enabled = true,\n        },\n    },\n    handlers = setmetatable({}, {\n        __index = function(_, method)\n            return require(\"copilot-lsp.handlers\")[method]\n        end,\n    }),\n    root_dir = vim.uv.cwd(),\n    on_init = function(client)\n        local au = vim.api.nvim_create_augroup(\"copilotlsp.init\", { clear = true })\n        --NOTE: Inline Completions\n        --TODO: We dont currently use this code path, so comment for now until a UI is built\n        -- vim.api.nvim_create_autocmd(\"TextChangedI\", {\n        --     callback = function()\n        --         inline_completion.request_inline_completion(2)\n        --     end,\n        --     group = au,\n        -- })\n\n        -- TODO: make this configurable for key maps, or just expose commands to map in config\n        -- vim.keymap.set(\"i\", \"<c-i>\", function()\n        --     inline_completion.request_inline_completion(1)\n        -- end)\n\n        --NOTE: NES Completions\n        local debounced_request = require(\"copilot-lsp.util\").debounce(\n            require(\"copilot-lsp.nes\").request_nes,\n            vim.g.copilot_nes_debounce or 500\n        )\n        vim.api.nvim_create_autocmd({ \"TextChangedI\", \"TextChanged\" }, {\n            callback = function()\n                debounced_request(client)\n            end,\n            group = au,\n        })\n\n        --NOTE: didFocus\n        vim.api.nvim_create_autocmd(\"BufEnter\", {\n            callback = function()\n                local td_params = vim.lsp.util.make_text_document_params()\n                client:notify(\"textDocument/didFocus\", {\n                    textDocument = {\n                        uri = td_params.uri,\n                    },\n                })\n            end,\n            group = au,\n        })\n    end,\n}\n"], ["/copilot-lsp/lua/copilot-lsp/completion/init.lua", "local M = {}\n\n---@param _results table<integer, { err: lsp.ResponseError, result: lsp.InlineCompletionList}>\n---@param _ctx lsp.HandlerContext\n---@param _config table\nlocal function handle_inlineCompletion_response(_results, _ctx, _config)\n    -- -- Filter errors from results\n    -- local results1 = {} --- @type table<integer,lsp.InlineCompletionList>\n    --\n    -- for client_id, resp in pairs(results) do\n    --     local err, result = resp.err, resp.result\n    --     if err then\n    --         vim.lsp.log.error(err.code, err.message)\n    --     elseif result then\n    --         results1[client_id] = result\n    --     end\n    -- end\n    --\n    -- for _, result in pairs(results1) do\n    --     --TODO: Ghost text for completions\n    --     -- This is where we show the completion results\n    --     -- However, the LSP being named \"copilot_ls\" is enough for blink-cmp to show the completion\n    -- end\nend\n\n---@param type lsp.InlineCompletionTriggerKind\nfunction M.request_inline_completion(type)\n    local params = vim.tbl_deep_extend(\"keep\", vim.lsp.util.make_position_params(0, \"utf-16\"), {\n        textDocument = vim.lsp.util.make_text_document_params(),\n        position = vim.lsp.util.make_position_params(0, \"utf-16\"),\n        context = {\n            triggerKind = type,\n        },\n        formattingOptions = {\n            --TODO: Grab this from editor also\n            tabSize = 4,\n            insertSpaces = true,\n        },\n    })\n    vim.lsp.buf_request_all(0, \"textDocument/inlineCompletion\", params, handle_inlineCompletion_response)\nend\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/config.lua", "---@class copilotlsp.config.nes\n---@field move_count_threshold integer Number of cursor movements before clearing suggestion\n---@field distance_threshold integer Maximum line distance before clearing suggestion\n---@field clear_on_large_distance boolean Whether to clear suggestion when cursor is far away\n---@field count_horizontal_moves boolean Whether to count horizontal cursor movements\n---@field reset_on_approaching boolean Whether to reset counter when approaching suggestion\n\nlocal M = {}\n\n---@class copilotlsp.config\n---@field nes copilotlsp.config.nes\nM.defaults = {\n    nes = {\n        move_count_threshold = 3,\n        distance_threshold = 40,\n        clear_on_large_distance = true,\n        count_horizontal_moves = true,\n        reset_on_approaching = true,\n    },\n}\n\n---@type copilotlsp.config\nM.config = vim.deepcopy(M.defaults)\n\n---@param opts? copilotlsp.config configuration to merge with defaults\nfunction M.setup(opts)\n    opts = opts or {}\n    M.config = vim.tbl_deep_extend(\"force\", M.defaults, opts)\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/types.lua", "---@class copilotlsp.InlineEdit : lsp.TextEdit\n---@field command lsp.Command\n---@field text string\n---@field textDocument lsp.VersionedTextDocumentIdentifier\n\n---@class copilotlsp.copilotInlineEditResponse\n---@field edits copilotlsp.InlineEdit[]\n\n---@class copilotlsp.nes.TextDeletion\n---@field range lsp.Range\n\n---@class copilotlsp.nes.InlineInsertion\n---@field text string\n---@field line integer\n---@field character integer\n\n---@class copilotlsp.nes.TextInsertion\n---@field text string\n---@field line integer insert lines at this line\n---@field above? boolean above the line\n\n---@class copilotlsp.nes.InlineEditPreview\n---@field deletion? copilotlsp.nes.TextDeletion\n---@field inline_insertion? copilotlsp.nes.InlineInsertion\n---@field lines_insertion? copilotlsp.nes.TextInsertion\n"], ["/copilot-lsp/lua/copilot-lsp/init.lua", "local config = require(\"copilot-lsp.config\")\n\n---@class copilotlsp\n---@field defaults copilotlsp.config\n---@field config copilotlsp.config\n---@field setup fun(opts?: copilotlsp.config): nil\nlocal M = {}\n\nM.defaults = config.defaults\nM.config = config.config\n\n---@param opts? copilotlsp.config configuration to merge with defaults\nfunction M.setup(opts)\n    config.setup(opts)\n    M.config = config.config\nend\n\nreturn M\n"], ["/copilot-lsp/plugin/copilot-lsp.lua", "vim.api.nvim_set_hl(0, \"CopilotLspNesAdd\", { link = \"DiffAdd\", default = true })\nvim.api.nvim_set_hl(0, \"CopilotLspNesDelete\", { link = \"DiffDelete\", default = true })\nvim.api.nvim_set_hl(0, \"CopilotLspNesApply\", { link = \"DiffText\", default = true })\n"], ["/copilot-lsp/lua/copilot-lsp/errors.lua", "return {\n    ErrNotStarted = \"Copilot LSP not started\",\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 00:43:18", "created_task_model": "DeepSeek-R1", "function_skeleton": "function () end", "code_description": "This code segment functions to: Monitor cursor movement patterns and user interaction modes to determine when to automatically dismiss displayed suggestions based on configurable distance thresholds and movement count limits."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```lua\n[TASK_BEGIN]\nfunction()\n    local current_line = vim.api.nvim_win_get_cursor(0)[1] - 1 -- convert to 0-based\n    local current_col = vim.api.nvim_win_get_cursor(0)[2]\n    if current_line ~= vim.b[bufnr].copilotlsp_nes_last_line or current_col ~= vim.b[bufnr].copilotlsp_nes_last_col then\n        M.clear_suggestion(bufnr, ns_id)\n        vim.b[bufnr].copilotlsp_nes_last_line = current_line\n        vim.b[bufnr].copilotlsp_nes_last_col = current_col\n    end\nend\n[TASK_END]\n```", "inference_time": "2025-08-21 00-43-36"}, "editdistance_info": {"edit_distance": 15.7221, "calculate_time": "2025-08-21 00:43:36", "true_code_clean": "function()\n            if not vim.b[bufnr].nes_state then\n                return true\n            end\n            local cursor = vim.api.nvim_win_get_cursor(0)\n            local cursor_line = cursor[1] - 1 \n            local cursor_col = cursor[2]\n            local suggestion_line = suggestion.range.start.line\n            local last_line = vim.b[bufnr].copilotlsp_nes_last_line or cursor_line\n            local last_col = vim.b[bufnr].copilotlsp_nes_last_col or cursor_col\n            vim.b[bufnr].copilotlsp_nes_last_line = cursor_line\n            vim.b[bufnr].copilotlsp_nes_last_col = cursor_col\n            local line_distance = math.abs(cursor_line - suggestion_line)\n            local last_line_distance = math.abs(last_line - suggestion_line)\n            local moved_horizontally = (cursor_line == last_line) and (cursor_col ~= last_col)\n            local mode = vim.api.nvim_get_mode().mode\n            local should_count = false\n            local first_char = mode:sub(1, 1)\n            if first_char == \"i\" then\n                if moved_horizontally or line_distance ~= last_line_distance then\n                    should_count = true\n                end\n            elseif first_char == \"v\" or first_char == \"V\" or mode == \"\\22\" then\n                should_count = true\n            elseif moved_horizontally and config.nes.count_horizontal_moves then\n                should_count = true\n            elseif line_distance > last_line_distance then\n                should_count = true\n            elseif line_distance < last_line_distance and config.nes.reset_on_approaching then\n                if line_distance > 1 then \n                    vim.b[bufnr].copilotlsp_nes_cursor_moves = 0\n                end\n            end\n            if should_count then\n                vim.b[bufnr].copilotlsp_nes_cursor_moves = (vim.b[bufnr].copilotlsp_nes_cursor_moves or 0) + 1\n            end\n            if vim.b[bufnr].copilotlsp_nes_cursor_moves >= config.nes.move_count_threshold then\n                vim.b[bufnr].copilotlsp_nes_cursor_moves = 0\n                vim.schedule(function()\n                    M.clear_suggestion(bufnr, ns_id)\n                end)\n                return true\n            end\n            if config.nes.clear_on_large_distance and line_distance > config.nes.distance_threshold then\n                M.clear_suggestion(bufnr, ns_id)\n                return true\n            end\n            return false \n        end", "predict_code_clean": "function()\n    local current_line = vim.api.nvim_win_get_cursor(0)[1] - 1 \n    local current_col = vim.api.nvim_win_get_cursor(0)[2]\n    if current_line ~= vim.b[bufnr].copilotlsp_nes_last_line or current_col ~= vim.b[bufnr].copilotlsp_nes_last_col then\n        M.clear_suggestion(bufnr, ns_id)\n        vim.b[bufnr].copilotlsp_nes_last_line = current_line\n        vim.b[bufnr].copilotlsp_nes_last_col = current_col\n    end\nend"}}
{"repo_name": "copilot-lsp", "file_name": "/copilot-lsp/lua/copilot-lsp/nes/ui.lua", "inference_info": {"prefix_code": "local M = {}\nlocal config = require(\"copilot-lsp.config\").config\n\n---@param bufnr integer\n---@param ns_id integer\nlocal function _dismiss_suggestion(bufnr, ns_id)\n    pcall(vim.api.nvim_buf_clear_namespace, bufnr, ns_id, 0, -1)\nend\n\n---@param bufnr? integer\n---@param ns_id integer\nfunction M.clear_suggestion(bufnr, ns_id)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    -- Validate buffer exists before accessing buffer-scoped variables\n    if not vim.api.nvim_buf_is_valid(bufnr) then\n        return\n    end\n    if vim.b[bufnr].nes_jump then\n        vim.b[bufnr].nes_jump = false\n        return\n    end\n    _dismiss_suggestion(bufnr, ns_id)\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return\n    end\n\n    -- Clear buffer variables\n    vim.b[bufnr].nes_state = nil\n    vim.b[bufnr].copilotlsp_nes_cursor_moves = nil\n    vim.b[bufnr].copilotlsp_nes_last_line = nil\n    vim.b[bufnr].copilotlsp_nes_last_col = nil\nend\n\n---@private\n---@param bufnr integer\n---@param edit lsp.TextEdit\n---@return copilotlsp.nes.InlineEditPreview\nfunction M._calculate_preview(bufnr, edit)\n    local text = edit.newText\n    local range = edit.range\n    local start_line = range.start.line\n    local start_char = range.start.character\n    local end_line = range[\"end\"].line\n    local end_char = range[\"end\"].character\n\n    -- Split text by newline. Use plain=true to handle trailing newline correctly.\n    local new_lines = vim.split(text, \"\\n\", { plain = true })\n    local num_new_lines = #new_lines\n\n    local old_lines = vim.api.nvim_buf_get_lines(bufnr, start_line, end_line + 1, false)\n    local num_old_lines = #old_lines\n\n    local is_same_line = start_line == end_line\n    local is_deletion = text == \"\"\n    local lines_edit = is_same_line or (start_char == 0 and end_char == 0)\n    local is_insertion = is_same_line and start_char == end_char\n\n    if is_deletion and is_insertion then\n        -- no-op\n        return {}\n    end\n\n    if is_deletion and lines_edit then\n        return {\n            deletion = {\n                range = edit.range,\n            },\n        }\n    end\n\n    if is_insertion and num_new_lines == 1 and text ~= \"\" then\n        -- inline insertion\n        return {\n            inline_insertion = {\n                text = text,\n                line = start_line,\n                character = start_char,\n            },\n        }\n    end\n\n    if is_insertion and num_new_lines > 1 then\n        if start_char == #old_lines[1] and new_lines[1] == \"\" then\n            -- insert lines after the start line\n            return {\n                lines_insertion = {\n                    text = table.concat(vim.list_slice(new_lines, 2), \"\\n\"),\n                    line = start_line,\n                },\n            }\n        end\n\n        if end_char == 0 and new_lines[num_new_lines] == \"\" then\n            -- insert lines before the end line\n            return {\n                lines_insertion = {\n                    text = table.concat(vim.list_slice(new_lines, 1, num_new_lines - 1), \"\\n\"),\n                    line = start_line,\n                    above = true,\n                },\n            }\n        end\n    end\n\n    -- insert lines in the middle\n    local prefix = old_lines[1]:sub(1, start_char)\n    local suffix = old_lines[num_old_lines]:sub(end_char + 1)\n    local new_lines_extend = vim.deepcopy(new_lines)\n    new_lines_extend[1] = prefix .. new_lines_extend[1]\n    new_lines_extend[num_new_lines] = new_lines_extend[num_new_lines] .. suffix\n    local insertion = table.concat(new_lines_extend, \"\\n\")\n\n    return {\n        deletion = {\n            range = {\n                start = { line = start_line, character = 0 },\n                [\"end\"] = { line = end_line, character = #old_lines[num_old_lines] },\n            },\n        },\n        lines_insertion = {\n            text = insertion,\n            line = end_line,\n        },\n    }\nend\n\n---@private\n---@param bufnr integer\n---@param ns_id integer\n---@param preview copilotlsp.nes.InlineEditPreview\n", "suffix_code": "\n\n---@private\n---@param bufnr integer\n---@param ns_id integer\n---@param edits copilotlsp.InlineEdit[]\nfunction M._display_next_suggestion(bufnr, ns_id, edits)\n    M.clear_suggestion(bufnr, ns_id)\n    if not edits or #edits == 0 then\n        return\n    end\n\n    local suggestion = edits[1]\n    local preview = M._calculate_preview(bufnr, suggestion)\n    M._display_preview(bufnr, ns_id, preview)\n\n    vim.b[bufnr].nes_state = suggestion\n    vim.b[bufnr].copilotlsp_nes_namespace_id = ns_id\n    vim.b[bufnr].copilotlsp_nes_cursor_moves = 1\n\n    vim.api.nvim_create_autocmd({ \"CursorMoved\", \"CursorMovedI\" }, {\n        buffer = bufnr,\n        callback = function()\n            if not vim.b[bufnr].nes_state then\n                return true\n            end\n\n            -- Get cursor position\n            local cursor = vim.api.nvim_win_get_cursor(0)\n            local cursor_line = cursor[1] - 1 -- 0-indexed\n            local cursor_col = cursor[2]\n            local suggestion_line = suggestion.range.start.line\n\n            -- Store previous position\n            local last_line = vim.b[bufnr].copilotlsp_nes_last_line or cursor_line\n            local last_col = vim.b[bufnr].copilotlsp_nes_last_col or cursor_col\n\n            -- Update stored position\n            vim.b[bufnr].copilotlsp_nes_last_line = cursor_line\n            vim.b[bufnr].copilotlsp_nes_last_col = cursor_col\n\n            -- Calculate distance to suggestion\n            local line_distance = math.abs(cursor_line - suggestion_line)\n            local last_line_distance = math.abs(last_line - suggestion_line)\n\n            -- Check if cursor changed position on same line\n            local moved_horizontally = (cursor_line == last_line) and (cursor_col ~= last_col)\n\n            -- Get current mode\n            local mode = vim.api.nvim_get_mode().mode\n\n            -- Determine if we should count this movement\n            local should_count = false\n            local first_char = mode:sub(1, 1)\n\n            -- In insert mode, only count cursor movements, not text changes\n            if first_char == \"i\" then\n                if moved_horizontally or line_distance ~= last_line_distance then\n                    should_count = true\n                end\n            elseif first_char == \"v\" or first_char == \"V\" or mode == \"\\22\" then\n                should_count = true\n            -- In normal mode with horizontal movement\n            elseif moved_horizontally and config.nes.count_horizontal_moves then\n                should_count = true\n            -- In normal mode with line changes\n            elseif line_distance > last_line_distance then\n                should_count = true\n            -- Moving toward suggestion in normal mode\n            elseif line_distance < last_line_distance and config.nes.reset_on_approaching then\n                if line_distance > 1 then -- Don't reset if 0 or 1 line away\n                    vim.b[bufnr].copilotlsp_nes_cursor_moves = 0\n                end\n            end\n\n            -- Update counter if needed\n            if should_count then\n                vim.b[bufnr].copilotlsp_nes_cursor_moves = (vim.b[bufnr].copilotlsp_nes_cursor_moves or 0) + 1\n            end\n\n            -- Clear if counter threshold reached\n            if vim.b[bufnr].copilotlsp_nes_cursor_moves >= config.nes.move_count_threshold then\n                vim.b[bufnr].copilotlsp_nes_cursor_moves = 0\n                vim.schedule(function()\n                    M.clear_suggestion(bufnr, ns_id)\n                end)\n                return true\n            end\n\n            -- Optional: Clear on large distance\n            if config.nes.clear_on_large_distance and line_distance > config.nes.distance_threshold then\n                M.clear_suggestion(bufnr, ns_id)\n                return true\n            end\n\n            return false -- Keep the autocmd\n        end,\n    })\n    -- Also clear on text changes that affect the suggestion area\n    vim.api.nvim_create_autocmd({ \"TextChanged\", \"TextChangedI\" }, {\n        buffer = bufnr,\n        callback = function()\n            if not vim.b[bufnr].nes_state then\n                return true\n            end\n            -- Check if the text at the suggestion position has changed\n            local start_line = suggestion.range.start.line\n            -- If the lines are no longer in the buffer, clear the suggestion\n            if start_line >= vim.api.nvim_buf_line_count(bufnr) then\n                M.clear_suggestion(bufnr, ns_id)\n                return true\n            end\n            return false -- Keep the autocmd\n        end,\n    })\nend\n\nreturn M\n", "middle_code": "function M._display_preview(bufnr, ns_id, preview)\n    if preview.deletion then\n        local range = preview.deletion.range\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, range.start.line, range.start.character, {\n            hl_group = \"CopilotLspNesDelete\",\n            end_row = range[\"end\"].line,\n            end_col = range[\"end\"].character,\n        })\n    end\n    local inline_insertion = preview.inline_insertion\n    if inline_insertion then\n        local virt_lines =\n            require(\"copilot-lsp.util\").hl_text_to_virt_lines(inline_insertion.text, vim.bo[bufnr].filetype)\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, inline_insertion.line, inline_insertion.character, {\n            virt_text = virt_lines[1],\n            virt_text_pos = \"inline\",\n        })\n    end\n    local lines_insertion = preview.lines_insertion\n    if lines_insertion then\n        local virt_lines =\n            require(\"copilot-lsp.util\").hl_text_to_virt_lines(lines_insertion.text, vim.bo[bufnr].filetype)\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, lines_insertion.line, 0, {\n            virt_lines = virt_lines,\n            virt_lines_above = lines_insertion.above,\n        })\n    end\nend", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "lua", "sub_task_type": null}, "context_code": [["/copilot-lsp/lua/copilot-lsp/nes/init.lua", "local errs = require(\"copilot-lsp.errors\")\nlocal nes_ui = require(\"copilot-lsp.nes.ui\")\nlocal utils = require(\"copilot-lsp.util\")\n\nlocal M = {}\n\nlocal nes_ns = vim.api.nvim_create_namespace(\"copilotlsp.nes\")\n\n---@param err lsp.ResponseError?\n---@param result copilotlsp.copilotInlineEditResponse\n---@param ctx lsp.HandlerContext\nlocal function handle_nes_response(err, result, ctx)\n    if err then\n        -- vim.notify(err.message)\n        return\n    end\n    -- Validate buffer still exists before processing response\n    if not vim.api.nvim_buf_is_valid(ctx.bufnr) then\n        return\n    end\n    for _, edit in ipairs(result.edits) do\n        --- Convert to textEdit fields\n        edit.newText = edit.text\n    end\n    nes_ui._display_next_suggestion(ctx.bufnr, nes_ns, result.edits)\nend\n\n--- Requests the NextEditSuggestion from the current cursor position\n---@param copilot_lss? vim.lsp.Client|string\nfunction M.request_nes(copilot_lss)\n    local pos_params = vim.lsp.util.make_position_params(0, \"utf-16\")\n    local version = vim.lsp.util.buf_versions[vim.api.nvim_get_current_buf()]\n    if type(copilot_lss) == \"string\" then\n        copilot_lss = vim.lsp.get_clients({ name = copilot_lss })[1]\n    end\n    assert(copilot_lss, errs.ErrNotStarted)\n    ---@diagnostic disable-next-line: inject-field\n    pos_params.textDocument.version = version\n    copilot_lss:request(\"textDocument/copilotInlineEdit\", pos_params, handle_nes_response)\nend\n\n--- Walks the cursor to the start of the edit.\n--- This function returns false if there is no edit to apply or if the cursor is already at the start position of the\n--- edit.\n---@param bufnr? integer\n---@return boolean --if the cursor walked\nfunction M.walk_cursor_start_edit(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return false\n    end\n\n    local cursor_row, _ = unpack(vim.api.nvim_win_get_cursor(0))\n    if cursor_row - 1 ~= state.range.start.line then\n        vim.b[bufnr].nes_jump = true\n        ---@type lsp.Location\n        local jump_loc_before = {\n            uri = state.textDocument.uri,\n            range = {\n                start = state.range[\"start\"],\n                [\"end\"] = state.range[\"start\"],\n            },\n        }\n        vim.schedule(function()\n            vim.lsp.util.show_document(jump_loc_before, \"utf-16\", { focus = true })\n        end)\n        return true\n    else\n        return false\n    end\nend\n\n--- Walks the cursor to the end of the edit.\n--- This function returns false if there is no edit to apply or if the cursor is already at the end position of the\n--- edit\n---@param bufnr? integer\n---@return boolean --if the cursor walked\nfunction M.walk_cursor_end_edit(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return false\n    end\n\n    ---@type lsp.Location\n    local jump_loc_after = {\n        uri = state.textDocument.uri,\n        range = {\n            start = state.range[\"end\"],\n            [\"end\"] = state.range[\"end\"],\n        },\n    }\n    --NOTE: If last line is deletion, then this may be outside of the buffer\n    vim.schedule(function()\n        pcall(vim.lsp.util.show_document, jump_loc_after, \"utf-16\", { focus = true })\n    end)\n    return true\nend\n\n--- This function applies the pending nes edit to the current buffer and then clears the marks for the pending\n--- suggestion\n---@param bufnr? integer\n---@return boolean --if the nes was applied\nfunction M.apply_pending_nes(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n\n    ---@type copilotlsp.InlineEdit\n    local state = vim.b[bufnr].nes_state\n    if not state then\n        return false\n    end\n    vim.schedule(function()\n        utils.apply_inline_edit(state)\n        vim.b[bufnr].nes_jump = false\n        nes_ui.clear_suggestion(bufnr, nes_ns)\n    end)\n    return true\nend\n\n---@param bufnr? integer\nfunction M.clear_suggestion(bufnr)\n    bufnr = bufnr and bufnr > 0 and bufnr or vim.api.nvim_get_current_buf()\n    nes_ui.clear_suggestion(bufnr, nes_ns)\nend\n\n--- Clear the current suggestion if it exists\n---@return boolean -- true if a suggestion was cleared, false if no suggestion existed\nfunction M.clear()\n    local buf = vim.api.nvim_get_current_buf()\n    if vim.b[buf].nes_state then\n        local ns = vim.b[buf].copilotlsp_nes_namespace_id or nes_ns\n        nes_ui.clear_suggestion(buf, ns)\n        return true\n    end\n    return false\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/util.lua", "local M = {}\n---@param edit copilotlsp.InlineEdit\nfunction M.apply_inline_edit(edit)\n    local bufnr = vim.uri_to_bufnr(edit.textDocument.uri)\n\n    ---@diagnostic disable-next-line: assign-type-mismatch\n    vim.lsp.util.apply_text_edits({ edit }, bufnr, \"utf-16\")\nend\n\n---Debounces calls to a function, and ensures it only runs once per delay\n---even if called repeatedly.\n---@param fn fun(...: any)\n---@param delay integer\nfunction M.debounce(fn, delay)\n    local timer = vim.uv.new_timer()\n    return function(...)\n        local argv = vim.F.pack_len(...)\n        timer:start(delay, 0, function()\n            timer:stop()\n            vim.schedule_wrap(fn)(vim.F.unpack_len(argv))\n        end)\n    end\nend\n\n---@private\n---@class Capture\n---@field hl string|string[]\n---range(0-based)\n---@field start_row integer\n---@field start_col integer\n---@field end_row integer\n---@field end_col integer\n\n---@param text string\n---@param lang string\n---@return Capture[]?\nlocal function parse_text(text, lang)\n    local ok, trees = pcall(vim.treesitter.get_string_parser, text, lang)\n    if not ok then\n        return\n    end\n    trees:parse(true)\n\n    local captures = {}\n\n    trees:for_each_tree(function(tree, _ltree)\n        local hl_query = vim.treesitter.query.get(lang, \"highlights\")\n        if not hl_query then\n            return\n        end\n\n        local iter = hl_query:iter_captures(tree:root(), text)\n        vim.iter(iter):each(function(id, node)\n            local name = hl_query.captures[id]\n            local hl = \"Normal\"\n            if not vim.startswith(name, \"_\") then\n                hl = \"@\" .. name .. \".\" .. lang\n            end\n            local start_row, start_col, end_row, end_col = node:range()\n\n            -- Ignore zero-width captures if they cause issues (sometimes happen at EOF)\n            if start_row == end_row and start_col == end_col then\n                return\n            end\n\n            table.insert(captures, {\n                hl = hl,\n                start_row = start_row,\n                start_col = start_col,\n                end_row = end_row,\n                end_col = end_col,\n            })\n        end)\n    end)\n    return captures\nend\n\nlocal function merge_captures(captures)\n    table.sort(captures, function(a, b)\n        if a.start_row == b.start_row then\n            return a.start_col < b.start_col\n        end\n        return a.start_row < b.start_row\n    end)\n    local merged_captures = {}\n    for i = 2, #captures do\n        local prev = captures[i - 1]\n        local curr = captures[i]\n        if\n            prev.start_row == curr.start_row\n            and prev.start_col == curr.start_col\n            and prev.end_row == curr.end_row\n            and prev.end_col == curr.end_col\n        then\n            local prev_hl = type(prev.hl) == \"table\" and prev.hl or { prev.hl }\n            local curr_hl = type(curr.hl) == \"table\" and curr.hl or { curr.hl }\n            ---@diagnostic disable-next-line: param-type-mismatch\n            vim.list_extend(prev_hl, curr_hl)\n            curr.hl = prev_hl\n        else\n            table.insert(merged_captures, prev)\n        end\n    end\n    table.insert(merged_captures, captures[#captures])\n\n    return merged_captures\nend\n\nfunction M.hl_text_to_virt_lines(text, lang)\n    local lines = vim.split(text, \"\\n\")\n    local normal_hl = \"Normal\"\n    local bg_hl = \"CopilotLspNesAdd\"\n\n    local function hl_chunk(chunk, hl)\n        if not hl then\n            return { chunk, { normal_hl, bg_hl } }\n        end\n        if type(hl) == \"string\" then\n            return { chunk, { hl, bg_hl } }\n        end\n        hl = vim.deepcopy(hl)\n        table.insert(hl, bg_hl)\n        return { chunk, hl }\n    end\n\n    local captures = parse_text(text, lang)\n    if not captures or #captures == 0 then\n        return vim.iter(lines)\n            :map(function(line)\n                return { hl_chunk(line) }\n            end)\n            :totable()\n    end\n\n    captures = merge_captures(captures)\n\n    local virt_lines = {}\n\n    local curr_row = 0\n    local curr_col = 0\n    local curr_virt_line = {}\n\n    vim.iter(captures):each(function(cap)\n        -- skip if the capture is before the current position\n        if cap.end_row < curr_row or (cap.end_row == curr_row and cap.end_col <= curr_col) then\n            return\n        end\n\n        if cap.start_row > curr_row then\n            -- add the rest of the line\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1)\n            table.insert(curr_virt_line, hl_chunk(chunk_text))\n            table.insert(virt_lines, curr_virt_line)\n\n            for i = curr_row + 1, cap.start_row - 1 do\n                local line_text = lines[i + 1]\n                table.insert(virt_lines, { hl_chunk(line_text) })\n            end\n\n            curr_row = cap.start_row\n            curr_col = 0\n            curr_virt_line = {}\n        end\n\n        assert(curr_row == cap.start_row, \"Unexpected start row\")\n\n        if cap.start_col > curr_col then\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1, cap.start_col)\n            table.insert(curr_virt_line, hl_chunk(chunk_text))\n            curr_col = cap.start_col\n        end\n\n        assert(curr_col == cap.start_col, \"Unexpected start column\")\n\n        if cap.end_row > curr_row then\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1)\n            table.insert(curr_virt_line, hl_chunk(chunk_text, cap.hl))\n            table.insert(virt_lines, curr_virt_line)\n\n            for i = curr_row + 1, cap.end_row - 1 do\n                local line_text = lines[i + 1]\n                table.insert(virt_lines, { hl_chunk(line_text, cap.hl) })\n            end\n\n            curr_row = cap.end_row\n            curr_col = 0\n            curr_virt_line = {}\n        end\n\n        assert(curr_row == cap.end_row, \"Unexpected end row\")\n\n        if cap.end_col > curr_col then\n            local chunk_text = string.sub(lines[curr_row + 1], curr_col + 1, cap.end_col)\n            table.insert(curr_virt_line, hl_chunk(chunk_text, cap.hl))\n            curr_col = cap.end_col\n        end\n    end)\n\n    if #curr_virt_line > 0 then\n        table.insert(virt_lines, curr_virt_line)\n    end\n\n    return virt_lines\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/handlers.lua", "---@type table<string, lsp.Handler>\nlocal M = {}\n\nlocal methods = {\n    signIn = \"signIn\",\n    didChangeStatus = \"didChangeStatus\",\n}\n\n-- copy from copilot.lua\nlocal function open_signin_popup(code, url)\n    local lines = {\n        \" [Copilot-lsp] \",\n        \"\",\n        \" First copy your one-time code: \",\n        \"   \" .. code .. \" \",\n        \" In your browser, visit: \",\n        \"   \" .. url .. \" \",\n        \"\",\n        \" ...waiting, it might take a while and \",\n        \" this popup will auto close once done... \",\n    }\n    local height, width = #lines, math.max(unpack(vim.tbl_map(function(line)\n        return #line\n    end, lines)))\n\n    local bufnr = vim.api.nvim_create_buf(false, true)\n    vim.bo[bufnr].buflisted = false\n    vim.bo[bufnr].buftype = \"nofile\"\n    vim.bo[bufnr].bufhidden = \"wipe\"\n    vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines)\n\n    local winnr = vim.api.nvim_open_win(bufnr, true, {\n        relative = \"editor\",\n        style = \"minimal\",\n        border = \"single\",\n        row = (vim.o.lines - height) / 2,\n        col = (vim.o.columns - width) / 2,\n        height = height,\n        width = width,\n    })\n    vim.wo[winnr].winhighlight = \"Normal:Normal\"\n    vim.wo[winnr].winblend = 0\n\n    return function()\n        vim.api.nvim_win_close(winnr, true)\n    end\nend\n\nlocal function copy_to_clipboard(s)\n    vim.fn.setreg(\"+\", s)\n    vim.fn.setreg(\"*\", s)\nend\n\n---@param res {command: lsp.Command, userCode: string, verificationUri: string}\nM[methods.signIn] = function(err, res, ctx)\n    if err then\n        vim.notify(\"[copilot-lsp] failed to start signin flow: \" .. vim.inspect(err), vim.log.levels.ERROR)\n        return\n    end\n\n    local client = vim.lsp.get_client_by_id(ctx.client_id)\n    if not client then\n        return\n    end\n\n    vim.g.copilot_lsp_signin_pending = true\n\n    local close_signin_popup = open_signin_popup(res.userCode, res.verificationUri)\n    copy_to_clipboard(res.userCode)\n\n    client:exec_cmd(\n        res.command,\n        { bufnr = ctx.bufnr },\n\n        ---@param cmd_res {status: string, user: string}\n        function(cmd_err, cmd_res)\n            vim.g.copilot_lsp_signin_pending = nil\n            close_signin_popup()\n\n            if cmd_err then\n                vim.notify(\"[copilot-lsp] failed to open browser: \" .. vim.inspect(cmd_err), vim.log.levels.WARN)\n                return\n            end\n            if cmd_res.status == \"OK\" then\n                vim.notify(\"[copilot-lsp] successfully signed in as: \" .. cmd_res.user, vim.log.levels.INFO)\n            else\n                vim.notify(\"[copilot-lsp] failed to sign in: \" .. vim.inspect(cmd_res), vim.log.levels.ERROR)\n            end\n        end\n    )\nend\n\n---@param client_id integer\n---@param bufnr integer\nlocal function sign_in(client_id, bufnr)\n    if vim.g.copilot_lsp_signin_pending then\n        return\n    end\n\n    local client = vim.lsp.get_client_by_id(client_id)\n    if not client then\n        return\n    end\n\n    for _, req in pairs(client.requests) do\n        if req.method == methods.signIn and req.type == \"pending\" then\n            return\n        end\n    end\n\n    client:request(methods.signIn, vim.empty_dict(), nil, bufnr)\nend\n\n---@param res {busy: boolean, kind: 'Normal'|'Error'|'Warning'|'Inactive', message: string}\nM[\"didChangeStatus\"] = function(err, res, ctx)\n    if err then\n        return\n    end\n    -- real error message: You are not signed into GitHub. Please sign in to use Copilot.\n    if res.kind == \"Error\" and res.message:find(\"not signed into\") then\n        sign_in(ctx.client_id, ctx.bufnr)\n    end\nend\n\nreturn M\n"], ["/copilot-lsp/lsp/copilot_ls.lua", "local version = vim.version()\n\n---@type vim.lsp.Config\nreturn {\n    --NOTE: This name means that existing blink completion works\n    name = \"copilot_ls\",\n    cmd = {\n        \"copilot-language-server\",\n        \"--stdio\",\n    },\n    init_options = {\n        editorInfo = {\n            name = \"neovim\",\n            version = string.format(\"%d.%d.%d\", version.major, version.minor, version.patch),\n        },\n        editorPluginInfo = {\n            name = \"Github Copilot LSP for Neovim\",\n            version = \"0.0.1\",\n        },\n    },\n    settings = {\n        nextEditSuggestions = {\n            enabled = true,\n        },\n    },\n    handlers = setmetatable({}, {\n        __index = function(_, method)\n            return require(\"copilot-lsp.handlers\")[method]\n        end,\n    }),\n    root_dir = vim.uv.cwd(),\n    on_init = function(client)\n        local au = vim.api.nvim_create_augroup(\"copilotlsp.init\", { clear = true })\n        --NOTE: Inline Completions\n        --TODO: We dont currently use this code path, so comment for now until a UI is built\n        -- vim.api.nvim_create_autocmd(\"TextChangedI\", {\n        --     callback = function()\n        --         inline_completion.request_inline_completion(2)\n        --     end,\n        --     group = au,\n        -- })\n\n        -- TODO: make this configurable for key maps, or just expose commands to map in config\n        -- vim.keymap.set(\"i\", \"<c-i>\", function()\n        --     inline_completion.request_inline_completion(1)\n        -- end)\n\n        --NOTE: NES Completions\n        local debounced_request = require(\"copilot-lsp.util\").debounce(\n            require(\"copilot-lsp.nes\").request_nes,\n            vim.g.copilot_nes_debounce or 500\n        )\n        vim.api.nvim_create_autocmd({ \"TextChangedI\", \"TextChanged\" }, {\n            callback = function()\n                debounced_request(client)\n            end,\n            group = au,\n        })\n\n        --NOTE: didFocus\n        vim.api.nvim_create_autocmd(\"BufEnter\", {\n            callback = function()\n                local td_params = vim.lsp.util.make_text_document_params()\n                client:notify(\"textDocument/didFocus\", {\n                    textDocument = {\n                        uri = td_params.uri,\n                    },\n                })\n            end,\n            group = au,\n        })\n    end,\n}\n"], ["/copilot-lsp/lua/copilot-lsp/completion/init.lua", "local M = {}\n\n---@param _results table<integer, { err: lsp.ResponseError, result: lsp.InlineCompletionList}>\n---@param _ctx lsp.HandlerContext\n---@param _config table\nlocal function handle_inlineCompletion_response(_results, _ctx, _config)\n    -- -- Filter errors from results\n    -- local results1 = {} --- @type table<integer,lsp.InlineCompletionList>\n    --\n    -- for client_id, resp in pairs(results) do\n    --     local err, result = resp.err, resp.result\n    --     if err then\n    --         vim.lsp.log.error(err.code, err.message)\n    --     elseif result then\n    --         results1[client_id] = result\n    --     end\n    -- end\n    --\n    -- for _, result in pairs(results1) do\n    --     --TODO: Ghost text for completions\n    --     -- This is where we show the completion results\n    --     -- However, the LSP being named \"copilot_ls\" is enough for blink-cmp to show the completion\n    -- end\nend\n\n---@param type lsp.InlineCompletionTriggerKind\nfunction M.request_inline_completion(type)\n    local params = vim.tbl_deep_extend(\"keep\", vim.lsp.util.make_position_params(0, \"utf-16\"), {\n        textDocument = vim.lsp.util.make_text_document_params(),\n        position = vim.lsp.util.make_position_params(0, \"utf-16\"),\n        context = {\n            triggerKind = type,\n        },\n        formattingOptions = {\n            --TODO: Grab this from editor also\n            tabSize = 4,\n            insertSpaces = true,\n        },\n    })\n    vim.lsp.buf_request_all(0, \"textDocument/inlineCompletion\", params, handle_inlineCompletion_response)\nend\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/config.lua", "---@class copilotlsp.config.nes\n---@field move_count_threshold integer Number of cursor movements before clearing suggestion\n---@field distance_threshold integer Maximum line distance before clearing suggestion\n---@field clear_on_large_distance boolean Whether to clear suggestion when cursor is far away\n---@field count_horizontal_moves boolean Whether to count horizontal cursor movements\n---@field reset_on_approaching boolean Whether to reset counter when approaching suggestion\n\nlocal M = {}\n\n---@class copilotlsp.config\n---@field nes copilotlsp.config.nes\nM.defaults = {\n    nes = {\n        move_count_threshold = 3,\n        distance_threshold = 40,\n        clear_on_large_distance = true,\n        count_horizontal_moves = true,\n        reset_on_approaching = true,\n    },\n}\n\n---@type copilotlsp.config\nM.config = vim.deepcopy(M.defaults)\n\n---@param opts? copilotlsp.config configuration to merge with defaults\nfunction M.setup(opts)\n    opts = opts or {}\n    M.config = vim.tbl_deep_extend(\"force\", M.defaults, opts)\nend\n\nreturn M\n"], ["/copilot-lsp/lua/copilot-lsp/types.lua", "---@class copilotlsp.InlineEdit : lsp.TextEdit\n---@field command lsp.Command\n---@field text string\n---@field textDocument lsp.VersionedTextDocumentIdentifier\n\n---@class copilotlsp.copilotInlineEditResponse\n---@field edits copilotlsp.InlineEdit[]\n\n---@class copilotlsp.nes.TextDeletion\n---@field range lsp.Range\n\n---@class copilotlsp.nes.InlineInsertion\n---@field text string\n---@field line integer\n---@field character integer\n\n---@class copilotlsp.nes.TextInsertion\n---@field text string\n---@field line integer insert lines at this line\n---@field above? boolean above the line\n\n---@class copilotlsp.nes.InlineEditPreview\n---@field deletion? copilotlsp.nes.TextDeletion\n---@field inline_insertion? copilotlsp.nes.InlineInsertion\n---@field lines_insertion? copilotlsp.nes.TextInsertion\n"], ["/copilot-lsp/lua/copilot-lsp/init.lua", "local config = require(\"copilot-lsp.config\")\n\n---@class copilotlsp\n---@field defaults copilotlsp.config\n---@field config copilotlsp.config\n---@field setup fun(opts?: copilotlsp.config): nil\nlocal M = {}\n\nM.defaults = config.defaults\nM.config = config.config\n\n---@param opts? copilotlsp.config configuration to merge with defaults\nfunction M.setup(opts)\n    config.setup(opts)\n    M.config = config.config\nend\n\nreturn M\n"], ["/copilot-lsp/plugin/copilot-lsp.lua", "vim.api.nvim_set_hl(0, \"CopilotLspNesAdd\", { link = \"DiffAdd\", default = true })\nvim.api.nvim_set_hl(0, \"CopilotLspNesDelete\", { link = \"DiffDelete\", default = true })\nvim.api.nvim_set_hl(0, \"CopilotLspNesApply\", { link = \"DiffText\", default = true })\n"], ["/copilot-lsp/lua/copilot-lsp/errors.lua", "return {\n    ErrNotStarted = \"Copilot LSP not started\",\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 00:43:00", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Render visual indicators for proposed text modifications by applying syntax-highlighted virtual text overlays and highlighting ranges for content removal within a buffer."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```lua\n[TASK_BEGIN]\nfunction M._display_preview(bufnr, ns_id, preview)\n    -- Handle deletion preview\n    if preview.deletion then\n        local range = preview.deletion.range\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, range.start.line, range.start.character, {\n            end_line = range[\"end\"].line,\n            end_col = range[\"end\"].character,\n            hl_group = config.nes.hl_group.delete,\n            hl_eol = true,\n        })\n    end\n\n    -- Handle inline insertion preview\n    if preview.inline_insertion then\n        local ins = preview.inline_insertion\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, ins.line, ins.character, {\n            virt_text = {{ins.text, config.nes.hl_group.insert}},\n            virt_text_pos = \"inline\",\n        })\n    end\n\n    -- Handle multi-line insertion preview\n    if preview.lines_insertion then\n        local ins = preview.lines_insertion\n        local lines = vim.split(ins.text, \"\\n\", { plain = true })\n        for i, line in ipairs(lines) do\n            local lnum = ins.line + (ins.above and -1 or 0) + (i - 1)\n            vim.api.nvim_buf_set_extmark(bufnr, ns_id, lnum, 0, {\n                virt_text = {{\"\" .. line, config.nes.hl_group.insert}},\n                virt_text_pos = \"eol\",\n            })\n        end\n    end\nend\n[TASK_END]\n```", "inference_time": "2025-08-21 00-44-35"}, "editdistance_info": {"edit_distance": 39.726, "calculate_time": "2025-08-21 00:44:35", "true_code_clean": "function M._display_preview(bufnr, ns_id, preview)\n    if preview.deletion then\n        local range = preview.deletion.range\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, range.start.line, range.start.character, {\n            hl_group = \"CopilotLspNesDelete\",\n            end_row = range[\"end\"].line,\n            end_col = range[\"end\"].character,\n        })\n    end\n    local inline_insertion = preview.inline_insertion\n    if inline_insertion then\n        local virt_lines =\n            require(\"copilot-lsp.util\").hl_text_to_virt_lines(inline_insertion.text, vim.bo[bufnr].filetype)\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, inline_insertion.line, inline_insertion.character, {\n            virt_text = virt_lines[1],\n            virt_text_pos = \"inline\",\n        })\n    end\n    local lines_insertion = preview.lines_insertion\n    if lines_insertion then\n        local virt_lines =\n            require(\"copilot-lsp.util\").hl_text_to_virt_lines(lines_insertion.text, vim.bo[bufnr].filetype)\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, lines_insertion.line, 0, {\n            virt_lines = virt_lines,\n            virt_lines_above = lines_insertion.above,\n        })\n    end\nend", "predict_code_clean": "function M._display_preview(bufnr, ns_id, preview)\n    if preview.deletion then\n        local range = preview.deletion.range\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, range.start.line, range.start.character, {\n            end_line = range[\"end\"].line,\n            end_col = range[\"end\"].character,\n            hl_group = config.nes.hl_group.delete,\n            hl_eol = true,\n        })\n    end\n    if preview.inline_insertion then\n        local ins = preview.inline_insertion\n        vim.api.nvim_buf_set_extmark(bufnr, ns_id, ins.line, ins.character, {\n            virt_text = {{ins.text, config.nes.hl_group.insert}},\n            virt_text_pos = \"inline\",\n        })\n    end\n    if preview.lines_insertion then\n        local ins = preview.lines_insertion\n        local lines = vim.split(ins.text, \"\\n\", { plain = true })\n        for i, line in ipairs(lines) do\n            local lnum = ins.line + (ins.above and -1 or 0) + (i - 1)\n            vim.api.nvim_buf_set_extmark(bufnr, ns_id, lnum, 0, {\n                virt_text = {{\"\" .. line, config.nes.hl_group.insert}},\n                virt_text_pos = \"eol\",\n            })\n        end\n    end\nend"}}