All Hail The Mighty Vim

17th June 2018

Vim is a cruel learning curve, it's a long way from modern text editors, and yet it is still a popular choice for programmers. Why?! Because it's worth it. There are many things Vim does well, many things that I could use to show it off. But for this post, I had to choose only one thing, which is evaluating commands.


THE EXAMPLE used is complete nonsense, designed just to show off what Vim can do. I’ve turned off my plugins so this is just raw Vim. Let’s break it down.

Vim editing HTML using Python3
Vim editing HTML using Python3

<ul>

FIRST JOB is a simple one, <ESC> is the escape key, <CR> is return key:

i <ul><ESC> yyp a / <ESC> O <CR><CR><CR><ESC> kk
This translates as “go into insert mode type in <ul> yank that line and paste it below, after the cursor add a / then go back to normal mode.” That gives us:

<ul>
</ul>

And saves a whole key-stroke! The rest is putting a gap between the <ul> tags for the <li> tags, so O puts a blank line above, I hit <CR> more than needed, and k moves us back up.

Wait, Is That Python?!

YES, YES it is. Just for fun, I import randint from random and use it to print out some random numbers between <li> tags.

from random import randint
for _ in range(15):
    print(f"  <li>{randint(0,9)}</li>")

Then I run that code as a file, the output replaces it! Vim is magic!. Here’s how I did that:

vip :!python3<CR>
This translates as “visual mode (v), select in the paragraph (ip), run the shell command(:!) python3”. And that’s it, Vim’s magic will do the rest. The quirks around using this are that the selected text is treated like a file input, Vim will replace the selected text with whatever was output to stdout. This includes errors! If you made a mistake, u to undo!

Bash Power

AS THE selected text is input as a file and replaced with the output given to stdout, you can use your shell programs and scripts. So to finish off I select the new output and pass it to sort piped into uniq:

vip :!sort|uniq<CR>

Tidying Up

FOR THE sake of completeness, I finish off with deleting the blank lines:

k dd } 2dd

This translates as “up a line (k), delete line (dd), go to end of paragraph (}), delete two lines (2dd).”

Conclusion

YES VIM is quite a learning curve. But it’s powerful stuff and works under harsh coding environments. When you get used to it, you really miss it everywhere else you’re typing! Hopefully this will have inspired you to take a look, or if you’re already a Vim user, maybe given you some ideas of using code to help with some tasks.

Post Tags


All Tags



LIFE IS better when we share.


Comments

JOIN THE conversation: awesome comments.