How can I create a keymap using treesitter to jump to the next markdown header?

I Know ts_utils and treesitter text-objects but what is the most effective way of achieving that result?

local query=vim.treesitter.query.parse('markdown','((atx_heading) @header)')
vim.keymap.set('n',']h',function ()
    local root=vim.treesitter.get_parser():parse()[1]:root()
    local _,node,_=query:iter_captures(root,0,vim.fn.line'.',-1)()
    if not node then return end
    require'nvim-treesitter.ts_utils'.goto_node(node)
end)
2 Likes

Once you gave me this amazong solution, how would it be the jump inthe oposite direction?

The native treesitter text-objects solution is this:

require'nvim-treesitter.configs'.setup {
  textobjects = {
    move = {
      enable = true,
      set_jumps = true, -- whether to set jumps in the jumplist
      goto_next_start = {
        ["]m"] = "@function.outer",
        ["]]"] = { query = "@class.outer", desc = "Next class start" },
        --
        -- You can use regex matching (i.e. lua pattern) and/or pass a list in a "query" key to group multiple queires.
        ["]o"] = "@loop.*",
        -- ["]o"] = { query = { "@loop.inner", "@loop.outer" } }
        --
        -- You can pass a query group to use query from `queries/<lang>/<query_group>.scm file in your runtime path.
        -- Below example nvim-treesitter's `locals.scm` and `folds.scm`. They also provide highlights.scm and indent.scm.
        ["]s"] = { query = "@scope", query_group = "locals", desc = "Next scope" },
        ["]z"] = { query = "@fold", query_group = "folds", desc = "Next fold" },
      },
      goto_next_end = {
        ["]M"] = "@function.outer",
        ["]["] = "@class.outer",
      },
      goto_previous_start = {
        ["[m"] = "@function.outer",
        ["[["] = "@class.outer",
      },
      goto_previous_end = {
        ["[M"] = "@function.outer",
        ["[]"] = "@class.outer",
      },
      -- Below will go to either the start or the end, whichever is closer.
      -- Use if you want more granular movements
      -- Make it even more gradual by adding multiple queries and regex.
      goto_next = {
        ["]d"] = "@conditional.outer",
      },
      goto_previous = {
        ["[d"] = "@conditional.outer",
      }
    },
  },
}

It’s a bit ruff, but here is how to do it in reverse direction

local query=vim.treesitter.query.parse('markdown','((atx_heading) @header)')
vim.keymap.set('n','[h',function ()
    local root=vim.treesitter.get_parser():parse()[1]:root()
    if vim.fn.line'.'==1 then return end
    local node
    for _,n,_ in query:iter_captures(root,0,0,vim.fn.line'.'-1) do
        node=n
    end
    if not node then return end
    require'nvim-treesitter.ts_utils'.goto_node(node)
end)