nvim-treesitter / nvim-treesitter-context

Show code context
MIT License
2.5k stars 201 forks source link

Allow jumping to nearest context with go_to_context() #453

Open toupeira opened 4 months ago

toupeira commented 4 months ago

I wanted to have a mapping to jump to whatever is the current "parent" node, and found the go_to_context() function which works great! But it only jumps to contexts that are also displayed by the plugin, and I'd like this mapping to be more granular and also consider contexts that are in view, or hidden by my max_lines setting.

I managed to hack something together if I expose the iter_context_parents function from the plugin:

-- add in `lua/treesitter-context/context.lua`
M.iter_context_parents = iter_context_parents

-- in my mapping:
local context = require('treesitter-context.context')
local cursor = vim.api.nvim_win_get_cursor(0)
local row = cursor[1]
local parents, _query = context.iter_context_parents(0, { row - 1, 0, row - 1, 0 })()

for i = 1, #parents do
  local parent_row = parents[i]:range() + 1
  if parent_row < row then
    vim.cmd([[ normal! m' ]])
    vim.api.nvim_win_set_cursor(0, { parent_row, 0 })
    vim.cmd.normal('^')
    return
  end
end

This seems to work how I want, and now I wonder what it would take to implement a cleaner version of this inside the plugin, or what bits could be exposed to allow a custom mapping like this (iter_context_parents seems a bit too low-level).

Also not sure if there's a way to do this using e.g. nvim-treesitter-textobjects, it seems the magic sauce that's needed are the queries collected in this plugin.