A Real World VimGolf Challenge

In my CUA Mode Video post, I mentioned that the pointer to the video came from a comment to one of the posts in the Google+ Emacs Community. That post asks for advice on the best way of changing

a[0] = b[0];
a[1] = b[1];
a[2] = b[2];


c[0] = d[0];
c[1] = d[1];
c[2] = d[2];

My first thought (and what I'd probably just do if I needed this change) is a query-replace to replace a with c, followed by 【Meta+<】 to return to the top of the buffer and then another query-replace to replace b with d. That's 13 keystrokes. Not too bad but can we do better?

Here's a solution in 12 keystrokes using cua-selection-mode.

Ctrl+Return Invoke rectangle mode
Ctrl+2 Ctrl+n Form rectangle of a's
Meta+f c Fill rectangle with c's
Ctrl+7 Ctrl+f Move to last b
Ctrl+Return Invoke rectangle mode
Ctrl+2 Ctrl+P Form rectangles of b's
Meta+f d Fill rectangle with d's

Using Magnar Sveen's essential multiple-cursors package I can do it in 9 (8 if I don't exit multiple-cursors mode) with essentially the same strategy as above but, of course, that's not using stock Emacs. If you have a clever solution, leave a comment.

This entry was posted in General and tagged . Bookmark the permalink.
  • A bit off tangent, maybe, but yesterday I had use for a functionality in multiple-cursors that I thought was a "vimgolf-challenge-feature" - ie not useful in everyday life. So today I had to make it. In the newest version of multiple-cursors on MELPA, mc/insert-numbers will insert increasing numbers (starting at zero) for each cursor, from top to bottom. Optionally offset by prefix. :-)

    • jcs

      Nice. Actually, that may be useful for an upcoming VimGolf challenge.

      In my experience, in challenges where it applies, multiple-cursors almost always provides the winning strategy.

  • Here's a 11 keystroke solution without MC (and please tell me how to make the keys pretty formatted :P)

    I assume the cursor is at the first 'a'. Use this sequence

    C-6 C-f
    C-o (forward-line, not standard binding I think)

    Macros are awesome :)

    • jcs

      Macros are awesome. It's amazing how versatile they are.

      If by pretty keys you mean This, it's all CSS magic. If you just want to do them here, simply wrap the name of the key in <kbd> </kbd> tags. If you want to use it somewhere else, here's the CSS I'm using

      .kbd {
      border:solid 1px #989898;
      border-radius: 3px;
      background-color: #F4F4F4;
      padding-left: .25ex;
      padding-right: .25ex;
      font-family: monospace;

      Of course, I have some Elisp that takes care of turning ctrl+x into Ctrl+x.

    • jcs

      Also, I think you can save another keystroke by replacing the first F4 with Ctrl+3 F4 and getting rid of the last two lines of your solution.

      • Ha, nice! I didn't know about this trick. It's quite obvious now that you mentioned it :D


        PS: Yea, by pretty keys I ment how to do them on your blog.