util.lua (2746B)
1 -- Nursery for random things that may later find their way into stdlib if they mature. 2 3 local M = {} 4 5 --- Adds one or more blank lines above or below the cursor. 6 -- TODO: move to _core/defaults.lua once it is possible to assign a Lua function to options #25672 7 --- @param above? boolean Place blank line(s) above the cursor 8 local function add_blank(above) 9 local offset = above and 1 or 0 10 local repeated = vim.fn['repeat']({ '' }, vim.v.count1) 11 local linenr = vim.api.nvim_win_get_cursor(0)[1] 12 vim.api.nvim_buf_set_lines(0, linenr - offset, linenr - offset, true, repeated) 13 end 14 15 -- TODO: move to _core/defaults.lua once it is possible to assign a Lua function to options #25672 16 function M.space_above() 17 add_blank(true) 18 end 19 20 -- TODO: move to _core/defaults.lua once it is possible to assign a Lua function to options #25672 21 function M.space_below() 22 add_blank() 23 end 24 25 --- Edit a file in a specific window 26 --- @param winnr number 27 --- @param file string 28 --- @return number buffer number of the edited buffer 29 M.edit_in = function(winnr, file) 30 local function resolved_path(path) 31 if not path or path == '' then 32 return '' 33 end 34 return vim.fn.resolve(vim.fs.abspath(path)) 35 end 36 37 return vim.api.nvim_win_call(winnr, function() 38 local current_buf = vim.api.nvim_win_get_buf(winnr) 39 local current = resolved_path(vim.api.nvim_buf_get_name(current_buf)) 40 41 -- Check if the current buffer is already the target file 42 if current == resolved_path(file) then 43 return current_buf 44 end 45 46 -- Read the file into the buffer 47 vim.cmd.edit(vim.fn.fnameescape(file)) 48 return vim.api.nvim_get_current_buf() 49 end) 50 end 51 52 --- Read a chunk of data from a file 53 --- @param file string 54 --- @param size number 55 --- @return string? chunk or nil on error 56 function M.read_chunk(file, size) 57 local fd = io.open(file, 'rb') 58 if not fd then 59 return nil 60 end 61 local chunk = fd:read(size) 62 fd:close() 63 return tostring(chunk) 64 end 65 66 --- Check if a range in a buffer is inside a Lua codeblock via treesitter injection. 67 --- Used by :source to detect Lua code in non-Lua files (e.g., vimdoc). 68 --- @param bufnr integer Buffer number 69 --- @param line1 integer Start line (1-indexed) 70 --- @param line2 integer End line (1-indexed) 71 --- @return boolean True if the range is in a Lua injection 72 function M.source_is_lua(bufnr, line1, line2) 73 local ok, parser = pcall(vim.treesitter.get_parser, bufnr) 74 if not ok or not parser then 75 return false 76 end 77 -- Parse from buffer start through one line past line2 to include injection closing markers 78 local range = { line1 - 1, 0, line2 - 1, -1 } 79 parser:parse({ 0, 0, line2, -1 }) 80 local lang_tree = parser:language_for_range(range) 81 return lang_tree:lang() == 'lua' 82 end 83 84 return M