1

I'm trying to insert a table of contents with an external process. Currently, I have this:

.config/nvim/after/ftplugin/markdown.lua

--- @param v boolean
local function toc(v)
  if v then
    vim.cmd([['<,'>d]])
    vim.cmd("w")
  end
  vim.cmd([[ exe 'r!md-toc --indent 2 %' ]])
end
vim.keymap.set("n", "<localleader>T", toc, { desc = "insert toc" })
vim.keymap.set("v", "<localleader>T", function() toc(true) end, { desc = "insert toc" })

This works for normal mode, but for visual mode, I get:

   Error  13:23:19 msg_show.emsg E5108: Error executing lua: vim/_editor.lua:0: nvim_exec2(): Vim(delete):E20: Mark not set
stack traceback:
    [C]: in function 'nvim_exec2'
    vim/_editor.lua: in function 'cmd'
    /Users/h4s/commons/.config/nvim/after/ftplugin/markdown.lua:4: in function 'toc'
    /Users/h4s/commons/.config/nvim/after/ftplugin/markdown.lua:10: in function </Users/h4s/commons/.config/nvim/after/ftplugin/markdown.lua:10>

I'm not sure why these marks go away when I call the function. How can I have access to the range within the function?

1 Answer 1

1

I would do:

--- @param v boolean
local function toc()
  vim.cmd([[ exe 'r!md-toc --indent 2 %' ]])
end
vim.keymap.set("n", "<localleader>T", toc, { desc = "insert toc" })
vim.keymap.set("v", "<localleader>T", ":d<CR>:normal <localleader>T<CR>", {})

The problem you have is that the '< and '> marks are only set after the Visual selection has been cleared.

4
  • I saw somewhere about the range markers not being set until the selection was cleared, so I tried various ways of escaping to address that, without success. But I don't see how you code sample addresses this. So, is <c-s> some copypasta from an example. I'm just a bit confused.
    – theherk
    Mar 7 at 15:02
  • Sorry for the copy paste (I copy the code I tested on my machine where <localleader>T is already mapped to something else :-|). The strategy of the code is to trigger the deletion on the current selection (using :d) and then use the Normal mode and the normal mode mapping to insert the table of content. Mar 7 at 15:08
  • 1
    Oh yeah, that makes perfect sense now, and is a simpler solution. Thanks a ton.
    – theherk
    Mar 7 at 15:08
  • 1
    Thanks for the feedback :-) Mar 7 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.