Learning Vim – Part 3

Wow – it’s been a long time since my last post on my journey into the world of learning Vim. Since then I’ve started a new job at the wonderful Mozilla as a mobile software engineer and they have a really messed up complicated build system, so even though I’m working on an Android project, I haven’t got the pleasure of being able to use any of the IDEs that I’ve grown to love. The majority of people I’m working with use Emacs or Vi(m), so it’s been a pretty good chance for me to get my learn on!

The first thing I want to go over is tabs – if you’re going to use Vim to develop in then learning your way around the tab commands are essential.

First things first – to open several files from the command line in tabs:
vim -p file1 file2 file3

Next are a few commands to open files in tabs and switch tabs:

  • :tabe <filename> → open file in new tab
  • :tabp → switch to previous tab
  • :tabn → switch to next tab

That’s pretty good, but it makes it a bit of a job to navigate quickly, so below is how to setup a mapping so we can quickly access these keys. I’ve setup these up as two key mappings to reduce the chances of anything conflicting with the new setup. Open up the file ~/.vimrc and at the bottom paste these lines:

map <c-m><c-n> :tabp<CR>
map <c-m><c-p> :tabn<CR>

The <c-m> is the access modifier, it means press the ‘Ctrl’ and the ‘m’ key and yes the ‘m’ is for Martyn :). After that, with the ‘Ctrl’ key still held, press either ‘p’ or ‘n’ for previous and next tabs. The <CR> at the end is required to mark the end of that command.

Next up is better navigation:

  • w → go to start of next work
  • e → go to end of current/next word
  • b → go to start of current/previous word
  • b → go to start of current/previous word
  • 0 → go to start of the current line
  • ^ → go to start of the content in the current line
  • $ → go to the end of the current line

Sticking a number before each of these will repeat the command, so 2w will move you to the start of the next word twice, 2b will move you to the beginning of the previous word.

Searching is quite important, and fairly easy:

  • /<SEARCH TERM> → find the search term in the current file
  • n → after you have searched, this will go to the next occurrence

Search and replace is also essential and again pretty easy:

  • :s/SEARCH TERM/REPLACE TERM/ → replace the next occurrence of the SEARCH TERM in the current line with the REPLACE TERM
  • :s/SEARCH TERM/REPLACE TERM/g → replace every occurrence of the SEARCH TERM in the current line with the REPLACE TERM
  • :%s/SEARCH TERM/REPLACE TERM/g → replace every occurrence of the SEARCH TERM with the REPLACE TERM

Leave a Reply