Learn Vim Script The Hard Way Sample

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Learn Vimscript the Hard Way

Steve Losh

Learn Vimscript the Hard Way


2011 Steve Losh

is is a Leanpub book whi is for sale at hp://leanpub.com. Leanpub helps you connect with readers and sell your ebook, while you're writing it and aer it's done.

Contents
1 2 Preface Prerequisites Creating a Vimrc File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Eoing Messages Persistent Eoing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Setting Options Toggling Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cheing Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Options with Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Seing Multiple Options at Once . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Basic Mapping Special Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Commenting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Modal Mapping Muscle Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Insert Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 3 3 4 4 5 5 6 6 7 7 7 8 9 9 10 10 11 11 12 12

Preface
Programmers shape ideas into text. at text gets turned into numbers and those numbers bump into other numbers and make things happen. To get our ideas out of our heads and create the unks of text we call programs we use text editors. Full-time programmers will easily spend tens of thousands of hours of their lives interacting with their text editor doing many things: Geing raw text from brains into computers. Correcting mistakes in that text. Restructuring the text to formulate a problem in a dierent way. Recording how and why something was done a particular way. Communicating with other programmers about all of these things. Vim is incredibly powerful out of the box, but it doesnt truly shine until you take some time to customize it for your particular work, habits, and ngers. is book will introduce you to Vimscript, the main programming language used to customize Vim. Youll be able to mold Vim around your own personal text editing and make the rest of your time in Vim more ecient. Along the way Ill also mention things that arent strictly about Vimscript, but are more about learning and being more ecient in general. Learning Vimscript isnt going to help you mu if you wind up ddling with your editor all day instead of working, so you have to strike a balance. e style of this book is a bit dierent from most other books about programming languages. Instead of simply presenting you with facts about how Vimscript works, it guides you through typing in commands to see what they do. Frequently the book will lead you into dead ends before explaining the right way to solve a problem. Most other books dont do this, or only mention the stiy issues aer showing you the solution. is isnt how things typically happen in the real world, though. Most of the time youll be whipping up a qui piece of Vimscript and run into a quirk of the language that youll need to gure out. By stepping through this process in the book instead of glossing over it I hope to get you used to 1

PREFACE

the process of dealing with Vimscripts silliness so youre ready when you nd other edge cases. Practice makes perfect. Ea apter of the book focuses on a single topic. eyre short but paed with information, so dont just skim them. If you really want to learn the most you can you need to type in all of the commands. You may already be an experienced programmer whos used to reading code and understanding it straight away. If so: it doesnt maer. Learning Vim and Vimscript is a dierent experience from learning a normal programming language. Type in all the commands. Do all the exercises. ere are two reasons this is so important. First, Vimscript is old and has a lot of dusty corners and twisty hallways. One conguration option can ange how the entire language works. By typing every command in every lesson exercise and doing every exercise youll discover problems with your Vim build or conguration on the simpler commands, whi will be easier to diagnose and x. Second, Vimscript is Vim. To save a le in Vim, you type :write (or :w for short) and press return. To save a le in a Vimscript, you use write. Many of the Vimscript commands youll learn can be used in your day-to-day editing as well, but theyre only helpful if theyre in your muscle memory, whi simply doesnt happen from just reading. I hope youll nd this book useful. Its not meant to be a comprehensive guide to Vimscript. Its meant to get you comfortable enough with the language to write some simple plugins, read other peoples code (with regular side-trips to :help), and recognize some of the common pitfalls. Good lu!

Prerequisites
To use this book you should have the latest version of Vim installed, whi is version 7.3 at the time of this writing. New versions of Vim are almost always bawards-compatible, so everything in this book should work just ne with anything aer 7.3 too. You should be comfortable editing les in Vim. You should know basic Vim terminology like buer, window, normal mode, insert mode and text object. If youre not at that point yet go through the vimtutor program, use Vim exclusively for a month or two, and come ba when youve got Vim burned into your ngers. You should have some programming experience. If youve never programmed before e out Learn Python the Hard Way rst and come ba to this book when youre done.

Creating a Vimrc File


If you already know what a vimrc le is and have one, go on to the next apter. A vimrc le is a le you create that contains some Vimscript code. Vim will automatically run the code inside this le every time you open Vim. On Linux and Mac OS X this le is located in your home directory and named .vimrc. On Windows this le is located in your home folder and named _vimrc. To easily nd the location and name of the le on any operating system, run :echo $MYVIMRC in Vim. e path will be displayed at the boom of the screen. Create this le if it doesnt already exist.

http://learnpythonthehardway.org/

Echoing Messages
e rst piece of Vimscript well look at is echom. You can read the full documentation for the command by running :help echom in Vim. As you go through this book you should try to read the :help for every new command you encounter to get a beer understanding of how to use ea one. Run the following command: :echo "Hello, world!" You should see Hello, world! appear at the boom of the window.

Persistent Echoing
Now run the following command: :echom "Hello again, world!" You should see Hello again, world! appear at the boom of the window. To see the dierence between these two commands, run one more new command: :messages You should see a list of messages. Hello, world! will not be in this list, but Hello again, world! will be in it. When youre writing more complicated Vim scripts later in this book you may nd yourself wanting to print some output to help you debug problems. Plain old :echowill print output, but it will oen disappear by the time your script is done. Using :echom will save the output and let you run :messages to view it later.

ECHOING MESSAGES

Comments
Before we move on we should mention comments. When you write Vimscript code (in your /.vimrc le or another one) you can add comments with the " aracter, like this: " Make space more useful nnoremap <space> za is doesnt always work (thats one of those ugly corners of Vimscript), but in most cases it does, and well talk about when it wont (and why that happens).

Exercises
Read :help echo. Read :help echom. Read :help messages. Add a line to your vimrc le that displays a friendly ASCII-art cat (>.<) whenever you open Vim.

Setting Options
Vim has many options you can set to ange how it behaves. ere are two main kinds of options: boolean options (either on or o) and options that take a value. Run the following command: :set number Line numbers should appear in Vim. Now run this: :set nonumber e line numbers should disappear. number is a boolean option it can be o or on. You turn it on by running :set number and o with :set nonumber.

Toggling Options
You can also toggle boolean options to set them to the opposite of whatever they are now. Run this: :set number! e line numbers should reappear. Now run it again: :set number! ey should disappear once more. Adding a ! (exclamation point or bang) to a boolean option toggles it.

SETTING OPTIONS

Checking Options
You can ask Vim what an option is currently set to by using a ?. Run these commands and wat what happens aer ea: :set :set :set :set number number? nonumber number?

Notice how the rst :set number? command displayed number while the second displayed nonumber.

Options with Values


Some options take a value instead of just being o or on. Run the following commands and wat what happens aer ea: :set :set :set :set number numberwidth=10 numberwidth=4 numberwidth?

e numberwidth option anges how wide the column containing line numbers will be. Try eing what a few other common options are set to: :set wrap? :set numberwidth?

Setting Multiple Options at Once


Finally, you can specify more than one option in the same :set command. Try running this: :set number numberwidth=6

SETTING OPTIONS

Exercises
Read :help number. Read :help relativenumber. Read :help numberwidth. Read :help wrap. Add a few lines to your vimrc le to set these four options however you like.

Basic Mapping
If theres one feature of Vimscript that will let you bend Vim to your will its the ability to map keys. Mapping keys lets you tell Vim: when I press this key, I want you to do this stu instead of whatever you would normally do. Were going to start o by mapping keys in normal mode. Well talk about how to map keys in insert and other modes in the next apter. Type a few lines of text into a le, then run: :map \ x Put your cursor somewhere in the text and press \. Notice how Vim deleted the aracter under the cursor, just like if you had pressed x. We already have a key for delete that aracter under the cursor, so lets ange that mapping to something slightly more useful. Run this command: :map \ dd Now put your cursor on a line somewhere and press \ again. is time Vim deletes the entire line, because thats what dd does.

Special Characters
You can use <keyname> to tell Vim about special keys that are hard to type. Try running this command: :map <space> viw Put your cursor on a word in your text and press the space bar. Vim will visually select the word. You can also map modier keys like Ctrl and Alt. Run this: :map <c-d> dd Now pressing Ctrl+d on your keyboard will run dd. 9

BASIC MAPPING

10

Commenting
Remember in the rst lesson where we talked about comments? Mapping keys is one of the places where Vim comments dont work. Try running this command: :map <space> viw " Use space to select a word If you try pressing <space> now, something horrible will almost certainly happen. Why?

When you press the space bar now, Vim thinks you want it to do what viw<space>"<space>Use<space>space< would do. Obviously, this isnt what we want. is mapping is even more interesting though, because if you look closely at its eect you might notice something strange. Take a few minutes to try to gure out what it is before you move on. Dont worry if you dont get it now, because well talk about it more later.

Exercises
Map the - key to delete the current line, then paste it below the one were on now. is will let you move lines downward in your le with one keystroke. Add that mapping command to your /.vimrc le so you can use it any time you start Vim. Figure out how to map the _ key to move the line up instead of down. Add that mapping to your /.vimrc le too. Try to guess how you might remove a mapping and reset a key to its normal function.

Modal Mapping
In the last apter we talked about how to map keys in Vim. We used the map command whi made our keys work in normal mode. If you played around a bit before moving on to this apter, you may have noticed that our mappings also took eect in visual mode. We can be more specic about when we want our mappings to work by using nmap, vmap, and imap. ese tell Vim to only use the mapping in normal, visual, or insert mode respectively. Run this command: nmap \ dd Now put your cursor in your text le, make sure youre in normal mode, and press \. Vim will delete the current line. Now enter visual mode and try pressing \. Nothing will happen, because we told Vim to only use that mapping in normal mode (and \ doesnt do anything by default). Run this command: vmap \ U Enter visual mode and select some text, then press \. Vim will convert the text to uppercase! Try the \ key a few times in normal and visual modes and notice that it now does something completely dierent depending on whi mode youre in.

Muscle Memory
At rst the idea of mapping the same key to do dierent things depending on whi mode youre in may sound like a terrible idea. Why would you want to have to stop and think whi mode youre in before pressing the key? Wouldnt that negate any time you saved from the mapping itself? In practice it turns out that this isnt really a problem. Once you start using Vim a lot you wont be thinking about the individual keys youre typing any more. Youll think: delete a line and not press dd. Your ngers and brain will learn your mappings and the keys themselves will become subconscious. 11

MODAL MAPPING

12

Insert Mode
Now that weve covered how to map keys in normal and visual mode, lets move on to insert mode. Run this command: imap <c-d> dd You might think that this would let you press Ctrl+d whenever youre in insert mode to delete the current line. is would be nice, because now you dont need to go ba into normal mode to cut out lines! Go ahead and try it. It wont work instead it will just put two ds in your le! ats prey useless. e problem is that Vim is doing exactly what we told it to. We said: when I press <c-d> I want you to do what pressing d and d would normally do. Well, normally when youre in insert mode and press the d key twice, you get two ds in a row! To make this mapping do what we intended we need to be very explicit. Run this command to ange the mapping: imap <c-d> <esc>dd e <esc> is our way of telling Vim to press the Escape key, whi will take us out of insert mode. Now try the mapping. It works! But notice how youre now ba in normal mode. is makes sense, because we told Vim that <c-d> should exit insert mode and delete a line, but we never told it to go ba into insert mode. Run one more command to x the mapping once and for all: imap <c-d> <esc>ddi e i at the end reenters insert mode for us, and our mapping is nally complete.

Exercises
Set up a mapping so that you can press <c-u> to convert the current word to uppercase when youre in insert mode. Remember that U in visual mode will uppercase the selection. I nd this mapping extremely useful when Im writing out the name of a long constant I type out the constant in lower case and then uppercase it. Add that mapping to your /.vimrc le. Set up a mapping so that you can uppercase the current word with <c-u> when in normal mode. is will be slightly dierent than the previous mapping because you dont need to enter normal mode and you should end up ba in normal mode instead of in insert mode. Add that mapping to your /.vimrc le as well.

You might also like