Last active
December 11, 2024 21:46
-
-
Save mkatychev/0ac9b4144899edb81451993270881776 to your computer and use it in GitHub Desktop.
Tiny Neovim buffer formatter in lua
This file contains hidden or 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 read_buf = function(bufnr) | |
local bufin = table.concat(vim.api.nvim_buf_get_lines(bufnr, 0, -1, true), "\n") | |
if vim.api.nvim_get_option_value("eol", { buf = bufnr }) then bufin = bufin .. "\n" end | |
return bufin | |
end | |
local format_buf = function(fmt_cmd) | |
-- exit early if buffer is not writeable | |
if vim.bo.modifiable == false or vim.bo.readonly == true then return end | |
-- save cursor position | |
local save_cursor = vim.fn.getpos(".") | |
local save_view = vim.fn.winsaveview() | |
local bufin = read_buf(vim.fn.bufnr("%")) | |
local bufout = vim.fn.system(fmt_cmd, bufin) | |
if vim.v.shell_error ~= 0 then | |
print(bufout) | |
return | |
end | |
if bufout == bufin then | |
return | |
end | |
local new_lines = vim.fn.split(bufout, "\n") | |
vim.api.nvim_buf_set_lines(0, 0, -1, false, new_lines) | |
-- restore cursor position | |
vim.fn.setpos(".", save_cursor) | |
vim.fn.winrestview(save_view) | |
end | |
-- example use case | |
autocmd("BufWritePre", { | |
pattern = { "*.py", "*.lua" }, | |
callback = function() | |
local fmt_cmd_table = { | |
["lua"] = "stylua --indent-width 2 -", | |
["python"] = "ruff format -", | |
} | |
format_buf(fmt_cmd_table[vim.bo.filetype]) | |
end, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment