Tuesday, July 30, 2013

Fibonacci Number with Vim

The goal of the blog is to generate a series of Fibonacci numbers (from Start to End) with VIM ---- the best text editor known to human beings. 

[For Vim newbies] Oh really you are not using VIM? If you run a Mac or Linux machine, you can open up a terminal, and type in vi anything, then you will see the checkout point as below.

Start:
End:

Vim Magic

Please type in the following characters:
i*<ESC>Ypqak2YGpgJq20@a:%!awk<space>'{print<space>length}'
Bang! Check out what you've got now. 

Step by Step Explanation

  • i: switch to edit mode
  • <ESC>: switch to navigation mode
  • Y: yank current line
  • p: paste buffer
  • qa: record a sequence of operations registered as 'a'
  • k: go up by a line
  • 2Y: yank 2 lines
  • G: go to last line
  • p: paste buffer
  • gJ: join lines
  • q: finish recording
  • 20@a: execute 'a' 20 times
  • :: open command line
  • !awk<space>'{print<space>length}': execute AWK command
The last step is definitely cheating, makes the script somewhat ugly because it's no longer pure vim script. However, the beauty of this script is until last command, there is not any number involved. All the Fibonacci logic is done by less than 20 characters. It's too soon to be impressed, this is  only tip of the iceberg of what Vim can do. Actually with Vim and AWK, I claim you can do anything you want, sending emails, brushing teeth, etc..

Learn Vim

I recommend Learn Vim Progressively for starters. If you want to get little bit more involved, usr_toc is definitely the choice. It is written by Bram Moolenaar, the author of Vim. 

Reference:

  1. https://en.wikipedia.org/wiki/Vim_(text_editor)
  2. https://en.wikipedia.org/wiki/AWK
  3. http://yannesposito.com/Scratch/en/blog/Learn-Vim-Progressively/
  4. http://vimdoc.sourceforge.net/htmldoc/usr_toc.html


2 comments:

  1. "the best text editor know to human beings"

    I would say "known". lol

    ReplyDelete