306 45 1MB
English Pages [125] Year 2014
Painless Vim A Sane Person’s Guide to the World’s Most Powerful Editor Nate Dickson This book is for sale at http://leanpub.com/painless_vim This version was published on 2017-10-10
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. © 2013 - 2017 Nate Dickson
Tweet This Book! Please help Nate Dickson by spreading the word about this book on Twitter! The suggested tweet for this book is: I’m taking the sane route to learning vim with Painless Vim The suggested hashtag for this book is #painlessvim. Find out what other people are saying about the book by clicking on this link to search for this hashtag on Twitter: #painlessvim
Also By Nate Dickson Painless Tmux
Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Why? Why This? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I’m a Stranger Here, Myself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . Why Learn Vim . . . . . . . . . . . . . . . . . . . . . . . What This Book Is . . . . . . . . . . . . . . . . . . . . . . What This Book Isn’t . . . . . . . . . . . . . . . . . . . . Who am I? . . . . . . . . . . . . . . . . . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . Sample Documents . . . . . . . . . . . . . . . . . . . . . The Obligatory “Conventions Used in This Book” Section
. . . . . . . .
iii iii iv v v vi vi vi
1. Get In, Get Out, Get Comfortable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Line numbers and Moving Around . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1 2
2. Moving Around in Vim: Baby Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Zoom! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4 6
3. Your .vimrc File And You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I Was Promised Color Schemes! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using Keymaps to Get Unlost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7 9 10
4. Interlude: The Joy of a Good Cheat Sheet . . . . . . . . . . . . . . . . . . . . . . . . .
12
5. Moving Around in Vim: Grown Up Steps . . . . . . . . . . . . . . . . . . . . . . . . .
13
6. Operators 1: Changing Letters and Lines . . . . . . . Operators Alone: Changing Single Characters . . . . . Operating on a Line . . . . . . . . . . . . . . . . . . . Single Caps vs. Double Taps . . . . . . . . . . . . . . . How to Instantly Make Your Life Easier with cc (or C)
. . . . .
15 16 17 19 19
7. Doing Things More Than Once . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
21
. . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
. . . . .
. . . . . . . .
i i i
. . . . .
CONTENTS
Using Counts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using Text Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Behold The All-Powerful Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8. Moving Around in Vim: Dance Steps Words and WORDS . . . . . . . . . . Inner and All . . . . . . . . . . . . . . Move by Counting . . . . . . . . . . . (Book)marks . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
25 25 25 27 27
9. Modes at Last . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What Modes Are . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What is Normal, Anyway? . . . . . . . . . . . . . . . . . . . . . . . --INSERT-- Means You Are Free to Type Normally. . . . . . . . . . Command Mode: The One You’ve Been Secretly Using all This Time. Visual Mode: Marking Text . . . . . . . . . . . . . . . . . . . . . . . …And all the Rest . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
30 30 30 31 32 33 33
10. Plugins . . . . . . . . . . What a Plugin Is . . . . . Plugins the Hard Way . . And Now, the Easy Way . Nate’s Favorite Plugins .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
34 34 34 35 36
11. Operators: Moving and Changing at the Same Time . . . . . . . . . . . . . . . . . . . Move-and-Edit Commands; or “Vim Commands 202” . . . . . . . . . . . . . . . . . . . .
39 39
12. Interlude: How to Back Off Without Giving Up . . . . . . . . . . . . . . . . . . . . . .
43
13. Registers: Clipboards as Far as the Eye Can See Say Hi to the Named Registers . . . . . . . . . . Little Changes, Big Changes . . . . . . . . . . . . Really Actually Deleting Stuff . . . . . . . . . . .
. . . .
44 44 45 46
14. Text Origami. :h folding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Okay, But How Do I Fold Things? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
47 48
15. Searching and (More Importantly) Finding Whole File Searches: / and ? . . . . . . . . . Find Me Another One of These: * and # . . . Line Searching: t/T and f/F . . . . . . . . . R…R…Regular Expressions?!? . . . . . . . . .
. . . . .
50 50 50 51 52
16. Using Vim’s Help System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
56
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . .
. . . . .
. . . . .
. . . . .
. . . .
. . . . .
. . . . .
. . . . .
. . . .
. . . . .
. . . . .
. . . . .
. . . .
. . . . .
. . . . .
. . . . .
. . . .
. . . . .
. . . . .
. . . . .
. . . .
. . . . .
. . . . .
. . . . .
. . . .
. . . . .
. . . . .
. . . . .
. . . .
. . . . .
. . . . .
. . . . .
. . . .
. . . . .
. . . . .
21 22 23
. . . . .
. . . .
. . . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
CONTENTS
Getting the Help You Need . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Relatively Shallow Secrets of the Help System . . . . . . . . . . . . . . . . . . . . . . . .
56 57
17. Doing Things at Vim Speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
59
18. Mapping Keys . . . . . . . . . . . . . . . . . All the Key map Commands . . . . . . . . . Take me to your Key! . . . . . . . What not to map . . . . . . . . . . . . . . . . What to Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Recursive Mappings, and How to Avoid Them
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
61 61 62 63 64 65 66
19. Fancy Insert Mode Tricks x Adventures . . . r Funtimes . . . . . Completions! . . . . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
69 69 69 70
20. Vim Windows Are Not Microsoft Windows . . . . . Opening and Closing Windows :h opening-window Window Commands begin with w . . . . . . . Moving Between Windows :h window-move-cursor Resizing Windows h: window-resize . . . . . . . . Moving Windows Around :h window-moving . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
71 71 71 72 72 73
21. Tab Pages Are Not Browser Tabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How To Use Tab Pages :h tabpage . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
75 75
22. Interlude: Reviewing Views Files . . . . . . . . . . . . . . Windows . . . . . . . . . . . Tabs . . . . . . . . . . . . . .
. . . .
77 77 78 78
23. How Vim Thinks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . You Don’t Edit Files, you Edit Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . Updating Vim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
80 80 80
24. Visual (Mode) Basics :h visual-mode . . . . . . . . . . Characterwise Visual Mode :h characterwise-visual Linewise Visual Mode :h linewise-visual . . . . . . . Blockwise Visual Mode :h blockwise-visual . . . . . Common Visual Mode Commands . . . . . . . . . . . . .
. . . . .
82 82 82 82 84
25. Vim GUIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
85
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
CONTENTS
Setting Expectations, Then Setting Some Settings . . . . . . . . . . . . . . . . . . . . . . Setting the Font in gvim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26. Menus Everywhere! :h menus Adding a Menu . . . . . . . . . Keeping Things In Order . . . . Making the Menu Come to You . Linux and Windows . . . . . . . MacVim is a Special Snowflake! .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
89 90 91 92 92 93
27. Literary Vim: Writing Prose in Vim . . . . . . . . . . . . . . . . . Setting up the a Writing Workflow . . . . . . . . . . . . . . . . . . Writer-Friendly Vim Settings . . . . . . . . . . . . . . . . . . . . . Spreading the Word: How to Get Your Message Out Into the World More Formats! I Need More Formats! . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
94 94 95 96 97
28. Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
99
Appendix 1: Links to References . Color Scheme References . . . Cheat Sheets . . . . . . . . . . Great Books on vim . . . . . . Great Sites to Learn more Vim More About Expressions . . . . Bundle Managers . . . . . . .
. . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
85 86
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
100 100 100 100 101 101 101
Appendix 2: Quick Reference Charts Motions . . . . . . . . . . . . . . . Commands . . . . . . . . . . . . . Text Objects . . . . . . . . . . . . Registers . . . . . . . . . . . . . . Folding . . . . . . . . . . . . . . . Menus . . . . . . . . . . . . . . . Tab Commands . . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
102 102 102 103 103 103 104 104
Appendix 3: Sample .vimrc files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 About This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 About the Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 About the cover . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Special Thanks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Preface Why? Why This? Look, we’ve all been through this: someone says, “You should learn vim. I did, and now I’m 10000% faster at everything and people like me more.” So you download the latest version for your OS and start it up and, hey look, there’s that screen with a bunch of tildes down the side asking you to donate to kids in Uganda. Just like the last time you tried this. You know from experience that typing :help isn’t going to be super helpful, because you’ll get stuck in the help window and you’ll never be able to get it to go away. You start typing and the terminal beeps at you or says it’s in some weird mode now or –if you’re lucky– starts putting letters on the screen at some point. Then it’s a quick trip to Google to figure out how to get back out of Vim, and you shudder, vowing not to go back. It doesn’t have to be this way. At its heart, Vim is about making life easier for developers. But most of the “beginners” advice you get sounds like there’s a big trial by fire initiation that you have to pass before you can get to that programmer’s nirvana. People tell you that the “only way” you’ll ever get good at using the power of vim is to throw your mouse out the window, disable all the hotkeys you’re used to, and just spend a few months doing nothing but learning how to use an editor. Bless their pointy little heads. It’s true that once you’re good at vim you will start to see all the system shortcuts and mouse shortcuts as inefficient. But when you’re starting out they make it feel like you’re suddenly in a foreign country where you don’t speak the language. They mean well, but that sort of initiation is exactly wrong for a newcomer. It’s advice like that that is impeding vim, keeping it from being the editor that everyone uses1 .
I’m a Stranger Here, Myself The fact is, you can learn vim at your own pace and be fairly productive with it right out of the box. And that’s what this book is about. If vim were a foreign country, I would be the guy who walks up to you in the hotel lobby and says, “Hey, how’s it going? Just get here? I’m a stranger here myself.” And then I would show you all the good restaurants and stuff, because I understand what you’re going through. So instead of lecturing you on learning all the underlying ex and vi commands that you “have to know to truly experience the raw power of vim” I’m going to show you how to get in, get comfortable, and start branching out into bigger and better things. I’m going to take it as read that you’re not 1
You and I aren’t the only ones that feel this way. Even very smart people can get caught by the “throw the newbie in the deep end” problem.
Preface
ii
100% committed to leaving all other text editors behind. Heck, I’d strongly suggest having a copy of Sublime Text (more on that later) available for the times where you’re just sick to the eye teeth of vim. It happens! But come back to vim, because I plan to show you that vim isn’t that hard, and that learning it can be painless.
Introduction Why Learn Vim Vim, for all its eccentricities, is designed to be fast and developer friendly. Smart people have been using and improving it for decades and it’s gotten to the point that it’s pretty darn good in the right hands. As a former vim critic who has started using it, I can tell you that it is that fast when you get going. You can make a surprising number of changes quickly and efficiently in vim, and once you start navigating, making changes, and issuing commands using just the home row keys using anything else will feel clunky by comparison.
It is that fast Vim, used well, is a speed demon. Once you get used to the slightly weird controls every other text editor will feel unwieldy. Vim was designed to keep your hands where they belong, without using the mouse or the arrow keys. Now, like I said before, if you want to use the mouse and arrow keys while you get used to vim, go right ahead! You’re not being productive if all you’re doing is trying to remember how to edit the third character in the line below your cursor. But the promise is that eventually you’ll get comfortable with the vim way of doing things and be much happier. There are other reasons, too:
Vim commands get around A lot of unix-y things use the vim keybindings for moving around. Even web services like gmail use the h j k l magic keys to move between emails. If you get comfortable with vim idioms you’ll be more comfortable with a lot of other tools as well.
Vim itself gets around Let’s face it, vim is everywhere. If you install git on windows vim comes along for the ride. If you have a Linux box or a Mac you’ve already got vim. And if you’re like me2 it’s always slightly bugged you that there was this editor on your machine that you don’t like or know how to use. If you get comfortable with vim then you don’t have to panic when you have to enter a commit message from the command line in git. 2
A few months ago
Introduction
iv
What This Book Is This book aims to be:
Short You’ve got better things to do than read books about editors. The main goal of this book is to get you comfortable with the editor and feeling like you’re ready to move on, bending vim to your wishes. If you’re like me, you get annoyed at making changes someone else forced on you after a while, and you just want to strike out and do it yourself. I’ll let you do just that.
Cheap Vim is free. While I don’t want to sell my work for nothing, I’m coming pretty darn close. This is a beginner’s book, and my goal is to lower the bar to entry. To start with, I’ll price it low and hope that helps you along.
Easy to understand Vim is complex; this book shouldn’t be. My main goal here is to help you build confidence and get your feet under you. If you’re reading this during the beta period and you’ve got suggestions, please send them on over to me! I’m more than willing to listen and change.
Friendly! My high horse died a while back, and I never bothered to buy myself a soapbox, so I won’t be doing any preaching. Remember that friendly face in the hotel who shows you all the great spots in town? That’s this book. I’m not here to judge.
Opinionated (but in a good way) I’ll keep the tone friendly, but I got opinions people. There are things I think are good and things I think aren’t so good. But I’ll let you know why I think some things are good or not so good and let you make up your mind on your own.
Lighthearted, but serious The tone of the book is meant to be light and approachable, but the advice is meant to be rock solid. I’m not going to have you do things to your configuration files that I wouldn’t do, even temporarily, or to prove a point. The goal is to make it easy for you to get things right 3 the first time. 3
According to me, see the whole “Opinionated” thing up above.
Introduction
v
What This Book Isn’t This book definitely is not:
The end-all-be-all reference on vim I’m here to help you get started, not to be the only book you’ll ever buy on the subject. The main reason for this isn’t laziness, thank you very much. Well, okay, it kind of is. There are a ton of books, websites, wikis, and other documentation out there that will help you along, once you get over the initial learning curve. I’m here to help you over that first curve.
A list of tips A lot of the stuff in the later chapters won’t make a ton of sense if you haven’t been through the earlier chapters. The chapters are laid out iteratively, starting with small changes that build up to a final configuration that should work well. Then you’ll have a good jumping-off point for your further modifications.
A deep dive The goal here is to give you enough information to be comfortable, but not all the underlying technologies and line editor commands and other such things. Again, these are available online and in many other reference guides all over the place. When you decide that you want to know more about something you’ll be able to find it. I have faith in you.
Who am I? I’m Nate Dickson, it says so right on the cover. But beyond that, I’m a professional programmer by day, blogger, writer, and daddy by night. You can check out a fairly large amount of my writing on my personal blog4 , or my less-maintained Apple blog5 . You can also check me out on Twitter6 , or Github7 . In terms of my vim credentials, I don’t have many. I use vim in my day job and I’m a command line junky, with the .zshrc and .tmux.conf files to prove it. But my quasi newbie status is part of why I’m writing this book right now. I’ve spent the last few months combing blogs and websites, buying or borrowing books on vim and grabbing onto the arm 4
http://natedickson.com http://crazyapplenews.com 6 @poginate 7 http://github.com/PogiNate 5
Introduction
vi
of anyone I know who uses vim and begging them to help me fix whatever mess I’ve most recently gotten myself into. Now that I’m fairly comfortable, I’d like to pass what I’ve learned along to ease the learning curve for everyone else.
References I will refer you to a lot of other books, posters, blogs, wikis, etc. etc. over the course of this book. For the most part these are things I’ve used extensively myself, and can heartily recommend. Again, I’ll try to provide reasons for my references and let you decide if it sounds like something you’d like to investigate on your own.
Sample Documents Throughout the book there will be exercises to try out. For convenience, I have created a repository of sample documents for use with these exercises. They are stored on Github8 , and the readme file has instructions for how to get them in place, if you’re not familiar with git and Github.
The Obligatory “Conventions Used in This Book” Section First off, regarding the actual word “vim”. In general I will write it all lowercase, because that’s how most people think of it, like “perl” or “ruby”. That’s the command you enter to start the editor, and that’s really the name of the program. However, when it’s in a book, chapter, or section title I will capitalize it, just as I would any other word in a title: Painless Vim Ironically, even though it’s probably the most correct, I will never write it as “VIM”, even though it is a acronym (kinda) for “Vi IMproved” Other than that, I use the same conventions everyone else uses. Code appears in a monospaced font, and longer blocks of code will appear 1 2
in a large block of monospaced text.
Special keys like , , , will have angle brackets around the name to make it real obvious that you shouldn’t be typing that word, you should be pressing that key. If you need to 8
https://github.com/PogiNate/Painless-Vim-Samples
Introduction
vii
press and another key at the same time (and you will need to do this, quite frequently) I’ll just write them like so: d. Vim uses both upper- and lower-case characters, so remember that “S” is s and “s” is just s. Those are the only two times you should ever need to press two keys at the same time: either to hit and a character, or to press and a character to make something upper-case. Which is good, because there will be a lot of times where you have to hit multiple characters in sequence. For example, let’s say you need to delete the next character after your cursor. You would press d (for delete) and then l (for the next character. Don’t worry about it now; we’ll get into it later). When I write this out in the book I will just write the two letters in a row, like so : 1
dl
I realize that looks exactly the same as my “type them at the same time” notation. Just remember that you’ll only ever need to press or at the same time as another character. In all other situations, two characters in sequence means type them one after the other. Okay, got it? It’s pretty natural, I promise. Let’s move on. From time to time I will need to show you exactly where your cursor needs to be when you perform a command. In these cases I will put a pipe symbol where the cursor resides, like so: 1
The cursor is in the middle of the word pi|pe
Again, this will all make more sense in a bit. For now let’s get moving.
1. Get In, Get Out, Get Comfortable Okay, you’ve gotten through the introduction. Good for you. I’d like to say that the style will settle down at this point, but I can’t promise that. Here’s where we get started on the real meat of learning vim. We’re going to start simple: open the editor. For now I’d recommend doing things from the command line, not because I have some big problem with GUI’s, but because the graphical versions of vim tend to make little changes that can get in the way of the things we’re trying to do here. So, open a Terminal 1 and enter the following: 1
$ vim
I have been here before. I don’t like it.
There! That’s not so scary, is it? Just a bunch of tildes and some version information! Not scary at all! Well, okay, yeah it is. You’re in this editor with no discernible way out. So let’s cut straight to the quick and talk about how to get back out. For now we’re going to use the absolute “oh crap let me out” method. Type :q!2 and you should be right back to the command prompt, which looks like this: 1
I’m going to use lowest common denominator words like “Terminal” a lot. If your OS calls it something different like a shell or a command line or (heaven help you) cmd.exe then just substitute that in your head. 2 Later on you’ll want to know that this is the “quit and don’t save anything” way of getting out. There are a few other ways to exit vim, but we’ll get there later.
Get In, Get Out, Get Comfortable
1
2
$
Okay, breathe. This time we’re going to go in armed a little better. Before you dive back in, find a file you’ve been working on lately. HTML files work well, but pretty much anything that is structured text or code will work just fine. If you don’t have anything that springs easily to mind you can use sample.html from my sample repository. Switch to the directory where that file is kept: 1
cd /path/to/where/the/file/lives
And do this: 1
vim file1.html
And you should see…a boring representation of your file. But we’re going to fix that right now. Enter the following: 1
:syntax on
And the file should brighten up a bit. We’ll talk more about colorful files in a bit, but for now let’s get back out of vim, because it’s still scary: 1
:q!
Okay, you’re safe. Let’s take a minute out here in the real world to formalize what we’ve just learned: 1. When you start vim, the keyboard makes things happen instead of making letters appear. 2. When you want to send a command to vim, you preface it with a colon (:). 3. :q! gets you back out of vim without saving any changes. Cool.
Line numbers and Moving Around All right, now that we’ve had a breather, let’s dive back into vim. Open your test file again with 1
$ vim file1.html
And you’ll see you’re right back to boring plain ol’ text. You can tell vim to color it again with
Get In, Get Out, Get Comfortable
1
3
:syntax on
But it seems like a bummer to have to do this by hand every time you start vim. You’re right. Don’t worry, we’ll fix that. But there’s more. We’ve learned that when you send commands to vim that start with a : you have to press at the end. This is useful information, because I’m going to stop putting after every command from here on out. Remember that if you start a vim command with a colon it always ends with an . There are other commands that don’t need an at the end. We’ll get to them in time. For now let’s look around this file.
2. Moving Around in Vim: Baby Steps Now that you’re in a file, it’s time to move around a little bit. If you’ve ever played with vim before, you’ve probably seen something that looks like this: 1 2 3
k h
l j
This is a super-unintuitive way of telling you which keys will move your cursor which directions. In English it goes like this: • • • •
h moves your cursor one space left l moves your cursor one space right k moves your cursor one line up j moves your cursor one line down
So play with those four keys for a while. The layout is weird at first, I’ll grant you, but it serves the purpose of keeping your hand firmly on home row, and after a while you’ll start to just believe that h j k l should always move your cursor around. This is great when you’re using a program that understands vim keys. It also means that you’ll end up in an instant message conversation with someone, and you’ll inadvertently send them a message that says “jjjkl” as you try to figure out why you can’t move your cursor. It’s a curse. Okay, moving on. Once you’ve gotten comfortable moving your cursor around, it’s time to edit something. Use the movement keys to get your cursor where you want it and press i. At the bottom of the screen you should see a message appear: 1
--INSERT--
This is vim’s way of telling you that pressing keys now will make things change in your text. In vim parlance, you have just entered insert mode. Type something witty in the document. I would put “So long, and thanks for all the fish” because it’s better than “hello world”. But I know it doesn’t matter what I tell you to enter; you’ll put whatever you want. That’s just how you are. You’re independent and I respect that. Once your witticism is entered it’s time to save it up. Hit and the --INSERT-- message at the bottom of the screen should disappear. This means that the keyboard is back to issuing commands to vim instead of changing the text on the screen. Vim calls this normal mode, but don’t worry too much about that yet. Type
Moving Around in Vim: Baby Steps
1
5
:w
And your changes are saved, friend.1 Now let’s do something a little more daring and, dare I say it, useful. Moving around with your fingers on home row is nice and all, but it’s not worth all this hassle and bother. Let’s look at some slightly larger jumps in the text. Position your cursor somewhere on a line of text–anywhere is fine– and make sure the -- INSERT -- thingy is gone by pressing a bunch of times until vim starts beeping and/or flashing at you. 2 Now press A. Note that was an uppercase A, not a lowercase a. This handy little shortcut moves you to the end of the line and puts you back into insert mode, all at once. Think of it as “append” or “add”. Nifty, huh? Okay, press again and let’s do another one. Press o. (Again, note the case.) Vim adds an empty line, right under the line you were on, and once again you’re in Insert mode, ready to enter new text into the file. Write something if you want, and then press again to get out of Insert mode.
What Are All These Modes You Keep Mentioning? I’m getting there, little by little. If you want to skip ahead to the chapter on Modes feel free, but the path I’m taking will be a little nicer. For now you only need to know that when vim says 1
-- INSERT --
you’re in insert mode (so called because that’s how you insert text) and when it doesn’t you’re (probably) in normal mode. There are other modes, and a lot more to say on the topic, but right now we’re getting used to moving around, and we don’t want to be bothered.
We’re going to talk more about moving the cursor around later, but for now look how awesome you already are! Since you don’t need to worry about changes this time, you can just type 1
:q!
To exit vim. 1 Remember that commands that start with a colon : require you to press to make them execute. Okay, this is definitely the last time I’m going to repeat that. 2 I’ve heard it said that some people call Normal Mode “Beep Mode” because you’ll try to switch back to it and the terminal will beep at you and you’ll realize you’re already in it. I don’t know if I believe that anybody actually calls it that, but since I’m writing a vim book I’m honor bound to pass this bit of information on to you. Just like if I were writing Beginner’s Big Book o’ Computer Facts I would feel obligated to mention that four bits is called a “nibble” (because it’s half a byte and “byte” sounds like “bite”! Get it? GET IT???), even though I’m pretty sure that’s just a joke that got put in some textbook years ago and has since gotten out of hand.
Moving Around in Vim: Baby Steps
6
More Ways Out Vim is a strong believer in the “TIMTOWTDI” 3 principle. There are five main ways to get out of vim: • • • • •
:q Quits. This will fail if you have unsaved changes in your file. :q! Force quits, even if you have unsaved changes. :wq Writes (saves) and quits. ZZ Same as :wq, but much easier to type. ZQ Same as :q!, but way easier to type. 4
I would strongly recommend getting used to the ZZ and ZQ versions, since they are the easiest to type and remember. But hey, it’s up to you.
Zoom! Let’s go back into vim and play with three simple (but useful) commands that I call the zoom commands. To enter vim this time type 1
$ vim sample1.html
So that we’ve got a document to play with. Press j repeatedly to move your cursor down a few lines, it doesn’t matter where it ends up. What we’re going to do is tell vim to scroll the window so that the line the cursor is on is positioned where we want it. The first “zoom” command is zt, which (I say) stands for “zoom top.” When you press zt in command mode it will move your current line to (you guessed it) the top of the screen. So, if your cursor is on line 15 and is one third of the way down the screen it will now be at the top of the screen. Next up is zb, or “zoom bottom.” As you can guess, it moves your current line to the bottom of the screen, letting you see everything that came before. The third and arguably most useful zoom command is zz, which positions the line your cursor is on in the middle of the screen, so that you can see that line in context. I use all three commands fairly frequently, but I find this is the one I like the best. It’s my secret favorite child. All right, we’ve done some good work here. You’ve started vim and gotten around a bit, and more importantly, you made your code all pretty. In the next chapter we’ll get down to the single most important thing you ever have to do with an editor: choose your color scheme. 3
“There is more than one way to do it” usually pronounced “Tim-Toady” Here are two secret bonus ways to exit vim that you won’t need to know about until you know how to open multiple files: :qa closes all open files and quits vim, and :qa! does the same thing even if any file has unsaved changes. Don’t worry, we’ll review them again when we talk about opening multiple files. 4
3. Your .vimrc File And You Okay, let me start by saying I didn’t lie to you. This chapter is about choosing a color scheme. But to do that we need to talk about how to save your settings from session to session. And the way to do this is through a .vimrc file.
Why is it called vimrc? The rc ending has been around in Unixland forever, and as near as anyone can tella it stands for one of the following: • • • • •
run command(s) resource control run control runtime configuration runcom
Most people use it to mean “a configuration file”. Many programs will look for a configuration file and run through it when starting up. a
http://stackoverflow.com/questions/11030552/what-does-rc-means-in-dot-files
For now, we’re going to start very very simply and just add a few lines. In general, any command that you can send to vim by typing : and then hitting enter can be put in your .vimrc file. We’re going to add two lines right now to solve a problem we had in the last chapter. Start by telling vim to open your .vimrc file. On a Unix-based machine it’s found at ∼/.vimrc 1 From the command line open vim for editing with your .vimrc file as the subject: 1
$ vim ~/.vimrc
And, if you’re using a fresh install, you should see a completely empty file. Go into insert mode by pressing i and enter the following lines:
1
On windows the situation is a little more complicated. We’re going to proceed as if you’re on a Unix-ish machine, because it’s easier.
Your .vimrc File And You
1 2 3 4
8
set nocompatible syntax on set nu filetype indent plugin on
I realize this all looks like witchcraft at the moment, but it’s really just telling vim a few things about how you want it to behave. Let’s go through it line by line and you’ll see how simple it really is: • What’s that “nocompatible” thing? That line simply tells vim to be vim instead of being vi. It’s a good way to turn off all the old, weird, useless things that are holdovers from vim’s even older and more arcane predecessor. Just set that line and forget all about it. All it’s doing is protecting you. • ‘Syntax on‘ is what we’ve been talking about: this tells vim to do syntax highlighting. This is what turns on your pretty colors for good. • Okay, so, what about this nu thing? That tells vim to display line numbers down the left-hand side of the screen. You could (temporarily) do the same thing by typing :nu while in normal mode, but since vim is a programmer’s editor we’re going to make it a part of your everyday setup. If you hate line numbers you can omit it. • The last one…the last one is a bit magic. In a nutshell we’re telling vim to figure out what kind of file it’s looking at and load the appropriate filetype plugin. This has a lot of benefits for programmers2 , and even if you don’t fully understand it I would recommend setting it. Some of the great tricks you’ll learn later on in this book depend on it. Press to get out of insert mode and save the file by typing 1
:w
So, now you have two choices. You can exit vim and start it again to have your changes take effect, or you can do some vim awesomeness. Instead of exiting vim, enter the following: 1
:so %
Now, before you close this book, feeling all hurt that I’m going to spring terrible surprises on you like .vimrc files and arcane :so % commands, hear me out. What you just did is tell vim to source 3 the current file. The so command is a shortcut for source, and % is a shortcut for “the current file”. See? Nothing scary happened here. This is a useful command to know while you’re getting your vim setup just right, and it makes you feel cool as well. 2 3
Or people who write vim books in Markdown. which is unix-speak for “read a file and do what it says”
Your .vimrc File And You
9
I Was Promised Color Schemes! Okay, look, all of this was just ground work we had to get through to get you your colors on a permanent basis. Adding a color scheme to vim is a two step process: 1. Install a color scheme. 2. Tell vim to use it. And the easiest way to accomplish step 2 is in your .vimrc file.
Picking a Color Scheme There are a ton of pre-built color schemes out there for vim. After all, people have been using it for more than 20 years, and everybody loves colors. There are many places to go to peruse available schemes and find one that fits your own personal style, a few of which are listed in Appendix 1 . For the purpose of this section, we’re going to install the Tomorrow Theme4 , because it comes with a few nice and elegant variations, and because it’s the one that I use right now. More specifically, I use “Tomorrow Night Eighties,” and therefore–at least for a little while–so will you. I’m all opinionated, remember? So, to install the scheme, download the contents of the colors folder in the github repository. You should see a list of files, all of which have a .vim extension. Now it’s time to do some diving. In your home directory there’s a hidden folder called .vim, which is where vim keeps all of its configuration stuff. Inside that directory is a folder called “colors,” and that’s where you want to put the color schemes you just downloaded. We’re going to discuss a better way to do this soon, but for now just move those files from wherever you downloaded them to ∼/.vim/colors. On OSX I would do this: 1
$ mv ~/Downloads/colors/*.vim ~/.vim/colors
But however you get the files in place, you’ll want to end up in a situation where the output of ls ∼/.vim/colors looks like this: 1 2 3 4
Tomorrow-Night-Blue.vim Tomorrow-Night-Bright.vim Tomorrow-Night-Eighties.vim Tomorrow.vim
You get the idea. Once that’s done it’s time to edit your .vimrc file some more. Open it up in vim and add this line: 4
https://github.com/chriskempson/tomorrow-theme/tree/master/vim
Your .vimrc File And You
1
10
colorscheme Tomorrow-Night-Eighties
And then hit to go back to normal mode. Save your work (:w), and then call on our old friend :so % to see your new color scheme in all its glory.
Using Keymaps to Get Unlost Let’s add one more line to your .vimrc, both as instruction and because it’s useful. From time to time your cursor can get lost on screen. It’s nobody’s fault, screens these days are large and cursors are small. Therefore a lot of people like having their editor highlight the line where the cursor is sitting. Given vim’s line-editing abilities, this isn’t a terrible idea. There are definitely times where I want my cursor line highlighted, but not all the time. So let’s add a keymap to .vimrc that allows us to highlight and un-highlight the current line at will. Paste the following into your .vimrc file: 1
nnoremap :set cursorline!
Wha? Don’t worry, we will be going over all this nnoremap stuff in the chapter on Key Mappings. For now just nod along, this is a good template to get used to. Keymaps are basically a way to make one or two keystrokes do the work of many keystrokes. But like I said, we’ll get to those in due course.
The heart of this line is the command 1
`:set cursorline!`
All of that stuff before the command is simply a way to tell vim that we want it to do something when we press the key. Let’s examine the command in excruciating detail. • As we’ve learned before, if you type : at the beginning of something it tells vim that you’re sending it a command. • The set command tells vim that we’re going to, well, set an option. If we set things from the command line in vim it will be set for this session, if we set them in .vimrc they will be set for every vim session. • The cursorline option tells vim to highlight the line where the cursor is right now. • The ! at the end of the option tells vim to toggle the cursorline option. If it’s currently on, turn it off and vice versa.
Your .vimrc File And You
11
• The at the end tells vim to simulate pressing the key. Remember, if a command begins with a colon it has to end with an .
Toggling and Querying Most of the vim :set commands turn into toggles if you append an exclamation point to the end of them. But wait, there’s more! (There’s always more.) Adding an question mark to the end of the :set commands will tell you the current status instead of setting something. So :set cursorline? will display either cursorline or nocursorline in the status area, just in case you couldn’t tell by looking at the actual screen. This will come in handy later.
4. Interlude: The Joy of a Good Cheat Sheet While you’re learning vim it can be hard to remember all the commands and controls and letters and combinations and stuff, and sometimes no matter how much you ask your brain to pull up the one you need it’s just not going to do it. Which is why it’s a good idea to have someone help you out. A simple memory prompt hung up on the wall behind your computer can spur your brain back into activity. There are a lot of cheat sheets out there, most of which are the product of a lot of time and effort on the part of the creator, who was usually trying to create the “perfect” cheat sheet, meaning the one that works best for the way they think. In fact, since I first wrote this “interlude” I have created my own cheat sheet, which is included in your Painless Vim download. And hey, you spent the money on a vim book, you deserve a cheat sheet to go along with it. My cheat sheet is a distillation of all the commands and actions that I find myself using most frequently. But if you’re overburdened with cash, or just don’t particularly care for the Painless Vim cheat sheet then read on, my friend. I won’t be offended, I promise. For my money 1 the best one out there is the “Beautiful” Vim Cheat Sheet2 , because it’s clean, well laid out, and informative. When you start out you can just focus on the movement arrows that dominate the top left corner, and after a while you will start to see that the whole thing is packed with things you can use. There are a number of other good choices. The point of this interlude is to spend a little time finding one that makes sense to you. But the “Beautiful” one has earned itself a permanent spot on the wall behind my monitor. 3 1
And it actually cost me some cash money, but not a ton. http://vimcheatsheet.com/ 3 Until I created my own, that is. 2
5. Moving Around in Vim: Grown Up Steps Okay, now that the serious business of getting a color scheme set up is taken care of, let’s get back to moving around. It’s often said that programming is roughly 90% thinking and 10% typing 1 . While this may be true, I would add that a fair amount of time is also spent getting the cursor where you need it to be. Let’s say you made a change on line 15, and from there you need to move the end of the file to add a new method. In a regular editor you have a few choices: you can either press the down arrow a bunch of times, or take one hand off the keyboard entirely and click on the last line of the file. Vim has a better idea: 1
G
That’s it! Upper-case G, all by itself, will move your cursor to the last line of the file. Want to get back to the top of the file? 1
gg
And you’re there. The point is that moving around is supremely easy in vim, once you get the hang of it. So, let’s take a look at some of the most used motions2 in vim: simple motions
Keystroke
Motion
h j k l b e ctrl+d ctrl+f ctrl+u
move right move down move up move left previous word end of word move down by 1/2 screen move down by 1 screen move up by 1/2 screen
1 By programmers at any rate. Managers would suggest that at least a portion of that 90% is actually spent furtively reading tech blogs and web comics. 2 I use the name “motions” instead of “commands” or “actions” quite intentionally. For now don’t worry about it, just remember it for later.
14
Moving Around in Vim: Grown Up Steps
simple motions
Keystroke
Motion
ctrl+b gg G ^ $
move up by 1 screen jump to the start of the file jump to the end of the file first non-whitespace character of the line last non-whitespace character of the line beginning of the line
0
There are quite a few more, but this will give us enough to get on with. Let’s play around with these actions for a moment. Open a file and jump around a bit, moving to the start and end of lines, bouncing around between words, etc. The “screen” motions are a little harder to pin down, but once you get used to them they make sense. A “screen” consists of the number of lines that fit in your current terminal window. So if your terminal window is 80 rows tall a screen is probably 79 rows (one row is taken up for the status line), and a half screen is around 40. But if you resize your terminal window the size of a “screen” changes accordingly. Still, take some time getting used to “scrolling” through the file quickly using the 1/2 and full screen motions, and getting a feel for how fast you can get around. These motions are useful by themselves, and the better you get at them the more fun you’ll have in vim. But they get even better when combined with the operators and counts we’ll meet in the next two chapters.
6. Operators 1: Changing Letters and Lines Okay so, you’ve got line numbers, colors, and a basic idea of how to get your cursor from place to place. If you wanted, you could stop here, move the cursor around in normal mode, press i to go into insert mode, and make all your changes like you would in any other editor. But vim has a better idea. You can make a lot of the most common changes right from normal mode. For now we’re going to focus on the three most common commands: Cut, copy, and paste. Only they have different names in vim. Remember that vi1 has been around since before the whole “clipboard” metaphor was ubiquitous. So instead of “cut, copy, paste” it’s “delete, yank, put.” Let’s use a table to introduce the commands for some of the most common operators: basic commands
Keystroke
Command
d c y u p r
delete change (delete and enter insert mode) yank (copy) undo put (paste) replace (with whatever character you press next)
Why “yank” ? I don’t know. Nobody really knows2 . My favorite theory is that all the useful mnemonics were taken, and “yank” kind of means the same thing as “pull,” and “pull” could kind of mean the same thing as “cut”, but less drastic, so they went with it. The other possibility, of course, is that it’s yet another hilarious programming joke, like recursive acronyms or punny program names. It’s worth noting that if you ever decide to learn emacs you’ll be annoyed by the fact that “yank” in emacs is exactly the opposite of “yank” in vim: In vim “yank” means “copy”. In emacs, it means “paste.”
To play with these three commands, let’s open up a sample document that we don’t mind really, 1 I’m only going to cover this once, because it’s annoying. Fans of vi will insist that you pronounce “vi” like “vee eye” instead of like “vie” because shut up. “vim”, thankfully, is pronounced “vim”. This is yet another reason to never ever use non-improved vi. 2 http://english.stackexchange.com/questions/40657/how-yank-came-about-in-vi-and-emacs
Operators 1: Changing Letters and Lines
16
really messing up. The sample documents folder has a file called operators.txt that would be perfect for this purpose.
Operators Alone: Changing Single Characters Killing Text For the most part, operators by themselves work on a single character. The first section in operators.txt has words with duplicated letters like “ddoctor”, a not-uncommon mistake to make while typing. Getting rid of the extra letter is easy. Just position your cursor on the duplicated character and hit d (for delete) or x (for…a mnemonic that is supposed to simulate striking something out on a typewriter. I’m guessing the majority of people reading this book have never put in any serious time on a typewriter, so that little mnemonic is kind of obsolete now).
Do we need two ways to delete a single letter? Not really, no. In practice I would recommend getting used to just using d, because x is limited to single character deletion, whereas d can be used in much bigger and better ways, as we’ll see shortly. Additionally, the d key is on the home row (on a qwerty keyboard, anyway) and x involves moving your finger off home row for a common operation, and those are milliseconds you won’t get back.
Resurrecting Text Once you’ve deleted text it’s not actually gone, it’s in a register, or a special place in memory where vim can bring it back quickly if needed. In normal mode, pressing p will “put” whatever text was most recently yanked or deleted before the cursor.
Two Fun Ones There are two operators that are useful in specific situations: ∼ and r ∼ Changes the case of a single letter, while r lets you replace a single character with the next letter you type. You can use both of these to correct line 13 of operators.txt, which reads: 1
"you can't grep a fred tree" --larry wall
Using the ∼ operator three times 3 and the r operator once 4 you have a well formatted quote, even if the attribution may be a bit suspect. 3 4
Once on the first word of the sentence, once on “Larry” and once on “Wall”. to make “fred” “dead”.
Operators 1: Changing Letters and Lines
17
Operating on a Line Changing single letters is fun and all, but sometimes you need to overhaul a line of text instead of a single letter 5 . Vim includes shortcuts for changing a line into a more pleasing shape, like a shorter line, two of the same line, or no line at all. Before we dive in, we should take a look at how vim defines what a “line” is and isn’t. Vim “lines” are everything between one press of the key and the next, even if that spans several visible “lines” on the screen. If word wrap is turned on vim will continue a line of text, like so: 1 2 3 4 5 6 7
8 This is the eighth line of text in this document. It just rambles on and on. You'll notice that even though there are several sentences in this line, it still counts as a single "line" in vim, and there isn't a new line number until I press enter. 9 Okay, this is a new line, because I pressed enter. Which is why there's a 9 over there in the line number column.
This is a useful way to think in programming, because you usually put a single statement on a line by itself. It’s less useful when you are working with long-form text 6 . When you’re writing prose in vim, it’s helpful to think “paragraph” instead of “line”.
Traditional Emacs Bashing Sections While I personally have nothing against emacs, and have even used it from time to time, it’s traditional to say bad things about it in vim books and thus perpetuate a pointless holy war. To this end, the sample texts will have a few emacs-bashing things in them. But don’t worry, we’ll be deleting or mutilating said sentences throughout each exercise. Which makes it okay.
The line must be drawn here! This far! No further! Sometimes you need to cut the end off of a line, either to replace it with something else, or just to get rid of it. In vim, the uppercase versions of commands operate on the line from your cursor to the end of the line. Find the following line in operators.txt: 1
Emacs is a great operating system, it just needs a good editor.
You can make this sentence slightly less snide by positioning the cursor right before the comma, then pressing D: 5 6
We’ll get to things like changing words and sentences soon enough. Don’t worry, I won’t leave you hanging. Like, say, a book about how vim works.
Operators 1: Changing Letters and Lines
1
18
Emacs is a great operating system
But then we’re left with a sentence fragment in search of a period. We can do better than that. Press u (for “undo) to restore the text you just deleted and let’s try again. If you press C vim will remove the same text as before, but this time it puts you in insert mode, ready for you to write something new here. All we want to do is add a period and then get back to normal mode, which seems a little wasteful. Press to get back into normal mode and let’s try one more thing. Press u to restore the text one last time. Okay, this time we’re going to combine two commands: Move your cursor one space right of the comma and press D to delete the text. Your cursor should now be on the comma, and you can just press r. to replace it with a period, all without leaving normal mode. Put is a little different: lowercase p will put the most recently yanked or deleted text after the cursor, while uppercase P will put the text before the cursor. Here’s a demonstration: We’re going to say we cut the word seven from one line and want to paste it into the next line: 1
four score and |years ago...
In this situation, pressing p to paste would result in: 1
four score and yseven ears ago...
Because the cursor is “on” the letter y. But “yseven ears” isn’t what we want. but if you use P then you get the expected result: 1
four score and seven years ago...
The way you’ve always remembered it. And let’s be honest, that’s all of the speech you can remember.
A Whole New Line To make the d/y/c operators affect an entire line simply duplicate the operator. So yy copies (or “yanks”) an entire line, dd deletes the line, and cc “changes” the line. (That is: deletes the line and puts you in insert mode). You can play with these as well in operators.txt, starting on line 31. For starters, copy line 33, then paste it twice below to give three cheers for your vim knowledge. This can be accomplished by yanking the entire line, then putting it twice. This can be done in four simple keystrokes, once your cursor is on the line that says - Hip Hip, Hooray!. Simply hit yy to yank the entire line, then press p twice to paste it two times. Since copying an entire line also copies the invisible line break character, you don’t even need to move your cursor.
Operators 1: Changing Letters and Lines
19
Single Caps vs. Double Taps Okay, we’ve introduced two ways to operate on a line instead of a single character. Let’s sum them up one more time. To operate on an entire line you double the command, like cc to change an entire line, dd to delete an entire line, yy to yank an entire line, and so forth. To operate on a line from your cursor to the end you capitalize the command instead. So C removes the line from your cursor onward and puts you in insert mode, Y yanks all the words from your cursor forward, and so forth. Here’s a quick example. Let’s say we want to get rid of half of the following line, because it’s backwards: 1
Four score and seven years ago years seven and score four
We would just put our cursor after the word “ago” and press C to get this: 1
Four score and seven years ago|
Type out the rest of the real sentence 7 and life gets better quickly. Now a slightly more complex scenario: Take the three somewhat muddled lines and put them in the right order. This can be done by deleting the line that is in the wrong place (which, again, removes the line-ending character, effectively moving the following line up a notch) with dd and putting it back where it fits with p.
How to Instantly Make Your Life Easier with cc (or C) There’s a common scenario in programming. You are declaring a new function and you want to make sure all your braces are matched from the get-go. So you set up your declaration, put an empty line in the middle, and set up your closing braces. Something like this: 1 2 3
$scope.awesome = function(arg){ };
And then you move your cursor up to that middle line and… it’s right up against the left border, where you don’t want it: 7
If you know it. Or you can just type three periods (which you can call an ellipsis, if you know that) and call it good.
Operators 1: Changing Letters and Lines
1 2 3
20
$scope.awesome = function(arg){ | };
You want your cursor to start properly indented, and you have probably developed a million ways to make that happen. When I was first starting my coding career I would position my cursor on that empty line, hit to create a new line, because that new line was usually properly indented by the IDE I was using, then go back and delete the improperly-indented line. And that trick will work in vim as well, but that’s no way to live. Fortunately there’s a better way: just position your cursor on that empty line and hit cc (or C if you like that better). Think about what you just did: you told vim “delete everything on this line, and put me in edit mode.” Vim does that, takes a look at the lines above and below and does you one better: it puts you in insert mode with your cursor properly indented, all ready to write nicely formatted code: 1 2 3
$scope.awesome = function(arg){ | };
This is just another way that vim demonstrates its love for you. Note that this trick only works if you added the 1
Filetype indent plugin on
Line I suggested a few chapters back. I told you it would be good for something! So, with all that under your belt go ahead and mess up the rest of the file moving and removing lines. When you’re feeling fairly comfortable with the process let’s move on to the fascinating topic of repetition. 8 8
You would think that I would repeat myself here, wouldn’t you? I know. I’m just as surprised as you are.
7. Doing Things More Than Once One of the great things about vim is that it has been built for the way programmers work. We often want to jump to a specific word or symbol in the text without moving there line by line, or we want to replace the next four words with four new words, or other such silliness. It’s part of our job, and as I’ve said before, vim is all about making our jobs easier. It’s good at it! Part of how it makes our job easier is by letting us repeat our actions as many times as we need to accomplish what we’re doing.
Using Counts This is usually accomplished by typing a number before you give vim a command. For example, let’s say you wanted to move the cursor four characters to the right. You could do this by typing llll or you could type 4l and you just saved yourself two whole keystrokes! That’s money in the bank, friend. But as useful as it is to save two whole keystrokes, you can apply this concept to a lot of other motions and actions as well. Open up counts.txt in the sample documents and find this line 6
I am so incredibly stupid, useless, and talented.
Now, reading this, you realize that you need to get rid of the words stupid, useless and. You could delete those three words individually by putting your cursor before a word and typing dw1 three times, but why waste the time? Instead, put your cursor before the word “stupid” and type 3dw. BAM! Just like that your sentence is much more indicative of you as a person: 6
I am so incredibly talented.
The Exception to the Rule The “count + action” pattern can be used just about everywhere in vim, and is often the simplest way to do things. In general, if you hit [number][letter] it will do whatever [letter] does [number] times. We’ll explore this pattern more in the following section. But we need to talk about one useful exception to that pattern. You see, normally, when you hit G it will move your cursor to the end of the file. So you would think that 13G would somehow move your cursor to the end of the file 13 times. But that’s not a very useful command. So capital-Gplus-count behaves differently. Instead of jumping to the end of the file 13 times, it just jumps to 1
Wondering what that w means? Good eye. We will be getting to that right after the aside.
22
Doing Things More Than Once
line 13. As you would expect, 42G would jump to line 42. So, remember the rule that I’m teaching in the rest of this chapter, but also remember this exception to that rule.
Using Text Objects Sometimes you don’t want to manually count how many characters you need to operate on. You want to delete the next word without counting how many letters are in it. Vim is here for you. We’ve already covered part of this in a sneaky way in the “Operating on an Entire Line”. If you double an operator you’re (usually) telling vim to apply it to the line as a whole. In this case, “the line as a whole” is what vim calls a text object. If you’re a programmer you’re probably already familiar with the concept of objects: they’re the building blocks of most of the programming we’ve done since 1980. But I’m going to go ahead and explain objects anyway. In vim terms, a text object is a set of characters. It can be a single character, a few characters, a word, an entire line…all the way up to the entire document. Clever person that you are, you’ve already been using text objects in the last section. When you tell vim d5l what you are telling it is “the five characters to the right of the cursor make up a text object. Delete it.” If you told it d5j you’d be telling it that the next five lines constitute a text object whose presence is no longer required. But vim also gives us shortcuts for a number of other common text objects: Text Object Shortcuts
Shortcut
Text Object
w W s ’ or “ l
from the cursor to the end of the word from the cursor to the end of the WORD2 the current sentence a string surrounded in quotes from the cursor to the end of the line
There are many many others, but this will get us going. When you combine an operator with a count and a motion you have a command 3 .
2 I’ll get to the difference between a lower case word and an upper case WORD very soon. 3
There is a lot of discussion about what this is actually called. I’ll let you dive into that fun world of terminology on your own some other time. I believe my nomenclature for things like motions, counts, operators and commands makes sense, and won’t get you lost when you start diving into vim’s help system.
Doing Things More Than Once
23
“Commands” Don’t Sound “Painless”! I understand the feeling. But think of it like this: When you tell someone to do something, you usually have a noun, a verb and a location, like “Bring the car around.” In this sentence, bring is the verb, the car is the noun, and around is the location. Vim commands are compact sentences telling vim what to do. The operator is the verb (things like “delete” or “copy”), the text object is the noun (“5 lines” or “current word”) and the motion is the location. This syntax gives you the flexibility to make specific changes to the text quickly.
For now let’s practice a bit. Open the file counts.txt and go to line 9. There are four lines here that are just begging to be deleted. Let’s fulfill their wish, with three keystrokes. Using the operatorcount-motion syntax you can just type d4j and those lines are gone. Only they’re not. You can use counts with p as well. Go down a few lines and paste them back two or three times. We’re not sure when you’d want to paste multiple lines multiple times, but it’s worth playing with at the very least.
Behold The All-Powerful Dot This particular trick doesn’t have anything to do with counting, but it will be used with counted actions a lot. The . character, that simplest of all characters, is one of your best friends in vim. It’s meaning is simple: it repeats the last change you made to the text, but at your current position.
What is a “Change”? A change is anything that alters the text between two normal mode commands. If you go into insert mode, add three empty lines, write two paragraphs, and then delete the first paragraph all before you go back into normal mode vim will call all of that one “change”. For this reason, vim folks like to suggest that you keep your changes small: edit a few characters or a line and then get back to normal mode as quickly as possible. This has two advantages: first, it means that the u key is more useful, because it will only undo a little bit of work instead of removing two paragraphs. And second, it makes your changes more reusable, as we’re about to see. It’s worth remembering that you can make changes from normal mode as well. Using dd to remove a line is a change, just as if you’d deleted the line from insert mode. The . command will redo normal mode changes just like it will insert mode changes.
In counts.txt there’s a wonderfully contrived example: The simple “Jack and Jill” nursery rhyme, but somehow “Jill” got replaced with “Jack”. Which means the first line reads
Doing Things More Than Once
1
24
Jack and Jack went up the hill to fetch a pail of water
That’s a good trick, Jack! Let’s fix up the second “Jack” using the change operator. Position your cursor after the letter J: 1
J|ack
And type cw (that’s “change everything from where the cursor is to the end of the word”). You should now have 1
J|
And be in insert mode. Type ill and hit . Now that the second Jack is a Jill, you can read through the rest of the poem and find any other mistakes. On the third line it says 1
And Jack came tumbling after.
Which makes no sense. Slap your cursor down like last time, but instead of typing cw you can just hit the period button and bam! Your last change is repeated with a single keystroke. If you’ve ever had to change all instances of a variable name in a file you can readily appreciate how useful this can be. It’s especially great when combined with searches, but more on that later. The dot command is a good reason to be selective about what you do in insert mode, and how much you do between returns to normal mode.
8. Moving Around in Vim: Dance Steps Now let’s take everything we’ve learned about motion and give it a few last tweaks to make it really super useful. There are two text objects that look like they’re the same thing but aren’t. The difference between them can either cause you problems or make your life better. These text objects are words and WORDS.
Words and WORDS The easiest way to describe a WORD is that it’s every character between one whitespace and the next. Thus http://I.am.a.frog.com is a single WORD, even though you and I would parse it as six words1 . The lowercase “word” text object is any uninterrupted series of letters. Thus http://I.am.a.frog.com is made up of six “word” objects, separated by punctuation marks. When you compose vim commands, you’ll specify that you want to operate on a “WORD” with a W and a “word” with a w, as you might expect. If you want to play with the differences you can check out motion3.txt, and have a look at the exercises there. Using the url above, you could position the cursor at the beginning of the word frog and change just that word with the cw command. If you wanted to change the entire string into something else you could put your cursor at the beginning of the line and type cW instead. But always moving your cursor to the beginning of a text object to operate on it is a pain. Vim is smart, and can figure out where word boundaries are even if your cursor is in the middle of the word. You just need to tell it what boundaries you’re looking for. You can do that with the “inner” and “all” command modifiers.
Inner and All As you know, the text object commands w s l operate on the current text object (either a word, a sentence or a line, respectively. Check the table if you need a quick refresher) from your cursor position to the end. But what if you’ve got a long word like “Omphaloskepsis2 ” and your cursor is somewhere around the first s? It’s silly to have to move your cursor back to the initial O just to be able to delete the word, and vim has a much better way. You simply tell vim how to handle the borders of the text object in question and what to do with the text object. What constitutes a border depends on the kind of text object you’re using. A “WORD” is 1 2
Or possibly five words and a protocol specification. Contemplation of your navel as an aid to meditation. Really.
Moving Around in Vim: Dance Steps
26
bordered by whitespace on both sides. A “word” is bordered by whatever isn’t a letter on either side. A sentence is bordered by a line ending or period. In general, vim works hard to match its concepts of borders to what humans think of as borders. If you tell vim to operate on an inner text object it will leave the borders alone. For example, if I do a diw on the word “Galt” in the sentence Who is John Galt? we are left with Who is John ? Which isn’t grammatical, with that question mark floating around by itself at the end. However, if I were doing a ciw instead it would preserve the space between John and whatever new last name I want to give to Ayn Rand’s character: 1
Who is John Punchfist?
Much better. However, when you’re straight up deleting text, you often want to modify all of a text object, spare whitespace included. To do this change the i in the previous commands to an a. If I had said daw on John’s last name in the example above the resulting sentence would have read Who is John? which is perfectly grammatical, if a bit vague, and nowhere near as awesome as asking who John Punchfist is. You can no doubt see why I wouldn’t want to do caw there, because then I would have to type that space between “John” and “Punchfist” back in all by myself. Can you even imagine? But i and a can do more than that. The “Inner” and “All” commands operate on just about any text object, including some fairly clever ones. Vim is smart enough to know that some symbols, like parentheses and quotation marks, wrap text objects that you may want to operate on as a whole. So it’ll let you! For example, consider the following sentence: 1
"Hello there! (He| lied)". Ted was always cheerful.
Not only is it terrible writing, it’s terrible grammar. But it’s a fun sentence to play with. Let’s say we want to get rid of the whole (he lied) bit. Easy! We’re going to tell vim to “Delete everything inside these parentheses, and take the parentheses with it.” It’s easier in vim speak, just type da( Just like that you’ve got 1
"Hello there! |". Ted was always cheerful.
Now let’s say we want to change Ted’s greeting. Since your cursor is already inside the quotation marks you can change the text between quotes and leave the quotes alone. ci" is your command of choice, and you can make Ted say whatever you want:
27
Moving Around in Vim: Dance Steps
1
"| ". Ted was always cheerful.
Vim is smart about these enclosures, and there are quite a few you can use. Here are a few of the more obvious ones: Enclosures
Enclosure
Meaning
{ [ < t
Everything between two curly braces Everything between two square brackets Everything between two angle brackets Everything inside the closest XML or HTML tags
These all give you an easy way to modify exactly the text you want to change and nothing else.
Move by Counting We’ve already seen the beginning of this concept in the Using Counts section, but let’s flesh it out a bit here. Motion commands are still commands, and you can tell vim to repeat them just like anything else. This means that you can move five words right by simply typing 5w, or you can move six lines down: 6j. This is often a faster way to get where you’re going than hitting j j j j j j. But not always. The reason for this is the human ability called subitizing3 . Simply put, we as humans can easily recognize groups of things up to about three or four without counting them, but once you get above four we slow down considerably. In vim terms this means that if you look at a sentence and see that you have to move three words right you will just hit 3w without thinking about it. But if you have to move six words right you’re probably counting those words, then entering the command, and that’s often slower than just mashing the w key six times, or (even better) just searching for the exact spot where you need to make your changes. More on that coming soon.
(Book)marks Every once in a while you want to get from place to place quickly and easily without counts, without searches, without doing anything but telling vim where you would like to go, thank you so very much. Kind of like a bookmark in your browser, but for a text file. That’s what marks are for. A mark is just a pointer to a line in a file. If you set a mark at line seven of a file that’s where it will stay, giving you an easy way to return to line seven. But vim wouldn’t leave anything that boring or underdeveloped. 3
https://en.wikipedia.org/wiki/Subitizing
Moving Around in Vim: Dance Steps
28
Just a quick note: Vim calls these “marks” not “bookmarks” for the good and proper reason that vim is an editor, not a book. Just so you know. Okay, as you were.
The marks are roughly divided into two groups: lowercase marks and uppercase, orfile, marks. The obvious difference between the two is how you refer to the mark. The important difference is that lowercase marks are limited to lines inside a single file, while uppercase marks can jump freely to any line of any file. The two types of marks work in much the same way with slight differences. Let’s look at how to use lowercase marks first. To set a mark you type m followed by a letter in normal mode. That’s all there is to it! Unless of course you want to get back to that mark later. Then there’s a little more. There are two ways to return to a mark. If you want to return to the exact character on the exact line where you set the mark you type a back tick (usually the same key as ∼, right next to the number 1 on your keyboard) and the letter. So if you set mark a on line 5 you could then go anywhere else you want in the file and jump back to line 5 by typing 1
`a
If you only want to get to the line where you set the mark you can use a straight single quote (same key as double quotes, next to enter) and the letter. To get back to line 5 at the beginning you can just type 1
'a
And you’re good. But wait, there’s more! (There’s always more.) Whenever you jump to a mark, vim remembers where you jumped from, and stores it as a special mark ’ . So you can jump to line 5 with your a mark, make your change, and then just hit the single-quote key twice and you’re back where you started. Naturally, you can do this with any letter from a to z, meaning you’ve got twenty-six marks you can set in any file you’re working on. But what about when you’re working on a bunch of files? That’s where the uppercase marks come in. Uppercase marks behave the same way as lowercase marks, with one notable exception: they allow you to jump from one file to another with the greatest of ease. Like the lowercase marks, uppercase marks are set on a specific character of the file, meaning not only can you get from sample.c to sample.h in a single motion, you can get to line 471 of sample.h from anywhere with a single motion. But as much fun as it is to write c code, let’s talk about an uppercase mark that is instantly useful to every vim user everywhere. This is an exercise that you’ll definitely want to do. • Open your .vimrc file in vim.
Moving Around in Vim: Dance Steps
29
• Type mV • Open any other file in vim. • Type 'V Boom! You can now get to your .vimrc configuration file from anywhere at any time. While it’s true that you will eventually stop playing around with your configuration on a daily basis, when you’re first learning and configuring vim to work for you instead of against you this particular mark can save you a lot of time.
9. Modes at Last Given that modes are an integral part of vim, given that an understanding of modes is integral to using vim well, why did I decide to put off the chapter on vim’s modes until way into the text? There are a couple of reasons. The first one is that I believe in learning by doing. By now switching between normal mode and insert mode should be fairly familiar, so the concept doesn’t seem so foreign. So now you’re ready to learn a bit more. So, without further ado, let’s get into vim’s modal nature. This is often the thing that scares people off, so we’re going to take it easy, and remember to breathe. Remember: you’ve already been using this stuff, we’re just putting names to things you’ve already been doing.
What Modes Are The simplest way to think about modes is that they change your keyboard. In insert mode the keys put letters on the screen, just like in a regular ol’ word processor. But when you switch into a different mode your keys change from letter-putters into command-makers 1 . The h j k l keys go from being four letters to being arrow keys, . changes from a full stop into the “do it again” button, and so forth. So far so good. You’ve been using both of these modes for a while now, and none of this is much of a surprise. What you don’t know is that you’ve been using a couple of other modes as well, and now that I’ve mentioned them I’m maddeningly going to go back to discussing normal mode and insert mode before I talk about two other modes that you never knew you were using.
What is Normal, Anyway? In Mostly Harmless, the fifth book in Douglas Adams’ Hitchhiker’s Guide Trilogy, there are animals called “Perfectly Normal Beasts” that suddenly appear out of nowhere on one side of a plain, thunder across the plain in giant herds, and suddenly disappear on the other side of the plain. Six months later they do the same thing, but backwards. They’re called “Perfectly Normal Beasts” because someone was wise enough to realize that calling them that would help people accept their totally impossible behavior as something that just happens, not something to get all worked up about. Normal mode in vim is almost entirely unlike that, but there’s a similar concept at work. As you know, normal mode is where you issue commands, not where you edit text. Most newcomers to vim find this ironic in the extreme. After all, vim is a text editor, not a command editor. Shouldn’t 1
Sorry about the super-technical jargon there.
Modes at Last
31
editing text be the “normal” mode and “doing weird stuff with counts and operators and motions” be the “special” mode? The answer, in vim’s mind, is “no”. And if you think about how you write software you’ll see why. In software development, you don’t just sit down, pound out code at 80 words per minute for 8 hours and then go home, a job well done. Software is written incrementally and iteratively, with a lot of time being spent looking at the interconnectedness of your various methods and variables and whatnot. You write a function header, give it some space between some curly braces for the function body, realize you forgot a needed parameter, add that, write some function code, realize you’ll need to call a new function you haven’t written yet, dummy that one up, and so forth. Coding isn’t as much like writing as it is like drawing 2 . When you draw, you start with some guide lines, an oval for a face, with crossed lines to give you dimensions. Rough outlines of background and scenery get sketched in, and little by little, line by line, the rough outlines are added unto, refined and turned into a finished product. It’s hard to say where they made the jump, but out of all those seemingly disconnected lines a work of art emerges. Code is the same way. We add line upon line, sometimes putting in scaffolding code that will only be there for a little while, then be discarded when the logic it was supporting can stand on its own. It’s hard to say when, but somewhere in the process that seemingly random collection of lines of code 3 turns into a finished product. Well, okay, it usually happens when some manager says that we absolutely can’t miss another deadline or we’ll all be fired and we’ve got to ship something right now, but you get the picture. Which is nice and all, but what does that have to do with “normal” mode not being “insert” mode? To answer that (here we go again) think of how an artist draws. They don’t sit there, staring at the paper with their pencil pressed against it. Nor do they drag their pencil across the page when they want to work on a different corner of the drawing. And so it is with vim. Your “pencil” is your cursor, and for the most part it shouldn’t be sitting on the “paper” of your text file. You should be able to move it around without worrying about changing things along the way. This is the intent of “normal” mode. In normal mode you can move your cursor around and do quite a bit of very useful editing, but you won’t be adding new pencil strokes to the masterpiece that is your document.
--INSERT-- Means You Are Free to Type Normally. Insert mode was also very carefully named. You can do a lot of editing from normal mode, but you can’t really add new text. To do that you need to have your keyboard turn back into a standard press-letter-keys-and-letters-appear keyboard, and that’s what insert mode is all about. It still has a few tricks up its sleeve, though. We’ll get into some insert mode commands that let you make intelligent changes to the text without going back to normal mode. Since most of the 2 For that matter, writing prose isn’t usually a linear process anywhere other than junior high either. But we’ll stick with the metaphor for now. It’s probably worth pointing out that I don’t know anything about art, so the following analogy may be a bit odd. 3 See what I did there?
32
Modes at Last
heavy lifting is done in normal mode, insert mode is pretty light on commands, but there are a few. We’ll get into the fancier ones in the chapter on Fancy Insert Mode Commands and a little bit in the chapter on Registers. For now we’ll just do two simple ones: t and d. These two commands are incredibly simple: t indents the current line by one tab (more or less) and d outdents it by the same with4 . The application of this should be pretty obvious, especially if you work with structured code, like Python or HTML. lining up statements in a block makes them easier to read. But these two commands also show off an important point about insert mode commands: they all start with and a letter. See, this is the value of Painless Vim. Gems like that. In fact, I’m going to put it into a fancy tip block, just to reemphasize the point: Insert Mode Commands all Start With and a Letter.
Okay, Let’s move on.
Command Mode: The One You’ve Been Secretly Using all This Time. So, technically, every time you press : in normal mode, you’re entering a brand new mode called command mode. You’ve been using command mode ever since page 1, where you typed :q! to get out of vim. And this demonstrates the majority of uses you’ll have for command mode. In general it’s used to issue commands to vim that have little or nothing to do with the text you’re editing. :q is a perfect example: quitting the editor is a vim command, not a text command. We’re not going to deep-dive on command mode right now, just know that when you see a command with a : in front of it you’re probably looking at a system command.
How to Accidentally Enter Command Mode I do this all the time, and it’s always when I absolutely don’t want to. Here’s the thing: if you hit q: vim will enter command-line mode, with a history of all the commands you’ve run recently above the command line. This is super useful if you want to re-run a command quickly. It is much less useful if you meant to hit :q to exit vim. If you mess this up like I do you have two choices: either just hit (thus executing an empty command) and then hit :q the right way, or navigate to the last time you exited vim and re-run that command.
4
Technically they both move the cursor by one shiftwidth, which is usually four spaces and is usually the same as one tab.
Modes at Last
33
For more information on this actually quite useful command check out the vim help: :h q:
Visual Mode: Marking Text Now we’re getting into new territory. Visual mode is one we haven’t hit on before at all. Visual mode is often fairly neglected, which is too bad because it’s also very useful. In Visual mode, you visually select an area of text to edit, instead of counting or searching or what have you. Basically visual mode lets you mark the beginning of a section of text, move the cursor to the end of the section, and then enter an operator to operate on that chunk of text. There are three ways to enter visual mode: • v enters “characterwise” visual mode. In this version you can edit an area as small as a single character, up to the entire document. • V enters “line-wise” visual mode. In this mode you can operate on one or more lines all at the same time. • v enters “block-wise” visual mode. In this mode you can edit a block of characters that can span rows and lines and can be pretty much any dimensions you choose. All three types of visual mode have their uses, and we’ll go more into depth in the chapter on Visual (Mode) Basics. But for now we’re just going to acknowledge that visual mode lets you select ranges of text visually and move on.
…And all the Rest There are other modes, of course. According to vim’s built-in help there are six “basic” modes and six “additional” modes, which are variants of the basic modes. But for the most part they’re not super useful, and definitely not painless, so we’re going to blithely ignore them, after pointing you to a reference5 where you can learn a whole lot more. Here it is.6 5 6
technically a page from vim’s official help system, which we will get to soon. http://vimdoc.sourceforge.net/htmldoc/intro.html#vim-modes-intro
10. Plugins Vim is a great editor, but there is always room for expansion and improvement. Unfortunately, a small open source team can’t possibly keep up with every new language, technology, coding style, and theme needed to keep every developer in the world happy and productive. Fortunately, vim was designed so that those self-same developers can create plugins for vim that extend its functionality as new needs arise. Vim’s plugin system is as simple or as difficult as you want it to be. While the processes of creating a vim plugin is beyond the scope of this book, using them is something with which you should be intimately familiar.
What a Plugin Is In the simplest possible terms, a plugin is a set of new functions, shortcuts, and scripts that make vim work better in some specific way. It may be something as simple as syntax highlighting rules for the latest and greatest language to come down the pipe, or it could be an entire git repository management system. If you’ve ever added a new theme or extension to your browser you can think of vim plugins the same way. There are a few ways to install plugins for vim, but we’re only going to cover two of them: the hard way (meaning the totally manual way) and the easy way. Since this book is called Painless Vim I would be remiss if I didn’t give you a nice link to the easy way right here. So there it is.
Plugins the Hard Way Wow, you actually decided to read through this section. Okay! Well, that’s probably for the best, because even doing things the easy way you’ll have to go through these steps at least once. Fortunately, the hard way isn’t really all that hard; it’s just very manual. It involves moving files around by hand and whatnot. Since I’m still shooting for a Painless type book I’m going to choose a simple plugin as our example. Show Marks1 is a plugin that makes your marks visible, hence the name. To install it you have to do the following: 1. 2. 3. 4. 1
Download the .zip file from the link above Unzip the file Copy the unzipped file into your $HOME/.vim folder Restart vim
http://www.vim.org/scripts/script.php?script_id=152
Plugins
35
Man! Dang, sorry about all the hard work there! Whew! I’m sweating from all that hard hard work! Okay yeah it’s not that hard at all. But like I said, that’s an easy one. There are plugins that are significantly more complex, requiring you to copy several files into several locations…okay, it’s not ever all that difficult, but if you’ve got a lot of plugins it can get confusing to keep them all straight, and should you decide to get rid of one it can be a pain to clean up after that plugin and get rid of all the files it brought down with it. Fortunately, there is a (much) better way.
And Now, the Easy Way Unsurprisingly, there have been other people who have looked at the vim plugin installation procedure and decided that there is room for improvement there. While there are a number of plugins that help you manage other plugins, I’m just going to talk about one of them in depth. There are links to (and a few comments about) other plugin managers in the appendix. I’ll be covering Pathogen2 because it’s the one that I personally happen to like best. Pathogen requires very little by way of setup, and the homepage has clear instructions on how to install it. The “copy and paste” instructions work exactly as they should. Once you’ve installed Pathogen, you can start installing other plugins simply by cloning them into your ∼/.vim/bundle directory and Pathogen will make sure they’re all loaded correctly when you start vim. That part is nice and easy to understand, but that’s only half of the value. Pathogen is set up to put each plugin in it’s own directory, meaning it’s trivial to remove a plugin should you decide you don’t like it any more. You just delete the plugin’s folder from the bundle directory and restart vim. Once you have installed some favorite plugins just restart vim and they should be ready to go. But wait, there’s more! (there’s always more). Pathogen gives you a single command to integrate the help files from each of the plugins you’ve installed into Vim’s help system. All you have to do is run :Helptags from the vim command line and it will scan all the plugins and get the help system set up. One step, no problems. You could put the Helptags command in your .vimrc file, but the author of the plugin doesn’t recommend it.
Let’s Install a Plugin! Okay, let’s put the rubber to the road. I’m going to operate under the assumption that you have already installed Pathogen following the instructions on the Github site. Once that’s done we can move on. Go ahead. I’ll wait. Okay! Let’s install the Commentary3 plugin. This plugin makes it trivial to do line and block comments in many types of files using some pre-set keystrokes, and is super-useful for all of us programmer types. So, all that said, follow the steps below to install Commentary: • Open a command line 2 3
https://github.com/tpope/vim-pathogen https://github.com/tpope/vim-commentary
36
Plugins
• Enter the following at the command line: cd ∼/.vim/bundle git clone https://github.com/tpope/vim-commentary.git • Start up vim and type Helptags Okay! The plugin is all kinds of installed now! To learn more about how Commentary works just type :h commentary and vim will start up its help viewer to show you everything you need to know. If you’re still afraid of the help system, that’s understandable. You can wait until the chapter on Help Files. It’s coming right up.
A Word About Tim Pope You may have noticed that both Pathogen and Commentary are plugins created by a man named Tim Pope. Good eye! The fact is, he’s done a lot more. Tim Pope is definitely a vim power user, and he’s not stingy with that power. There are a lot of other useful plugins that he’s created, such as Fugitivea , which makes working with git repositories easy and fun, and Surroundb , which lets you simply surround or un-surround passages of text in all manner of bracket-like characters. So, get used to his name and maybe some day, if you get a chance, just hire him or whatever. It’d be worth your time. (This message was not paid for by Tim Pope or the Council to Elect Tim Pope as President.) a b
https://github.com/tpope/vim-fugitive https://github.com/tpope/vim-surround
Nate’s Favorite Plugins Remember that whole “opinionated” thing from the introduction? Well, here comes a whole wave o’ opinions. These are plugins that I like and use on a daily basis. Feel free to check them out and see if they work for you.
CtrlP CtrlP4 gives you fuzzy matching file finding, a la SublimeText or Textmate. If you don’t know what that means, you just hit p and start typing any part of the path or filename you can remember and the plugin will find the file you mean. It’s wonderful.
NERDTree 4
https://github.com/kien/ctrlp.vim
Plugins
37
NERDTree5 provides a nice sidebar to vim that gives you a file explorer, much like you’d see in any other text editor. This makes it easy to find the file you want to work on. If you decide to use NERDTree I would recommend adding a line to your .vimrc like the following: 1
noremap n :NERDTreeToggle
Don’t worry about what all is going on there (we’ll cover it more in the chapter about Key Maps, but the upshot is that you can type \n and have the NERDTree sidebar pop up. Then you can choose a file to edit and dismiss the sidebar with the same \n keystroke. When you get a little more comfortable with vim you can also use single key commands in NERDTree to edit files in their own window or tab.
Fugitive If you use git in any of your projects Fugitive6 is one of the best things to happen to vim. It gives you a simple and clear way to perform all the git commands you need without leaving vim. You can stage or unstage files simply and quickly, commit them from the same window, then go back to editing your source code. (More on (windows soon)[#windows].) One of the nice things about Fugitive is that it comes with a lot of keyboard shortcuts built in to make doing all the things you would normally do even easier; things like staging a file (position your cursor on the line and press -) and committing the staged files (type cc in the Fugitive window). Suddenly git and vim are best friends.
Zen Coding Zen Coding7 provides support for the fabulous Emmet Toolkit8 . If you haven’t played with Emmet yet, it’s a way to quickly write something like: 5
https://github.com/scrooloose/nerdtree https://github.com/tpope/vim-fugitive 7 https://github.com/mattn/zencoding-vim 8 http://emmet.io/ 6
38
Plugins
1
html>head>title{This is a webpage!}^body>p{Some text!}
and simply press Ctrl+y to have it expand into 1 2 3 4 5 6 7 8
This is a webpage
Some Text!