├── .gitignore ├── README.md ├── SUMMARY.md ├── book.json ├── charityware.md ├── colophon.md ├── editing_basics.md ├── feedback.md ├── first_steps.md ├── help.md ├── img ├── .DS_Store ├── first_steps_edit.png ├── first_steps_insert.png ├── first_steps_normal.png ├── first_steps_open.png ├── first_steps_quit.png ├── first_steps_type.png ├── first_steps_write.png ├── hands_on_keyboard.gif ├── hands_on_keyboard.png ├── hjkl.png ├── multiple_tabs.png ├── multiple_windows.png └── vi-vim-cheat-sheet.gif ├── installation.md ├── introduction.md ├── modes.md ├── more.md ├── moving_around.md ├── multiplicity.md ├── neovim.md ├── pim.md ├── plugins.md ├── preface.md ├── programmer_editor.md ├── scripting.md ├── translations.md ├── typing_skills.md └── what_next.md /.gitignore: -------------------------------------------------------------------------------- 1 | _book/ 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # A Byte of Vim 2 | 3 | "A Byte of Vim" is a book which aims to help you to learn how to use the [Vim editor](http://www.vim.org) (version 7), even if all you know is how to use the computer keyboard. 4 | 5 | The first part of this book is meant for new users who want to understand what Vim is and learn how to use it. 6 | 7 | The second part of this book is for people who already know how to use Vim and want to learn about features that make Vim so powerful, such as windows and tabs, personal information management, making it a programmer's editor, how to extend Vim with your own plugins, and more. 8 | 9 | ## Status: Incomplete 10 | 11 | Please note that the conversion of the book to this Markdown sources is *incomplete*! 12 | 13 | The original PDF is at https://vim.swaroopch.com/byte-of-vim.pdf - unfortunately the original sources are lost. 14 | 15 | I welcome your contributions to complete the porting of text from the original PDF to this new book's sources at https://github.com/swaroopch/byte-of-vim . 16 | 17 | ## Who reads A Byte of Vim? {#who-reads} 18 | 19 | > Thanks to A Byte of Vim, I have learnt how to use vim. Thank you very much for this excellent book! ;) 20 | > -- Camille L (France) 21 | 22 | 23 | 24 | > Well done!!! I've been only using vim for like 2/3 weeks now, and thus I can say that it's just perfect for beginners like me!!! 25 | > -- [Jay](https://groups.google.com/group/vim_use/msg/e1625069d4ea0ef9) 26 | 27 | 28 | 29 | > The book is very good and fun to read too. Thank you for sharing it. 30 | > -- [Yosi Izaq](http://groups.google.com/group/vim_use/msg/09ca306a67b9d2cd) 31 | 32 | 33 | 34 | > Your books should sell like hot cakes for their way of presentation. 35 | > -- [Deepak](http://twitter.com/peerlessdeepak/status/1024279089) 36 | 37 | 38 | 39 | > Awesome! Thank you for all of your hard work. It is especially nice that the beginning starts the reader off gradually. After using vim for a couple of years I've forgotten how weird it seems at first, so I probably wouldn't explain it that good to someone. I will be sure to share your book to spread the vim propaganda. ;-) 40 | > -- [Joseph Sullivan](http://groups.google.com/group/vim_use/msg/362a82a4af132317) 41 | 42 | 43 | 44 | > What I am trying to say is if you have basic computer competency you should immediately get Vim on your machine and improve your life. The best place to learn about is to read Swaroop C H's awesome eBook A Byte of Vim, it will revolutionize how you think about text editors in the future. 45 | > -- ["wooden nickels"](http://woodennickels.posterous.com/text-editing-your-way-to-heave) 46 | 47 | 48 | 49 | > Have been thumbing through 'byte of vim'. learning a ton even having used vim for years. 50 | > -- [Josh Nichols](http://twitter.com/techpickles/status/1025775542) 51 | 52 | 53 | 54 | > Great Book !! Although I use vim everyday as an editor as well as an ide, the book makes u realise how much more it can do. 55 | > -- [Raseel Bhagat](http://twitter.com/raseel/status/1024291090) 56 | 57 | 58 | 59 | > Wonderful! This was one most-required-book. I was a vim user for the past years, but never have seen these much of facilities inside that! Thanks for the Book, Swaroop! 60 | > -- [Hiran Venugopalan](http://www.swaroopch.com/2008/11/25/a-free-book-on-vim/) 61 | 62 | 63 | 64 | > What a nice book. I'm a long-time vim user, but never managed to get my head around vim scripting (apart from fixing some bugs in others' scripts). This is the best introduction to Vim scripting (writing plugins, syntax files, ...) I have seen so far. Thanks for putting it online! 65 | > -- Anonymous (132.230.122.35) 66 | 67 | 68 | 69 | > Thank you Swaroop! I've begun reading it and must say it's very well written. And I have no doubts this great community of us vim users here will improve it through fixes, additions or small corrections. 70 | > -- [Eduard Fabra](http://groups.google.com/group/vim_use/msg/dac94f3332f733e4) 71 | 72 | 73 | 74 | > I'd recommend A Byte of Vim as a good intro for new and experienced users alike. 75 | > -- [James Kovacs, Germany](http://twitter.com/JamesKovacs/statuses/19106427185) 76 | 77 | 78 | 79 | > Este libro me ayudó muchísimo a sacarle provecho a vim 80 | > (This book helped me a lot to take advantage of vim) 81 | > -- [Antonio Touriño, Panamá](http://twitter.com/techiebits/status/19079448462) 82 | 83 | 84 | 85 | > I have used vi for quite a while and am pretty comfortable with it. But all I do in vi is first get into insert mode and edit the file as if I am using notepad. I started searching for tutorials on vi and found one that is so simple yet so amazing. I thank Swaroop CH, yes the same guy who wrote the book A Byte of Python, for another amazing book A Byte of Vim. It was so amazing and I started using vi like a novice vimmer. 86 | > -- [Nishanth](http://pyandme.blogspot.com/2010/02/vim-mode.html) 87 | 88 | 89 | 90 | > A Byte of Vim saved my day once again... 91 | > -- [@reku](http://twitter.com/reku/status/14579836693) 92 | 93 | Also: 94 | 95 | - The book was listed as the top tip for Dec 2008 on the [Official Vim Tips wiki](http://vim.wikia.com/wiki/Main_Page#Did_you_know.3F_view_archive). 96 | 97 | ## License 98 | 99 | This book is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). 100 | 101 | This means: 102 | 103 | - You are free to Share i.e. to copy, distribute and transmit this book 104 | - You are free to Remix i.e. to make changes to this book (especially translations) 105 | - You are free to use it for commercial purposes 106 | 107 | Please note: 108 | 109 | - Please do *not* sell electronic or printed copies of the book unless you have clearly and prominently mentioned in the description that these copies are *not* from the original author of this book. 110 | - Attribution *must* be shown in the introductory description and front page of the document by linking back to {{ book.officialUrl }} and clearly indicating that the original text can be fetched from this location. 111 | - All the code/scripts provided in this book is licensed under the [3-clause BSD License](http://www.opensource.org/licenses/bsd-license.php) unless otherwise noted. 112 | 113 | ## Read Now 114 | 115 | You can read it online at {{ book.officialUrl }} 116 | 117 | ## Buy The Book 118 | 119 | A printed hardcopy of the book can be purchased at {{ book.buyBookUrl }} for your offline reading pleasure, and to support the continued development and improvement of this book. 120 | 121 | ## Download 122 | 123 | Visit {{ book.downloadUrl }} for the following types of downloads: 124 | 125 | - [PDF (for desktop reading, etc.)](https://www.gitbook.com/download/pdf/book/swaroopch/byte-of-vim) 126 | - [EPUB (for iPhone/iPad, ebook readers, etc.)](https://www.gitbook.com/download/epub/book/swaroopch/byte-of-vim) 127 | - [Mobi (for Kindle)](https://www.gitbook.com/download/mobi/book/swaroopch/byte-of-vim) 128 | 129 | Visit {{ book.sourceUrl }} for the raw content (for suggesting corrections, changes, translating, etc.) 130 | 131 | ## Read the book in your native language 132 | 133 | If you are interested in reading or contributing translations of this book to other human languages, please see "Translations" chapter. 134 | -------------------------------------------------------------------------------- /SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | * [Preface](preface.md) 4 | * [Introduction](introduction.md) 5 | * [Installation](installation.md) 6 | * [First Steps](first_steps.md) 7 | * [Modes](modes.md) 8 | * [Typing Skills](typing_skills.md) 9 | * [Moving Around](moving_around.md) 10 | * [Help](help.md) 11 | * [Editing Basics](editing_basics.md) 12 | * [Multiplicity](multiplicity.md) 13 | * [Personal Information Management](pim.md) 14 | * [Scripting](scripting.md) 15 | * [Plugins](plugins.md) 16 | * [A Programmer's Editor](programmer_editor.md) 17 | * [More](more.md) 18 | * [What Next](what_next.md) 19 | * [Feedback](feedback.md) 20 | * [Charityware](charityware.md) 21 | * [Colophon](colophon.md) 22 | * [Versions](versions.md) 23 | -------------------------------------------------------------------------------- /book.json: -------------------------------------------------------------------------------- 1 | { 2 | "variables": { 3 | "authorUrl": "http://www.swaroopch.com/about/", 4 | "buyBookUrl": "http://www.swaroopch.com/buybook/", 5 | "contactUrl": "http://www.swaroopch.com/contact/", 6 | "downloadUrl": "https://www.gitbook.com/book/swaroopch/byte-of-vim/details", 7 | "officialUrl": "http://vim.swaroopch.com/", 8 | "pythonBookUrl": "http://python.swaroopch.com/", 9 | "sourceUrl": "https://github.com/swaroopch/byte-of-vim" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /charityware.md: -------------------------------------------------------------------------------- 1 | # Charityware 2 | Vim is "charityware". If you find Vim useful, you are encouraged to help the [ICCF Holland foundation](http://iccf-holland.org) in any way you can. 3 | 4 | From their website: 5 | 6 | The south of Uganda has been suffering from the highest HIV infection rate in the world. Parents die of AIDS, just when their children need them most. An extended family can be their new home. Fortunately there is enough food in this farming district. But who will pay their school fees, provide medical aid and help them grow up? That is where ICCF Holland helps in the hope that they will be able to take care of themselves, and their children, in the long run. 7 | 8 | Details on ICCF can be found in Vim by running `:help iccf`. 9 | 10 | You can [sponsor Vim development](http://www.vim.org/sponsor/faq.php) by making a monetary donation and becoming a Vim registered user; you get to vote on what new features will be added to Vim! 11 | -------------------------------------------------------------------------------- /colophon.md: -------------------------------------------------------------------------------- 1 | # Colophon 2 | ## About this book 3 | This is an alpha edition of the book. That means it may contain incomplete sections, obvious mistakes, blatant lack of detail, and more. Please feel free to [send constructive suggestions](http://www.swaroopch.com/contact/). 4 | 5 | ## Creating this book 6 | This book would have never been written without Vim 7. My life would never have been complete without Vim. Thank you Bram Moolenaar and Vimmers all over the world. 7 | 8 | The original content was written in Viki syntax were then strung together using [deplate](http://deplate.sourceforge.net). Special thanks to [Thomas Link](http://www.vim.org/account/profile.php?user_id=4037) for patiently answering all my queries on how to use Viki/Deplate :-) 9 | 10 | The book was later converted into a wiki format. Even though the book is now being edited online live, I still use Vim to write and copy/paste to [MediaWiki](https://www.mediawiki.org/wiki/MediaWiki) to save the text. 11 | 12 | ## Inspiration 13 | I started writing this book in 2004 or so. It ended up on the back burner. 14 | 15 | I revived writing the book in the month after [foss.in 2006](https://en.wikipedia.org/wiki/FOSS.IN) thanks to the infective spirit of the people there. 16 | 17 | But yet again, I couldn't sustain the momentum. I started to be more productive when I started following David Allen's [Getting Things Done](http://gettingthingsdone.com/) principles. This led me to revive working on the book. I finally got it in good-enough shape to be released to the world on the first day of [foss.in 2008](https://en.wikipedia.org/wiki/FOSS.IN). 18 | 19 | ## About the author 20 | 21 | Swaroop C H is 26 years of age. He graduated in B.E. (Computer Science) from PESIT, Bangalore, India. He currently works at his co-founded startup [IONLAB](http://www.ionlab.in). He has previously worked at Yahoo! and Adobe. His passions are reading and writing, running and cycling, and some coding. 22 | 23 | More about him at [http://www.swaroopch.com/about/](http://www.swaroopch.com/about/) 24 | 25 | He can be contacted via [http://www.swaroopch.com/contact/](http://www.swaroopch.com/contact/) 26 | -------------------------------------------------------------------------------- /editing_basics.md: -------------------------------------------------------------------------------- 1 | # Editing Basics 2 | 3 | Let's learn the basic editing commands in Vim for reading/writing files, cut/copy/paste, undo/redo and searching. 4 | 5 | ## Reading and writing files 6 | 7 | ### Buffers 8 | 9 | When you edit a file, Vim brings the text in the file on the hard disk to the computer's RAM. This means that a copy of the file is stored in the computer's memory and any changes you make is changed in the computer's memory and immediately displayed. Once you have finished editing the file, you can save the file which means that Vim writes back the text in the computer's memory to the file on the hard disk. The computer memory used here to store the text temporarily is referred to as a "buffer". Note that this same concept is the reason why we have to "save" files in all editors or word processors that we use. 10 | 11 | Now open up Vim, write the words `Hello World` and save it as the file `hello.txt`. If you need to remember how to do this, please refer to the [First Steps chapter](./first_steps.md#write-file). 12 | 13 | ### Swap 14 | 15 | Now you will notice that another file has been created in the same directory as this file, the file would be named something like `.hello.txt.swp`. Run `:swapname` to find out the exact name of the file. 16 | 17 | What is this file? Vim maintains a backup of the buffer in a file which it saves regularly to the hard disk so that in case something goes wrong (like a computer crash or even Vim crashes), you have a backup of the changes you have made since you last saved the original file. This file is called a "swap file" because Vim keeps swapping the contents of the buffer in the computer memory with the contents of this file on the hard disk. See `:help swap-file` to know more details. 18 | 19 | ### Save my file 20 | 21 | Now that the file has been loaded, let's do a minor editing. Press the ~ key to change the case of the character on which the cursor is positioned. You will notice that Vim now marks the file having been changed (for example a `+` sign shows up in the title bar of the GUI version of Vim). You can open up the actual file in another editor and check that it has not changed yet i.e. Vim has only changed the buffer and not yet saved it to the hard disk. 22 | 23 | We can write back the buffer to the original file in the hard disk by running `:write`. 24 | 25 | > NOTE: To make saving easier, add the following line to your vimrc file: 26 | >
27 | > ``` viml 28 | > " To save, ctrl-s. 29 | > nmap :w 30 | > imap :wa 31 | > ``` 32 | >
33 | > Now you can simply press `ctrl-s` to save the file. 34 | 35 | ### Working in my directory 36 | 37 | Vim starts up with your home directory as the default directory and all operations will be done within that directory. 38 | 39 | To open files located in other directories, you can use the full or relative paths such as: 40 | 41 | ``` viml 42 | :e ../tmp/test.txt 43 | :e C:\\shopping\\monday.txt 44 | ``` 45 | 46 | Or you can switch Vim to that directory: 47 | 48 | ``` viml 49 | :cd ../tmp 50 | ``` 51 | 52 | `:cd` is short for 'c'hange 'd'irectory. 53 | 54 | To find out the current directory where Vim is looking for files: 55 | 56 | ``` viml 57 | :pwd 58 | ``` 59 | 60 | `:pwd` is short for 'p'rint 'w'orking 'd'irectory. 61 | 62 | ## Cut, Copy and Paste 63 | 64 | As Sean Connery says, in the movie [Finding Forrester](http://www.imdb.com/title/tt0181536/): 65 | 66 | > No thinking - that comes later. You must write your first draft with your heart. You rewrite with your head. The first key to writing is... to write, not to think! 67 | 68 | When we rewrite, we frequently rearrange the order of the paragraphs or sentences i.e. we need to be able to cut/copy/paste the text. In Vim, we use a slightly different terminology: 69 | 70 | | Desktop world | Vim world | Operation | 71 | | --- | --- | --- | 72 | | cut | delete | `d` | 73 | | copy | yank | `y` | 74 | | paste | paste | `p` | 75 | 76 | In normal desktop terminology, 'cut'ting text means removing the text and putting it into the clipboard. The same operation in Vim means it deletes the text from the file buffer and stores it in a 'register' (a part of the computer's memory). Since we can choose the register where we can store the text, it is referred to as the "delete" operation. 77 | 78 | Similarly, in normal desktop terminology, 'copy' text means that a copy of the text is placed on the clipboard. Vim does the same, it "yanks" the text and places it in a register. 79 | 80 | "Paste" means the same in both terminologies. 81 | 82 | We have seen how you can do cut/copy/paste operations in Vim. But how do you specify which text that these operations should work on? Well, we have already explored that in the previous [Text Objects section](./moving_around.md#text-objects). 83 | 84 | Combining the operation notation and the text object notation means we have innumerable ways of manipulating the text. Let's see a few examples. 85 | 86 | Write this text in Vim (exactly as shown): 87 | 88 | > This is the rthe first paragraph.
89 | > This is the second line.
90 | >
91 | > This is the second paragraph.
92 | 93 | Place the cursor at the topmost leftmost position, by pressing `1G` and `|` that moves to the first line and the first column respectively. 94 | 95 | Let's see the first case: We have typed an extra 'r' which we have to remove. Press `3w` to move forward by 3 words. 96 | 97 | Now, we need to delete one character at the current cursor position. 98 | 99 | Note that there are two parts to this: 100 | 101 | | Operation | Text Object / Motion | 102 | | --- | --- | 103 | | Delete | One character at current cursor position | 104 | | `d` | `l` | 105 | 106 | So, we have to just press `dl` and we delete one character! Notice that we can use `l` even though it is a motion. 107 | 108 | Now we notice that the whole word is redundant because we have "the" twice. Now think carefully on what should be fastest key combination to fix this? 109 | 110 | Take some time to think and figure this out for yourself. Take your time. Now read on. 111 | 112 | | Operation | Text Object / Motion | 113 | | --- | --- | 114 | | Delete | Word | 115 | | `d` | `w` | 116 | 117 | So, press `dw` and you delete a word. Voila! So simple and so beautiful. The beauty is that such simple concepts can be combined to provide such a rich range of possibilities. 118 | 119 | How do we achieve the same operation for lines? Well, lines are considered special in Vim because lines are usually how we think about our text. As a shortcut, if you repeat the operation name twice, it will operate on the line. So, dd will delete the current line and yy will yank the current line. 120 | 121 | Our example text in Vim should now look like this: 122 | 123 | > This is the first paragraph.
124 | > This is the second line.
125 | >
126 | > This is the second paragraph. 127 | 128 | Go to the second line by pressing `j`. Now press `dd` and the line should be deleted. You should now see: 129 | 130 | > This is the first paragraph.
131 | >
132 | > This is the second paragraph. 133 | 134 | Let's see a bigger case: How do we yank the current paragraph? 135 | 136 | | Operation | Text Object / Motion | 137 | | --- | --- | 138 | | Yank | A Paragraph | 139 | | `y` | `ap` | 140 | 141 | So, `yap` will copy the current paragraph. 142 | 143 | Now that we have done copying the text, how do we paste it? Just `p` it. 144 | 145 | You should now see: 146 | 147 | > This is the first paragraph.
148 | > This is the first paragraph.
149 | >
150 | >
151 | > This is the second paragraph. 152 | 153 | Notice that the blank line is also copied when we do yap, so p adds that extra blank line as well. 154 | 155 | There are two types of paste that can be done exactly like the two types of inserts we have seen before: 156 | 157 | | Key | Mnemonic | 158 | | --- | --- | 159 | | `p` | paste after current cursor position | 160 | | `P` | paste before current cursor position | 161 | 162 | Taking the idea further, we can combine these into more powerful ways. 163 | 164 | How to swap two characters? Press `xp`. 165 | 166 | - `x` → delete one character at current cursor position 167 | - `p` → paste after current cursor position 168 | 169 | How to swap two words? Press `dwwP`. 170 | 171 | - `d` → delete 172 | - `w` → one word 173 | - `w` → move to the next word 174 | - `P` → paste before the current cursor position 175 | 176 | The important thing is *not* to learn these operations by rote. These combinations of operations and text objects/motions should be automatic for your fingers, without you needing to put in mental effort. This happens when you make using these a habit. 177 | 178 | ## Marking your territory 179 | 180 | You are writing, and you suddenly realize you have to change sentences in a previous section to support what you are writing in this section. The problem is that you have to remember where you are right now so that you can come back to it later. Can't Vim remember it for me? This can be achieved using marks. 181 | 182 | You can create a mark by pressing m followed by the name of the mark which is a single character from `a-zA-Z`. For example, pressing `ma` creates the mark called 'a'. 183 | 184 | Pressing `'a` returns the cursor to line of the mark. Pressing `a will take you to the exact line and column of the mark. 185 | 186 | The best part is that you can jump to this position using these marks any time thereafter. 187 | 188 | See `:help mark-motions` for more details. 189 | 190 | ## Time machine using undo/redo 191 | 192 | Suppose you are rewriting a paragraph but you end up muddling up what you were trying to rewrite and you want to go back what you had written earlier. This is where we can "undo" what we just did. If we want to change back again to what we have now, we can "redo" the changes that we have made. Note that a change means some change to the text, it does not take into account cursor movements and other things not directly related to the text. 193 | 194 | Suppose you have the text: 195 | 196 | > I have coined a phrase for myself - 'CUT to the G':
197 | > 1. Concentrate
198 | > 2. Understand
199 | > 3. Think
200 | > 4. Get Things Done
201 | >
202 | > Step 4 is eventually what gets you moving, but Steps 2 and 3 are equally important. As Abraham Lincoln once said "If I had eight hours to chop down a tree, I'd spend six hours sharpening my axe." And to get to this stage, you need to do Step 1 which boils down to one thing - It's all in the mind. That's why it's so hard. 203 | 204 | Now, start editing the first line: 205 | 206 | 1. Press `S` to 's'ubstitute the whole line. 207 | 2. Type the text `After much thought, I have coined a new phrase to help me solidify my approach:`. 208 | 3. Press ``. 209 | 210 | Now think about the change that we just did. Is the sentence better? Hmm, was the text better before? How do we switch back and forth? 211 | 212 | Press `u` to undo the last change and see what we had before. You will now see the text `I have coined a phrase for myself - 'CUT to the G':`. To come back to the latest change, press `ctrl-r` to now see the line `After much thought, I have coined a new 213 | phrase to help me solidify my approach:`. 214 | 215 | It is important to note that Vim gives unlimited history of undo/redo changes, but it is usually limited by the `undolevels` setting in Vim and the amount of memory in your computer. 216 | 217 | Now, let's see some stuff that really shows off Vim's advanced undo/redo functionality, some thing that other editors will be jealous of: Vim is not only your editor, it also acts as a time machine. 218 | 219 | For example, `:earlier 4m` will take you back by 4 minutes i.e. the state of the text 4 minutes "earlier". 220 | 221 | The power here is that it is superior to all undoes and redoes. For example, if you make a change, then you undo it, and then continue editing, that change is actually never retrievable using simple u again. But it is possible in Vim using the `:earlier` command. 222 | 223 | You can also go forward in time: `:later 45s` which will take you later by 45 seconds. 224 | 225 | Or if you want the simpler approach of going back by 5 changes: `:undo 5`. 226 | 227 | You can view the undo tree using `:undolist`. 228 | 229 | See :help `:undolist` for the explanation of the output from this command. 230 | 231 | See `:help undo-redo` and `:help usr_32.txt` for more details. 232 | 233 | ## A powerful search engine but not a dotcom 234 | 235 | Vim has a powerful built-in search engine that you can use to find exactly what you are looking for. It takes a little getting used to the power it exposes, so let's get started. 236 | 237 | Let's come back to our familiar example: 238 | 239 | > I have coined a phrase for myself - 'CUT to the G':
240 | > 1. Concentrate
241 | > 2. Understand
242 | > 3. Think
243 | > 4. Get Things Done
244 | >
245 | > Step 4 is eventually what gets you moving, but Steps 2 and 3 are equally important. As Abraham Lincoln once said "If I had eight hours to chop down a tree, I'd spend six hours sharpening my axe." And to get to this stage, you need to do Step 1 which boils down to one thing - It's all in the mind. That's why it's so hard. 246 | 247 | Suppose we want to search for the word "Step". In normal mode, type `/Step` (i.e. `/Step` followed by `enter` key). This will take you to the first occurrence of those set of characters. Press `n` to take you to the 'n'ext occurrence and `N` to go in the opposite direction i.e. the previous occurrence. 248 | 249 | What if you knew only a part of the phrase or don't know the exact spelling? Wouldn't it be helpful if Vim could start searching as and when you type the search phrase? You can enable this by running: 250 | 251 | ``` viml 252 | set incsearch 253 | ``` 254 | 255 | You can also tell Vim to ignore the case (whether lower or upper case) of the text that you 256 | are searching for: 257 | 258 | ``` viml 259 | set ignorecase 260 | ``` 261 | 262 | Or you can use: 263 | 264 | ``` viml 265 | set smartcase 266 | ``` 267 | 268 | When you have `smartcase` on: 269 | 270 | - If you are searching for `/step` i.e. the text you enter is in lower case, then it will search for any combination of upper and lower case text. For example, this will match all the following four - "Step", "Stephen", "stepbrother", "misstep." 271 | - If you are searching for `/Step` i.e. the text you enter has an upper case, then it will search for **only** text that matches the exact case. For example, it will match "Step" and "Stephen", but not "stepbrother" or "misstep." 272 | 273 | > NOTE: I recommend that you put these two lines in your vimrc file (explained later, but see `:help vimrc-intro` for a quick introduction) so that this is enabled always. 274 | 275 | Now that we have understood the basics of searching, let's explore the real power of searching. The first thing to note that what you provide Vim can not only be a simple phrase, it can be a "expression". An expression allows you to specify the 'kinds' of text to search for, not just the exact text to look. 276 | 277 | For example, you will notice that /step will take you to steps as well as step and even footstep if such a word is present. What if you wanted to look for the exact word step and not when it is part of any other word? Then you can search using `/\`. The `\<` and 278 | `\>` indicate the start and end positions of a "word" respectively. 279 | 280 | Similarly, what if you wanted to search for any number? Searching for `/\d` will look for a 'digit'. But a number is just a group of digits together. So we specify "one or more" digits together as `/\d\+`. If we were looking for zero or more characters, we can use the `*` instead of the `+`. 281 | 282 | There are a variety of such magic stuff we can use in our search patterns. See `:help pattern` for details. 283 | 284 | ## Summary 285 | 286 | We have explored some of the basic editing commands that we will use in our everyday usage of Vim. *It is very important that you go through these concepts again and make them a habit.* It is not important to learn each and every option or nuances of these commands. If you know how to use the command and know how to find out more on it based on what you need, then you're a true Vimmer. 287 | 288 | Now, go ahead and start editing! 289 | -------------------------------------------------------------------------------- /feedback.md: -------------------------------------------------------------------------------- 1 | # Feedback 2 | This book is a work-in-progress. Your feedback is essential to improving the book. So, please do [send in your comments](http://www.swaroopch.com/contact/). 3 | 4 | This book is also available on its official website as a wiki so go ahead and [fix things yourself](http://www.swaroopch.com/notes/Vim) as well! 5 | 6 | Known Gaps are: 7 | 8 | * Inconsistent use of examples 9 | * Current strength is the later chapters (for experienced Vimmers) as opposed to the beginners' chapters. 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /first_steps.md: -------------------------------------------------------------------------------- 1 | # First Steps 2 | 3 | ## Starting Vim 4 | 5 | First step is, of course, to learn how to start Vim. 6 | 7 | ### Graphical Version 8 | 9 | #### Windows 10 | 11 | Click on Start → Programs → Vim 7 → gVim. 12 | 13 | #### Mac OS X 14 | 15 | Click on Finder → Applications → MacVim. 16 | 17 | #### Linux / BSD 18 | 19 | Click on Applications → Accessories → GVim Text Editor, or press `Alt+F2`, type `gvim` and press the `enter` key. 20 | 21 | ### Terminal version 22 | 23 | #### Windows 24 | 25 | Click on Start → Run, type `vim` and press the `enter` key. 26 | 27 | #### Mac OS X 28 | 29 | Click on Finder → Applications → Utilities → Terminal, type `vim` and press the `enter` key. 30 | 31 | #### Linux / BSD 32 | 33 | Click on Applications → Accessories → Terminal, or press `Alt+F2`, type `konsole`/`gnome-terminal` and press the `enter` key. Then, type `vim` and press the `enter` key. 34 | 35 | ### Summary 36 | 37 | From now onwards when we say 'open Vim', use either of the two methods mentioned above. 38 | 39 | > NOTE: When you started Vim, you might have noticed that you can't immediately start typing text. Don't panic, all will be explained in a little while. 40 | 41 | ## Graphical or Terminal? 42 | 43 | The graphical version of Vim has menus at the top of the application as well as various options accessible via the mouse, but note that this is completely optional. You can still access all the features of Vim using *only* the keyboard. 44 | 45 | Why is this important? Because once a person becomes efficient at typing, using only the keyboard makes the person much faster and less error-prone, as opposed to using the mouse. This is because the hand movement required to switch between the keyboard and the mouse is slow and there is a context switch required in the mind of the person when shifting the hand between the keyboard and the mouse. If we make it a habit to use the keyboard as much as possible, you're saving valuable hand movement. 46 | 47 | Of course, this is subjective. Some people prefer the mouse and some prefer the keyboard. I encourage you to use the keyboard as much as possible to experience the real power of Vim. 48 | 49 | ## Introduction to Modes 50 | 51 | Imagine it's a Saturday evening and you're bored of the shows on television. You want to watch an old favorite movie instead. So, you *switch the TV to video mode* so that it shows what the DVD player is displaying instead of the cable channels. Note that the television is still displaying video, but you switch the context on whether you want to watch a DVD or a live television channel. 52 | 53 | Similarly, Vim has modes. For example, Vim has a mode for writing text, a mode for 54 | running commands, etc. They are all related to the main purpose of editing text, but you switch context on whether you want to simply type stuff or you want to run some commands on the text. 55 | 56 | Isn't that simple? 57 | 58 | Traditionally, the concept of modes is the most oft-cited reason by beginners on why they find Vim "confusing". I compare it to riding a bicycle - you'll trip a few times, but once you've got the hang of it, you'll wonder what the fuss was all about. 59 | 60 | So why does Vim have modes? To make things as simple as possible, even though its usage may seem "strange" at first. 61 | 62 | What do I mean by that? Let's take an example - one of the key goals in Vim is to make it fully accessible from the keyboard without ever having to need to use a mouse (you can still use the mouse if you want to but it is strictly optional). In such a scenario, how would you distinguish between the text you want to write, and the commands that you want to run? Vim's solution is to have a "normal" mode where you can execute commands and an "insert" mode where you are simply writing text. You can switch between the two modes any time. For example, pressing `i` switches Vim to insert mode, and pressing `` switches Vim back to normal mode. 63 | 64 | How do traditional editors achieve this distinction between commands and writing text? By using graphical menus and keyboard shortcuts. The problem is that this does not scale. First of all, if you have hundreds of commands, creating menus for each of these commands would be insane and confusing. Secondly, customizing how to use each of these commands would be even more difficult. 65 | 66 | Let's take a specific example. Suppose you want to change all occurrences of the word "from" to the word "to" in a document. In a traditional editor, you can run a menu command like Edit → Replace (or use a keyboard shortcut like `ctrl-r`) and then enter the 'from' word and the 'to' word and then click on 'Replace'. Then, check the 'Replace All' option. In Vim, you simply run `:%s/from/to/g` in the normal mode. The `:s` is the "substitute" command. See how simpler this is? 67 | 68 | What if you want to now run this substitution only in the first 10 lines of the text and you want to have a yes/no confirmation for each replacement? In traditional text editors, achieving the yes/no confirmation is easy by unchecking the 'Replace All' option, but notice that you have to first search for this option and then use the mouse to click on the option (or use a long series of keys using the keyboard). But how will you run the Replace for only the first 10 lines? In Vim, you can simply run `:0,10s/from/to/gc`. The new `c` option we are using means we want a 'c'onfirmation message for every replace. 69 | 70 | By separating the writing (insert) and command (normal) modes, Vim makes it easy for us to switch the two contexts easily. 71 | 72 | Notice how the first steps to using Vim seem a little "weird", a little "strange", but once you have seen it in action, it starts to make sense. The best part is that these core concepts will help you to understand all you need to know on how to use Vim. 73 | 74 | Since you now understand the difference between normal mode and insert mode, you can look up the various commands you can run in the normal mode, and you can immediately start using them. Compare that to learning new commands in traditional editors which generally means having to read a lot of documentation, searching a lot of menus, a lot of trial and error or plain asking someone for help. 75 | 76 | Personally, I find the names of the modes not intuitive to beginners. I prefer calling the insert mode as "writing" mode and the normal mode as "rewriting" mode, but we will stick to the standard Vim terminology to avoid confusion. 77 | 78 | > NOTE: All commands in the normal mode should end with the enter key to signal Vim that we have written the full command. So, when we say run `:help vim-modes-intro`, it means you should type `:help vim-modes-intro` and then press the enter key at the end of the command. 79 | 80 | ## Writing a file {#write-file} 81 | 82 | 1. Open Vim. ![](img/first_steps_open.png) 83 | 2. Type `:edit hello.txt` and press the enter key. ![](img/first_steps_edit.png) 84 | 3. Press `i` to switch to insert mode. ![](img/first_steps_insert.png) 85 | 4. Type the text `Hello World`. ![](img/first_steps_type.png) 86 | 5. Press the `` key. ![](img/first_steps_normal.png) 87 | 6. Type `:write` and press the `enter` key. ![](img/first_steps_write.png) 88 | 7. Close Vim by running `:quit`. ![](img/first_steps_quit.png) 89 | 90 | Congratulations! You just wrote your first file using Vim :-). 91 | 92 | Does this seem like a lot of steps? Yes, it does, *at first*. That is because this is the first time we are getting used to opening Vim, writing a file and closing Vim. You have to keep in mind that this will only be a minor part of your time compared to the actual time that goes into in editing the content of the document. 93 | 94 | Let us see what the above commands do. 95 | 96 | - `:edit hello.txt` or simply `:e hello.txt` 97 | - This opens a file for editing. If the file with the specified name does not exist, it will be created the first time we "save" the file. 98 | - Press `i` 99 | - This switches Vim to the insert mode 100 | - Type the text `Hello World` 101 | - This is where you type the actual text that you want to write. 102 | - Press `` 103 | - This escapes Vim back to normal mode 104 | - `:write` or simply `:w` 105 | - This tells Vim to *w*rite the text (which is currently stored in the computer's memory) to the file on the hard disk. This means that whatever we wrote so far is now permanently stored. 106 | - `:quit` or simply `:q` 107 | - This tells Vim to quit the file in the "window" that we are editing. If there was only one "window" open, this will also close Vim (Concept of windows will be discussed in a later chapter). 108 | 109 | Try to repeat this process a few times with different file names, different text, etc. so that you get used to the basic set of steps in using Vim. 110 | 111 | Notice that when you are in insert mode, Vim displays `-- INSERT --` at the bottom left corner. When you switch to normal mode, it will not display anything. This is because normal mode is the *default* mode in which Vim runs. 112 | 113 | Take some time to soak in this information, this is probably the hardest lesson there is to learn about Vim, the rest is easy :) 114 | 115 | And don't worry, help is not too far away. Actually, it's just a `:help` command away. For example, run `:help :edit` and you'll see the documentation open up. Go ahead, try it. 116 | 117 | ## Summary 118 | 119 | We have now discussed the basic concepts and usage of Vim. See `:help notation` and `:help keycodes` also. 120 | 121 | Be sure to understand these concepts well. Once you start "thinking in Vim", understanding the rest of Vim's features is easy. 122 | -------------------------------------------------------------------------------- /help.md: -------------------------------------------------------------------------------- 1 | # Help 2 | 3 | Vim has such a diverse list of commands, keyboard shortcuts, buffers, and so on. It's impossible to remember how all of them work. In fact, it is not even useful to know all of them. The best situation is that you know how to look for certain functionality in Vim whenever you need it. 4 | 5 | For example, you want to avoid having to type a long name every time, you suddenly remember there is an abbreviations feature in Vim that'll help you do just that, but don't remember how to use it. What do you do? 6 | 7 | Let's look at the various ways of finding help about how to use Vim. 8 | 9 | ## The `:help` command 10 | 11 | The first and most important place to try to look for help is the built-in documentation and Vim has one of the most comprehensive user manuals that I've ever seen. 12 | 13 | In our case, just run `:help abbreviation` and you'll be taken to the help for abbreviations and you can read about how to use the `:ab` and `:iab` commands. 14 | 15 | Sometimes, it can be as simple as that. If you don't know what you're looking for, then you can run `:help user-manual` and browse through the list of contents of the entire user manual and read the chapter that you feel is relevant to what you're trying to do. 16 | 17 | ## How to read the `:help` topic 18 | 19 | Let us take some sample text from `:help abbreviate`: 20 | 21 | ``` 22 | :ab[breviate] [] {lhs} {rhs} 23 | add abbreviation for {lhs} to {rhs}. If {lhs} already 24 | existed it is replaced with the new {rhs}. {rhs} may 25 | contain spaces. 26 | See |:map-| for the optional argument. 27 | ``` 28 | 29 | Notice that there is a standard way of writing help in Vim to make it easy for us to figure out the parts that are needed for us instead of trying to understand the whole command. 30 | 31 | The first line explains the syntax i.e. how to use this command. 32 | 33 | The square brackets in `:ab[breviate]` indicate that the latter part of the full name is optional. The minimum you have to type is `:ab` so that Vim recognizes the command. You can also use `:abb` or `:abbr` or `:abbre` and so on till the full name `:abbreviate`. Most people tend to use the shortest form possible. 34 | 35 | The square brackets in `[]` again indicate that the 'expression' is optional. 36 | 37 | The curly brackets in `{lhs} {rhs}` indicate that these are placeholders for actual arguments to be supplied. The names are short for 'left hand side' and 'right hand side' respectively. 38 | 39 | Following the first line is an indented paragraph that briefly explains what this command does. 40 | 41 | Notice the second paragraph which points you to further information. You can position the cursor on the text between the two pipe symbols and press `ctrl-]` to follow the "link" to the corresponding `:help` topic. To jump back, press `ctrl-o`. 42 | 43 | ## The `:helpgrep` command 44 | 45 | If you do not know what the name of the topic is, then you can search the entire documentation for a phrase by using `:helpgrep`. Suppose you want to know how to look for the beginning of a word, then just run `:helpgrep beginning of a word`. 46 | 47 | You can use `:cnext` and `:cprev` to move to the next and previous part of the documentation where that phrase occurs. Use `:clist` to see the whole list of all the occurrences of the phrase. 48 | 49 | ## Quick help 50 | 51 | Copy the following text into a file in Vim and then also run it: 52 | 53 | ``` viml 54 | :let &keywordprg=':help' 55 | ``` 56 | 57 | Now, position your cursor anywhere on the word `keywordprg` and just press `K`. You'll be taken to the help immediately for that word. This shortcut avoids having to type `:help keywordprg`. 58 | 59 | ## Mailing List 60 | 61 | If you are still not able to figure out what you want to do, then the next best thing is to approach other Vim users to help you out. Don't worry, this is actually very easy and it is amazing how other Vimmers who are willing to help you out. 62 | 63 | Search the Vim mailing list to see if someone has already answered your question. Just go to the [Vim Group search page](http://groups.google.com/group/vim_use) and then enter the keywords of your question. Most of the times, many common questions will be already answered since this is such a high-traffic mailing list i.e. lots and lots of people ask questions and give answers in this group. 64 | 65 | If you cannot find any relevant answer, then post your question in the same mailing list. 66 | 67 | ## Summary 68 | 69 | There is a wealth of information on how to do things using Vim, and many Vimmers would gladly help you out as well. The Vim community is one of the greatest strengths of the Vim editor, so make sure to use the resources and do join the growing community as well. 70 | 71 | > The true delight is in the *finding out* rather than in the *knowing*. 72 | > -- Isaac Asimov 73 | -------------------------------------------------------------------------------- /img/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/.DS_Store -------------------------------------------------------------------------------- /img/first_steps_edit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/first_steps_edit.png -------------------------------------------------------------------------------- /img/first_steps_insert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/first_steps_insert.png -------------------------------------------------------------------------------- /img/first_steps_normal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/first_steps_normal.png -------------------------------------------------------------------------------- /img/first_steps_open.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/first_steps_open.png -------------------------------------------------------------------------------- /img/first_steps_quit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/first_steps_quit.png -------------------------------------------------------------------------------- /img/first_steps_type.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/first_steps_type.png -------------------------------------------------------------------------------- /img/first_steps_write.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/first_steps_write.png -------------------------------------------------------------------------------- /img/hands_on_keyboard.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/hands_on_keyboard.gif -------------------------------------------------------------------------------- /img/hands_on_keyboard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/hands_on_keyboard.png -------------------------------------------------------------------------------- /img/hjkl.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/hjkl.png -------------------------------------------------------------------------------- /img/multiple_tabs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/multiple_tabs.png -------------------------------------------------------------------------------- /img/multiple_windows.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/multiple_windows.png -------------------------------------------------------------------------------- /img/vi-vim-cheat-sheet.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swaroopch/byte-of-vim/ff1bfd72ec93a22ec21b13adf2a26b9f10f9493b/img/vi-vim-cheat-sheet.gif -------------------------------------------------------------------------------- /installation.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | Let's see how to get Vim installed on your computer. 4 | 5 | ## Windows 6 | 7 | If you use Microsoft Windows, then the following steps will help you get the latest version of Vim 7 installed on your computer: 8 | 9 | 1. Visit http://www.vim.org/download.php#pc 10 | 2. Download the "Self-installing executable" (gvim72.exe [1] as of this writing) 11 | 3. Double-click the file and install Vim like any other Windows-based software. 12 | 13 | ## Mac OS X 14 | 15 | If you use Mac OS X, then you already have the terminal version of Vim installed. Run the menu command Finder → Applications → Utilities → Terminal. In the terminal, run the command vim and press enter, you should now see the Vim welcome screen. 16 | 17 | If you want to use a graphical version of Vim, download the latest version of the [Cocoa-based MacVim project](http://code.google.com/p/macvim/). Double-click the file (such as `MacVim-7_2-stable-1_2.tbz`), it will be unarchived and a directory called `MacVim-7_2-stable-1_2` will be created. Open the directory, and copy the MacVim app to your Applications directory. 18 | 19 | For more details MacVim diffrences, including how to run MacVim from the terminal see the macvim reference: 20 | 21 | 1. Click on Finder → Applications → MacVim. 22 | 2. Type :help macvim and press the Enter key. 23 | 24 | ## Linux / BSD 25 | 26 | If you are using a Linux or *BSD system, then you will have at least a minimal console version of Vim already installed. Open a terminal program such as `konsole` or `gnome-terminal`, run `vim` and you should see the Vim welcome screen. 27 | 28 | If you get a message like `vim: command not found`, then Vim is not installed. You will have to use your system-specific tools to install Vim, such as aptitude in Ubuntu/Debian Linux, yum in Fedora Linux, pkg_add or port in FreeBSD, etc. Please consult your specific system's documentation and forums on how to install new packages. 29 | 30 | If you want the graphical version, install the vim-gnome package or alternatively, the gvim package. 31 | 32 | ## Summary 33 | 34 | 35 | Depending on how it is installed, you can run the `vim` command in the shell or use your operating system's menus to open a graphical version of the Vim application. 36 | 37 | Now that we have Vim installed on your computer, let us proceed to use it in the next chapter. 38 | -------------------------------------------------------------------------------- /introduction.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | ## What is Vim? 4 | 5 | Vim is a computer program used for writing any kind of text, whether it is your shopping list, a book, or software code. 6 | 7 | What makes Vim special is that it is one of those few software which is both **simple and powerful**. 8 | 9 | Simple means it is easy to get started with. Simple means that it has a minimalistic interface that helps you to concentrate on your main task - writing. Simple means it is built around few core concepts that helps you learn deeper functionality easily. 10 | 11 | Powerful means getting things done faster, better and easier. Powerful means making not-so-simple things possible. Powerful does not mean it has to be complicated. Powerful means following the paradigm of **"Minimal effort. Maximal effect."** 12 | 13 | ## What can Vim do? 14 | 15 | I can hear you say, "So it's a text editor. What's the big deal anyway?" 16 | 17 | Well, a lot. 18 | 19 | Let's see some random examples to compare Vim with your current choice of editor. The point of this exercise is for you to answer the question *"How would I do this in the editor I currently use?"* for each example. 20 | 21 | > NOTE: Don't worry too much about the details of the Vim commands here, the point here is to enlighten you with the possibilities, not to start explaining how these things work. That is what the rest of the book is for. 22 | 23 | | Edit | In Vim | In your editor | 24 | | ---- | ------ | -------------- | 25 | | How do you move the cursor down by 7 lines? | Press `7j` | (Fill this column) | 26 | | How do you delete a word? Yes, a "word" | Press `dw` | | 27 | | How do you search the current file for the current word that the cursor is at? | Press `*` | | 28 | | How to find and replace only in lines 50-100? | Run `:50,10s/old/new/g` | | 29 | | How to view two different parts of the same file simultaneously? | Run `:sp` to 'split' the view | | 30 | | The cursor is at a file name, how to jump to that file? | Press `gf` (which means 'g'o to 'f'ile) | | 31 | | Switch to a better theme? | Run `:colorscheme desert` to choose the `desert` theme | | 32 | | How to map `ctrl-s` to save the file? | Run `:nmap :w` (`` means 'c'arriage 'r'eturn, i.e. the enter key) | | 33 | | How to save the current set of open files & settings so that you can restart the session later? | Run `:mksession ~/session.vim` and then open Vim next time with `vim -S ~/session.vim` | | 34 | | How to see colors for different parts of your code? | Run `:syntax on`. If it doesn't recognize the language properly, use `set ft=python` for example. | | 35 | | How to hide different parts of the file so that you can concentrate on only one part at a time? | Run `:set foldmethod=indent` assuming your file is properly indented. | | 36 | | How to open multiple files in tabs? | Use `:tabedit ` to open multiple files in "tabs" (just like browser tabs), and use `gt` to switch between tabs | | 37 | | You use some words frequently in your document and wish there was a way that it could be quickly filled in the next time you use the same word? | Press `ctrl-n` to see the list of "completions" for the current word, based on all the words that you have used in the current document. Alternatively, use `:ab mas Maslow's hierarchy of needs` to expadn the abbreviation automatically when you type `m a s `. | | 38 | | You have some data where only the first 10 characters in each line are useful and the rest is no longer useful for you. How do you get only that data? | Press `ctrl-v`, select the text and press `y` to copy the selected rows and columns of text. | | 39 | | What if you received a document from someone which is all in capitals, find it irritating and want to convert it to lower case? | (1) Run the following: :for i in range(0, line('$')) | call setline(i, tolower(getline(i))) | endfor.
(2) Don't worry, details will be explored in later chapters. A more succinct way would be to run `:%s#\\(.\\)#\\l\\1#g`, but the first way would be simpler. (3) Select all the text using `1GVG` and then using the `u` operator to convert the selection to lowercase. | | 40 | 41 | 42 | 43 | Phew. Are you convinced yet? 44 | 45 | In these examples, you can see the power of Vim in action. Any other editor would make it insanely hard to achieve the same level of functionality. And yet, amazingly, all this power is made as understandable as possible. 46 | 47 | Notice that we didn't use the mouse even once during these examples! This is a good thing. Count how many times you shift your hand between the keyboard and the mouse in a single day, and you'll realize why it is good to avoid it when possible. 48 | 49 | Don't be overwhelmed by the features here. The best part of Vim is that you don't need to know all of these features to be productive with it, you just need to know a few basic concepts. After learning those basic concepts, all the other features can be easily learned when you need them. 50 | -------------------------------------------------------------------------------- /modes.md: -------------------------------------------------------------------------------- 1 | # Modes 2 | 3 | We had our first encounter with modes in the previous chapter. Now, let us explore this concept further regarding types of modes available and what we can do in each mode. 4 | 5 | ## Types of modes 6 | 7 | There are three basic modes in Vim: 8 | 9 | 1. Normal mode is where you can run commands. This is the default mode in which Vim starts up. 10 | 2. Insert mode is where you insert i.e. write the text. 11 | 3. Visual mode is where you visually select a bunch of text so that you can run a command/operation only on that part of the text. 12 | 13 | ## Normal mode 14 | 15 | By default, you're in normal mode. Let's see what we can do in this mode. 16 | 17 | Type `:echo "hello world"` and press enter. You should see the famous words hello world echoed back to you. What you just did was run a Vim command called `:echo` and you supplied some text to it which was promptly printed back. 18 | 19 | Type `/hello` and press the enter key. Vim will search for that phrase and will jump to the first occurrence. 20 | 21 | This was just two simple examples of the kind of commands available in the normal mode. We will see many more such commands in later chapters. 22 | 23 | ## How to use the help 24 | 25 | Almost as important as knowing the normal mode, is knowing how to use the `:help` command. This is where you learn more about the commands available in Vim. 26 | 27 | Remember that you do not need to know every command available in Vim, it's better to simply know where to find them when you need them. For example, see `:help usr_toc` takes us to the table of contents of the reference manual. You can see `:help index` to search for the particular topic you are interested in, for example, run `/insert mode` to see the relevant information regarding insert mode. 28 | 29 | If you can't remember these two help topics at first, just press `F1` or run `:help`. 30 | 31 | ## Insert mode 32 | 33 | When Vim starts up in normal mode, we have seen how to use i to get into insert mode. There are other ways of switching from normal mode to insert mode as well: 34 | 35 | 1. Run `:e dapping.txt` 36 | 2. Press `i` 37 | 3. Type the following paragraph (including all the typos and mistakes, we'll correct them later): 38 | 39 | > means being determined about being determined and being passionate about being passionate 40 | 41 | 4. Press `` key to switch back to normal mode. 42 | 5. Run `:w` 43 | 44 | Oops, we seem to have missed a word at the beginning of the line, and our cursor is at the end of the line, what do we do now? 45 | 46 | What would be the most efficient way of going to the start of the line and insert the missing word? Should we use the mouse to move the cursor to the start of the line? Should we use arrow keys to travel all the way to the start of the line. Should we press home key and then press i to switch back to insert mode again? 47 | 48 | It turns out that the most efficient way to be press `I` (upper case I): 49 | 50 | 1. Press `I` 51 | 2. Type `Dappin` 52 | 3. Press `` key to switch back to the normal mode. 53 | 54 | Notice that we used a different key to switch to insert mode, its specialty is that it moves the cursor to the start of the line and then switches to the insert mode. 55 | 56 | Also notice how important it is to *switch back to the normal mode as soon as you're done typing the text*. Making this a habit will be beneficial because most of your work (after the initial writing phase) will be in the normal mode - that's where the all-important rewriting/editing/polishing happens. 57 | 58 | Now, let's take a different variation of the `i` command. Notice that pressing `i` will place your cursor before the current position and then switch to insert mode. To place the cursor 'a'fter the current position, press `a`. 59 | 60 | 1. Press `a` 61 | 2. Type `g` (to complete the word as "Dapping") 62 | 3. Press `` to switch back to normal mode 63 | 64 | Similar to the relationship between `i` and `I` keys, there is a relationship between the `a` and `A` keys - if you want to append text at the end of the line, press the `A` key. 65 | 66 | 1. Press `A` 67 | 2. Type `.` (put a dot to complete the sentence properly) 68 | 3. Press `` to switch back to the normal mode 69 | 70 | To summarize the four keys we have learnt so far: 71 | 72 | | Command | Action | 73 | | --- | --- | 74 | | `i` | insert text just before the cursor | 75 | | `I` | insert text at the start of the line | 76 | | `a` | append text just after the cursor | 77 | | `A` | append text at the end of the line | 78 | 79 | Notice how the upper case commands are 'bigger' versions of the lower case commands. 80 | 81 | Now that we are proficient in quickly moving in the current line, let's see how to move to new lines. If you want to 'o'pen a new line to start writing, press the `o` key. 82 | 83 | 1. Press `o` 84 | 2. Type `I'm a rapper`. 85 | 3. Press `` to switch back to the normal mode. 86 | 87 | Hmmm, it would be more appealing if that new sentence we wrote was in a paragraph by itself. 88 | 89 | 1. Press `O` (upper case 'O') 90 | 2. Press `` to switch back to the normal mode. 91 | 92 | To summarize the two new keys we just learnt: 93 | 94 | | Command | Action | 95 | | --- | --- | 96 | | `o` | open a new line below | 97 | | `O` | open a new line above | 98 | 99 | Notice how the upper and lower case 'o' commands are opposite in the direction in which they open the line. 100 | 101 | Was there something wrong in the text that we just wrote? Aah, it should be 'dapper', not 'rapper'! It's a single character that we have to change, what's the most efficient way to make this change? 102 | 103 | We could press `i` to switch to insert mode, press `` key to delete the `r`, type `d` and then press `` to switch back to the insert mode. But that is four steps for such a simple change! Is there something better? You can use the `s` key - s for 's'ubstitute. 104 | 105 | 1. Move the cursor to the character `r` (or simply press `b` to move 'b'ack to the start of the word) 106 | 2. Press `s` 107 | 3. Type `d` 108 | 4. Press `` to switch back to the normal mode 109 | 110 | Well, okay, it may not have saved us much right now, but imagine repeating such a process over and over again throughout the day! Making such a mundane operation as fast as possible is beneficial because it helps us focus our energies to more creative and interesting aspects. As Linus Torvalds says, *"it's not just doing things faster, but because it is so fast, the way you work dramatically changes."* 111 | 112 | Again, there is a bigger version of the `s` key, `S` which substitutes the whole line instead of the current character. 113 | 114 | 1. Press `S` 115 | 2. Type `Be a sinner`. 116 | 3. Press `` to switch back to normal mode. 117 | 118 | | Command | Action | 119 | | --- | --- | 120 | | `s` | substitute the current character | 121 | | `S` | substitute the current line | 122 | 123 | Let's go back our last action... Can't we make it more efficient since we want to 'r'eplace just a single character? Yes, we can use the `r` key. 124 | 125 | 1. Move the cursor to the first character of the word `sinner`. 126 | 2. Press `r` 127 | 3. Type `d` 128 | 129 | Notice we're already back in the normal mode and didn't need to press ``. 130 | 131 | There's a bigger version of `r` called `R` which will replace continuous characters. 132 | 133 | 1. Move the cursor to the 'i' in sinner. 134 | 2. Press `R` 135 | 3. Type `app` (the word now becomes 'dapper') 136 | 4. Press `` to switch back to normal mode. 137 | 138 | | Command | Action | 139 | | --- | --- | 140 | | `r` | replace the current character | 141 | | `R` | replace continuous characters | 142 | 143 | The text should now look like this: 144 | 145 | > Dapping means being determined about being determined and being passionate about being passionate. 146 | >
147 | > Be a dapper. 148 | 149 | Phew. We have covered a lot in this chapter, but I guarantee that this is the only step that is the hardest. Once you understand this, you've pretty much understood the heart and soul of how Vim works, and all other functionality in Vim, is just icing on the cake. 150 | 151 | To repeat, understanding how modes work and how switching between modes work is the key to becoming a Vimmer, so if you haven't digested the above examples yet, please feel free to read them again. Take all the time you need. 152 | 153 | If you want to read more specific details about these commands, see `:help inserting` and `:help replacing`. 154 | 155 | ## Visual mode 156 | 157 | Suppose that you want to select a bunch of words and replace them completely with some new text that you want to write. What do you do? 158 | 159 | One way would be to use the mouse to click at the start of the text that you are interested in, hold down the left mouse button, drag the mouse till the end of the relevant text and then release the left mouse button. This seems like an awful lot of distraction. 160 | 161 | We could use the `` or `` keys to delete all the characters, but this seems even worse in efficiency. 162 | 163 | The most efficient way would be to position the cursor at the start of the text, press v to start the visual mode, use arrow keys or any text movement commands to the move to the end of the relevant text (for example, press `5e` to move to the end of the 5th word counted from the current cursor position) and then press `c` to 'c'hange the text. Notice the improvement in efficiency. 164 | 165 | In this particular operation (the `c` command), you'll be put into insert mode after it is over, so press `` to return to normal mode. 166 | 167 | The `v` command works on a character basis. If you want to operate in terms of lines, use the upper case `V`. 168 | 169 | ## Summary 170 | 171 | Here is a drawing of the relationship between the different modes: 172 | 173 | ``` 174 | +---------+ i,I,a,A,o,O,r,R,s,S +----------+ 175 | | Normal +---------->------------+ Insert | 176 | | mode | | mode | 177 | | +----------<------------+ | 178 | +-+---+---+ +----------+ 179 | | | 180 | | | 181 | | | 182 | | | 183 | v, | | 184 | V V ^ 185 | | | 186 | | | 187 | | | 188 | | | 189 | +---+---+----+ 190 | | Visual | 191 | | mode | 192 | +------------+ 193 | ``` 194 | 195 | > NOTE: This drawing was created using Vim and [Dr.Chip's DrawIt plugin](http://www.vim.org/scripts/script.php?script_id=40). 196 | 197 | See `:help vim-modes-intro` and `:help mode-switching` for details on the various modes and how to switch between them respectively. 198 | 199 | If you remain unconvinced about why the concept of modes is central to Vim's power and simplicity, do read the articles on ["Why Vi"](http://www.viemu.com/a-why-vi-vim.html) and about the [vi input model](http://blog.ngedit.com/2005/06/03/the-vi-input-model/) on why it is a better way of editing. 200 | -------------------------------------------------------------------------------- /more.md: -------------------------------------------------------------------------------- 1 | # More 2 | ## Introduction 3 | We've explored so many features of Vim, but we still haven't covered them all, so let's take a quick wild ride through various topics that are useful and fun. 4 | 5 | ## Modeline 6 | What if you wanted to specify that a certain file should always use pure tabs and no spaces while editing. Can we enforce that within the file itself? 7 | 8 | Yes. Just put `vim: noexpandtab` within the first two lines or last two lines of your file. 9 | 10 | An example: 11 | ``` 12 | # Sample Makefile 13 | .cpp: 14 | $(CXX) $(CXXFLAGS) $< -o $@ 15 | 16 | # vim: noexpandtab 17 | ``` 18 | This line we are adding is called a "modeline." 19 | 20 | ## Portable Vim 21 | If you keep switching between different computers, isn't it a pain to maintain your Vim setup exactly the same on each machine? Wouldn't it useful if you could just carry Vim around in your own USB disk? This is exactly what [Portable GVim](http://portablegvim.sourceforge.net) is. 22 | 23 | Just unzip into a directory on the portable disk, then run `GVimPortable.exe`. You can even store your own `vimrc` and other related files on the disk and use it anywhere you have a Microsoft Windows computer. 24 | 25 | ## Upgrade plugins 26 | Any sufficiently advanced Vim user would be using a bunch of plugins and scripts added to their `~/.vim` or `~/vimfiles` directory. What if we wanted to update them all to the latest versions? You could visit the script page for each of them, download and install them, but there's a better way: just run `:GLVS` (which stands for 'G'et 'L'atest 'V'im 'S'cripts). 27 | 28 | See `:help getscript` for details. 29 | 30 | There are scripts to even [twitter from Vim](http://www.vim.org/scripts/script.php?script_id=1853)! 31 | 32 | ## Dr.Chip's plugins 33 | "Dr. Chip" has written some [amazing Vim plugins](http://www.drchip.org/astronaut/vim/) over many years. 34 | 35 | One of my favorites is [drawit.vim](http://www.vim.org/scripts/script.php?script_id=40), which helps you to draw text-based drawings such as those fancy ASCII diagrams you have seen before. 36 | 37 | Another is [align.vim](http://www.vim.org/scripts/script.php?script_id=294), which helps you to align consecutive lines together. For example, say you have the following piece of program code: 38 | ``` 39 | a = 1 40 | bbbbb = 2 41 | cccccccccc = 3 42 | ``` 43 | Just visually select these three lines and press \t=, and voila, it becomes like this: 44 | ``` 45 | a = 1 46 | bbbbb = 2 47 | cccccccccc = 3 48 | ``` 49 | This is much easier to read than before and makes your code look more professional. Explore Dr. Chip's page to find out about many more interesting plugins. 50 | 51 | ## Blog from Vim 52 | Using the [Vimpress plugin](http://www.vim.org/scripts/script.php?script_id=1953), you can blog to your Wordpress blog right within Vim. 53 | 54 | ## Make Firefox work like Vim 55 | Use the [Vimperator add-on](http://vimperator.mozdev.org/) to make Firefox behave like Vim, complete with modal behavior, keyboard shortcuts to visit links, status line, tab completion, and even marks support! 56 | 57 | ## Bram's talk on the seven habits 58 | Bram Moolenaar, the creator of Vim, had written an article long ago titled ["Seven habits of effective text editing"](http://www.moolenaar.net/habits.html) that explained how you should use a good editor (such as Vim). 59 | 60 | Bram recently gave a talk titled ["Seven habits for effective text editing, 2.0"](https://youtu.be/eX9m3g5J-XA) where he goes on to describe the newer features of Vim as well as how to effectively use Vim. This talk is a good listen for any regular Vim user. 61 | 62 | ## Contribute to Vim 63 | You can contribute to Vim in various ways, such as working on [development of Vim itself](http://groups.google.com/group/vim_dev), [writing plugins and color schemes](http://www.vim.org/scripts/), [contributing tips](http://vim.wikia.com), and [helping with the documentation](http://vimdoc.sourceforge.net). 64 | 65 | If you want to help in the development of Vim itself, see `:help development`. 66 | 67 | ## Community 68 | Many Vim users hang out at the [vim@vim.org mailing list](http://www.vim.org/maillist.php#vim) where questions and doubts are asked and answered. The best way to learn more about Vim and to help other beginners learn Vim is to frequently read (and reply) to emails in this mailing list. 69 | 70 | Find more articles and discussions at [Google+](https://plus.google.com/communities/105049811056605918816) and [reddit](http://www.reddit.com/r/vim/). 71 | 72 | ## Summary 73 | We've seen some wide range of Vim-related stuff and how it can be beneficial to us. Feel free to explore these and many more [Vim scripts](http://www.vim.org/scripts/) to help you ease your editing and make it even more convenient. 74 | -------------------------------------------------------------------------------- /moving_around.md: -------------------------------------------------------------------------------- 1 | # Moving Around 2 | 3 | Once you've written the initial text, editing and rewriting requires a lot of movement between the various parts of the document. For example, you're writing a story and you suddenly get an idea for a new plot, but to develop this plot you need to go back to the part where the protagonist enters the new city (or something like that)... how do you quickly move around the text so that you don't lose your train of thought? 4 | 5 | Let's see a few examples of how Vim makes this fast. 6 | 7 | - Want to move the cursor to the next word? Press `w`. 8 | - Want to move to to the next paragraph? Press `}`. 9 | - Want to move to the 3rd occurrence of the letter 'h'? Press `3fh`. 10 | - Want to move 35 lines downwards? Press `35j`. 11 | - After one of the above movements, want to jump back to the previous location? Press `ctrl-o`. 12 | 13 | Want to learn how all these work? Let's dive in. 14 | 15 | First, open a file called `chandrayaan.txt` and type the following [text from Wikipedia](http://en.wikipedia.org/wiki/Chandrayaan-1): 16 | 17 | > Chandrayaan-1 is India's first mission to the moon. Launched by India's national space agency the Indian Space Research Organisation (ISRO). The unmanned lunar exploration mission includes a lunar orbiter and an impactor. The spacecraft was launched by a modified version of the PSLV XL on 22 October 2008 from Satish Dhawan Space Centre, Sriharikota, Andhra Pradesh at 06:23 IST (00:52 UTC). The vehicle was successfully inserted into lunar orbit on 8 November 2008. The Moon Impact Probe was successfully impacted at the lunar south pole at 20:31 hours on 14 November 2008. 18 | >
19 | > The remote sensing satellite had a mass of 1,380 kilograms (3,042 lb) at launch and 675 kilograms (1,488 lb) at lunar orbit and carries high resolution remote sensing equipment for visible, near infrared, and soft and hard X-ray frequencies. Over a two-year period, it is intended to survey the lunar surface to produce a complete map of its chemical characteristics and 3-dimensional topography. The polar regions are of special interest, as they might contain ice. The lunar mission carries five ISRO payloads and six payloads from other international space agencies including NASA, ESA, and the Bulgarian Aerospace Agency, which were carried free of cost. 20 | 21 | ## Move your cursor, the Vim way 22 | 23 | The most basic keys that you should use are the 'hjkl' keys. These 4 keys correspond to the left, down, up and right arrow keys respectively. Notice these keys are situated directly under your right hand when they are placed on the home row. 24 | 25 | But why not use the arrow keys themselves? The problem is that they are located in a separate location in the keyboard and it requires as much hand movement as it requires to use a mouse. 26 | 27 | Remember, that the right hand fingers should always be placed on `jkl;` keys (and the thumb on the space bar). Now, let's see how to use these 4 keys: 28 | 29 | ![](img/hjkl.png) 30 | 31 | | Key | Mnemonic | 32 | |:---:| --- | 33 | | `h` | You have to stretch your index finger (which is on 'j') to the left to press the 'h'. This is the left-most key and signifies going left. | 34 | | `j` | The drooping 'j' key signifies going down. | 35 | | `k` | The upward pointing 'k' key signifies going up. | 36 | | `l` | The right-most 'l' key signifies going right. | 37 | 38 | Note that we can repeat the operation by prefixing a count. For example, `2j` will repeat the `j` operation 2 times. 39 | 40 | Open up the `chandrayaan.txt` text document and start practicing these keys: 41 | 42 | 1. Position your cursor at the first letter 'C' of the document. 43 | 2. Press `2j` and it should skip the current long line, the blank line and go to the second line i.e. second paragraph. 44 | 3. Press `2k` to get back to where we were. Or alternatively, press `ctrl-o` to jump back. 45 | 4. Press `5l` to move 5 characters to the right. 46 | 5. Press `5h` to move left by 5 characters. Or alternatively, press `ctrl-o` to jump back. 47 | 48 | Make it a habit to use the 'hjkl' keys instead of the arrow keys. Within a few tries, you'll notice how much faster you can be using these keys. 49 | 50 | Similarly, there are more simple keys that replace the following special movements. Notice that this again is intended to reduce hand movement. In this particular case, people are prone to searching and hunting for these special keys, so we can avoid that altogether. 51 | 52 | | Traditional | Vim | 53 | | --- | --- | 54 | | 'home' key moves to the start of the line | `^` key (think 'anchored to the start') | 55 | | 'end' key moves to the end of the line | `$` key (think 'the buck stops here') | 56 | | 'pgup' key moves one screen up | `ctrl-b` which means move one screen 'b'ackward | 57 | | 'pgdn' key moves one screen down | `ctrl-f` which means move one screen 'f'orward | 58 | 59 | If you know the absolute line number that you want to jump to, say line 50, press `50G` and Vim will jump to the 50th line. If no number is specified, `G` will take you to the last line of the file. How do you get to the top of the file? Simple, press `1G`. Notice how a single key can do so much. 60 | 61 | - Move the cursor to the first line by pressing `1G`. 62 | - Move 20 characters to the right by pressing `20l`. 63 | - Move back to the first character by pressing `^`. 64 | - Jump to the last character by pressing `$`. 65 | - Press `G` to jump to the last line. 66 | 67 | What if you wanted to the middle of the text that is currently being shown in the window? 68 | 69 | - Press `H` to jump as 'h'igh as possible (first line of the window) 70 | - Press `M` to jump to the 'm'iddle of the window 71 | - Press `L` to jump as 'l'ow as possible (last line being displayed) 72 | 73 | You must have started to notice the emphasis on touch-typing and never having to move your hands off the main area. That's a good thing. 74 | 75 | ## Words, sentences, paragraphs 76 | 77 | We have seen how to move by characters and lines. But we tend to think of our text as words and how we put them together - sentences, paragraphs, sections, and so on. So, why not move across such text parts i.e. "text objects"? 78 | 79 | Let's take the first few words from our sample text: 80 | 81 | > The polar regions are of special interest, as they might contain ice. 82 | 83 | First, let's position the cursor on the first character by pressing `^`. 84 | 85 | > [T]he polar regions are of special interest, as they might contain ice. 86 | 87 | 88 | 89 | > NOTE: We are using the square brackets to mark the cursor position. 90 | 91 | Want to move to the next 'w'ord? Press `w`. The cursor should now be at the 'p' in 'polar'. 92 | 93 | > The [p]olar regions are of special interest, as they might contain ice. 94 | 95 | How about moving 2 words forward? Just add the prefix count to 'w': `2w`. 96 | 97 | > The polar regions [a]re of special interest, as they might contain ice. 98 | 99 | Similarly, to move to the 'e'nd of the next word, press `e`. 100 | 101 | > The polar regions ar[e] of special interest, as they might contain ice. 102 | 103 | To move one word 'b'ackward, press `b`. By prefixing a count, `2b` will go back by 2 words. 104 | 105 | > The polar [r]egions are of special interest, as they might contain ice. 106 | 107 | See `:help word-motions` for details. 108 | 109 | We have seen character motions and word motions, let's move on to sentences. 110 | 111 | > [C]handrayaan-1 is India's first mission to the moon. Launched by India's national space agency the Indian Space Research Organisation (ISRO). The unmanned lunar exploration mission includes a lunar orbiter and an impactor. The spacecraft was launched by a modified version of the PSLV XL on 22 October 2008 from Satish Dhawan Space Centre, Sriharikota, Andhra Pradesh at 06:23 IST (00:52 UTC). The vehicle was successfully inserted into lunar orbit on 8 November 2008. The Moon Impact Probe was successfully impacted at the lunar south pole at 20:31 hours on 14 November 2008. 112 | 113 | Position the cursor at the first character using `^`. 114 | 115 | To move to the next sentence, press `)`. 116 | 117 | > Chandrayaan-1 is India's first mission to the moon. [L]aunched by India's national space agency the Indian Space Research Organisation (ISRO). The unmanned lunar exploration mission includes a lunar orbiter and an impactor. The spacecraft was launched by a modified version of the PSLV XL on 22 October 2008 from Satish Dhawan Space Centre, Sriharikota, Andhra Pradesh at 06:23 IST (00:52 UTC). The vehicle was successfully inserted into lunar orbit on 8 November 2008. The Moon Impact Probe was successfully impacted at the lunar south pole at 20:31 hours on 14 November 2008. 118 | 119 | Isn't that cool? 120 | 121 | To move to the previous sentence, press `(`. 122 | 123 | Go ahead, try it out and see how fast you can move. Again, you can prefix a count such as `3)` to move forward by 3 sentences. 124 | 125 | Now, use the whole text and try out moving by paragraphs. Press `}` to move to the next paragraph and `{` to move to the previous paragraph. 126 | 127 | Notice that the 'bigger' brackets is for the bigger text object. If you had already noticed this, then congratulations, you have already started to think like a winner, err, "think like a Vimmer". 128 | 129 | Again, don't try to *remember* these keys, try to make it a *habit* such that your fingers naturally use these keys. 130 | 131 | See `:help cursor-motions` for more details. 132 | 133 | ## Make your mark 134 | 135 | You are writing some text but you suddenly remember that you have to update a related section in the same document, but you do not want to forget where you are currently so that you can come back to this later. What do you do? 136 | 137 | Normally, this would mean scrolling to that section, update it, and then scroll back to where you were. This is a lot of overhead and we may tend to forget where we were last at. 138 | 139 | We can do things a bit smarter in Vim. Move the cursor to the 5th line in the following text (the words by John Lennon). Use `ma` to create a mark named 'a'. Move the cursor to wherever you want, for example `4j`. 140 | 141 | > I am eagerly awaiting my next disappointment. -- Ashleigh Brilliant
142 | > Every man’s memory is his private literature. -- Aldous Huxley
143 | > Life is what happens to you while you’re busy making other plans. -- John Lennon
144 | > Life is really simple, but we insist on making it complicated. -- Confucius
145 | > Do not dwell in the past, do not dream of the future, concentrate the mind on the present moment. -- Buddha
146 | > The more decisions that you are forced to make alone, the more you are aware of your freedom to choose. -- Thornton Wilder 147 | 148 | Press `'a` (i.e. single quote followed by the name of the mark) and voila, Vim jumps (back) to the line where that mark was located. 149 | 150 | You can use any alphabet (a-zA-Z) to name a mark which means you can have up to 52 named marks for each file. 151 | 152 | ## Jump around 153 | 154 | In the various movements that we have learned, we might often want to jump back to the previous location or to the next location after a movement. To do this, simply press `ctrl-o` to jump to the previous location and `ctrl-i` to jump forward to the next location again. 155 | 156 | ## Parts of the text {#text-objects} 157 | 158 | There are various ways you can specify text objects in Vim so that you can pass them to a command. For example, you want to visually select a part of the text and then convert the case (from upper to lower or from lower to upper case) of the text using the `~` key. 159 | 160 | Open the `dapping.txt` file that we created in previous chapters. Use the various keys to move to the first letter of the word 'dapper' in the second paragraph. Hint: Use `}`, `j`, `w`. 161 | 162 | > Dapping means being determined about being determined and being passionate about being passionate.
163 | > Be a dapper. 164 | 165 | Press `v` to start the visual mode, and press `ap` to select 'a' 'p'aragraph. Press `~` to flip the case of the text. If you want to cancel the selection, simply press ``. 166 | 167 | > Dapping means being determined about being determined and being passionate about being passionate.
168 | > bE A DAPPER. 169 | 170 | Other text object mnemonics are `aw` which means 'a' 'w'ord, `a"` means a quoted string (like "this is a quoted string"), `ab` means 'a' 'b'lock which means anything within a pair of parentheses, and so on. 171 | 172 | See `:help object-motions` and `:help text-objects` for more details. 173 | 174 | ## Summary 175 | 176 | We have seen the rich number of methods that Vim gives us to move around the text. It is not important to remember each of these movements, it is more important to make them a habit whenever you can, especially the ones that are most relevant to you, and when they become a habit they reduce the movement of your hands, you become faster, and ultimately spend more time on thinking about your writing rather than on the software you use to write. 177 | 178 | See `:help various-motions` as well as `:help motion` for more interesting ways of movement. 179 | -------------------------------------------------------------------------------- /multiplicity.md: -------------------------------------------------------------------------------- 1 | # Multiplicity 2 | 3 | In this chapter, let's explore how Vim helps us work between different parts of the file, different files, different 'windows' and different tabs to help us to handle more simultaneously. After all, an important part about good editing is managing files. 4 | 5 | ## Multiple Sections using Folds 6 | 7 | If you're editing a long document, wouldn't it be easier if you can "close" all sections of the document and focus on only one at a time? 8 | 9 | This is what we call *folding* in Vim. 10 | 11 | Let us take the example where your document is structured such that each level of the text is indented one level higher such as the following piece of text: 12 | 13 | ``` 14 | Book I 15 | The Shadow of the Past 16 | Three Rings for the Elven-kings under the sky, 17 | Seven for the Dwarf-lords in their halls of stone, 18 | Nine for Mortal Men doomed to die, 19 | One for the Dark Lord on his dark throne 20 | In the Land of Mordor where the Shadows lie. 21 | One Ring to rule them all, One Ring to find them, 22 | One Ring to bring them all and in the darkness bind them 23 | In the Land of Mordor where the Shadows lie. 24 | 25 | Three is Company 26 | 27 | The Road goes ever on and on 28 | Down from the door where it began. 29 | Now far ahead the Road has gone, 30 | And I must follow, if I can, 31 | Pursuing it with weary feet, 32 | Until it joins some larger way, 33 | Where many paths and errands meet. 34 | And whither then? I cannot say. 35 | ``` 36 | 37 | > NOTE: This text was [taken from WikiQuote](http://en.wikiquote.org/wiki/The_Fellowship_of_the_Ring). 38 | 39 | After writing this text, run `:set foldmethod=indent`, position your cursor on the text you want to indent, press `zc` and see how the text folds up. Press `zo` to open the fold. 40 | 41 | Basic commands are `zo` and `zc` where we can open and close the fold respectively. You can use `za` to 'a'lternate between opening and closing a fold respectively. You can make it even easier by using the spacebar (in normal mode) to open and close a fold: 42 | 43 | ``` viml 44 | :nmap za 45 | ``` 46 | 47 | Folding is a huge topic on its own with more ways of folding (manual, marker, expression) and various ways of opening and closing hierarchies of folds, and so on. See `:help folding` for details. 48 | 49 | ## Multiple Buffers 50 | 51 | Suppose you wanted to edit more than one file at a time using the same Vim, what do you do? 52 | 53 | Remember that files are loaded into buffers in Vim. Vim can also load multiple buffers at the same time. So, you can have multiple files open at the same time and you can keep switching between them. 54 | 55 | Let's say you have two files, `part1.txt` and `part2.txt`: 56 | 57 | *part1.txt* 58 | 59 | > I have coined a phrase for myself - 'CUT to the G':
60 | > 1. Concentrate
61 | > 2. Understand
62 | > 3. Think
63 | > 4. Get Things Done 64 | 65 | *part2.txt* 66 | 67 | > Step 4 is eventually what gets you moving, but Steps 2 and 3 are equally important. As Abraham Lincoln once said "If I had eight hours to chop down a tree, I'd spend six hours sharpening my axe." And to get to this stage, you need to do Step 1 which boils down to one thing - It's all in the mind. That's why it's so hard. 68 | 69 | Now, run `:e part1.txt` and then run `:e part2.txt`. Observe that you have the second file now open for editing. How do you switch back to the first file? In this particular case, you can just run `:b 1` to switch to 'b'uffer number '1'. You can also run `:e part1.txt` to open the existing buffer into view. 70 | 71 | You can see what buffers has been loaded and correspondingly, which files are being edited by running `:buffers` or a shorter form, `:ls` which stands for 'l'i's't buffers. 72 | 73 | Buffers will be automatically removed when you close Vim, so you don't have to do anything special other than making sure you save your files. However, if you really want to remove a buffer, for example in order to use less memory, then you can use `:bd 1` to 'd'elete the 'b'uffer numbered '1', etc. 74 | 75 | See `:help buffer-list` on the numerous things you can do with buffers. 76 | 77 | ## Multiple Windows 78 | 79 | We have seen how to edit multiple files at the same time, but what if we wanted to view two different files simultaneously. For example, you want to have two different chapters of your book open so that you can write the second chapter consistent with the wordings/description given in the first chapter. Or you want to copy/paste some stuff from the first file to the second file. 80 | 81 | In the last section, we used the same "view" to edit multiple buffers. Vim calls these "views" as windows. This term "window" should *not* be confused with your desktop application window which usually means the entire application itself. Just think of 'windows' as 'views' on different files. 82 | 83 | Let's take the same `part1.txt` and `part2.txt` sample files used in the previous section. 84 | 85 | First, load the part1.txt using `:e part1.txt`. Now, let's open a new buffer by splitting the window to create a new window - run `:new`. You should now be able to do any normal editing in the new buffer in the new window, except that you can't save the text because you haven't associated a file name with the buffer. For that, you can use `:w test.txt` to save the buffer. 86 | 87 | ![](img/multiple_windows.png) 88 | 89 | How do you switch between these two windows? Just use `ctrl-w ` to switch between the windows. Motion keys can be one of `h`, `j`, `k`, `l` or even any of the arrow keys (in this example, only up and down keys make sense). Remember that `ctrl-w` operations work on 'w'indows. 90 | 91 | As a quick shortcut, you can press `ctrl-w` twice i.e. `ctrl-w ctrl-w` to cycle between all the open windows. 92 | 93 | A particular situation where multiple windows are useful is when you want to view two different parts of the same file simultaneously. Just run `:sp` to create a 'sp'lit window and then you can scroll each window to a different position and continue your editing. Since they both are "windows" to the same buffer, changes in one window will be immediately reflected in the other window. You can also use `ctrl-w s` instead of `:sp`. 94 | 95 | To create a vertical split, use `:vsp` or `ctrl-w v`. To close a window, just run `:q`. 96 | 97 | Now that we have seen how to open and use multiple windows, let's see how to further play around with the display. 98 | 99 | - Suppose you have two split windows but want to reverse the windows, so that you can focus your eyes on the bottom part or top part of your computer screen, as per your preference? Press `ctrl-w r` to 'r'otate the windows. 100 | - Want to move the current window to the topmost position? Press `ctrl-w K`. 101 | - Want to resize a window to make it smaller or larger? Run `:resize 10` to make it 10 lines long display, etc. 102 | - Want to make the current window as big as possible so that you can concentrate on it? Press `ctrl-w _`. Think of the underscore as an indication that the other windows should be as small as possible. 103 | - Want to make the windows 'equal' in height again? Press `ctrl-w =`. 104 | 105 | See `:help windows` on more details on what you can do with windows. 106 | 107 | ## Multiple Tabs 108 | 109 | In web browsers (such as Firefox, Google Chrome or Safari), you may have used the tabs feature which allows you to open multiple websites in a single window so that you can switch between them without having the headache of switching between multiple windows. Well, tabs work exactly the same way in Vim also. Except that they are called "tab pages." 110 | 111 | Run `:tabnew` to open a new tab with a new buffer (analogous to `:new`). How do you switch between the tabs? By pressing `gt` to 'g'o to the next 't'ab and `gT` to 'g'o in the opposite direction i.e. the previous 't'ab. 112 | 113 | ![](img/multiple_tabs.png) 114 | 115 | I personally prefer to use the keys `alt-j` and `alt-k` for the same operations analogous to how the `j` and `k` keys work for characters and how `ctrl-w j` and `ctrl-w k` work for (horizontally split) windows. To enable this, add the following lines to your vimrc file: 116 | 117 | ``` viml 118 | " Shortcuts for moving between tabs. 119 | " Alt-j to move to the tab to the left 120 | noremap gT 121 | " Alt-k to move to the tab to the right 122 | noremap gt 123 | ``` 124 | 125 | To 'c'lose a 'tab', run `:tabc` or `:q`. 126 | 127 | You can even open text that opens in a new window to open in a new tab instead. For example, `:help tabpage` opens the help in a horizontally split window. To view it in a new tab instead, use `:tab help tabpage`. 128 | 129 | If you want to reorder the tabs, use `:tabmove`. For example, to move the current tab to the first position, use `:tabmove 0` and so on. 130 | 131 | See `:help tabpage` for more details on tab pages and the other operations that you can run, such as `:tabdo` to operate on each of the tab pages which are open, and customizing the title of the tab pages (`:help setting-guitablabel`), etc. 132 | 133 | ## Summary 134 | 135 | Vim provides a number of ways to edit multiple files at the same time - buffers, windows and tabs. Using these features depends on your personal habit. For example, using multiple tabs may obviate the usage of multiple windows. It's important to use the one which is most convenient and comfortable. 136 | -------------------------------------------------------------------------------- /neovim.md: -------------------------------------------------------------------------------- 1 | 2 | https://github.com/Silnar/dotfiles/blob/master/.config/nvim/init.vim 3 | 4 | https://github.com/benekastah/neomake 5 | 6 | https://www.reddit.com/r/emacs/comments/446wc4/vim_to_emacsevil_users_thoughts_on_neovim/ 7 | 8 | http://vimawesome.com 9 | -------------------------------------------------------------------------------- /pim.md: -------------------------------------------------------------------------------- 1 | ## Personal Information Management 2 | 3 | A chapter on 'personal information management' (PIM) in a book on an editor software seems strange, doesn't it? Well, there are lots of "professional software" that claim to do personal information management, so let us explore why can't we use a plain text editor like Vim for this purpose? 4 | 5 | Personal information management is about organizing all your "information" - such as your todo lists, diary entries, your reference material (such as important phone numbers), scratchpad and so on. Putting all of this in one convenient location can be extremely handy, and we will explore this using Vim and a few plugins. 6 | 7 | I tend to think of a PIM system is best organized as a wiki. A wiki is a quick way to link together various documents which are inter-related but are independent in their own right. Unsurprisingly, the word 'wiki' means 'quick' in the Hawaiian language. Think of a website - there is a home page, and there are related pages to which you see links, and each page will have its own content but can also inter-link to other pages. Isn't this an easy way of organizing websites? What if you could do the same for your own personal information? See this [LifeHack article 'Wikify Your Life: How to Organize Everything'](http://www.lifehack.org/articles/lifehack/wikify-your-life-how-to-organize-everything.html) on some great examples on what you can do. 8 | 9 | But does this really require a specialized Wiki software? What if you could do the same in just plain text files using Vim? Let's dive in. 10 | 11 | ## Installing Viki 12 | 13 | > NOTE: The `$vimfiles` directory corresponds to `~/.vim` on Linux/Mac, `C:/Documents and Settings//vimfiles` on Windows and `C:Users//vimfiles` on Windows Vista. See `:help vimfiles` for specific details. 14 | 15 | We're going to install Viki and its related plugins: 16 | 17 | 1. Download [multvals.vim](http://www.vim.org/scripts/script.php?script_id=171) and store as `$vimfiles/plugin/multvals.vim`. 18 | 2. Download [genutils.zip](http://www.vim.org/scripts/script.php?script_id=197) and unzip this file to `$vimfiles`. 19 | 3. Download [Viki.zip](http://www.vim.org/scripts/script.php?script_id=861) and unzip this file to `$vimfiles` (make sure all the folders and files under the 'Viki' folder name are stored directly in the `$vimfiles` folder) 20 | 21 | ## Get Started 22 | 23 | 1. Open the GUI version of Vim 24 | 2. `:e test.txt` 25 | 3. `:set filetype=viki` 26 | 4. Type the following text: 27 | 28 | ``` 29 | [[http://deplate.sourceforge.net/Markup.html][Viki syntax]] 30 | ``` 31 | 32 | 5. `:w` 33 | 6. Position your cursor on the above text and press `ctrl+enter`, or alternatively press `\vf`. 34 | 7. You should see a web browser open up with the above website page open. 35 | 36 | Similarly, you can write down any file name (with a valid path) - whether it is a `.doc` file or a `.pdf` file and then you can `ctrl+enter` to open the file in the corresponding Word or Acrobat Reader programs! 37 | 38 | The idea is that you can use plain text files to *hold* all your thinking together and you can `ctrl+enter` your way into everything else. 39 | 40 | Now, notice that we had to type the square brackets in pairs above to identify the target of the link and the words that describe the link. This is basically the syntax of the markup language which we will explore next. 41 | 42 | ## Markup language 43 | 44 | The [Viki syntax](http://deplate.sourceforge.net/Markup.html) page (that you just opened in your web browser) explains how to write the text to allow Viki to syntax highlight portions of your text as well as how to do the linking between 'wiki pages' and even write Viki-specific comments. 45 | 46 | Learning the basics of the syntax highlighting is useful because you can visually see the parts of your text file. For example, use `* List of things to do` to make it a header, and then use dashes to create a list: 47 | 48 | ``` 49 | * List of things to do 50 | 51 | - Finish the blog post on Brahmagiri trek 52 | - Fix footer bug on IONLAB website 53 | - Buy some blank CDs 54 | - Get motorbike serviced 55 | ``` 56 | 57 | ## Disabling CamelCase 58 | 59 | Writing `CamelCase` can create a wiki link in Viki, but I personally dislike this. I prefer that only explicit links like `[[CamelCase]]` be allowed to avoid situations where I have genuinely used a name which uses camel case but I don't want it to be a link (for example, the word "JavaScript"). To disable camel-case syntax, put `let g:vikiNameTypes = "sSeuix"` in your `~/.vimrc` file. 60 | 61 | ## Getting Things Done 62 | 63 | One of the major reasons for creating this 'viki' for myself is to maintain a 'Getting Things Done' system. 64 | 65 | [Getting Things Done ("GTD")](http://www.bnet.com/2403-13074_23-52958.html) is a system devised by David Allen to help manage your 'stuff' - which could mean anything from your career plans to the list of chores you have to do today. 66 | 67 | From David Allen's book: 68 | 69 | > "Get everything out of your head. Make decisions about actions required on stuff when it shows up - not when it blows up. Organize reminders of your projects and the next actions on them in appropriate categories. Keep your system current, complete, and reviewed sufficiently to trust your intuitive choices about what you're doing (and not doing) at any time." 70 | 71 | The GTD system basically consists of organizing your information into certain pages/folders: 72 | 73 | 1. Collection Basket 74 | 2. Projects List 75 | 3. Next Actions 76 | 4. Calendar 77 | 5. Someday/Maybe 78 | 6. Reference Material 79 | 7. Waiting For 80 | 81 | I created a viki to match this system by using the following method: 82 | 83 | 1. First, create a `StartPage` which is literally the start page to your personal organization system (hereby referred to as simply "your viki"). 84 | 2. Then, create a list of main sections of your viki: 85 | 86 | ``` 87 | * Getting Things Done 88 | 89 | 1. [[Collect][In Basket]] 90 | 2. [[Project][Projects List]] 91 | 3. [[NextActions][Next Actions]] 92 | 4. [[Calendar]] 93 | 5. [[SomedayMaybe][Someday/Maybe]] 94 | 6. [[Reference][Reference Material]] 95 | 7. [[Waiting][Waiting For]] 96 | ``` 97 | 98 | 3. Similarly, go to as much depth as you want, for example creating a `[[Reference.Career]]` to jot down your career plans, and `[[Project.TopSecret]]` to gather thoughts on your next project, and so on. 99 | 4. Every time you want to jot down something, use the `[[Collect]]` page and then process, organize, review and finally actually do your next-physical-actions. 100 | 5. It takes a while to get accustomed to using this system, but once you are comfortable, you can achieve clarity of mind, confidence that you're taking care of all the factors in your life, and most importantly, a sense of direction in knowing what are the important things in your life. 101 | 102 | Notice how we are managing an entire system using just plain text! 103 | 104 | ## Summary 105 | 106 | We have just explored how Vim can help you in creating a personal information management system for yourself. It's fascinating how we don't need a complicated software for such a system, just plain text files and Vim will do. 107 | 108 | See [Abhijit Nadgouda's article on using Vim as a personal wiki](http://ifacethoughts.net/2008/05/02/vim-as-a-personal-wiki/) for an alternative way of achieving the same using built-in Vim functionality. 109 | -------------------------------------------------------------------------------- /plugins.md: -------------------------------------------------------------------------------- 1 | # Plugins 2 | 3 | As we have seen in the previous chapter, we can write scripts to extend the existing functionality of Vim to do more stuff. We call these scripts which extend or add functionality as "plugins." 4 | 5 | There are various kinds of plugins that can be written: 6 | 7 | - vimrc 8 | - global plugin 9 | - filetype plugin 10 | - syntax highlighting plugin 11 | - compiler plugin 12 | 13 | Not only can you write your own plugins but also download and [use plugins written by others](http://www.vim.org/scripts/index.php). 14 | 15 | ## Customization using vimrc 16 | 17 | When I install a new Linux distribution or reinstall Windows, the first thing I do after installing Vim is fetch my latest `vimrc` file from my backups, and then start using Vim. Why is this important? Because the `vimrc` file contains various customizations/settings I like which makes Vim more useful and comfortable for me. 18 | 19 | There are two files you can create to customize Vim to your taste: 20 | 21 | 1. vimrc - for general customizations 22 | 2. gvimrc - for GUI specific customizations 23 | 24 | These are stored as: 25 | 26 | - `%HOME%/_vimrc` and `%HOME%/_gvimrc` on Windows 27 | - `$HOME/.vimrc` and `$HOME/.gvimrc` on Linux/BSD/Mac OS X 28 | 29 | See `:help vimrc` on the exact location on your system. 30 | 31 | These vimrc and gvimrc files can contain any Vim commands. The convention followed is to use only simple settings in the vimrc files, and advanced stuff are sourced from plugins. 32 | 33 | For example, here's a portion of my vimrc file: 34 | 35 | ``` viml 36 | " My Vimrc file 37 | " Maintainer: www.swaroopch.com/contact/ 38 | " Reference: Initially based on http://dev.gentoo.org/~ciaranm/docs/vim-guide/ 39 | " License: www.opensource.org/licenses/bsd-license.php 40 | 41 | " Use Vim settings, rather then Vi settings (much better!). 42 | " This must be first, because it changes other options as a side effect. 43 | set nocompatible 44 | 45 | 46 | " Enable syntax highlighting. 47 | syntax on 48 | 49 | " Automatically indent when adding a curly bracket, etc. 50 | set smartindent 51 | 52 | " Tabs should be converted to a group of 4 spaces. 53 | " This is the official Python convention 54 | " http://www.python.org/dev/peps/pep-0008/ 55 | " I didn't find a good reason to not use it everywhere. 56 | set shiftwidth=4 57 | set tabstop=4 58 | set expandtab 59 | set smarttab 60 | 61 | " Minimal number of screen lines to keep above and below the cursor. 62 | set scrolloff=999 63 | 64 | " Use UTF-8. 65 | set encoding=utf-8 66 | 67 | " Set color scheme that I like. 68 | if has("gui_running") 69 | colorscheme desert 70 | else 71 | colorscheme darkblue 72 | endif 73 | 74 | " Status line 75 | set laststatus=2 76 | set statusline= 77 | set statusline+=%-3.3n\ " buffer number 78 | set statusline+=%f\ " filename 79 | set statusline+=%h%m%r%w " status flags 80 | set statusline+=\[%{strlen(&ft)?&ft:'none'}] " file type 81 | set statusline+=%= " right align remainder 82 | set statusline+=0x%-8B " character value 83 | set statusline+=%-14(%l,%c%V%) " line, character 84 | set statusline+=%<%P " file position 85 | 86 | " Show line number, cursor position. 87 | set ruler 88 | 89 | " Display incomplete commands. 90 | set showcmd 91 | 92 | " To insert timestamp, press F3. 93 | nmap a=strftime("%Y-%m-%d %a %I:%M %p") 94 | imap =strftime("%Y-%m-%d %a %I:%M %p") 95 | 96 | " To save, press ctrl-s. 97 | nmap :w 98 | imap :wa 99 | 100 | " Search as you type. 101 | set incsearch 102 | 103 | " Ignore case when searching. 104 | set ignorecase 105 | 106 | " Show autocomplete menus. 107 | set wildmenu 108 | 109 | " Show editing mode 110 | set showmode 111 | 112 | " Error bells are displayed visually. 113 | set visualbell 114 | ``` 115 | 116 | Notice that these commands are not prefixed by colon. The colon is optional when writing scripts in files because it assumes they are normal mode commands. 117 | 118 | If you want to learn detailed usage of each setting mentioned above, refer `:help`. 119 | 120 | A portion of my gvimrc file is: 121 | 122 | ``` viml 123 | " Size of GVim window 124 | set lines=35 columns=99 125 | 126 | " Don't display the menu or toolbar. Just the screen. 127 | set guioptions-=m 128 | set guioptions-=T 129 | 130 | " Font. 131 | if has('win32') || has('win64') 132 | " set guifont=Monaco:h16 133 | " http://jeffmilner.com/index.php/2005/07/30/windows-vista-fonts-now-available/ 134 | set guifont=Consolas:h12:cANSI 135 | elseif has('unix') 136 | let &guifont="Monospace 10" 137 | endif 138 | ``` 139 | 140 | There are various example vimrc files out there that you should definitely take a look at and learn the various kinds of customizations that can be done, then pick the ones you like and put it in your own vimrc. 141 | 142 | A few good ones that I have found in the past are: 143 | 144 | - [Steve Francia's vim distribution](http://vim.spf13.com) 145 | - [Steve Losh's vim config](http://stevelosh.com/blog/2010/09/coming-home-to-vim/) 146 | - [bling's dotvim](https://github.com/bling/dotvim) 147 | - [Janus](https://github.com/carlhuda/janus) 148 | 149 | It is a known fact that a person's vimrc usually reflects how long that person has been using Vim. 150 | 151 | ## Global plugin 152 | 153 | Global plugins can be used to provide global/generic functionality. 154 | 155 | Global plugins can be stored in two places: 156 | 157 | 1. `$VIMRUNTIME/plugin/` for standard plugins supplied by Vim during its installation 158 | 2. To install your own plugins or plugins that you have download from somewhere, you can use your own plugin directory: 159 | 160 | - `$HOME/.vim/plugin/` on Linux/BSD/Mac OS X 161 | - `%HOME%/vimfiles/plugin/` on Windows 162 | - See `:help runtimepath` for details on your plugin directories. 163 | 164 | Let's see how to use a plugin. 165 | 166 | A useful plugin to have is [`highlight_current_line.vim`](http://www.vim.org/scripts/script.php?script_id=1652) by Ansuman Mohanty which does exactly as the name suggests. Download the latest version of the file `highlight_current_line.vim` and put it in your plugin directory (as mentioned above). Now, restart Vim and open any file. Notice how the current line is highlighted compared to the other lines in the file. 167 | 168 | But what if you don't like it? Just delete the `highlight_current_line.vim` file and restart Vim. 169 | 170 | Similarly, we can install our own `related.vim` or `capitalize.vim` from the Scripting chapter into our plugin directory, and this avoids us the trouble of having to use :source every time. Ultimately, any kind of Vim plugin that you write should end up somewhere in your `.vim/vimfiles` plugin directory. 171 | 172 | ## Filetype plugin 173 | 174 | Filetype plugins are written to work on certain kinds of files. For example, programs written in the C programming language can have their own style of indentation, folding, syntax highlighting and even error display. These plugins are not general purpose, they work for these specific filetypes. 175 | 176 | ### Using a filetype plugin 177 | 178 | Let's try a filetype plugin for XML. XML is a declarative language that uses tags to describe the structure of the document itself. For example, if you have a text like this: 179 | 180 | > Iron Gods
181 | > ---------
182 | >
183 | > Ashok Banker's next book immediately following the Ramayana is said to be a novel tentatively titled "Iron Gods" scheduled to be published in 2007. A contemporary novel, it is an epic hard science fiction story about a war between the gods of different faiths. Weary of the constant infighting between religious sects and their deities, God (aka Allah, Yahweh, brahman, or whatever one chooses to call the Supreme Deity) wishes to destroy creation altogether.
184 | >
185 | > A representation of prophets and holy warriors led by Ganesa, the elephant-headed Hindu deity, randomly picks a sample of mortals, five of whom are the main protagonists of the book--an American Catholic, an Indian Hindu, a Pakistani Muslim, a Japanese Buddhist, and a Japanese Shinto follower. The mortal sampling, called a 'Palimpsest' is ferried aboard a vast Dyson's Sphere artifact termed The Jewel, which is built around the sun itself, contains retransplanted cities and landscapes brought from multiple parallel Earths and is the size of 12,000 Earths. It is also a spaceship travelling to the end of creation, where the Palimpsest is to present itself before God to plead clemency for all creation.
186 | >
187 | > Meanwhile, it is upto the five protagonists, aided by Ganesa and a few concerned individuals, including Lucifer Morningstar, Ali Abu Tarab, King David and his son Solomon, and others, to bring about peace among the myriad warring faiths. The question is whether or not they can do so before the audience with God, and if they can do so peacefully--for pressure is mounting to wage one final War of Wars to end all war itself. 188 | 189 | (Excerpt taken from [Wikipedia](http://en.wikipedia.org/w/index.php?title=Ashok_Banker&oldid=86219280) under the GNU Free Documentation License) 190 | 191 | It can be written in XML form (specifically, in 'DocBook XML' format) as: 192 | -------------------------------------------------------------------------------- /preface.md: -------------------------------------------------------------------------------- 1 | # Preface 2 | 3 | ## About Vim 4 | 5 | [Vim](http://www.vim.org) is a computer program used for writing, and it provides a range of features that help you **write better**. 6 | 7 | ## Why Vim? 8 | 9 | Let's face it, it's very rare to produce your best work on the first attempt. Most likely, you will keep editing it frequently until it becomes 'good'. 10 | 11 | As Louis Brandeis once said: 12 | 13 | > There is no great writing, only great rewriting. 14 | 15 | Making these numerous rapid changes would be a lot easier if we had a capable editor to help us, and that is *exactly* where Vim shines, and is far better compared to most plain text editors and rich document editors. 16 | 17 | ## Why Write This Book? 18 | 19 | I have been using the Vim editor ever since I learned to use the old vi editor during Unix classes in college. Vim is one of the few pieces of software that I use for nearly 10 hours a day. I knew there were just so many features that I didn't know about but could potentially be useful to me, so I started exploring Vim little by little. 20 | 21 | To crystallize my understanding and to help others also explore Vim, I started writing this collection of notes, and called it a book. 22 | 23 | Some of the principles I have tried to keep in mind while writing these notes are: 24 | 25 | 1. Simple literature. The importance of this should be reinforced again and again. 26 | 2. Emphasis on examples and how-to. 27 | 3. The one-stop shop for readers to learn Vim - from getting started to learning advanced stuff. 28 | 4. Get the user to understand how to do things the Vim way - from modes to buffers to customization. Most people learn only the basic vi commands and do not attempt to learn anything beyond that. Learning such concepts is the tipping point, they become hardcore Vim users i.e. Vimmers, which means they extract the most out of Vim, which is the intent of this book. 29 | 5. A lot of things are documented and stored here as a reference for people such as how to use Vim as an IDE, etc. There are various ways of doing it and instead of the user struggling to figure out which plugins to try out, the book already has the basic background work already for the reader. 30 | 6. Just enough info to get you to understand and use, not everything required (Pareto principle) 31 | 7. Relatedly, the book shouldn't attempt to rewrite the reference manual. Where appropriate, it should simply point out the relevant parts. This way, there is no redundancy, the user learns to use the awesome built-in reference manual which is important, and the book can stand on its own strengths as well. 32 | 33 | To summarize, the mantra is *Concepts. Examples. Pithy.* 34 | 35 | ## Status of the Book 36 | 37 | The book was a work-in-progress and last updated in 2008. Eight years later (2016), I recreated the book in [GitBook format](http://www.gitbook.com). So let's just say it was a "1.0" book in 2008 :-) 38 | 39 | Constructive suggestions are most welcome. Please send your thoughts and suggestions [via email]({{ book.contactUrl }}) or [github issues]({{ book.sourceUrl }}). 40 | 41 | ## Official Website 42 | 43 | The official website of the book is {{ book.officialUrl }} . From the website, you can read the whole book online or download the latest versions of the book, and also send me feedback. 44 | 45 | ## Something To Think About 46 | 47 | > Books aren't written - they're rewritten. Including your own. It is one of the hardest things to accept, especially after the seventh rewrite hasn't quite done it. 48 | > -- Michael Crichton 49 | 50 | 51 | 52 | > Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away. 53 | > -- Antoine de Saint-Exupery 54 | -------------------------------------------------------------------------------- /programmer_editor.md: -------------------------------------------------------------------------------- 1 | # Programmers Editor 2 | 3 | ## Introduction 4 | 5 | Vim tends to be heavily used by programmers. The features, ease of use, and flexibility that Vim provide make it a good choice for people who write a lot of code. This should not seem surprising since writing code involves a lot of editing. 6 | 7 | Let me reiterate that typing skills are critical for a programmer. If our earlier discussion didn't convince you, we hope this article by Jeff Atwood, titled ['We Are Typists First, Programmers Second'](http://www.codinghorror.com/blog/archives/001188.html), will convince you. 8 | 9 | If you do not have programming experience, you can skip this chapter. 10 | 11 | For those who love programming, let's dive in and see how Vim can help you in writing code. 12 | 13 | ## Simple stuff 14 | The simplest feature of Vim that you can use to help you in writing code is syntax highlighting. This allows you to visualize, i.e. "see," your code, which helps you in reading and writing your code faster and helps avoid making obvious mistakes. 15 | 16 | ### Syntax highlighting 17 | Suppose you are editing a vim syntax file; run `:set filetype=vim` and see how Vim adds color. Similarly, if you are editing a Python file, run `:set filetype=python`. 18 | 19 | ![Syntax Highlighting for Python](syntax_highlighting.png) 20 | 21 | To see the list of language types available, check the `$VIMRUNTIME/syntax/` directory. 22 | 23 | #### Tip 24 | If you want the power of syntax highlighting for any Unix shell output, just pipe it to Vim. For example, `svn diff | vim -R -`. Notice the dash in the end which tells Vim that it should read text from its standard input. 25 | 26 | ### Smart indentation 27 | An experienced programmer's code is usually indented properly, which makes the code look "uniform" and the structure of the code more visually apparent. Vim can help by doing the indentation for you so that you can concentrate on the actual code. 28 | 29 | If you indent a particular line and want the lines following it to be also indented to the same level, then you can use the `:set autoindent` setting. 30 | 31 | If you start a new block of statements and want the next line to be automatically indented to the next level, then you can use the `:set smartindent` setting. Note that the behavior of this setting is dependent on the particular programming language being used. 32 | 33 | ### Bounce 34 | If the programming language of your choice uses curly brackets to demarcate blocks of statements, place your cursor on one of the curly brackets, and press the `%` key to jump to the corresponding curly bracket. This bounce key allows you to jump between the start and end of a block quickly. 35 | 36 | ### Shell commands 37 | You can run a shell command from within Vim using the `:!` command. 38 | 39 | For example, if the `date` command is available on your operating system, run `:!date` and you should see the current date and time printed out. 40 | 41 | This is useful in situations where you want to check something with the file system. For example, you can quickly check which files are in the current directory using `:!ls` or `:!dir` and so on. 42 | 43 | If you want access to a full-fledged shell, run `:sh`. 44 | 45 | We can use this facility to run external filters for the text being edited. For example, if you have a bunch of lines you want to sort, then you can run `:%!sort`. This passes the current text to the sort command in the shell and then the output of that command replaces the current content of the file. 46 | 47 | ## Jumping around 48 | There are many ways of jumping around the code. 49 | 50 | * Position your cursor on a filename in the code and then press gf to open the file. 51 | * Position your cursor on a variable name and press `gd` to move the local definition of the variable name. `gD` achieves the same for the global declaration by searching from the start of the file. 52 | * Use ]] to move to the next { in the first column. There are many similar motions - see `:help object-motions` for details. 53 | * See `:help 29.3`, `:help 29.4`, and `:help 29.5` for more such commands. For example, `[I` will display all lines that contain they keyword under the cursor! 54 | 55 | ## Browsing parts of the code 56 | ### File system 57 | Use `:Vex` or `:Sex` to browse the file system within Vim and subsequently open the required files. 58 | 59 | ### ctags 60 | We have seen how to achieve simple movements within the same file, but what if we want to move between different files and have cross-references between files? We can use tags to achieve this. 61 | 62 | For simple browsing of the file, we can use the `taglist.vim` plugin. 63 | 64 | 1. Install the [Exuberant ctags](http://ctags.sourceforge.net) program. 65 | 2. Install the [taglist.vim](http://www.vim.org/scripts/script.php?script_id=273) plugin. Refer the "install details" on the script page. 66 | 3. Run `:TlistToggle` to open the taglist window. Voila, now you can browse through parts of your program such as macros, typedefs, variables and functions. 67 | 4. You can use `:tag foo` to jump to the definition of foo. 68 | 5. Position your cursor on any symbol and press `ctrl-]` to jump to the definition of that symbol. 69 | * Press ctrl-t to return to the previous code you were reading. 70 | 6. Use `ctrl-w ]` to jump to the definition of the symbol in a split window. 71 | 7. Use `:tnext`, `:tprev`, `:tfirst`, `:tlast` to move between matching tags. 72 | 73 | Note that exuberant Ctags supports 33 programming languages as of this writing, and it can easily be extended for other languages. 74 | 75 | See `:help taglist-intro` for details. 76 | 77 | ### cscope 78 | To be able to jump to definitions across files, we need a program like `cscope`. However, as the name suggests, this particular program works only for the C programming language. 79 | 1. Install cscope. Refer `:help cscope-info` and `:help cscope-win32` regarding installation. 80 | 2. Copy [cscope_maps.vim](http:/\/cscope.sourceforge.net/cscope_maps.vim) to your `~/.vim/plugin/` directory. 81 | 3. Switch to your source code directory and run `cscope -R -b` to 'b'uild the database 'r'ecursively for all subdirectories. 82 | 4. Restart Vim and open a source code file. 83 | 5. Run `:cscope show` to confirm that there is a cscope connection created. 84 | ![cscope in action](cscope_in_action.png) 85 | 6. Run `:cscope find symbol foo` to locate the symbol `foo`. You can shorten this command to `:cs f s foo`. 86 | 87 | You can also: 88 | * Find this definition - `:cs f g` 89 | * Find functions called by this function - `:cs f d` 90 | * Find functions calling this function - `:cs f c` 91 | * Find this text string - `:cs f t` 92 | * Find this egrep pattern - `:cs f e` 93 | 94 | See `:help cscope-suggestions` for suggested usage of cscope with Vim. 95 | 96 | Also, the [Source Code Obedience](http://www.vim.org/scripts/script.php?script_id=1638) plugin is worth checking out as it provides easy shortcut keys on top of cscope/ctags. 97 | 98 | While we are on the subject of C programming language, the [c.vim](http://vim.sourceforge.net/scripts/script.php?script_id=213) plugin can be quite handy. 99 | 100 | ## Compiling 101 | We have already seen in the previous chapter regarding `:make` for the programs we are writing, so we won't repeat it here. 102 | 103 | ## Easy writing 104 | 105 | ## Omnicompletion 106 | One of the most-requested features which was added in Vim 7 is "omnicompletion" where the text can be auto-completed based on the current context. For example, if you are using a long variable name and you are using the name repeatedly, you can use a keyboard shortcut to ask Vim to auto-complete and it'll figure out the rest. 107 | 108 | Vim accomplishes this via ftplugins, specifically the ones by the name `ftplugin/complete.vim` such as `pythoncomplete.vim`. 109 | 110 | Let's start the example with a simple Python program: 111 | ``` 112 | def hello(): 113 | print 'hello world' 114 | 115 | def helpme(): 116 | print 'help yourself' 117 | ``` 118 | After typing this program, start a new line in the same file, type 'he' and press `ctrl-x ctrl-o` which will show you suggestions for the autocompletion. 119 | 120 | If you get an error like `E764: Option 'omnifunc' is not set`, then run `:runtime! autoload/pythoncomplete.vim` to load the omnicompletion plugin. 121 | 122 | To avoid doing this every time, you can add the following line to your `~/.vimrc:` 123 | 124 | ![Omni-completion in action](omni_completion_in_action.png) 125 | 126 | `autocmd FileType python runtime! autoload/pythoncomplete.vim` 127 | 128 | Vim automatically uses the first suggestion, you can change to the next or previous selection using `ctrl-n` and `ctrl-p` respectively. 129 | 130 | In case you want to abort using the omnicompletion, simply press `esc`. 131 | 132 | Refer `:help new-omni-completion` for details on what languages are supported (C, HTML, JavaScript, PHP, Python, Ruby, SQL, XML, ...) as well as how to create your own omnicompletion scripts. 133 | 134 | ### Note 135 | 136 | If you are more comfortable in using the arrow keys to select your choice from the omnicompletion list, see [Vim Tip 1228](http://www.vim.org/tips/tip.php?tip_id=1228) on how to enable that. 137 | 138 | I prefer to use a simple `ctrl-space` instead of the unwieldy `ctrl-x ctrl-o` key combination. To achieve this, put this in your `vimrc`: 139 | 140 | ``` 141 | imap 142 | ``` 143 | Relatedly, [the PySmell plugin](http://code.google.com/p/pysmell/) may be of help to Vim users who code in Python. 144 | 145 | ## Using Snippets 146 | Code snippets are small pieces of code that you repetitively tend to write. Like all good lazy programmers, you can use a plugin that helps you to do that. In our case, we use the amazing `SnippetsEmu` plugin. 147 | 1. Download the [snippetsEmu](http://www.vim.org/scripts/script.php?script_id=1318) plugin. 148 | 2. Create your `~/.vim/after/` directory if it doesn't already exist. 149 | 3. Start Vim by providing this plugin name on the command line. For example, start Vim as `gvim snippy_bundles.vba` 150 | 4. Run `:source %`. The 'vimball' will now unpack and store the many files in the appropriate directories. 151 | 5. Repeat the same process for `snippy_plugin.vba` 152 | 153 | Now, let's try using this plugin. 154 | 1. Open a new file called, say, `test.py`. 155 | 2. Press the keys `d`, `e`, `f` and then ``. 156 | 3. Voila! See, how `snippetsEmu` has created a structure of your function already. You should now see this in your file: 157 | 158 | ``` 159 | def <{fname}>(<{args}>): 160 | """ 161 | <{}> 162 | <{args}>""" 163 | <{pass}> 164 | <{}> 165 | ``` 166 | ### Note 167 | In case you see `def` and nothing else happened, then perhaps the snippets plugin is not loaded. Run `:runtime! ftplugin/python_snippets.vim` and see if that helps. 168 | 4. Your cursor is now positioned on the function name i.e. `fname`. 169 | 5. Type the function name, say, `test`. 170 | 6. Press `` and the cursor is automatically moved to the arguments. Tab again to move to the next item to be filled. 171 | 7. Now enter a comment: `Just say Hi` 172 | 8. Tab again and type `print 'Hello World'` 173 | 9. Press `` 174 | 10. Your program is complete! 175 | 176 | You should now see: 177 | ``` 178 | def test(): 179 | """ 180 | Just say Hi 181 | """ 182 | print 'Hello World' 183 | ``` 184 | The best part is that SnippetsEmu enables a standard convention to be followed and that nobody in the team 'forgets' it. 185 | 186 | ## Creating Snippets 187 | Let's now see how to create our own snippets. 188 | 189 | Let us consider the case where I tend to repeatedly write the following kind of code in ActionScript3: 190 | 191 | ``` 192 | private var _foo:Object; 193 | public function get foo():Object 194 | { 195 | return _foo; 196 | } 197 | public function set foo(value:Object) 198 | { 199 | _foo = value; 200 | } 201 | ``` 202 | 203 | This is a simple getter/setter combination using a backing variable. The problem is that's an awful lot of boilerplate code to write repeatedly. Let's see how to automate this. 204 | 205 | The SnippetsEmu language snippets plugins assume st `as` the start tag and `et` as the end tag. These are the same arrow-type symbols you see in-between which we enter our code. 206 | 207 | Let's start with a simple example. 208 | 209 | ``` 210 | exec "Snippet pubfun public function 211 | ".st.et.":".st.et."{".st.et."}" 212 | ``` 213 | Add the above line to your `~/.vim/after/ftplugin/actionscript_snippets.vim`. 214 | 215 | Now open a new file, say, `test.as` and then type pubfun and press `` and see it expanded to: 216 | 217 | ``` 218 | public function <{}>:<{}> 219 | { 220 | 221 | } 222 | 223 | ``` 224 | The cursor will be positioned for the function name, `tab` to enter the return type of the function, `tab` again to type the body of the function. 225 | 226 | Going back to our original problem, here's what I came up with: 227 | 228 | ``` 229 | exec "Snippet getset private var _".st."name".et.";public 230 | function get ".st."name".et."():".st."type".et."{return 231 | _".st."name".et.";}public function set 232 | ".st."name".et."(value:".st."type".et."){_".st."name".et." 233 | = value;}" 234 | ``` 235 | ### Note 236 | All snippets for this plugin must be entered on a single line. It is a technical limitation. 237 | 238 | Follow the same procedure above to use this new snippet: 239 | 240 | 1. Add this line to your `~/.vim/after/ftplugin/actionscript_snippets.vim`. 241 | 2. Open a new file such as `test.as`. 242 | 3. Type `getset` and press `` and you will see this: 243 | 244 | ``` 245 | private var _<{name}>; 246 | 247 | public function get <{name}>():<{type}> 248 | { 249 | return _<{name}>; 250 | } 251 | 252 | public function set <{name}>(value:<{type}>) 253 | { 254 | _<{name}> = value; 255 | } 256 | ``` 257 | 4. Type `color` and press ``. Notice that the variable name `color` is replaced everywhere. 258 | 5. Type `Number` and press ``. The code now looks like this: 259 | 260 | ``` 261 | private var _color; 262 | 263 | public function get color():Number 264 | { 265 | return _color; 266 | } 267 | 268 | public function set color(value:Number) 269 | { 270 | _color = value; 271 | } 272 | ``` 273 | Notice how many keystrokes we have eliminated! We have done away with typing approximately 11 lines of repetitive code with a single Vim script line. 274 | 275 | We can keep adding such snippets to make coding lazier and to help us concentrate on the real work in the software. 276 | 277 | See `:help snippets_emu.txt` for more details (this help file will be available only after you install the plugin). 278 | 279 | ## IDE 280 | Vim can be actually used as an IDE with the help of a few plugins. 281 | 282 | ### Project plugin 283 | The Project plugin is used to create a Project-manager kind of usage to Vim. 284 | 285 | 1. Download the [project](http://www.vim.org/scripts/script.php?script_id=69) plugin. 286 | 2. Unarchive it to your `~/.vim/` directory. 287 | 3. Run `:helptags ~/.vim/doc/`. 288 | 4. Download Vim source code from [http://www.vim.org/subversion.php](http://www.vim.org/subversion.php) 289 | 5. Run `:Project`. A sidebar will open up in the left which will act as your 'project window'. 290 | 6. Run `\\c` (backslash followed by 'c') 291 | 7. Give answers for the following options: 292 | * Name of entry, say `'vim7_src'` 293 | * Directory, say `C:\\repo\\vim7\\src\\` 294 | * CD option, same as directory above 295 | * Filter option, say `*.h *.c` 296 | 8. You will see the sidebar filled up with the list of files that match the filter in the specified directory. 297 | 9. Use the arrow keys or `j/k` keys to move up and down the list of files, and press the enter key to open the file in the main window. 298 | 299 | This gives you the familiar IDE-kind of interface, the good thing is that there are no fancy configuration files or crufty path setups in IDEs which usually have issues always. The Project plugin's functionality is simple and straightforward. 300 | 301 | You can use the standard fold commands to open and close the projects and their details. 302 | 303 | You can also run scripts at the start and end of using a project, this helps you to setup the PATH or set compiler options and so on. 304 | 305 | See `:help project.txt` for more details. 306 | 307 | ## Running code from the text 308 | You can run code directly from Vim using plugins such as [EvalSelection.vim](http://www.vim.org/scripts/script.php?script_id=889) or simpler plugins like [inc-python.vim](http://www.vim.org/scripts/script.php?script_id=1941). 309 | 310 | ## SCM integration 311 | If you start editing a file, you can even make it automatically checked out from Perforce using the [perforce plugin](http://www.vim.org/scripts/script.php?script_id=240). Similarly, there is a [CVS/SVN/SVK/Git integration plugin](http://www.vim.org/scripts/script.php?script_id=90). 312 | 313 | ## More 314 | To explore more plugins to implement IDE-like behavior in Vim, see: 315 | * Vim Tip: [Using vim as an IDE all in one](http://vim.wikia.com/wiki/Using_vim_as_an_IDE_all_in_one) 316 | * [C++/Python Vim+IDE plugins list](http://phraktured.net/vimmity-vim-vim.html) 317 | 318 | There are more language-specific plugins that can help you do nifty things. For example, for Python, the following plugins can be helpful: 319 | * [SuperTab](http://www.vim.org/scripts/script.php?script_id=1643) allows you to call omni-completion by just pressing tab and then use arrow keys to choose the option. 320 | * [python_calltips](http://www.vim.org/scripts/script.php?script_id=1074) shows a window at the bottom which gives you the list of possibilities for completion. The cool thing about this, compared to omni-completion, is that you get to view the documentation for each of the possibilities. 321 | * [VimPdb](http://www.vim.org/scripts/script.php?script_id=2043) helps you to debug Python programs from within Vim. 322 | 323 | ## Writing your own plugins 324 | You can write your own plugins to extend Vim in any way that you want. For example, here's a task that you can take on: 325 | 326 | Write a Vim plugin that takes the current word and opens a browser with the documentation for that particular word (the word can be a function name or a class name, etc.). 327 | 328 | If you really can't think of how to approach this, take a look at "Online documentation for word under cursor" tip at the [Vim Tips wiki](http://vim.wikia.com/wiki/Online_documentation_for_word_under_cursor). 329 | 330 | I have extended the same tip and made it more generic: 331 | 332 | ``` 333 | " Add the following lines to your ~/.vimrc to enable online documentation 334 | " Inspiration: http://vim.wikia.com/wiki/Online_documentation_for_word_under_cursor 335 | function Browser() 336 | if has("win32") || has("win64") 337 | let s:browser = "C:\\Program Files\\Mozilla Firefox\\firefox.exe -new-tab" 338 | elseif has("win32unix") " Cygwin 339 | let s:browser = "'/cygdrive/c/Program\ Files/Mozilla\ Firefox/firefox.exe' -new-tab" 340 | elseif has("mac") || has("macunix") || has("unix") 341 | let s:browser = "firefox -new-tab" 342 | endif 343 | 344 | return s:browser 345 | endfunction 346 | 347 | function Run(command) 348 | if has("win32") || has("win64") 349 | let s:startCommand = "!start" 350 | let s:endCommand = "" 351 | elseif has("mac") || has("macunix") " TODO Untested on Mac 352 | let s:startCommand = "!open -a" 353 | let s:endCommand = "" 354 | elseif has("unix") || has("win32unix") 355 | let s:startCommand = "!" let s:endCommand = "&" 356 | else 357 | echo "Don't know how to handle this OS!" 358 | finish 359 | endif 360 | 361 | let s:cmd = "silent " . s:startCommand . " " . a:command . " " . s:endCommand 362 | " echo s:cmd 363 | execute s:cmd 364 | endfunction 365 | 366 | function OnlineDoc() 367 | if &filetype == "viki" 368 | " Dictionary 369 | let s:urlTemplate = "http://dictionary.reference.com/browse/" 370 | elseif &filetype == "perl" 371 | let s:urlTemplate = "http://perldoc.perl.org/functions/.html" 372 | elseif &filetype == "python" 373 | let s:urlTemplate = "http://www.google.com/search?q=&domains=docs.python.org&sitesearch=docs.python.org 374 | elseif &filetype == "ruby" 375 | let s:urlTemplate = "http://www.ruby-doc.org/core/classes/.html" 376 | elseif &filetype == "vim" 377 | let s:urlTemplate = "http://vimdoc.sourceforge.net/search.php?search=&docs=help" 378 | endif 379 | 380 | let s:wordUnderCursor = expand("") 381 | let s:url = substitute(s:urlTemplate, '', s:wordUnderCursor, 'g') 382 | 383 | call Run(Browser() . " " . s:url) 384 | endfunction 385 | 386 | noremap :call OnlineDoc() 387 | inoremap :call OnlineDoc()a 388 | ``` 389 | ## Access Databases 390 | You can even talk to some 10 different databases from Oracle to MySQL to PostgreSQL to Sybase to SQLite, all from Vim, using the [dbext.vim plugin](http://www.vim.org/scripts/script.php?script_id=356). The best part is that this plugin helps you to edit SQL written within PHP, Perl, Java, etc. and you can even directly execute the SQL even though it is embedded within another programming language and even asking you for values for variables. 391 | 392 | ## Summary 393 | We have learned how Vim can be used for programming with the help of various plugins and settings. If we need a feature, it can be solved by writing our own Vim plugins (as we have discussed in the Scripting chapter). 394 | 395 | A good source of related discussions is at [Stack Overflow](http://stackoverflow.com/questions/tagged/vim) and [Peteris Krumins's blog](http://www.catonmat.net/tag/vim). 396 | -------------------------------------------------------------------------------- /scripting.md: -------------------------------------------------------------------------------- 1 | # Scripting 2 | 3 | If you want to customize any software, most likely you will change the various settings in the software to suit your taste and needs. What if you wanted to do more than that? For example, to check for conditions such as `if GUI version, then use this colorscheme else use this colorscheme`? This is where "scripting" comes in. Scripting basically means using a language where you can specify conditions and actions put together into 'scripts'. 4 | 5 | There are two approaches to scripting in Vim - using the built-in Vim scripting language, or using a full-fledged programming language such as Python or Perl which have access to the Vim internals via modules (provided that Vim has been compiled with these options enabled). 6 | 7 | This chapter requires some knowledge of programming. If you have no prior programming experience, you will still be able to understand although it might seem terse. If you wish to learn programming, please refer my other free book [A Byte of Python]({{ book.pythonBookUrl }}). 8 | 9 | There are two ways of creating reusable functionality in Vim - using macros and writing scripts. 10 | 11 | ## Macros 12 | 13 | Using macros, we can record sequences of commands and then replay it in different contexts. 14 | 15 | For example, suppose you had some text like this: 16 | 17 | ``` 18 | tansen is the singer 19 | daswant is the painter 20 | todarmal is the financial wizard 21 | abul fazl is the historian 22 | birbal is the wazir 23 | ``` 24 | 25 | There are many things to correct here: 26 | 27 | 1. Change the first letter of the sentence to upper case. 28 | 2. Change 'is' to 'was'. 29 | 3. Change 'the' to 'a'. 30 | 4. End the sentence with "in Akbar's court." 31 | 32 | One way would be to use a series of substitute commands, such as `:s/^\\w/\\u\\0/` but this would require 4 substitution commands and it might not be simple if the substitute command changes parts of the text which we do not want to be changed. 33 | 34 | A better way would be to use macros. 35 | 36 | 1. Position your cursor on the first letter of the first line: `tansen is the singer` 37 | 2. Type `qa` in normal mode to start recording the macro named as `a`. 38 | 3. Type `gUl` to switch the first letter to upper case. 39 | 4. Type `w` to move to the next word. 40 | 5. Type `cw` to change the word. 41 | 6. Type `was`. 42 | 7. Press ``. 43 | 8. Type `w` to move to the next word. 44 | 9. Type `cw` to change the word. 45 | 10. Type `a`. 46 | 11. Press ``. 47 | 12. Type `A` to insert text at the end of the line. 48 | 13. Type `in Akbar's court`. 49 | 14. Press ``. 50 | 15. Type `q` to stop recording the macro. 51 | 52 | That looks like a long procedure, but sometimes, this is much easier to do than cook up some complicated substitute commands! 53 | 54 | At the end of the procedure, the line should look like this: 55 | 56 | ``` 57 | Tansen was a singer in Akbar's court. 58 | ``` 59 | 60 | Great. Now, let's move on to apply this to the other lines. Just move to the first character of the second line and press `@a`. Voila, the line should change to: 61 | 62 | ``` 63 | Daswant was a painter in Akbar's court. 64 | ``` 65 | 66 | This demonstrates that macros can record complicated operations and can be easily replayed. This helps the user to replay complicated editing in multiple places. This is one type of reusing the manipulations you can do to the text. Next, we will see more formal ways of manipulating the text. 67 | 68 | > NOTE: If you want to simply repeat the last action and not a sequence of actions, you do not have to use macros, just press `.` (dot). 69 | 70 | ## Basics of Scripting 71 | 72 | Vim has a built-in scripting language using which you can write your own scripts to take decisions, "do" stuff, and manipulate the text. 73 | 74 | ### Actions 75 | 76 | How do you change the theme i.e. colors used by Vim? Just run: 77 | 78 | ``` viml 79 | :colorscheme desert 80 | ``` 81 | 82 | Here, I am using the 'desert' color scheme, which happens to be my favorite. You can view the other schemes available by typing `:colorscheme` and then pressing `` key to cycle through the available schemes. 83 | 84 | What if you wanted to know how many characters are in the current line? 85 | 86 | ``` viml 87 | :echo strlen(getline(".")) 88 | ``` 89 | 90 | Notice the names 'strlen' and 'getline'. These are "functions". *Functions* are pieces of scripts already written and have been given a name so that we can use them again and again. For example, the getline function fetches a line and we are indicating which line by the `.` (dot) which means the current line. We are passing the result returned by the `getline` function to the strlen function which counts the number of characters in the text and then we are passing the result returned by the `strlen` function to the `:echo` command which simply displays the result. Notice how the information flows in this command. 91 | 92 | The `strlen(getline("."))` is called an expression. We can store the results of such expressions by using variables. Variables do what the name suggests - they are names pointing to values and the value can be anything i.e. it can vary. For example, we can store the length as: 93 | 94 | ``` viml 95 | :let len = strlen(getline(".")) 96 | :echo "We have" len "characters in this line." 97 | ``` 98 | 99 | When you run this line on the second line above in this text, you will get the following output: 100 | 101 | ``` viml 102 | We have 46 characters in this line. 103 | ``` 104 | 105 | Notice how we can use variables in other 'expressions'. The possibilities of you can achieve with the help of these variables, expressions and commands are endless. 106 | 107 | Vim has many types of variables available via prefixes such as `$` for environment variables, `&` for options, and `@` for registers: 108 | 109 | ``` viml 110 | :echo $HOME 111 | :echo &filetype 112 | :echo @a 113 | ``` 114 | 115 | See `:help function-list` for a huge list of functions available. 116 | 117 | You can create your own functions as well: 118 | 119 | ``` viml 120 | :function CurrentLineLength() 121 | : let len = strlen(getline(".")) 122 | : return len 123 | :endfunction 124 | ``` 125 | 126 | Now position your cursor on any line and run the following command: 127 | 128 | ``` viml 129 | :echo CurrentLineLength() 130 | ``` 131 | 132 | You should see a number printed. 133 | 134 | Function names have to start with an upper case. This is to differentiate that built-in functions start with a lower case and user-defined functions start with an upper case. 135 | 136 | f you want to simply "call" a function to run but not display the contents, you can use `:call CurrentLineLength()` 137 | 138 | ## Decisions 139 | 140 | Suppose you want to display a different color schemes based on whether Vim is running in the terminal or is running as a GUI i.e. you need the script to take decisions. Then, you can use: 141 | 142 | ``` viml 143 | :if has("gui_running") 144 | : colorscheme desert 145 | :else 146 | : colorscheme darkblue 147 | :endif 148 | ``` 149 | 150 | How It Works: 151 | 152 | - `has()` is a function which is used to determine if a specified feature is supported in Vim installed on the current computer. See `:help feature-list` to see what kind of features are available in Vim. 153 | - The `if` statement checks the given condition. If the condition is satisfied, we take certain actions. "Else", we take the alternative action. 154 | - Note that an `if` statement should have a matching `endif`. 155 | - There is `elseif` also available, if you want to chain together multiple conditions and actions. 156 | 157 | The looping statements 'for' and 'while' are also available in Vim: 158 | 159 | ``` viml 160 | :let i = 0 161 | :while i < 5 162 | : echo i 163 | : let i += 1 164 | :endwhile 165 | ``` 166 | 167 | Output: 168 | 169 | ``` 170 | 0 171 | 1 172 | 2 173 | 3 174 | 4 175 | ``` 176 | 177 | Using Vim's built-in functions, the same can also be written as: 178 | 179 | ``` viml 180 | :for i in range(5) 181 | : echo i 182 | :endfor 183 | ``` 184 | 185 | - `range()` is a built-in function used to generate a range of numbers. See `:help range()` for details. 186 | - The `continue` and `break` statements are also available. 187 | 188 | ## Data Structures 189 | 190 | Vim scripting also has support for lists and dictionaries. Using these, you can build up complicated data structures and programs. 191 | 192 | ``` viml 193 | :let fruits = ['apple', 'mango', 'coconut'] 194 | 195 | :echo fruits[0] 196 | " apple 197 | 198 | :echo len(fruits) 199 | " 3 200 | 201 | :call remove(fruits, 0) 202 | :echo fruits 203 | " ['mango', 'coconut'] 204 | 205 | :call sort(fruits) 206 | :echo fruits 207 | " ['coconut', 'mango'] 208 | 209 | :for fruit in fruits 210 | : echo "I like" fruit 211 | :endfor 212 | " I like coconut 213 | " I like mango 214 | ``` 215 | 216 | There are many functions available - see 'List manipulation' and 'Dictionary manipulation' sections in `:help function-list`. 217 | 218 | ## Writing a Vim script 219 | 220 | We will now write a Vim script that can be loaded into Vim and then we can call its functionality whenever required. This is different from writing the script inline and running immediately as we have done all along. 221 | 222 | Let us tackle a simple problem - how about capitalizing the first letter of each word in a selected range of lines? The use case is simple - When I write headings in a text document, they look better if they are capitalized, but I'm too lazy to do it myself. So, I can write the text in lower case, and then simply call the function to capitalize. 223 | 224 | We will start with the basic template script. Save the following script as the file capitalize.vim: 225 | 226 | ``` viml 227 | " Vim global plugin for capitalizing first letter of each word 228 | " in the current line. 229 | " Last Change: 2008-11-21 Fri 08:23 AM IST 230 | " Maintainer: www.swaroopch.com/contact/ 231 | " License: www.opensource.org/licenses/bsd-license.php 232 | 233 | if exists("loaded_capitalize") 234 | finish 235 | endif 236 | let loaded_capitalize = 1 237 | 238 | " TODO : The real functionality goes in here. 239 | ``` 240 | 241 | How It Works: 242 | 243 | - The first line of the file should be a comment explaining what the file is about. 244 | - There are 2-3 standard headers mentioned regarding the file such as 'Last Changed:' which explains how old the script is, the 'Maintainer:' info so that users of the script can contact the maintainer of the script regarding any problems or maybe even a note of thanks. 245 | - The 'License:' header is optional, but highly recommended. A Vim script or plugin that you write may be useful for many other people as well, so you can specify a license for the script. Consequently, other people can improve your work and that it will in turn benefit you as well. 246 | - A script may be loaded multiple times. For example, if you open two different files in the same Vim instance and both of them are `.html` files, then Vim opens the HTML syntax highlighting script for both of the files. To avoid running the same script twice and redefining things twice, we use a safeguard by checking for existence of the name 'loaded_capitalize' and closing if the script has been already loaded. 247 | 248 | Now, let us proceed to write the actual functionality. 249 | 250 | We can define a function to perform the transformation - capitalize the first letter of each word, so we can call the function as `Capitalize()`. Since the function is going to work on a range, we can specify that the function works on a range of lines. 251 | 252 | ``` viml 253 | " Vim global plugin for capitalizing first letter of each word 254 | " in the current line 255 | " Last Change: 2008-11-21 Fri 08:23 AM IST 256 | " Maintainer: www.swaroopch.com/contact/ 257 | " License: www.opensource.org/licenses/bsd-license.php 258 | 259 | " Make sure we run only once 260 | if exists("loaded_capitalize") finish 261 | endif 262 | let loaded_capitalize = 1 263 | 264 | " Capitalize the first letter of each word 265 | function Capitalize() range 266 | for line_number in range(a:firstline, a:lastline) 267 | let line_content = getline(line_number) 268 | " Luckily, the Vim manual had the solution already! 269 | " Refer ":help s%" and see 'Examples' section 270 | let line_content = substitute(line_content, "\\w\\+", "\\u\\0", "g") 271 | call setline(line_number, line_content) 272 | endfor 273 | endfunction 274 | ``` 275 | 276 | How It Works: 277 | 278 | - The `a:firstline` and `a:lastline` represent the arguments to the function with correspond to the start and end of the range of lines respectively. 279 | - We use a 'for' loop to process each line (fetched using `getline()`) in the range. 280 | - We use the `substitute()` function to perform a regular expression search-and-replace on the string. Here we are specifying the function to look for words which is indicated by `\\w\\+` which means a word (i.e. a continuous set of characters that are part of words). Once such words are found, they are to be converted using `\\u\\0` - the `\\u` indicates that the first character following this sequence should be converted to upper case. The `\\0` indicates the match found by the `substitute()` function which corresponds to the words. In effect, we are converting the first letter of each word to upper case. 281 | - We call the `setline()` function to replace the line in Vim with the modified string. 282 | 283 | To run this command: 284 | 285 | 1. Open Vim and enter some random text such as 'this is a test'. 286 | 2. Run `:source capitalize.vim` - this 'sources' the file as if the commands were run in Vim inline as we have done before. 287 | 3. Run `:call Capitalize()`. 288 | 4. The line should now read 'This Is A Test'. 289 | 290 | Running `:call Capitalize()` every time appears to be tedious, so we can assign a keyboard shortcut using leaders: 291 | 292 | ``` viml 293 | " Vim global plugin for capitalizing first letter of each word 294 | " in the current line 295 | " Last Change: 2008-11-21 Fri 08:23 AM IST 296 | " Maintainer: www.swaroopch.com/contact/ 297 | " License: www.opensource.org/licenses/bsd-license.php 298 | 299 | " Make sure we run only once 300 | if exists("loaded_capitalize") 301 | finish 302 | endif 303 | let loaded_capitalize = 1 304 | 305 | " Refer ':help using-' 306 | if !hasmapto('Capitalize') 307 | map c Capitalize 308 | endif 309 | noremap