Last active
July 2, 2021 15:56
-
-
Save nfrid/7c7fffe7de60d06ada1ef9d6260df0a9 to your computer and use it in GitHub Desktop.
Easy and cool auto formatter/prettier implementation for neovim's init.lua
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
Format = function() | |
vim.api.nvim_command(":w") -- save first | |
local formatCmds = { -- these are just commands that formatting files next to them 'in-place' for each filetype | |
lua = 'lua-format --indent-width=2 --spaces-inside-table-braces -i', | |
go = 'gofmt -w', | |
javascript = 'prettier -w --loglevel error', | |
typescript = 'prettier -w --loglevel error', | |
javascriptreact = 'prettier -w --loglevel error', | |
typescriptreact = 'prettier -w --loglevel error', | |
json = 'prettier -w --loglevel error', | |
css = 'prettier -w --loglevel error', | |
scss = 'prettier -w --loglevel error', | |
cmake = 'cmake-format -i', | |
c = 'clang-format -style=file -i', | |
cpp = 'clang-format -style=file -i', | |
markdown = 'prettier -w --prose-wrap always --loglevel error', | |
python = 'black -q' | |
} | |
local cmd = formatCmds[vim.bo.filetype] or 'sed -i -e "s/\\s\\+$//"' -- set command or sed trailing whitespace if not specified | |
local f = io.popen(cmd .. ' "' .. vim.api.nvim_buf_get_name("%") .. '" 2>&1') | |
print(f:read('*all')) -- error to status to know what the fuck happened | |
f:close() | |
vim.api.nvim_command("let tmp = winsaveview()") | |
vim.api.nvim_command("e!") -- these three are reloading buffer saving your window's view | |
vim.api.nvim_command("call winrestview(tmp)") | |
vim.api.nvim_command("IndentBlanklineRefresh") -- this is for a plugin 'blankline', remove it if don't have it | |
-- and other refreshing stuff if needed | |
end | |
-- now map the key, gonna exec vimscript for simplicity | |
vim.exec('map <silent> <leader>F :lua Format()<CR>') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment