Last active
March 17, 2021 00:46
-
-
Save runiq/fc4be9804992cdc802ea6dcab1dabebb to your computer and use it in GitHub Desktop.
Automatically numbered print statements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local counter = 1 | |
local M = {} | |
--- Creates a function to insert customized numbered print statements. | |
--- | |
--@param context (string, default "print('%d')") The format string for the debug | |
--- statement. Should contain a single `%d`, which will be the insertion point | |
--- of the current counter value. | |
function M.debug_statement_factory(context) | |
local context = context or [[print('%d')]] | |
--- Adds numbered print statements. | |
--- | |
--- Calling the function inserts a print statement at the current cursor | |
--- position with the current counter - value and increments the counter. | |
--- The counter starts at 1. | |
--- | |
--- If the function is called with a {count}, the counter is set to {count}, a | |
--- print statement with {count} is inserted, and the counter is incremented. | |
--- | |
--@param count (number, default: current counter value) | |
return function(count) | |
local count = count ~= 0 and count or counter | |
local pos = vim.api.nvim_win_get_cursor(0) | |
local row = pos[1] - 1 -- make 0-idx'd | |
local col = pos[2] -- already 0-idx'd | |
local line = vim.api.nvim_buf_get_lines(0, row, row + 1, true)[1] | |
local _, last = line:find("^%s*") | |
local ws = line:sub(1, last) | |
vim.api.nvim_buf_set_text(0, row, last, row, last, {string.format(context, count), ws}) | |
vim.api.nvim_win_set_cursor(0, {row + 2, col}) | |
counter = count + 1 | |
end | |
end | |
-- Just a default for Lua | |
M.add_statement = M.debug_statement_factory() | |
return M |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Typing <leader>c inserts print("<current_counter_value>") and increments the counter | |
-- Typing 5<leader>c inserts `print("5")` and increments the counter | |
vim.api.nvim_set_keymap('', '<leader>c', "<cmd>lua require'add_incr_print'.add_statement(vim.v.count)<cr>", {silent=true, noremap=true}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment