
Vim has a lot of cool features, and one of them is the ability to take the text you are editing and run it through whatever text-parsing tool you like.
This tool can be a shell command, a standalone executable, or your very own script in your favorite scripting language.
The magic is all in this vim command:
:%!<shell command>
This will dump your buffer as standard output to the shell command and replace it with whatever the output of that command is.
You can also use this to fill up your buffer with text from a command, without having to switch to a console and copy-paste it. For example, this works fine:
:!dir *.*
But on with the magic stuff. Let’s use PowerShell to URL encode or decode text we have in our Vim buffer.
To set this up, we first need a PowerShell script that does just that. Through the power of .NET, this is pretty easy.
Here’s my decode-string.ps1
script:
[Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null
[System.Web.HttpUtility]::UrlDecode($input)
This is the encode-string.ps1
script:
[Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null
[System.Web.HttpUtility]::UrlEncode($input)
There is one trick to make this all work: the $input
variable.
This magic variable will automatically contain all the input piped into the command, so you don’t need to specify an input parameter. It’s one of the automatic variables in PowerShell, just like $_
.
Once you have these, all we need to do is set up some Vim bindings in our vimrc file to make this super easy to trigger.
nnoremap <Leader>dc :%!powershell.exe -noprofile -nologo -file c:\mytools\decode-string.ps1<CR>
nnoremap <Leader>ec :%!powershell.exe -noprofile -nologo -file c:\mytools\encode-string.ps1<CR>
What we do here is paste the current buffer’s text with %!
to our script, by running the powershell.exe
command. Passing in the -noprofile
and -nologo
make it run faster, because it skips loading custom user profile scripts.
From now on I can paste a URL encoded string in my Vim, press <leader>dc and *bam*, I have the decoded text right there.
Nothing is stopping you from using this for all sorts of text manipulations. You could use this to generate and format code for example. A JSON formatter is an option, although I use the jdaddy plugin for that. You don’t have to use PowerShell either. You can use any command line tool or scripting language you like, as long as it uses standard input & output, and can be called from the command line in Vim.
Happy hacking!