Wednesday, April 9, 2014

My Choicest Plugins

Some stuff sucks less.

I’ve written a lot of plugins for Vim in the… four years that I’ve been a Vim plugin dev. Sixty five at the time of writing, by my count. Some of them are even useful. Here are twenty of my favourite plugins. Enjoy. :-)

Note
  • Credit where due: Many of my plugins were co-written with the help of the indefatigable Israel Chauca (better know to vimmers as the lovable Raimondi).
  • Plugins are shown here in github stargazer rank, highest to lowest in each category. It’s not much of a metric as far as I’m concerned, but at least it’s more than just my opinion.

The Crowd Pleasers:
Go, you Good Thing!

Useful If Not (Yet?) Popular:
All puppies deserve love.

Learning Resources:
By far the most popular of my contributions:

Fringe:
Scary shit you never knew Vim could do:

There’s something in there for everyone. For questionable values of everyone. But if you’re in the set, \o/

Sunday, April 6, 2014

Seconds Count, Not Keystrokes


It’s not how short it is that matters, it’s how quick you are.
at the keys, not under the sheets
— Vimmers

Golf: A good edit ruined.

The Problems:
  • Vim Golf optimises on the wrong thing: keystrokes
  • Vim Golf demands a bare-metal Vim

Least Number of Keystrokes

Banging out thirty characters in a few seconds to solve a problem is immeasurably better than spending several minutes contemplating the fewest keystrokes possible to achieve the same result. The point here is, time is a better metric to test yourself against. Can you solve this problem any faster than the last time you tried? Perhaps since then, you’ve crafted a new map or text-object or macro to simplify the task. Isn’t that exactly what Vimmers should be doing? It is Bram’s key point in Seven Habits of Effective Text Editing suggestions, after all.

Bare-Metal Vim

EVERYONE uses a more able Vim than what Vim Golf insists upon. Everyone has better features enabled, Useful Plugins, and custom commands, maps and abbreviations to lighten their editing load. I get that competition requires a level playing field, but that in turn is hindering the competitors. Vimmers walk away from their morning on the golf course with less than they should. They should be able to utilise everything they practised.


Playa:  Aw… but how can I show my l33t skilz? :-(
Vimmer:  Play Vim Golf


Is There No Place for Vim Golf?

Of course there is. It has its uses. If you like playing, keep at it. I’ve seen positive effects in some Vimmers. I implied earlier that "spending minutes contemplating a fewer keystroke alternative" was inefficient and that you’d be better served by sticking to a more verbose alternative that you know well. To be clear, what I mean here is that if what you craft on the golf course is arcane, complex and immemorable (albeit awesomely short), you will end up not using it in your daily editing. Sure, you could try to make it a habit, but then you run into problem #2 — don’t remember a cryptic collage of keystrokes when Vim can do it for you, in a map, say.

Learning shorter ways to get stuff done in Vim is fun and enlightening. I know. I’ve spent many hours on this journey too. But it is a journey; the benefit comes from the process, not the product. Learning that there is a keystroke that lets you type Normal Mode commands in Insert Mode is eye-opening and, at first, spawns a desire to play with this shiny new toy. The Learned Vimmer soon realises though that this shiny new bauble is better left in the box and only taken out when maps are being made.
  • The process: discovery, assessment & assimilation.
  • The product: a new command that you really shouldn’t use when live-typing.

You want to learn every feature the editor offers and use the most efficient command all the time.
You will waste a lot of time learning things you will never use.

Seven Habits of Effective Text Editing - How not to edit effectively
— Bram Moolenaar


Perfect Practice Makes Perfect

Practice doesn’t make perfect. Perfect practice makes perfect.
Charles Birch
— Taekwondo Master
I learnt that quote first-hand from the inimitable Mr Birch. I internalised it at the time, reflect on it frequently, and counsel my own students likewise.

The point of the quote is: If you practice the wrong thing, then you’ll learn well to do it wrong. An additional note here is that repairing a bad habit costs more than learning good habits to begin with. The apocryphal metric tossed about on the training floor was: it takes 50 repetitions to learn a new move, and 200 to unlearn a bad one. Regardless of the accuracy of those particular numbers, the phenomenon it describes is nonetheless very real.


A Better Way

Use Your Vim, Luke

Vim Golf requires that you use a crippled Vim. No. Use your Vim. You’ve grown your ~/.vimrc with its suite of maps, abbreviations, commands and functions designed around your Vimming habits, and you’ve installed plugins that further enhance your editing prowess. Use them! Practice them. Cultivate them: throw away bad ones; repair broken ones; develop new ones.

Compete Against Younger You

Instead of comparing your keystroke length to that of others, you’re better off competing against your own Personal Best times for the editing task at hand.

Method

  1. Grab an editing task. These can come from your own experience or you can just use those on Vim Golf.
  2. Reflect on your prior attempt of this problem (you are repeating your practice exercises, right?!)
  3. Grab your stopwatch; time your execution; record the results.
  4. Reflect again. How did you go? Did you improve your Personal Best time? If not, why not? What are the time-sinks? What can you improve? Would a map help? Or a macro? A plugin?

Macros, Such Fleeting Pleasures
Have you ever crafted an awesome macro to refactor code, or munge data into structures, or perform a tedious operation that frequently arises in this particular file, task or programming language, only to lose all that effort when you close Vim? Sure, with :help 'viminfo you can have Vim persist your registers (in which your macros are stored), but their fragile nature means that you or any one of your plugins can overwrite them without warning.
VimLocalMacros was written to solve this problem. It stores the contents of registers inside comments within the current file so that when you come back to the file, you can restore the registers and have your macros at the ready without having to remember and recreate them over and again.

Those four steps sound easy enough, right? It couldn’t get any easier! Er, well, this is Vim. Of course it could be easier! :-) Get to the VimGym and let it handle all that finicky stuff, like:
  • keeping an extendible store of practice exercises
  • timing your attempts and storing the results
  • analysing your game, suggesting improvements and forcing extra practice in problem areas

VimKata was one of the very first Vim plugins I ever worked on, and so it was therefore doomed to failure from the outset. I didn’t have the skills necessary to tackle such a beast. I didn’t know how to build it; I didn’t know what to focus on; I didn’t know what I didn’t know.
VimGym is less than VimKata in some ways and therefore so very much more.

So, in summary, my thoughts on Vim Golf and Deliberate Practice for Vim are:
  • Vim Golf hobbles Vimmers by limiting them to an unrealistically featureless Vim
  • Vim Golf measures the wrong thing: time taken to complete the task is more important than the number of keystrokes
  • Improvement in a skill comes from repeatedly attempting tasks that are at the edge of your abilities and getting feedback on performance. Ideally this would come from an expert, but VimGym uses the task completion time as an acceptable fallback.
  • Vimmers should be adopting a Seven Habits to Effective Text Editing approach to Vimming whereby they identify inefficiencies, craft improvements, and exercise them to make them habitual.

Whether you choose to go it alone, stick with just VimGolf, or try VimGym too, I wish you well on your journey.

Saturday, March 22, 2014

Closures in VimL


I’ve talked about Anonymous Functions in VimL before, but what about closures?

What is necessary for a language to be able to say that it supports closures? What is sufficient for someone to be able to fake their way through it?

Here is the first example from Wikipedia’s Closure article:


def start(x):
    def increment(y):
        return x+y
    return increment

first_inc = start(0)
second_inc = start(8)

first_inc(3)   # returns 3
second_inc(3)  # returns 11

# The x value remains the same for new calls to the function:
first_inc(1)   # returns 1
second_inc(2)  # returns 10

Here is a faked-up alternative in VimL:


function! Start(x)
  let obj = {}
  let obj.x = a:x
  func obj.increment(y)
    return self.x + a:y
  endfunc
  return obj
endfunction

let first_inc = Start(0)
let second_inc = Start(8)

echo first_inc.increment(3)
echo second_inc.increment(3)

echo first_inc.increment(1)
echo second_inc.increment(2)

Okay, so not really what you think of as a closure, but it lets you get similar things done. Wikipedia says:
Closures are typically implemented with a special data structure that contains a pointer to the function code, plus a representation of the function’s lexical environment (i.e., the set of available variables) at the time when the closure was created.
— Wikipedia
The manual marshalling in our object-oriented implementation above probably doesn’t count, but it’s a similar idea… isn’t it?

Vim certainly has First Class Functions and with VimaholicsAnonymous, it has Anonymous Functions… Does it have closures? If not… does it matter? Can you achieve something similar using its prototypal object notation?

Vimmy the Pooh


Vimmy the Pooh
"When you first wake up in the morning, Pooh," said Piglet at last, "what’s the first thing you say to yourself?"
"What to edit?" said Vimmy the Pooh. "What do you say, Piglet?"
"I say, I wonder what’s going to happen exciting today?" said Piglet.
Pooh nodded thoughtfully. "It’s the same thing," he said.
kudos to watabou for the name.

Friday, March 21, 2014

Oh Vim, you so pretty

Oh Vim, you so pretty

— willmarshall on #vim

Aye, the years have been kind to Vim. She started out quite a plain lass from a simple, hard-working folk who didn’t have the means for the finer things in life. She toiled hard throughout her early years, learning and adapting to the changing workplace and ever increasing demands of her clients. Along the way, the awkward young girl blossomed into the stately matron Vim is today; masterly capable at her job and stylishly dressed at it.

When I started coding, on a C64, it was in a simple B&W editor. Then I upgraded to TurboC (<3) where I had the luxury of a couple of colours on that pleasant blue background. At uni, we had a massive line printer that screamed source code line at a time in a consistently jagged font with letters variously on, above or below the intended baseline; reading printouts was a necessary evil back then. When I saw my first printout from TurboC (or was it Turbo Pascal?) with its bold keywords and italics comments, I was in love. These days, with a thousand colour schemes containing millions of colours across dozens of colourable screen sections… we’re spoilt for choice, and waste our time exploring accordingly. Pick a colorscheme that doesn’t make you rage; get on with your real task.

Personally, for Vim I tolerate: jellybeans, eddie and neverland.

Sunday, March 2, 2014

Welcome to the Search Party

Enhanced searches, highlights and matches for Vim

Raimondi and I wrote a nifty little plugin and, well, we’d like to invite you to join the SearchParty.

SearchParty has these awesome features:

Visual Searches

  • * Searches for the next occurrence of the currently selected visual text.
  • # Searches for the prior occurrence of the currently selected visual text.
  • & Starts a :substitute using the currently selected visual text.
I’ve had a goodly amount of <3 on #vim for the visual & command.

Literal Search

<leader>/ prompts for a literal string to search for. This does NOT use a regular expression, so the characters you type here will be searched for literally without any magic interpretation. The <Up> key scrolls through the prior literal search history.

This one is a real crowd pleaser. People come for the highlight candy, but they stay for Literal Search.

Ranged Search


    :7,12 RSearch foo
Searches for "foo" only within the range from lines 7 through 12, both inclusive. The default range is % (the whole buffer).

Tip The normal next and previous keys (n and N) cycle within the range.

Multiple Replacements

<leader>mp prompts for a Search term and then prompts for space separated Replacement terms (use \\ to escape desired spaces). The current line is then duplicated as many times as there are replacements, minus one, and the Search term is then replaced on each line with each successive Replacement.

Perhaps an example would far better explain this:

Given the line:

   Don't credit it on the sunshine

With the cursor on that line, the command:

<leader>mp

Followed by:

Search:credit
Replace:blame

Will produce:

   Don't blame it on the sunshine

That’s no better than :s/// I know, but with the cursor still on the same line, check it:

<leader>mp

Followed by:

Search:sunshine
Replace:moonlight good\ times

Will produce:

   Don't blame it on the sunshine
   Don't blame it on the moonlight
   Don't blame it on the good times

Note Blaming it on the boogie is left as an exercise for the reader.

Search Highlighting

IIRC, this is where SearchParty all began — the ability to easily highlight the word under the cursor without silly machinations like: *#
  • <C-L> Temporarily clears search highlight.
  • <C-BSlash> Toggles search highlighting.
  • <leader>* Highlights all occurrences of word under the cursor.
  • <leader>mah Toggle automatic highlight of all occurrences of word under cursor.
  • <leader>g* Highlights all occurrences of WORD under the cursor.
Note You might think that <leader>mah is a bit verbose but toggling automatic word highlighting is not something I think you’ll need to do very often. If it does bother you, though, this mapping and all of the mappings in SearchParty are <Plug> maps, so you can customise them to your own tastes. Instructions for doing so are in the plugin docs.

Highlighting Print Command

Modern grep commands highlight the search term within the resulting lines (if you so desire). With SearchParty, Vim’s :g// command does too now:

    :g/something/P
Will show the matching lines with all occurrences of "something" on those lines highlighted.

Tip This command can also be used for an arbitrary range and it will highlight the most recent search pattern (@/) within those lines. E.g.:

    :10,20P

Set Search

Sometimes you’d like to highlight that word over there without having to go there, use <leader>* on it, and come back. <leader>ms is the answer.

Matches

This is one of my personal favourites — the ability to have up to six different strings highlighted in big, bold, bright colours all across the screen wherever they appear. The <leader>mm command prompts you for a string (kindly inserting the current word for you) to highlight. If you go past six then the first one is forgotten and replaced with your latest string (cycling like this ad infinitum). I find this useful for ensuring that a few particularly important strings don’t escape my attention throughout a document.

M.A.S.H.

Lastly, we have the Motion Activated Search Highlighter: when you press n/N/#/*/g#/g*, it highlights the match under the cursor differently to all the other matches on screen (if you have :set hlsearch activated). If you don’t use hlsearch, then it will still highlight the current match.

I really like this feature. I used to find it difficult to see where my cursor was when it was within a highlighted search term — the other similarly highlighted blobs would all compete for my attention. M.A.S.H makes this a no-brainer now.

SearchParty

So, welcome to the party. Grab yourself a buffer and get highlighting, make some matches or MASH out on the lounge. Enjoy your evening.

Saturday, February 22, 2014

neovim

I am quite excited by the promise of neovim, the most recent go at re-thinking Vim.

This project isn't a re-write. That's good. I think a whole re-write is a bad idea. They're starting with the modest goal of cleaning up the cruft that is the current Vim C pool and make system. Nicely played.

They have bigger ambitions though, like completely revamping the plugin system and catering for arbitrary GUIs through coprocesses, as well as the Holy Vim dream of embedding our beloved editor in foreign hosts through a Vim Library model. Sounds lovely.

I wish them well and will be cheering at the sidelines. I might even find a way to contribute if I get the chance.

Go, you good thing!