Skip to content

Instantly share code, notes, and snippets.

@eduardoarandah
Created February 7, 2025 05:43
Show Gist options
  • Save eduardoarandah/b65ad261b707f0e158734b3945059a0d to your computer and use it in GitHub Desktop.
Save eduardoarandah/b65ad261b707f0e158734b3945059a0d to your computer and use it in GitHub Desktop.
Copy context in neovim using textobjects
-----------------------------
-- Create context for the LLM
-----------------------------
-- Clear register z
vim.api.nvim_create_user_command("ContextClear", 'let @z=""', { bang = true })
-- Create a user command :CopyFunction that calls our function.
vim.api.nvim_create_user_command("ContextAddFunction", function()
-- Append relative path and line number
vim.fn.setreg("z", vim.fn.getreg("z") .. "file: " .. vim.fn.expand("%") .. " line: " .. vim.api.nvim_win_get_cursor(0)[1] .. "\n")
-- Copy local scope into register z
-- https://github.com/nvim-treesitter/nvim-treesitter-textobjects
vim.cmd('normal "Zyas')
-- Add blank line to register z and ---
vim.fn.setreg("z", vim.fn.getreg("z") .. "\n---\n\n")
end, { bang = true })
-----------
-- Mappings
-----------
-- ContextAddFunction
vim.keymap.set("n", "<leader>y", ":ContextAddFunction<CR>", { noremap = true, silent = true })
{
-- https://github.com/nvim-treesitter/nvim-treesitter-textobjects
"nvim-treesitter/nvim-treesitter-textobjects",
dependencies = {
{ "nvim-treesitter/nvim-treesitter" }, -- Required
},
config = function()
require("nvim-treesitter.configs").setup({
textobjects = {
select = {
enable = true,
-- Automatically jump forward to textobj, similar to targets.vim
lookahead = true,
keymaps = {
-- You can use the capture groups defined in textobjects.scm
-- https://github.com/nvim-treesitter/nvim-treesitter-textobjects/blob/master/README.md#built-in-textobjects
["af"] = "@function.outer", -- Select outer function
["if"] = "@function.inner", -- Select inner function
["ac"] = "@class.outer", -- Select outer class
["ic"] = "@class.inner", -- Select inner class
["as"] = { query = "@local.scope", query_group = "locals", desc = "Select language scope" },
},
},
},
})
end,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment