Skip to content

Instantly share code, notes, and snippets.

@chenasraf
Last active October 1, 2023 22:21
Show Gist options
  • Save chenasraf/0c64be1f1092b226790931efd4886716 to your computer and use it in GitHub Desktop.
Save chenasraf/0c64be1f1092b226790931efd4886716 to your computer and use it in GitHub Desktop.
nvim format with custom formatters support

nvim format with custom formatters support

This format function is great to use on any languages not supported by your current LSP or when you are trying to pass custom arguments.

This example shows how dart format can be used to reformat the current buffer (so the file save state is irrelevant), replace the buffer with the new contents, and put the cursor back in position.

We prevent the need to escape any variables or tokens inside by using bash heredoc so there should be no problems with \n or $ and the likes.

If there are errors, it won't do the replacement, and show the error in the nvim error log.

The other examples weren't tested, but they are there to get you started, maybe.

local function external_format_stdin(filetype, format_cmd)
if vim.bo.filetype == filetype then
local newline = "\n"
local buftxt = table.concat(vim.api.nvim_buf_get_lines(0, 0, -1, false), "\n")
local command = format_cmd .. [[ <<-'EOF']] .. newline .. buftxt .. newline .. [[EOF]]
local output = vim.fn.system(command)
local err = vim.v.shell_error
if err ~= 0 or output == "" or string.find(output, "command not found:") then
error("Error: " .. err .. ": " .. output)
end
local lines = vim.split(output, "\n")
vim.api.nvim_buf_set_lines(0, 0, -1, false, lines)
return true
end
return false
end
local function format()
local formatters = {
-- ["lua"] = "lua-format -i",
-- ["python"] = "black -",
-- ["sh"] = "shfmt -i 2 -ci -s -bn",
-- ["javascript"] = "prettier --stdin-filepath ${INPUT}",
-- ["typescript"] = "prettier --stdin-filepath ${INPUT}",
-- ["typescriptreact"] = "prettier --stdin-filepath ${INPUT}",
["dart"] = "dart format --output show",
}
for filetype, format_cmd in pairs(formatters) do
if external_format_stdin(filetype, format_cmd) then
return
end
end
vim.lsp.buf.format({ bufnr = vim.api.nvim_get_current_buf() })
vim.api.nvim_echo({ { "Formatted", "Type" } }, true, {})
end
vim.keymap.set("n", "<Leader>f", format, { desc = "[nolsp] format" })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment