Skip to content

Commit

Permalink
feat: add context helper functions
Browse files Browse the repository at this point in the history
  • Loading branch information
alisnic committed May 2, 2023
1 parent e1dc868 commit baa8047
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,25 @@ However, you can use this to create a border by applying an underline highlight,
hi TreesitterContextBottom gui=underline guisp=Grey
```

## Jumping to previous context (upwards)

```lua
local ts_context = require "treesitter-context"

vim.keymap.set("n", "[c", function()
local context = ts_context.previous_context()

if context == nil then
return
end

vim.fn.setpos(
".",
{ 0, context.range[1] + 1, context.range[2] }
)
end, { silent = true })
```

## Adding support for other languages

To add support for another language, simply add a `context.scm` file under
Expand Down
22 changes: 21 additions & 1 deletion 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 Context[]
local contexts = {}

--- @return TSNode
local function get_root_node()
---@diagnostic disable-next-line
Expand Down Expand Up @@ -636,7 +639,7 @@ local function open(ctx_ranges)
local context_text --[[@type string[] ]] = {}
local lno_text --[[@type string[] ]] = {}
local lno_highlights --[[@type table[] ]] = {}
local contexts --[[@type Context[] ]] = {}
contexts = {}

for _, range0 in ipairs(ctx_ranges) do
local lines, range = get_text_for_range(range0)
Expand Down Expand Up @@ -799,6 +802,23 @@ function M.setup(options)
end
end

function M.get_contexts()
return contexts
end

function M.previous_context()
local line = vim.api.nvim_win_get_cursor(0)[1]
local result = nil

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

return result
end

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

0 comments on commit baa8047

Please sign in to comment.