vim faster with maps

by

At myYearbook, we pack our JS and CSS files.  Much of this is automated now with Jenkins, but we still have legacy code that must be packed by hand.  And, at the same time, it's generally wise to test your product with a packed file regardless.  I also try to make it a habit to phpcs my file as often as possible.  The goal here is to keep the file as tidy as possible, and not waiting for the end to fix everything.  Also, during the course of development, I might come across other little things I want to do, and I use vim to make things as easy as possible.

maps

I do this through maps.  I map is fairly simple to setup in vim.

:map ,cs <ESC>:w|:!phpcs --standard=myYearbook %:p

Typing that into a vim instance means I can type ',cs' in normal mode, and vim will w my file to disk, then run phpcs using the myYearbook standard on the current file I'm working in.  Now, I use that often enough that I've added it to my .vimrc file.

map <Leader>cs <ESC>:w|:!phpcs --standard=myYearbook %:p

If you aren't aware, <Leader> is set to ',' using this bit of code in .vimrc:

let mapleader = ","

The comma is popular, but you can use whatever you want, really.

I can also pack my javascript and CSS files with similar ease using ",pj" and ",pc" (pack javascript, and pack css).

map <Leader>pj <ESC>:!jspack %:p > %:p:h/%:r:r.jsmap <Leader>pc <ESC>:!csspack %:p > %:p:h/%:r:r.css

You might be wondering what the '%:p' part is.  It's actually part of the expand functionality of vim.  Basically, the important parts here to understand is that the % is the current file name.  The ":p" and ":r" parts are the modifiers.  In this case, "%:p" has us expand to the full path.  The ":h" modifier removes the last component.  So, "%:p:h" basically says "Give us the full path, and then remove the head.  The head in this case is the file name, so if the full path ("%:p") is /Users/jasonlotito/test.php, "%:p:h" gives us "/Users/jasonlotito".

"%:p:h/%:r:r.js" allows me to rename my file.  In our setup, unpacked files contain the extension ".unpack."  By Simply using the ":r:r" modifiers, I strip off the ".js", and then the ".unpack", leaving me with just the file name.  So, if my javascript file was named Modifiers.unpack.js, I'd be left with Modifiers.  I prefix that with %:p:h/ which gives me the directory the file is in, and append ".css" to the path.

Being able to map commonly performed actions, especially to external tools, means I can stay in vim longer.  Sure, I'll still background vim when I need to perform certain actions, but I'm more apt to start scripting repeated actions, and then mapping them.