Vim Tips: Map key to shell command

When using Vim, I want to keep keystrokes to a minimum and my focus on the current terminal window.  While using Ruby I found that saving a file, flipping to a different terminal window, executing specs and flipping back was taking too much effort.

All the above steps can be solved by simply mapping a keystroke. For example, when in Normal mode I can now save the file and execute RSpec by hitting the comma key.

   :nmap , :w | !rspec --colour %

The format is fairly straight forward.
:nmap == Map a key for normal mode
, == key you want to map
:w == save file
| == join multiple commands forward
!rspec == execute RSpec
% == current file
% == cr is a carriage return meaning the command gets executed straight away

With it being this fast to map keys, if you find yourself typing too much then you can speed up your productivity with a few simply mappings based on your current context.

Leave a Reply

Your email address will not be published. Required fields are marked *