How to run vim buffer through external command

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the vim category.

Last Updated: 2024-11-23

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:

Be aware of two differing behaviors of %:

Taking all this into account, I came up with a command to format every time an SQL file is saved.:

autocmd BufWritePost *.sql :% !sqlformat