Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add context jump function #260

Merged
merged 3 commits into from
May 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,14 @@ However, you can use this to create a border by applying an underline highlight,
hi TreesitterContextBottom gui=underline guisp=Grey
```

## Jumping to context (upwards)

```lua
vim.keymap.set("n", "[c", function()
require("treesitter-context").go_to_context()
end, { silent = true })
```

## Adding support for other languages

To add support for another language, simply add a `context.scm` file under
Expand Down
24 changes: 24 additions & 0 deletions lua/treesitter-context.lua
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ local ns = api.nvim_create_namespace('nvim-treesitter-context')
--- @type TSNode[]?
local previous_nodes

--- @type table<integer, Context[]>
local all_contexts = {}

--- @return TSNode
local function get_root_node()
---@diagnostic disable-next-line
Expand Down Expand Up @@ -667,6 +670,8 @@ local function open(ctx_ranges)
table.insert(lno_highlights, hl)
end

all_contexts[bufnr] = contexts

set_lines(gbufnr, lno_text)
highlight_lno_str(gbufnr, lno_text, lno_highlights)

Expand Down Expand Up @@ -803,6 +808,25 @@ function M.setup(options)
end
end

function M.go_to_context()
local line = vim.api.nvim_win_get_cursor(0)[1]
local context = nil
local bufnr = api.nvim_get_current_buf()
local contexts = all_contexts[bufnr] or {}

for _, v in ipairs(contexts) do
if v.range[1] + 1 < line then
context = v
end
end

if context == nil then
return
end

vim.api.nvim_win_set_cursor(0, { context.range[1] + 1, context.range[2] })
end

command('TSContextEnable' , M.enable , {})
command('TSContextDisable', M.disable, {})
command('TSContextToggle' , M.toggle , {})
Expand Down