Skip to content

Integrating with Hydra

Ben Lubas edited this page Dec 27, 2023 · 3 revisions

hydra.nvim can make navigating a notebook and running code cells really convenient. Credit to NotebookNavigator.nvim for this great idea.

This guide assumes that you will read the hydra.nvim README if you would like to customize things even further.

The example hydra can:

  • jump between code cells
  • run code cells
  • run lines of code

Guide

1) Add hydra as a dependency in your configuration

{
    "nvimtools/hydra.nvim",
}

2) Treesitter text objects

navigation is better with treesitter, but you don't need it. You could instead use vim search, but I won't cover that here.

If you use treesitter-text-objects there are two options for queries, they're both listed in the code snippet. But the commented one needs an additional treesitter query:

Put this in /path/to/nvim_conf/nvim/after/queries/markdown/textobjects.scm only required if you're using @class query in the code block below.

;extends

(fenced_code_block (code_fence_content) @class.inner) @class.outer
-- ... other config
textobjects = {
  move = {
    enable = true,
    set_jumps = false,
    goto_next_start = {
      ["]b"] = { query = "@block.inner", desc = "next code block" },
      -- The @class.inner queries also catch on markdown headings. @block.inner does not
      -- ["]b"] = { query = "@class.inner", desc = "next block" },
    },
    goto_previous_start = {
      ["[b"] = { query = "@block.inner", desc = "previous code block" },
      -- ["[b"] = { query = "@class.inner", desc = "previous block" },
    },
  },
},
-- ... other config

3) Create the hydra

Add this to your nvim configuration, tweak the keys to your liking.

local function keys(str)
  return function()
    vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(str, true, false, true), "m", true)
  end
end

local hydra = require("hydra")
hydra({
    name = "QuartoNavigator",
    hint = [[
      _j_/_k_: move down/up  _r_: run cell
      _l_: run line  _R_: run above
      ^^     _<esc>_/_q_: exit ]],
    config = {
        color = "pink",
        invoke_on_body = true,
        hint = {
            border = "rounded", -- you can change the border if you want
        },
    },
    mode = { "n" },
    body = "<localleader>j", -- this is the key that triggers the hydra
    heads = {
        { "j", keys("]b") },
        { "k", keys("[b") },
        { "r", ":QuartoSend<CR>" },
        { "l", ":QuartoSendLine<CR>" },
        { "R", ":QuartoSendAbove<CR>" },
        { "<esc>", nil, { exit = true } },
        { "q", nil, { exit = true } },
    },
})