This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the vim category.
Last Updated: 2025-10-25
I had some poorly formatted SQL on my hands and wished to clean it up. There was
no VIM plugin that matched my needs, but I did see a handy looking external
tool, sqlformat. How could I run it on the whole file from within Vim?
Generally:
:read !{cmd} e.g. :r ! ls:{range} !{cmd},
e.g. :3,5 !ls (be careful if results of shell command are longer)% stands for "whole file range", replace the whole file with :% !{cmd}.Be aware of two differing behaviors of %:
! in the command it means the whole file (i.e. the range 1,$)! symbol (i.e. as part of the external command) it means the filename. This allows you to refer to the current file in the command.Taking all this into account, I came up with a command to format every time an SQL file is saved.:
autocmd BufWritePost *.sql :% !sqlformat