Painless Vim

Painless Vim is written by a professional developer who tried to learn vim a number of times before it finally stuck. I

307 45 1MB

English Pages [125] Year 2014

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Table of Contents......Page 5
I'm a Stranger Here, Myself......Page 9
Why Learn Vim......Page 11
What This Book Is......Page 12
Who am I?......Page 13
The Obligatory ``Conventions Used in This Book'' Section......Page 14
Get In, Get Out, Get Comfortable......Page 16
Line numbers and Moving Around......Page 17
Moving Around in Vim: Baby Steps......Page 19
Zoom!......Page 21
Your .vimrc File And You......Page 22
I Was Promised Color Schemes!......Page 24
Using Keymaps to Get Unlost......Page 25
Interlude: The Joy of a Good Cheat Sheet......Page 27
Moving Around in Vim: Grown Up Steps......Page 28
Operators 1: Changing Letters and Lines......Page 30
Operators Alone: Changing Single Characters......Page 31
Operating on a Line......Page 32
How to Instantly Make Your Life Easier with cc (or C)......Page 34
Using Counts......Page 36
Using Text Objects......Page 37
Behold The All-Powerful Dot......Page 38
Inner and All......Page 40
(Book)marks......Page 42
What is Normal, Anyway?......Page 45
–INSERT– Means You Are Free to Type Normally.......Page 46
Command Mode: The One You've Been Secretly Using all This Time.......Page 47
…And all the Rest......Page 48
Plugins the Hard Way......Page 49
And Now, the Easy Way......Page 50
Nate's Favorite Plugins......Page 51
Move-and-Edit Commands; or ``Vim Commands 202''......Page 54
Interlude: How to Back Off Without Giving Up......Page 58
Say Hi to the Named Registers......Page 59
Little Changes, Big Changes......Page 60
Really Actually Deleting Stuff......Page 61
Text Origami. :h folding......Page 62
Okay, But How Do I Fold Things?......Page 63
Find Me Another One of These: * and #......Page 65
Line Searching: t/T and f/F......Page 66
R…R…Regular Expressions?!?......Page 67
Getting the Help You Need......Page 71
Relatively Shallow Secrets of the Help System......Page 72
Doing Things at Vim Speed......Page 74
All the Key map Commands......Page 76
Take me to your Key!......Page 77
What not to map......Page 78
What to Map......Page 79
......Page 80
Recursive Mappings, and How to Avoid Them......Page 81
r Funtimes......Page 84
Completions!......Page 85
Window Commands begin with w......Page 86
Resizing Windows h: window-resize......Page 87
Moving Windows Around :h window-moving......Page 88
How To Use Tab Pages :h tabpage......Page 90
Files......Page 92
Tabs......Page 93
Updating Vim......Page 95
Blockwise Visual Mode :h blockwise-visual......Page 97
Common Visual Mode Commands......Page 99
Setting Expectations, Then Setting Some Settings......Page 100
Setting the Font in gvim......Page 101
Menus Everywhere! :h menus......Page 104
Adding a Menu......Page 105
Keeping Things In Order......Page 106
Linux and Windows......Page 107
MacVim is a Special Snowflake!......Page 108
Setting up the a Writing Workflow......Page 109
Writer-Friendly Vim Settings......Page 110
Spreading the Word: How to Get Your Message Out Into the World......Page 111
More Formats! I Need More Formats!......Page 112
Conclusion......Page 114
Great Books on vim......Page 115
Bundle Managers......Page 116
Commands......Page 117
Folding......Page 118
Tab Commands......Page 119
Appendix 3: Sample .vimrc files......Page 121
About the cover......Page 124
Special Thanks......Page 125
Recommend Papers

Painless Vim

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

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!



In essence, you just write what you mean and emmet turns it into HTML. It’s pretty great.

Vim Colorschemes I only kinda recommend this one. Vim Colorschemes9 packs a few hundred of the most popular colorschemes into a single plugin. Once installed you can switch to any of them by just changing the colorscheme line to whatever scheme you want to use. Most of them are pretty solid, battle tested schemes that a lot of people have used, but this is definitely a case where your milage may vary. The reason I “only kinda” recommend this one is that it’s entirely possible to waste a whole day choosing your favorite colors for things. Not that I would ever do that. Five times a year. I mean, it’s not like I’ve already switched color schemes once in the middle of writing this book, or anything. Seriously, choose one you like and then stick with it forever or else you’ll go insane. Save yourself! 9

https://github.com/flazz/vim-colorschemes

11. Operators: Moving and Changing at the Same Time So, now that you know all about counting and Operators and all the nuances of moving the cursor around, we’re going to solidify our understanding of how motions and operators can work together.

Move-and-Edit Commands; or “Vim Commands 202” Okay, we’re going to re-hash a little here. A vim command consists of: • An operator • A count • A motion Depending on the situation, all three are optional. If you type 4 by itself vim will wait for you to tell it what to do four times. So you can give it a motion, like j, and it will move the cursor down four lines. Or you can give it an operator like p to paste something four times. Or you can give it both an operator and a motion, like dl to delete the next four characters. The last one is an example of editing by motion. Deleting a bunch of lines at once is just the tip of the iceberg. The great thing about learning to edit in this way is that once you’ve got the hang of it you can combine commands to make any change you want. Let’s take a look at something I’m doing at work right now: Writing a Gruntfile.js configuration script for the Grunt1 automation system. What Grunt does is immaterial to the discussion; for now all we need to know is that there’s a section that looks like this:

1

http://gruntjs.com

Operators: Moving and Changing at the Same Time

1 2 3 4 5 6 7 8

40

grunt.loadNpmTasks('grunt-contrib-jade'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy');

And so on for a bunch of lines. Now, I could have entered each of these lines by hand, but that’s just stupid and painful and pointless. Vim made it much faster. The nice thing is that there are a couple of fast ways to do this, depending on how much thinking ahead you were able to do. Let’s look at some repetitive editing tasks, from the least forethought to the most.

Least Forethought: Copy this line So, let’s say I typed the first line, and realized that I’m going to add another line just like it. I start out with this: 1

grunt.loadNpmTasks('grunt-contrib-jade');

And with my cursor at any point on that line I type yyp. In other words “yank the entire line and paste it.” Now I have 1 2

grunt.loadNpmTasks('grunt-contrib-jade'); grunt.loadNpmTasks('grunt-contrib-jade');

Which is close to what I want. I can get my cursor to the word jade in the second line, type ciw and replace it with the word watch. There! I’ve added a new line. What’s more, I can just type p and I’ll have a third line that I can modify in the same way. I can keep doing this until I’ve got all the modules I need listed in my Gruntfile.

Slightly More Forethought: Copy this line. A LOT. Okay, so let’s go back to square one: I’ve got the first line written, and I realize that I’m going to need more than one copy of the line. No problem. But since I’m thinking ahead this time I’m not going to copy the word jade because I’m just going to change it in all of the copies. So I’ll delete the word right now, giving me

Operators: Moving and Changing at the Same Time

1

41

grunt.loadNpmTasks('grunt-contrib-');

This has the added side-benefit of throwing an error if I try to run grunt, since that’s not a real module. A little added error checking is a good thing, I say. I’m thinking ahead, so instead of just hitting p to give myself a new copy I hit 7p and have seven new lines ready for me to edit. Not bad! Now, I realize that sometimes you don’t know how many nearly-identical lines you’ll need, but we’ll pretend it’s more common than it is, because otherwise the next section is entirely pointless.

Uncanny Levels of Forethought: Knowing how many copies you want Before you start typing Let’s say that you know, right this moment, that you’ll need 8 copies of a line that you haven’t even typed. Good for you! You can do this all in one step, and here’s how. Ready? Watch close, this’ll go by fast: 1

8i grunt.loadNpmTasks('grunt-contrib-');

And you’re there. You can see that all we did was put a count (namely, 8) before the “enter insert mode” operator i. So we told Vim to re-do anything we do in insert mode eight times. This is awesome, no? Again, I realize that it’s not always what you want to do, nor is it even OFTEN something you want. But knowing about it is useful for two reasons: one, you can pull this trick when you need it, and two, you can figure out what just happened when you pull a trick like missing the G key and instead of going to line 55 and typing something you type something right where you are, then copy it 55 times. Not that I’ve ever done that. Today. In this chapter. Cough What?

The Triumphant Return Of The Almighty Dot Okay, but here’s the most useful edit-by-motion command you’ll ever see ever. Let’s say you’ve got a file where the indentation is all messed up, and there are entire methods that are over-indented. In the old days (assuming you weren’t using Sublime Text in the old days) fixing this involved using the mouse to highlight all those lines and then hit shft-tab to un-indent that method. Vim can do you one step better. If you can quickly count all the lines you want to operate on at once, you can just put that number in front of the to make the window wider (think of it as pushing the right side of the window out farther). To make it thinner you do the opposite: w : Make the window wider to indent the region by one “tab”1 . Similarly, pressing < while in visual block mode “outdents”2 the entire region by one tab. 1 2

Technically one shiftwidth, but who’s counting? I know that’s not really a word, but it’s easier to say than “reduces the indentation level” the entire region by one tab.

Visual (Mode) Basics :h visual-mode

84

Common Visual Mode Commands Block mode’s Prepend feature is great, but there are a lot of other features that all the visual modes share. here’s a quick highlight list: When you’re in a visual mode, you can use o to jump between the beginning and end of your selected region. This is helpful if you want to expand the selected region to include a few characters you missed at the beginning, then jump back to the end of the selection and grab a few more characters there. In normal mode gv will re-select your previously selected area, which is useful if you…want to select the same area again. If you’ve recently done a search gn will highlight everything between your cursor and the next occurrence of the search term, while gN will select everything between your cursor and the previous occurrence, much like n and N move your cursor between occurrences of a search term. Again, this is not a complete list. If you want to see all the commands and text objects you can use while in Visual mode you can check out the help document in vim by using :h visual-operators.

25. Vim GUIs There are a lot of good reasons to use vim from the terminal: it’s fast, light on your system, and when paired with tmux it lets you keep all your command line eggs in one basket. But there are good reasons to use the graphical versions of vim as well: they’ve usually got better system integration, buttons, tabs, and all the things you thought you were losing forever when you started on this vim adventure. Let’s spend a little time exploring the graphical side of vim. There are (more or less) three different graphical versions of vim: gvim, MacVim, and Windows Vim. But all of them will start if you call gvim at the command line, so we’re going to call all of them “gvim” for the sake of simplicity. Installing them is beyond the scope of this book, because the process varies so much from system to system. A search engine is your friend in this case.

Setting Expectations, Then Setting Some Settings First off, let’s clarify what we mean when we say “graphical” vim. You’re not getting a full on IDE like IntelliJ or Visual Studio. In general what you get is system chrome around a regular vim session, and a few other perks. If you use tab pages they will be rendered as actual, clickable tabs, just like in an IDE. There can be a few buttons on the screen. You can play with menus, if that’s your thing. We’ll get to all these things in a minute. But first, let’s talk about settings. Throughout this book I’ve been showing you changes you can make to your .vimrc file, the allpowerful settings file that tells vim how to behave. And if you want, you can just keep using that file to hold all of your gvim-specific settings. But there’s a better way. You see, when you start up gvim it sources1 your .vimrc file first and then looks for a file called .gvimrc. If it finds that file it will source it as well. If you don’t have a .gvimrc file then it’s done. There are two benefits to this approach. The first is that you can keep your gvim settings all in one place and not have to wade through them when you’re working on your regular vim stuff. The second is that vim doesn’t have to wade through them when you’re just loading up terminal vim. The third (okay, there are three main benefits to this approach) benefit is that you can override settings from terminal vim when you run gvim. If you don’t already have a .gvimrc file set up you can simply start editing it and put all your gui-specific stuff in the new file. And what kind of stuff would that be, you ask? You can find an exhaustive list of all options you can set by going into vim and typing :h option-list as you might expect. As you might also expect, this list will give you a slight headache2 if you try to process it all at once. For our purposes you can do a search for the string gui to get to the options we’re thinking about now. 1 2

Remember, in unix land when we say something “sources” a file we mean it “reads that file and does what it says.” And take up your entire day as you find new settings you want to add to your .vimrc

Vim GUIs

86

Most of these are things you won’t have to worry about directly, but there’s one that we all love: guifont.

Setting the Font in gvim In terminal vim you set your font in your terminal and it applies to everything that you do in that terminal. But if you want to set your font in gvim it’s a little different. I mean, sure you could just find a menu option that would allow you to set your font, but where’s the fun in that? I’m going to show you the way the cool kids set their gvim font in three easy steps.

Step 1: Use the Font Picker, Luke Open up gvim and type 1

:set guifont=*

on the command line. It should pop open your system’s font picker. MacVim will even be so kind as to choose the “monospaced” font group to give you the best code fonts. Choose the font you want, then close the font picker. You might think this would be the one and only step. You would be wrong, sadly.

Step 2: Find out What Vim Thinks Your Font Is Called Vim uses vimscript, an archaic language that uses a few non-intuitive conventions. Instead of figuring out how to tell vim what font you want by trial and error you can type 1

:set guifont?

And it will tell you what font you’re currently using. My gvim at the moment would say 1

Andale Mono:h14

The h14 part, as you might expect, is the size in points. Or h, apparently.

Step 3: Set the font in .gvimrc Okay, so now all you have to do is open up .gvimrc and paste in what you got back from the :set guifont? command, right? Well, almost right. If there is a space in the font name (like, say “Andale Mono”) you need to escape that space with a slash, like so:

87

Vim GUIs

1

:set guifont=Andale\ Mono:h14

And you’re set. Save the file, source it (:so % will still work, but will only do anything if you’re using gvim) and you should see your new font in all its glory. This gives you a pattern to follow for any other gui-only settings you want to change. If you want to see a bunch of useful settings see :h gvim. There are a lot of useful things you can play with, but in the next chapter we’re going to play with a fun one instead.

Why Are My Colors Different In Gvim? That is a good question with a long answer. If you’re not interested in the long answer here’s the quick version: tl:dr, Terminal emulators lie about colors. Okay, the short answer isn’t very helpful. The long answer is that terminals were originally meant to be big, dumb machines that sat on your desk and gave you access to a mainframe somewhere else in the world. Because networks were slow in those days terminals were monochrome, because sending color data required sending extra data, and sending data took time, and time is money, so you got one color. Extra colors are for closers. After a while the mainframe and the terminal merged into a single machine called the PC, and you were only sending data from one part of the system to another part of the same system. So we opened the terminal world up to 4, then 8, then 16 colors. And it kind of stuck at 16 for a long time. After all, it’s a terminal, why would you need more colors? To make things easier, those 16 colors were given namesa , so you could just tell the terminal to draw something in “blue” and not worry about exactly how “blue” was represented on the terminal.

“Bright Black” is my favorite color.

A few more years down the road, and monitors are to the point where they can represent lots of colors. So some smart people decide that their terminal programs will let you decide what each of the 16 ANSI colors actually look like on your screen. You can theme your terminal! If you want ANSI Blue to actually be green and ANSI Bright Blue to actually be purple, that’s all up to you! But it means that your vim color scheme might look really weird. These days, both vim and most terminal programs can represent a whopping 256 colors, but most themes are written using the standard ANSI colors, because not every terminal can display the whole 256 color palette.

Vim GUIs

The point of all this is that gvim and it’s kin will represent ANSI colors faithfully, while your terminal will represent them however you tell it to. Thank you for joining me on my rant about colors. a Technically they were added to a struct that mapped an integer to a standard color name, but you only care about that if you’re a C developer who wants to create a new shell that implements the ANSI colors.

88

26. Menus Everywhere! :h menus This isn’t strictly a gvim thing, but vim does give you the ability to make your very own menus. They work better in gvim than they do in terminal vim, but they can work in both places. Be aware, though, that this is a less painless topic than just about anything I have covered in this book.

Why would I want menus? It’s a good question. Vim is supposed to be the last word in touch editing, everything done via keyboard, nothing done via the mouse, right? And that’s not a terrible goal. But here’s the thing: there are a lot of commands to remember, and some of us could use a little break every once in a while, a little help with those awesome commands we only use every once in a while. Also, how cool do you feel when you have your own custom menu pop up whenever you want it? The bottom line is this: If you don’t want menus that’s totally fine. But if there is a set of commands that you would like to be able to use without memorizing them that’s fine too. Gvim’s menu system has you covered.

First off, gvim loads a standard set of menus when you start it. You don’t need to mess with them. You can if you want to; but you’re on your own there. I’m going to cover the basics of creating a brand new menu, and then show you how to make it pop up when you want it, wherever you want it. There are a lot of caveats in the menu stuff: parts of it work cross platform, parts don’t, so we’re going to cover a basic menu with just a few options. This menu will provide access to Tim Pope’s fugitive1 plugin, letting you run git commands without leaving vim. If you want to follow along exactly you’ll need to install that plugin first. Checkout the chapter on plugins for a quick refresher on how to add stuff using Pathogen. Okay! Let’s get started. Fugitive gives you access to a plethora of useful git features with parameters and ranges and powerful, intuitive features that we’re going to ignore completely. For now we’re going to provide access to exactly three features: • Git Status • Git Blame • Git Remove 1

https://github.com/tpope/vim-fugitive

90

Menus Everywhere! :h menus

Which, now that we look at it, would make a pretty good layout for our menu!

Make Sure You Test on a Git-Controlled File! When you’re testing your menu setup you need to make sure the file you have open in your editor is under git version control, or all the commands will fail.

Fugitive’s Gstatus command gives you access to a surprisingly wide array of functions; things like staging or un-staging files, and committing your changes. So naturally it would be the first thing we would want to add to our menu. So hey, I’ll start there.

Adding a Menu Adding a menu is similar to adding a keymap: you can set the menu to only work in certain modes, or all modes. You can make it recursive or non-recursive, etc. etc. And, like keymapping, you can test your new menus before adding them to your .gvimrc file. Let’s test it now: Open a file that is under git control and enter the following: 1

:menu Git.Status :Gstatus

And then hit . You should see a new “Git” menu item appear in your menu bar. If you click it you’ll see a “Status” menu item. Click that and you should see the awesome fugitive status screen pop up in a new window. Nice, right? In this example we just used the :menu option, which enables your menu in Normal, Visual and Operator-pending mode. There are other options, which leads to a familiar looking table: Menu Commands

Command ——————:menu :nmenu :vmenu :omenu :menu! :menu :amenu

Modes ———— Normal, Insert, Operator-Pending Normal Visual Operator-pending Insert, Command-line Command-line All

In this table I kinda saved the best for last there. Most of the time you’ll probably use the :amenu option. In fact, there are two shortcuts you can use if you’re just testing menus you haven’t put into

91

Menus Everywhere! :h menus

your config files yet! The commands :an and :am are both aliases for :amenu2 . Okay! Let’s get back to the menu definition we set up earlier. After you choose where you want the menu to be active you name the menu. You’ll notice that we called this one Git.Status. The period in the middle defines a sub menu, and you can keep going, if you hate your life and want to keep on nesting: 1

:menu Git.Should.Be.Easier.To.Use.Than.This.Status :Gstatus

And you get something a little like this:

Please, please don’t do this

But now that we’ve had our fun we’re going to go back to sane menus, hmm?

Keeping Things In Order Unless you’re some kind of crazy bohemian, you’re going to want to define the order in which your menus appear. You do this by adding a priority to the menu definition. The lower the priority number, the closer to the left the menu will appear. The default menus have the following priorities3 • • • • • • •

File: 10 Edit: 20 Tools: 40 Syntax: 50 Buffers: 60 Window: 70 Help: 9999

In general they suggest not setting the priority of your menu higher than 9999, but nobody’s stopping you. To create a menu with a priority you just put the priority before the menu command, like so: 1

:80menu Git.Status :Gstatus

Which will put your menu after the Window menu. If you don’t give a priority vim will assign your menu a priority of 500. If you want to set priorities for sub menus you put the priorities in a dot-seperated list after the menu command: 2 I’m not sure why :an is in there. I like to believe that someone just kept hitting the wrong key and finally decided to map the command so that it would work. 3 you can see this list in the help text by using :h menu-priority

Menus Everywhere! :h menus

1

92

:menu 80.100 Git.Status :Gstatus

Will put the Git menu after window, and set the Status menu fairly early on the list (because any menu without a set priority will default to 500). Okay, so, armed with this information, let’s create the menu for our thee git commands. The following would go well in your .gvimrc file: 1 2 3

:menu 80.1 Git.Status :Gstatus :menu 80.2 Git.Blame :Gblame :menu 80.4 Git.Remove :Gremove

Save your file, source it, and you should have a pretty git menu all ready to go.

Making the Menu Come to You One of the whole points of vim is that you don’t have to move your hands from the keyboard to do things. Which makes menus a problem. You have to pull one hand off of the keyboard, move the mouse all the way to the top of the screen to click on some stuff, and then get your hands back into position. Well, we’re going to get rid of one of those steps. Vim provides a :popup command that lets you call a specific menu to the position of your cursor. So, let’s say you want your new git menu. Just go to the command line and type 1

:popup Git

And the Git menu should show up…somewhere close to your mouse. The behavior of the popup option isn’t totally reliable, and it may go away at some point, but for now it looks super awesome. It looks even cooler if you map a shortcut, like so: 1

nmap g :popup Git

So, armed with this knowledge, we can move on. The problem is that there are two divergent paths from here. Vim on Linux or Windows works pretty much the same, while MacVim has some of its own ideas about life. Choose the section that works best for you.

Linux and Windows If you look at the File menu on gvim under Linux or Windows you’ll notice that some menu items have underlined letters, and even shortcuts listed to the side of the menu item. You’re probably familiar with these from, well, every other program. If you press o when the File menu is open it’ll open a new file. You can define both accelerator keys and reminders for your menus as well. All it takes is a few little additions to the menu command. Let’s go back to our Git.Status entry. If we want to define g as the command to open the Git menu, we would set it up with an ampersand (&) before the letter G:

Menus Everywhere! :h menus

1

93

:menu 80.1 &Git.&Status :Gstatus

We also set s to be the accelerator key for the status menu item. But let’s say we want to get off of menus altogether. We can have the menu tell us the command we could run if we wanted to avoid the menu. You just put the text you want right-aligned after the literal string , like so: 1

:menu 80.1 &Git.&Status:Gstatus :Gstatus

Hidden Menus If you want to be super cool you can set up a menu that won’t appear in the menu bar, a menu that is only accessible as a popup. Again, this is a simple change: the name of your menu needs to have the character ] at the beginning of its name, like so: 1

:menu ]Git.Status:Gstatus :Gstatus

And once you’ve defined it this way you need to remember to call it with the square bracket: 1

nmap g :popup ]Git

And viola! You’ve got a menu that appears as if by magic from nowhere! This, my friend, is the good life.

MacVim is a Special Snowflake! MacVim handles menus differently, which shouldn’t be surprising, because OSX handles menus differently. If you’re setting up a .gvimrc that is expected to be used in MacVim you’ve got two new commands to play with to make your menus fully Mac compatible. However they’re definitely not painless. As in “so far I haven’t been able to add a new menu item using the MacVim menu commands.” You can use the regular menu commands listed before, but assigning mac-specific keyboard shortcuts so far eludes me. And as I already mentioned, you can’t hide menus in MacVim; they’ll always show up on the menubar, even if you preface the name with ]. So, if you want to learn how to make OSX specific menus check out :h macvim-menus from MacVim and let me know what you find.

27. Literary Vim: Writing Prose in Vim First of all, I have a confession to make: I wrote very little of this book in vim. For the most part I wrote, reviewed, and edited this book in Scrivener, occasionally switching to Multimarkdown Composer for fancy markdown features like tables and such. 1 This isn’t because vim is a bad choice for prose writing, it more because I have grown quite familiar with and fond of Scrivener over the years, and I find it works well for the way I write prose. But that’s me. I have had a number of people ask me how to use vim for writing instead of coding. It’s a fair question, and not surprisingly, vim is quite adept at being a writer’s editor of choice. With just a little work you can put the full power of vim behind your blog, thesis, or book about using Scrivener. Turnabout is fair play after all.

Writing and Coding In this chapter, I’m just going to say “writing” when I mean “writing not-code” and “coding” when I mean “writing code”. I’m fully aware that writing code is a creative act just like writing anything else. As WordPress is so fond of saying, “Code is poetry2 .”

Setting up the a Writing Workflow When I write prose I almost universally use Markdown3 , or, more specifically MultiMarkdown4 instead of writing in a word processor like Word, Pages, LibreOffice etc. In this chapter I’m going to go ahead and assume you’re doing the same.

What is Markdown? If you don’t know what Markdown is, it’s a text-only way to denote formatting in text files. So if you want something italicized you would write it *with single asterisks* around it. Bold text is written **with double asterisks**. Then when you want to publish your text you run it through a program that converts all those marks into formatted text. The full scope of how to use markdown is beyond the scope of this book, but it’s worth noting that this book was written entirely using markdown, and these days I can’t imagine writing a book without it. 1

See the About section for more information on other tools used in the creation of this book. http://wordpress.org/ 3 http://daringfireball.net/projects/markdown/ 4 http://fletcherpenney.net/multimarkdown/ 2

Literary Vim: Writing Prose in Vim

95

So, to write prose we need a (multi)markdown syntax file, so that vim can help us do all the syntax highlighting and other helpful things it does so well. So far the best I have found is by (you guessed it) Tim Pope, and is available on GitHub5 . See the chapter on plugins for a refresher on how to install it. Later on we’re going to talk about actually exporting your markdown-style text to something pretty and fully formatted, so let’s install the software we need for that now, while we’ve already got our hands dirty. MultiMarkdown6 is my converter of choice. It runs on any desktop OS, adeptly converts Markdown and MultiMarkdown into a variety of formats, and is free and frequently updated. Once you’ve got mmd up and running it’s time to set vim up in writing mode instead of coding mode.

Writer-Friendly Vim Settings One of the great benefits of using vim as your main writing tool is that it is one of the original distraction free writing programs. Open vim up full screen and you have nothing to do but write. But there are a few settings we need to tweak to get started. The first is line wrapping. When you’re programming you usually want each line to stay on its own line, so you can make sure things line up or whatever. When you’re writing prose, not so much. Fortunately, vim has a line-wrapping feature, and it’s easy to use. But you’ll need to make some decisions ahead of time. The main decision is if you want wrapping on all the time or only occasionally. If you are using vim primarily as a code editor you probably want line wrapping off by default. If you’re using it as a text editor you probably want it on. Since we’re talking about literary vim right now we’ll go with line wrapping on, and then talk about how to toggle it easily. In order for vim to handle line wrapping intelligently you need to set a few flags in your .vimrc: 1 2 3

set wrap set linebreak set nolist

The first one is obvious: we want it to wrap. The second one tells vim to break lines at one of a list of line break characters instead of just saying “okay! That’s 80 columns! Next character goes on the next line!”. It’s the difference between this:

5 6

https://github.com/tpope/vim-markdown http://fletcherpenney.net/multimarkdown/

Literary Vim: Writing Prose in Vim

1 2

96

Here I am on line one. This is a good line. I wo nder when I will hit line two?

And this: 1 2

Here I am on line one. This is a good line. I wonder when I will hit line two?

You can check out ‘:h linebreak” for more information on what characters trigger a line break and how it all works. But for now we’ll just stick with the stock answer: it works very well. The next thing to say about wrap and linebreak is that they insert soft line breaks instead of hard line breaks. A hard line break is like actually hitting the key, a soft line break only visually moves your text onto the next line. If you make your vim window wider the text will re-flow to the end of the new wider window. If you’re writing in Markdown you absolutely want soft line breaks, as the Markdown parser will format your text appropriately when you run it. So, what about nolist? We turn it off is because list breaks wrap and line break. You can read more about it in the help file: :h list, but for now let’s just turn it off. Okay, so now vim is all ready to write! But what if we want to go back to coding? What if we suddenly hate line wrapping? Good question. Let’s add one more line to our .vimrc to let us turn line wrapping off anytime we want: 1

nnoremap :set wrap!

The purpose of this command should be fairly obvious. You could map it to something like w if you wanted, but I find that using the keys for toggling vim behaviors works for me.

Spreading the Word: How to Get Your Message Out Into the World At length, it will be time for your words to leave the warm embrace of your computer and fend for themselves out in the real world. It’s a proud and terrifying time. If you’re publishing your opus via some awesome markdown-aware self publishing site like, say, Leanpub7 then your work is pretty much done. Follow their instructions for getting your text on their servers and sit back, a job well done. However, if you’re using any other method of publication we’ve still got some work to do. The reason we wrote in Markdown is because your text can now be converted into whatever format you need, 7

http://leanpub.com

Literary Vim: Writing Prose in Vim

97

be it PDF, HTML, DOCX, or some other combination of letters. This is where mmd comes into play. Let’s take this very simply to begin with. You can practice on the literary.md file in the sample files repository. Okay, let’s say you need to convert your text into an HTML page8 . All we have to do is this: 1

mmd literary.md

And just like that you’ve got a new HTML page right next to your markdown file. If you pop that page open in a browser you will see that all your text formatting, like tables, italics, bolds, footnotes etc. are there, but precious little other formatting is. This is because we haven’t told MultiMarkdown what fonts, colors, justifications etc. to use. And while you could do that by giving it a stylesheet you want used with your output, I would recommend against doing so. Once you’ve got a basic formatted version of your text you have a couple of options: • Turn it over to a publisher and use their formatting • Take a pass at your text with a word processor or other program that handles customizable text formatting. While you were writing it was time to get your words out into the open, get them down in bits so that you wouldn’t forget them. Now it’s time to polish them up, make them look as good as possible for whatever format you choose, and you should really take the time to do that by hand.

More Formats! I Need More Formats! The official MultiMarkdown program can convert your text into a list of formats that is impressive, but if you’re like most people you’re going to notice a couple of glaring omissions. Where, for example, is the option to create a .docx file for Word, or a PDF file? The short answer is that mmd can turn your markdown into LaTeX, and you can turn .tex files into just about anything, if you want. But that’s probably not the answer you were looking for. Learning the mysteries of LaTeX formatting is probably not what you set out to do. Fortunately there are ways around that. Pandoc9 is one such way. Pandoc seeks to turn just about anything into just about anything else, text-wise. If you wanted to make a Microsoft Word document out of literary.md all you would have to do is this: (after installing pandoc, of course) 8 We’re converting it to HTML first for two reasons: 1.) it’s the easiest and 2.) because you’ll quickly see just how not ready for primetime the output is. 9 http://johnmacfarlane.net/pandoc/installing.html

Literary Vim: Writing Prose in Vim

1

98

pandoc -f markdown_mmd -t docx -o literary.docx literary.md

The switches we’re using here are: • -f incoming format • -t target format • -o output file name And finally the name of the file you want to convert. It’s worth noting that pandoc also doesn’t do PDF output. Microsoft Word, however, does. But what if you don’t want to write all this stuff on the command line? What if you want live previews of what your text is going to look like, and the ability to actually finally create a PDF from your text? Well, there are apps for that. My favorite app on OSX is Marked10 . Marked lets you see how all your formatting is going to look, has a number of built-in stylesheets as well as the ability to add new stylesheets of your own, does a surprisingly wide array of sanity and writing checks on your text, and it can export a PDF of your file. It’s basically a writer’s best friend. 10

http://marked2app.com

28. Conclusion Well, here we are at the end of all things Painless and Vimish1 . We’ve had some good times, we’ve learned how to do a lot of things in an editor that has been proven (by other people) to be fast and user friendly in the right hands. I hope you’ve seen that you’ve got a great tool at your disposal, and that it isn’t as scary as it looked all those chapters ago when you were first starting out. But there’s still a long way to go, a lot more to learn. We haven’t covered everything you can do with vim, not by a long chalk. I haven’t even touched topics like writing your own plugins using vim script, and for good reason: I have no idea how to do that. But hopefully at this point you are feeling like those topics aren’t too scary, you’re feeling like you can handle this whole vim thing without fear, and you can hop onto anybody’s computer and use the world’s most built-in text editor instead of making excuses. Like I said, there’s still a long way to go. Fortunately there is an entire internet full of resources out there to help you reach true vim mastery, if such is your goal. If you just want to use vim you’re probably just about there. I’d recommend going back over this material in small bites from time to time as you settle into using vim on a daily basis. Perhaps there was something you read about a while ago that you wanted to try, and now that you’re more comfortable you can add a few new commands to your arsenal. If you want to expand beyond what you’ve read here I’d recommend picking up a more advanced book; there are a few listed in the Appendices. If you want to start writing vim plugins there’s no better time than the present to start learning vim script. Last of all, I would like to thank you. Writing this book has been an adventure for me. I’ve learned a ton about vim, and about writing, in this process. All the positive comments and suggestions have been deeply felt and appreciated. And your confidence, expressed in the form of actually dipping into your own hard-earned cash and buying this book is simply amazing. Again, I thank you. –Nate Dickson

1

No, it probably isn’t a word, but I’m sticking with it.

Appendix 1: Links to References This appendix is the catch-all for long-form reference discussions that didn’t flow properly in the main text.

Color Scheme References (Linked from Picking a Color Scheme) • Vim Color Scheme Test2 has a lot of color schemes listed, with links to the files, and full previews of the scheme rendering different types of files. • The vim-colorschemes3 plugin installs a ton of color schemes for you to peruse and sample from the comfort of your own terminal. • Vivify4 lets you choose one of many color schemes and edit it to your heart’s content.

Cheat Sheets • Beautiful Vim Cheat Sheet5 : Born on Kickstarter, now out in the wild, this is the cheat sheet that I have pinned up prominently behind my laptop at all times.

Great Books on vim • Practical Vim6 : Presented as a series of tips, Practical Vim is a peek into the vim mindset, and a way to make the jump from user to power user. Every time I dip into it I come away with something that extends my vim skills and makes vim just that much more useful for me. • Learning the Vi and Vim Editors7 :This is the “everything and the kitchen sink” book on vim. As the title suggests, it also spends a fair amount of time in vi world, and even dives deeper into the underlying ed and ex editors upon which vim is built. If you want to know it all, this is the book for you. 2

https://code.google.com/p/vimcolorschemetest/ https://github.com/flazz/vim-colorschemes 4 http://bytefluent.com/vivify/ 5 http://vimcheatsheet.com/ 6 http://pragprog.com/book/dnvim/practical-vim 7 http://amzn.to/16ELAeG 3

Appendix 1: Links to References

101

Great Sites to Learn more Vim • Vim Adventures8 : This is a fun site that teaches vim as a video game. You can play a few levels for free, which will help you with the basic motion keys, or pay to get access to the more advanced levels as well. • The Vim Tips Wiki9 : What better place to find information about an open source project than a community-maintained wiki? There is a lot of good information on this site for when you’re ready to move beyond the basics and get into some true vim black magic.

More About Expressions • It’s always good to stop in at Stack Overflow10 for a simple, clear, and concise answer to a question. • Andreas Grech has a simple explanation of how to use the expression register to run ruby files11 • Use Vim tiptoes into using VimScript in the Expression Register12

Bundle Managers In the chapter on Plugins I covered the Pathogen manager fairly thoroughly, but there are other great options. Here are a couple more that you might want to check out: • Vundle13 is a popular plugin manager for vim. You tell it which bundles you want in your .vimrc file and it downloads and installs them for you. This is the mirror opposite of how Pathogen works, but it makes it easy to move your entire configuration with you wherever you go. • NeoBundle14 is similar to Vundle in use and in aims, but seeks to improve on some of Vundle’s features. All of these bundle managers perform more or less the same functions, it’s just a matter of which one works best for you. 8

http://vim-adventures.com/ http://vim.wikia.com/wiki/Vim_Tips_Wiki 10 http://stackoverflow.com/questions/7027741/what-is-the-purpose-of-the-expression-register 11 http://blog.dreasgrech.com/2010/06/extending-vim-with-expression-register.html 12 http://usevim.com/2013/06/28/expression-syntax/ 13 https://github.com/gmarik/vundle 14 https://github.com/Shougo/neobundle.vim 9

Appendix 2: Quick Reference Charts Motions simple motions

Keystroke

Motion

h j k l b e ctrl+d ctrl+f ctrl+u ctrl+b gg G ^ $

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 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

Commands 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)

103

Appendix 2: Quick Reference Charts

Text Objects Text Object Shortcuts

Shortcut

Text Object

w W s l ’ or “

from the cursor to the end of the word from the cursor to the end of the WORD15 the current sentence from the cursor to the end of the line a string surrounded in quotes Everything between two curly braces Everything between two square brackets Everything between two angle brackets Everything inside the closest XML or HTML tags

{ [ < t

Registers Named Registers

Register Keystroke

Name

What Goes In It

"" "_ "\

The Unnamed Register The Black Hole Register The Last Pattern Register

"-

The Small Delete Register

"1

The Big Delete Register

"2-"9

Big Delete Register Stack

"+

The System Clipboard

"a-"z "A-"Z

The Named Registers The Append Registers

Every cut or copy Anything you want to get rid of A copy of the last thing you searched for The last cut or copy that was less than one entire line long The last thing you cut or copied that was 1 or more lines long A running stack of big deletes. "1 gets pushed to "2 and so on If it works. It doesn’t always work Anything you want Using "A will append to register "a instead of overwriting it

Folding

15

I’ll get to the difference between a lower case word and an upper case WORD very soon.

104

Appendix 2: Quick Reference Charts

Folding Commands

Command

Option

zc zo za zC zO zA zr zm zR zM

Close current fold Open current fold Toggle current fold Close all possible folds at cursor Open all possible folds at cursor Toggle all possible folds at cursor Reduce folding by one level throughout the document Increase folding by one level throughout the document Open all folds Fold everything

Menus Menu Commands

Command —— :menu :nmenu :vmenu :omenu :menu! :menu :amenu

Modes —— Normal, Insert, Operator-Pending Normal Visual Operator-pending Insert, Command-line Command-line All

Tab Commands • Opening a new tab: – :tabnew filename – :tabe filename • Close current tab – :tabc * :tabclose * Note that both of the above methods can take a ! to force the tab to close even if there are unsaved changes in a buffer. • Close other tabs – :tabo Close all other tabs. • Go to the next tab - gt - :tabn

Appendix 2: Quick Reference Charts

105

• Go to the previous tab - gT - :tabp • Go to a specific tab - :tabfir goes to the first tab - :tabl goes to the last tab - tabNumber gt Goes to the tab number given - tabNumber gT Goes to the tab number given • Reorder tabs - :tabmnumber places a tab after the given tab number. Use 0 to make the current tab first. - :tabm +number move a tab number places right - :tabm -number move the tab number places left • List all open tabs - :tabs

Appendix 3: Sample .vimrc files This section gives you a look at a couple of simple (but functional) .vimrc files, with annotations. Note that these aren’t my .vimrc file, although they are more or less based on mine. These are intended to be simple starting points from which you can get ideas. You could use these for a while, tweak them, and get to where you’ve got something you’re happy with over time. If you want to see what I’m using right now you can view it on GitHub16 . I try to back it up regularly. You could theoretically copy mine directly, but it’s got a lot of things in it that you don’t need, unless you’re one of the five other people on Earth who do XQquery development for a living. For that matter, if you’re not keeping your .vimrc and other files backed up on an online service, now would be a good time to start. There are few things more frustrating than realizing all your customizations have just disappeared without a trace. Okay, without further ado, the absolute simplest, most basic sample file that I would actually use:

Comments in vim in normal vimscript you open a comment with a double quote (") and everything to the end of the line is a comment. For some reason the syntax parser for this book thinks comments should go until they find a second double quote; so I will be closing all the comments in these samples. You will not need to do this in real life. A sample .vimrc file

1 2 3 4 5 6 7 8 9 10 11

"This tells vim to only run as VIM, not as vi" set nocompatible "Remember that it has to be in your ~/.vim/colors folder" colorscheme jellybeans "Displays line numbers down the left side of the screen" set nu "Change the key to comma instead of \ " let mapleader="," "enable syntax highlighting" syntax on "Handle things like indents and plugins intelligently." 16

https://github.com/PogiNate/dots/blob/master/home/.vimrc

Appendix 3: Sample .vimrc files

12 13 14 15 16 17 18 19 20 21 22 23 24

filetype plugin indent on "Make the Backspace Sane" "The Backspace in vim is weird by default." "This makes it behave the way you expect." set backspace=2 "More backspace sanity" set backspace=indent,eol,start " Pathogen settings" " This line tells vim to load all your Pathogen-installed plugins." " Naturally, Pathogen needs to be installed before this works." execute pathogen#infect()

A slightly longer .vimrc file

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

" This tells vim to only run as VIM, not as vi" set nocompatible " Any color scheme in your ~/.vim/colors folder" colorscheme jellybeans " Displays line numbers down the left side of the screen." set nu "Change the key to comma instead of \ " let mapleader="," "Turn tabs into spaces when saving." "I prefer this, as it keeps things orderly." set expandtab " Wrap long lines." set wrap " Enable syntax highlighting" syntax on "Handle things like indents and plugins intelligently." filetype plugin indent on "Make the Backspace Sane"

107

Appendix 3: Sample .vimrc files

27 28 29 30 31 32 33 34 35 36 37 38 39

set backspace=2 set backspace=indent,eol,start " Pathogen settings" " Use pathogen with it's pun-filled method names." execute pathogen#infect() "Folding" " You can set this to 'indent' or 'syntax' if you like;" " I prefer manual" set foldmethod=manual " This tells vim to only fold one level at a time." set foldlevel=1

108

About This Book About the Text Painless Vim is by Nathanial Ellsworth Dickson, but you can call me Nate. It was written using an unwieldy combination of (in alphabetical order): • • • • • •

Marked17 MultiMarkdown Composer18 Scapple19 Scrivener20 Ulysses21 vim22 (of course)

It was written on an unlikely number of macs.

About the cover The cover features an illustration by Callihan23 . Used with permission. The typefaces used on the cover are: • Matchbook Serif (title) • Aleo Light (subtitle) • Caviar Dreams (by line) The cover was designed by Nate Dickson using iDraw24 and Pixelmator25 17

http://markedapp.com/ http://multimarkdown.com/ 19 http://www.literatureandlatte.com/scapple.php 20 http://www.literatureandlatte.com/scrivener.php 21 http://www.ulyssesapp.com/ 22 http://www.vim.org/ 23 http://www.shutterstock.com/pic.mhtml?id=94462300 24 http://www.indeeo.com/idraw/ 25 http://www.pixelmator.com/ 18

Special Thanks I would like to thank, first and foremost, my dear Libbie, for her support, kind words, encouragement, proofreading, spell checking, questions, and love. I’m the luckiest husband ever. Slightly less mushy thanks also go out to my team of underpaid (indeed unpaid) proof readers: • • • •

Holly McNeil Jesse Booth Joanna Noall Josh English