diff options
Diffstat (limited to 'runtime/ftplugin/help.lua')
-rw-r--r-- | runtime/ftplugin/help.lua | 53 |
1 files changed, 52 insertions, 1 deletions
diff --git a/runtime/ftplugin/help.lua b/runtime/ftplugin/help.lua index 8d991be0e4..a6169a1d9d 100644 --- a/runtime/ftplugin/help.lua +++ b/runtime/ftplugin/help.lua @@ -31,5 +31,56 @@ vim.keymap.set('n', 'gO', function() require('vim.vimhelp').show_toc() end, { buffer = 0, silent = true }) -vim.b.undo_ftplugin = (vim.b.undo_ftplugin or '') .. '\n exe "nunmap <buffer> gO"' +-- Add "runnables" for Lua/Vimscript code examples. +---@type table<integer, { lang: string, code: string }> +local code_blocks = {} +local tree = vim.treesitter.get_parser():parse()[1] +local query = vim.treesitter.query.parse( + 'vimdoc', + [[ + (codeblock + (language) @_lang + . + (code) @code + (#any-of? @_lang "lua" "vim") + (#set! @code lang @_lang)) +]] +) +local run_message_ns = vim.api.nvim_create_namespace('nvim.vimdoc.run_message') + +vim.api.nvim_buf_clear_namespace(0, run_message_ns, 0, -1) +for _, match, metadata in query:iter_matches(tree:root(), 0, 0, -1) do + for id, nodes in pairs(match) do + local name = query.captures[id] + local node = nodes[1] + local start, _, end_ = node:parent():range() + + if name == 'code' then + vim.api.nvim_buf_set_extmark(0, run_message_ns, start, 0, { + virt_text = { { 'Run with `g==`', 'LspCodeLens' } }, + }) + local code = vim.treesitter.get_node_text(node, 0) + local lang_node = match[metadata[id].lang][1] --[[@as TSNode]] + local lang = vim.treesitter.get_node_text(lang_node, 0) + for i = start + 1, end_ do + code_blocks[i] = { lang = lang, code = code } + end + end + end +end + +vim.keymap.set('n', 'g==', function() + local pos = vim.api.nvim_win_get_cursor(0)[1] + local code_block = code_blocks[pos] + if not code_block then + vim.print('No code block found') + elseif code_block.lang == 'lua' then + vim.cmd.lua(code_block.code) + elseif code_block.lang == 'vim' then + vim.cmd(code_block.code) + end +end, { buffer = true }) + +vim.b.undo_ftplugin = (vim.b.undo_ftplugin or '') + .. '\n exe "nunmap <buffer> gO" | exe "nunmap <buffer> g=="' vim.b.undo_ftplugin = vim.b.undo_ftplugin .. ' | call v:lua.vim.treesitter.stop()' |