Dozy’s Little Vim Helpers

Today: A filter for URI encoding / decoding

The script introduced in this post will read input from stdin, encode / decode URI’s and URI components and spit the result to stdout.

Required software: Vim, Bash, Spidermonkey (a javascript shell)

Use Case

Say you are working in Vim (which makes sense) and need to encode a URI component that in its unencoded form looks like so (it’s the bit after question mark):

<a href="">Your linktext here</a> 

If you run a site with standard-compliant HTML (which you should) then the above link should show up in your source like so:

<a href="">Your linktext here</a> 

Maybe you belong to those maniacs who speak, write and read hex and just type stuff like that as you go. Well congratulations, you won’t need this. If, however, you belong to the rest of us who would rather have a script do such conversions for you, then the following can help:


# take whatever came from stdin
# and park in a var
thing=$(< /dev/stdin)

# check params and act accordingly
# basically the rawurl var then holds
# a little javascript
case $1 in
rawurl="var urlin = encodeURI(\"${thing}\"); print(urlin);"
rawurl="var urlin = \"${thing}\"; var x = urlin.split(\"?\"); var y = encodeURIComponent(x[1]); print(x[0]+\"?\"+y);"
rawurl="var urlin = decodeURIComponent(\"${thing}\"); print(urlin);"

# pipe the script to Spidermonkey
# its print() built in writes the encoded
# string to stdout
echo "${rawurl}" | smjs

# get the hell out of Dodge

Park this somewhere in your path – mine sits in ~/bin/ and is called urler. Zero points for imaginative naming, as usual.


The smallest piece of information Vim can send to a filter is a line. Meaning, the bit you send to the script needs to sit on a line of its own.

This is how it works:

Write or paste your URI (component) onto a line of its own. Select with v$h to make sure that you don’t send any trailing whitespace to the script. Type : and the status line will look like :'<,'> now type ,!urler c <Enter>. Your URI component will be replaced by its encoded version.

You can of course do the same with query strings to encode / decode those pesky ampersands that just about every CMS uses as arg separators.



About dozykraut

Proud member of Hillbilly's on Linux, promoting open source redneckism in remote parts of the Milky Way.
This entry was posted in Bash and tagged , . Bookmark the permalink.

One Response to Dozy’s Little Vim Helpers

  1. Nadav says:

    This is cool. I will add a shortcut to my vimrc.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s