13 ms·
Vim anti-patterns
- bsmith 15y agoI just started learning vim. It would be great if someone made a game for learning that taught some simple commands—something along the lines of, "Perform the needed operation(s) in the fewest number of keystrokes possible." For instance, add an attribute to an html tag with your cursor at a certain starting point on the line. Then have a leaderboard of the shortest key-combos used, with comments. I'll bet more experienced vimers could learn something from this, too.
- chmielewski 15y agoIt's called VIM Golf. http://www.vimgolf.com http://www.vimgolf.com You might also be interested in http://stackoverflow.com/questions/2588481/are-there-any-kata-for-practice-vim http://stackoverflow.com/questions/2588481/are-there-any-kat...
- bsmith 15y agoThanks! That's definitely getting there. It would be even better if I could do it in the browser, with simpler challenges to start out. Maybe a few intro tutorials or the like.
- Wilduck 15y agoHere's my advice. Instead of trying to learn all of these tips at once, bookmark the page (or leave it open), and try to use one of the tips at a time for at least a week. If you focus on one at a time, you'll get a much better feel for when the command is actually saving you time/thought. Also, they'll stick more permanently in memory/muscle memory.
- johncoltrane 15y agoDon't try to learn everything at once. $ vimtutor is great. Do it a few times until you don't need to read it. It's not really game-y but it's quite challenging when you come from TextMate world. Also there is a site called http://openvim.com http://openvim.com that works more or less like what you describe. I hate it, though. I can't bear the tone and the forced jokes and it's nowhere near as well thought out as $vimtutor. Others have pointed at vimgolf. One of the cool things about Vim is that you always learn new tricks.
- gnosis 15y agoAnother great way to learn new vim tricks is to simply hang out on #vim on freenode. I've learned a lot that way, and still do every day.
- xxdiamondxx 15y agoIt's amazing how many articles like this there are, and how I always seem to learn something new.
- oacgnol 15y agoHere's a good tip I picked up recently when working with numbers: Increment a number on or after the cursor with Ctrl-A and decrement with Ctrl-X in normal mode. Saves a few keystrokes over having to replace or enter insert mode.
- tyrmored 15y agoYou can prepend a count to that too, to increment/decrement by a fixed amount. This gets scary useful when you use tpope's speeddating plugin.
- ilikepi 15y agoI've been using those more and more recently and have noticed a couple interesting things to be aware of. First, Vim interprets a dash character immediately preceding the number as a negative sign. (In playing around a bit I suspect this behavior is slightly influenced by the syntax rules for the particular filetype you're working with.) The effect of this is to flip the behavior of CTRL-A and CTRL-X. Secondly, if the first digit of the number is '0', Vim will behave as if the number is octal, so incrementing "07" once will result in "010". Similarly, a prefix of "0x" or "0X" will cause a number to be treated as hex.
- johncoltrane 15y agoTo avoid the "07" -> "010" problem you can add set nrformats-=octal to your .vimrc.
- Nick_C 15y agoJust be aware if you are in a screen session, ctrl-a ctrl-x chord will lock the screen. It bit me only an hour ago.
- fferen 15y agoL, M, and H are also very useful for vertical movement. My general procedure for navigating (when I don't have anything particular to find), from general to specific, is: Ctrl-f/Ctrl-b, L/M/H, j/k).
- babarock 15y agoOf all the "Vim tricks" article I came across, this one is my favorite so far. I have been a vim power user for a little over 2 years now. I never bothered installing plugins and spent all my time instead learning ... the exact same commands described in the article. Now I type fast, I mean real fast. A couple more tips I find useful: - 'gg' and 'G' in command mode will send you to the beginning and the ending of the file. - 'Ctrl-N' and 'Ctrl-P' in insert mode will auto-complete (suggestions only come from existing words in opened buffers, for more you'd probably need plugins). All the other tips are _spot on_! I especially like the first one about moving vertically one line at a time. It takes some time getting used to, but the fact that you can repeat the 'jump' or jump back to your previous position. Believe me, you'll fly :) My new set of advice for blazing fast typing: 1. Learn to touch type. The rest is meaningless without this. 2. Repeat 'vimtutor' religiously for 10-15 days. 3. Read this post and apply every tip until it's hard-written in your fingers' muscle memory. 4. ... voila!
- nimrody 15y agoIn case you missed it, this one will teach you much more than just a few commands... It's all about combining commands or producing 'sentences' as the author calls it: http://yanpritzker.com/2011/12/16/learn-to-speak-vim-verbs-nouns-and-modifiers/ http://yanpritzker.com/2011/12/16/learn-to-speak-vim-verbs-n...
- graywh 15y agoDiscussion on HN: https://news.ycombinator.com/item?id=3361993 https://news.ycombinator.com/item?id=3361993
- graywh 15y agoThere's an option to configure how keyword completion works when ctrl-p or ctrl-n is used: 'complete'. Vim can scan the current buffer, other windows, other buffers, dictionaries, spell checking, thesaurus, included files, tags.
- dwc 15y ago> I never bothered installing plugins and spent all my time instead learning This wisdom should be shared with everyone learning vi/vim, since this leads directly to the largest payoff.
- nfm 15y agozt, zz and zb are great too. They redraw the screen so that the line the cursor is currently on becomes the top, middle, or bottom line of the window.
- Jach 15y agoOther "z" commands (these are the ones I always get mixed up): :setlocal spell spelllang=en_us - turn on spell check z= - bring up list of suggestions zg - add word to dict zug - undo add to word zw - mark as wrong zuw - undo wrong :help fold zf<motion> - create fold (common motions '%', 'a{', 'a(' ) zo - open fold zA - open folds recursively zc - close fold zd - forget fold zj - move to next fold zk - move to prev fold (up)
- re_todd 15y agoYeah, I like the fold commands, which I barley discovered a few weeks ago. I typically do "set foldmethod=indent" then pres "zr" multiple times until I'm at the fold level I want. Then I can just do "zo" on the parts of code I'm interested in.
- jamesrcole 15y agothere's also zR - Open all folds zM - Close all folds zO - Open all folds under the cursor recursively zC - Close all folds under the cursor recursively zX - Undo manually opened and closed folds: re-apply 'foldlevel'.
- Nick_C 15y agoSome simple mnemonics might help you out. zg g = Good word, add to personal dict zug Undo Good word. zw obviously, Wrong word. ... zo Open zA open All zc Close zj uses the same movement as the j key zk ditto Once you have the mnemonics sorted, sometimes you find you can remember the others because they are the ones "left out" of those with mnemonics, like zd doesn't have a mnemonic, so the command left over is "forget fold", so zd is that one. After a while, muscle memory takes over.
- malingo 15y ago
- Davertron 15y agoOne other major feature I would mention: text-objects text-objects are basically things Vim knows about that you can operate on with the "verbs" of vim (d/c/y etc). So, for example, if you're inside quotes, you can yank everything inside the quotes with yi" (to include the quotes, you use ya"), regardless of where the cursor is inside the quotes. For more information see :h text-objects
- erikcw 15y agoAnd to complement them, the surround.vim plugin: http://www.vim.org/scripts/script.php?script_id=1697 http://www.vim.org/scripts/script.php?script_id=1697
- francoisdevlin 15y agoOkay, here's one that I've been stuck with. What does Ctrl-Z do in vim, and how do I "undo" it? I always have to kill -9 the vim process, and it sucks cleaning up where I was.
- blackRust 15y agoNormally Ctrl-Z will pause a process and it will be kept as a background job. Type 'jobs' in your prompt to see running jobs. If there is only one a '%' will bring to foreground the last job, otherwise you can do 'fg x' where 'x' is the job number.
- lparry 15y agoIt backgrounds the running process. Type 'fg' to bring it back to the foreground. This isn't actually a vim thing, it's a shell thing
- mvanveen 15y agotl;dr: type `fg`. One nice thing about this setup is you can "stack" processes in the shell. Say you're working on file_x, but file_x depends on header_file_y and file_z. file_x makes sense on its own, so you don't want to split a new pane; you just want to leave your workspace as it is and come back to it later. Hit ctrl-z, and fire up vim with the new stuff you want. When you're done, quit the current vim session and come back to your old context with `fg`. The key observation is this stacks inductively, so you cant tumble down the dependency rabbit hole and always come back to the context you were at originally. This feature alone has made it impossible to ever leave console vi. It really came in handy in my Operating Systems class where I could fly around the codebase an order or magnitude faster than everyone else. If you really need to go back to a particular context %[num] lets you go back to the nth suspended process, but this will corrupt your stack of processes, so `fg` won't be in a clean order.
- shabble 15y agoand if you've gone so far down the hole you're completely lost, 'jobs' is a useful way (in most shells, I think?) to figure out where you are.
- oinksoft 15y agoThe Escape key on modern keyboards is a lot further from home row than it was on Bill Joy’s keyboard back when he designed vi. Hitting Escape is usually unnecessary; Ctrl+[ is a lot closer, and more comfortable. That's not an "anti-pattern," that's an opinion. I think C-[ is uncomfortable as hell.
- blahedo 15y agoIt's probably more comfortable than reaching an unremapped modern PC Escape key, though. And if you do light remapping, making Caps a Control instead (as in the Mac's Keyboard control panel) makes ^[ even easier. If you're really down with keyboard remapping, though, go for putting the Escape key somewhere closer. I learned a Sun keyboard in grad school, which put Esc where PCs have backquote/tilde, and I've remapped every keyboard I use regularly to this arrangement. (I also swap backslash and backspace for roughly the same reason.)
- Dobbs 15y agoI have caps setup as a third ctrl key. So at least for me Ctrl-[ is super easy to hit, as is every other ctrl based modifier. I greatly prefer this setup. I never used Caps before and now I have a useful key in a useful position.
- icebraining 15y agoIt depends on the keyboard layout, though. To write [ I need to type Right Alt + 8.
- tomn 15y agoThese kind of articles always have a few new things in them, even of most of it is familiar -- I guess everyone just has a slightly slightly different set of indispensable tricks. The most most useful Vim trick I've seen recently is "set relativenumber". This makes Vim show line numbers relative to the current line. This is awesome, because it lets you easily jump to any line you can see. eg. you can get to a line marked "9" above the cursor by pressing "9k". It can be slightly tricky to get used to if you're used to absolute numbers (have to use gg more), but for me it's worth it.
- telemachos 15y agoI've tried relative numbers a few times in Vim, but always found it hard to adjust. But recently Jeff Kreeftmeijer wrote up a way to get the best of both worlds[1]: relative numbers in command mode and absolute numbers in insert mode or if Vim loses focus. Just another option to consider. [1] http://jeffkreeftmeijer.com/2012/relative-line-numbers-in-vim-for-super-fast-movement/ http://jeffkreeftmeijer.com/2012/relative-line-numbers-in-vi...
- dasil003 15y agoThat's a good hack. Personally I just have F4 mapped to toggle between relative and absolute, but relative is the default. I rarely care about specific line numbers because if I'm looking at a stack trace for something I just jump directly with :#
- secoif 15y agoIf you train yourself, you can get good at guessing the line numbers, plus is makes you feel godly when you correctly dd the 17 lines you want.
- tomn 15y agoThat, or subtracting ;) I swear the entire UI of Vim is made to make the user feel like a ninja.
- 15y ago
- eob 15y agoWow, it's almost like you studied a video of me coding to write that post. Thanks. This will improve my vim-fu tremendously.
- goatslacker 15y agoI'm guilty of some of these anti-patterns (like for example the arrow keys) but honestly I feel incredibly fast and productive when using ViM. I'm afraid to drastically tweak my workflow at this point because I don't think the optimization will be worth it. Overall it feels like good advice but it's just not my cup of tea.
- secoif 15y agoCars? I'd have to learn to drive? What's wrong with my horse I already know how to ride?
- goatslacker 15y agohaha, I see what you mean and it does sound like I have a bad attitude. But I feel like the overall gain I'd get from this isn't worth the time I'll spend retraining my muscle memory. Or in other terms, I don't think I'm going from horse to car. Perhaps I should experiment for a month and see if it does actually make a difference.
- yabai 15y agoI like :sh and ctrl-d to bounce back and forth...
- literalusername 15y agoWhy not ^Z and ^D? I just recently learned to use ^D to exit a shell. It's amazing how many times in my life I've typed out exit^M -- or worse, exot^H^Hit^M -- when all I needed was ^D. Edit: I now realize that you can't pair ^Z and ^D. It's either ^Z and fg, or :sh and ^D.
- lutusp 15y ago> The benefits of getting to grips with Vim are immense ... This may be true, but IMHO it can't compare to dumping Vim and choosing an editor that more efficiently exploits modern computers and their interfaces. Many people don't realize this, but Vim arose from vi, which in turn arose from "ed". This family of editors contains a command infrastructure meant to avoid the waste of paper on a teletype terminal (ed's original display device). And how do I know this? I used ed, and an early version of vi, years ago during my NASA engineering days in the 1970s, while designing part of the Space Shuttle. All those separate vi modes -- insert, delete, move the cursor, and others -- originated in ed, at a time when it was a priority to assist the operator while typing blind, before wasting another 11 inches of paper just to see how it all turned out. The first version of vi was screen oriented, but it carried over the original separate modes, and kept them separate. When I wrote the first version of Apple Writer (http://en.wikipedia.org/wiki/Apple_Writer http://en.wikipedia.org/wiki/Apple_Writer) in 1979, people had a hard time adjusting to an editor that allowed you to insert, delete and move the cursor without changing modes. It seemed a rather simple idea to me, but at the time, among vi users, it was met with shock and disbelief. And here we are, over 30 years later, and people are still learning vi/Vim, as though it represents cutting edge technology. I think we should hold a wake for vi/Vim, and maybe we should invite Fortran to the party.
- vectorpush 15y ago>Many people don't realize this, but Vim arose from vi, which in turn arose from "ed". So what if it "arose" from previous software? Should we hold a wake for the UNIX model? Everything as a file? Come on, it's 2012! I'll spare you a list of popular software that still employs metaphors from the 70s and just say that vim != ed. The robust plugin system alone allows vim to be pretty much anything you want, and I can't think of any features from any modern IDE that vim doesn't support.
- lutusp 15y ago> So what if it "arose" from previous software? You're missing the point that Vim still has the infrastructure of the original program -- it still has three separate modes: insert, delete and move the cursor, just as its distant predecessor did. This has no purpose except to agree with tradition.
- dbbo 15y agoJudging by how frequent and popular these "baby steps with Vim" type posts are, I'm guessing that not many people on HN both use Vim and care enough about it to use :help.
- vectorpush 15y agoOk, I'm going to get a little blasphemous here, but I retain functionality of the arrow keys because they allow me to move the cursor while in INSERT mode. I find that ESC + [hjkl] + I to be slower than just using the arrow keys since the distance to escape vs arrows keys is about the same for the respective fingers (minus the cost of exiting and re-entering INSERT mode). I am sometimes told I should remap ESC to facilitate the use of hjkl, but the benefits seem dubious since I rarely have a need to move one or two spaces/lines outside of INSERT mode (instead, opting to traverse my code via line number, [], g/G, w/b, A/I, or marks). tl;dr - arrow keys vs hjkl makes little productivity difference to an experienced vim user (unless of course, you've baked hjkl into your workflow, but remember that the reverse is true as well) edit: I also find it productive to have one mental model for cursor movement as well as selecting splits or tmux panes.
- ernestipark 15y agoThis isn't an issue if you've mapped ESC to jk or something similar.
- vectorpush 15y ago<j><k><k><i> OR <up> I prefer a single key to four, even if I have to move my hand off the home-row.
- djacobs 15y agoHow often is it that you want to perform this move (edit the character immediately above the cursor, but not in block mode)? If you're moving horizontally by a single space, you have backspace and delete for single-character moves (which are an edge case). If you're intending to add new content in a new line, why not <Esc>O?
- wahnfrieden 15y agoArrow keys are fine in insert mode but it sounds like you might be spending too much time in insert mode rather than considering normal to be the default mode. Do you use arrows in normal mode too?
- shadowmint 15y agoMm... Agree with those. I use vim a lot and I'd add these as things in vim I found to be major productivity sinks too: - using tabs Simply too finiky. Create windows using :split and :vsplit. Swap between them using control-W h/j/k/l or :winc h/j/k/l Also: CTRL-W =, CTRL-W N-, CTRL-W N+, CTRL-W N<, CTRL-W N> Especially useful on large visual terminals where you can have multiple files open all at once and swap between them without touching the mouse. - cwBLAH . . . . . agh. Use :%s/blah/BLAH/g :)
- nymacro 15y agoThis article only touches on the "c" noun. There are quite a few handy things which you can do with it, such as delete all the text between quotes and put you insert mode (ci"). I recommend that anyone who doesn't use this give it a try, as it saves a few keystrokes. PS. I guess the "i" subject is useful too for operating "inside" specific characters.
- jamesrcole 15y agoI've thought for a while that Vim could analyze how a user edits and spot repeated use of inefficienct techniques like these -- and then suggest the more efficient alternatives to the user. Implementing this could make a nice project.
- rhdoenges 15y agoQuestion for wiser vim users than myself: If I delete (say, a line comment) with `D`, how do I paste it as a line of its own without macro trickery involving `o<esc>p`? Is that possible?
- jdludlow 15y agoYou mean that you deleted it with dd? Can you show a before and after of what you're trying to accomplish, because it's very likely possible. I'm just not sure what you're trying to do.
- rhdoenges 15y agosay I have a line here ( | being my cursor) callFunction(); |// HEY THIS IS A REALLY LONG COMMENT From there, I hit D, which is the same as d$. I want to then paste it so I have something like // HEY THIS IS A REALLY LONG COMMENT callFunction(); But I want to do that without entering insert mode.
- weaksauce 15y agohow about remapping? nnoremap <leader>d DO<esc>p
- mct 15y agoTo break a single line into two lines on a whitespace boundary, one pattern I find myself using often is moving the cursor to the whitespace and hitting 'r<return>'. (The 'r' command replaces the character under the cursor with the next key typed, without going into insert mode.)
- dasil003 15y agoOh that's a nice trick, I'll remember that one. As an avid user of J I've been wanting its inverse.
- 15y ago
- bsergean 15y agoI prefer to keep using Echap so it works in a terminal with vi keybindings. The visual mode is not mentioned and this is super useful to see what you want to copy / delete. Also getting rid of the arrows is the way to go.
- alinajaf 15y agoAfter around 5 years of using vim, I'm at the point now where everything in this article and comment thread is already in muscle memory. My only advice would be similar to whats in other comments: * Learn to touch-type * Learn new features slowly, giving each of them time to find their place in your workflow. My questions for other vim power users: * What _epic_ custom mappings do you have? Steve Losh's <Leader>ev for editing .vimrc and <Leader>sv for sourcing completely changed how I use and customize vim... are the any others with that level of impact? * How have you mapped control of buffers/windows/tabs? Command-T buffer mode takes care of open buffers, and the default window/tab control mappings seem good enough for me, but I'm wondering if there's a nicer way for this interaction to work. Currently I've got arrow keys mapped to moving tab focus, but it feels like their might be a better way here. * Are there any fun and creative ways you've integrated with the shell/plugins? Here are some examples I've got: <Leader>r :!rake <Leader>rs :!rake spec <Leader>rl :!rake spec (test near this line) <Leader>gs :GStatus (fugitives 'git status') <Leader>gb :GBlame (fugutives 'git blame') * What's a nice way to do find in project? Both vimgrep and :Ggrep are OK, but I find it weird that I'm taken out of the editor for both of those... Ideally I'd like the results to open up in a buffer which I can then browse through in some nice way.
- dasil003 15y agoI've only been using vim full-time for a year and a half, but I'm slowly ramping up on things like window and buffer management. Probably my favorite life-changing trick is the quick macro: nnoremap <Space> @q It dramatically lowers the mental barrier to macro use (at least when you're starting out with macros). Where I use to use ragex search and replace I now instinctively go for macros, and I'm getting good at choosing the most robust commands for the situation. The pattern of qq => /foo => cwbar => Esc => Space-Space-Space is incredible. It's so infinitely superior to regex search and replace, and the fact that you can paste the macro and modify it as text is the cherry on top.
- alinajaf 15y agoNice! I think I might add that to my .vimrc. The only thing I'd add about macros is that I generally use them for multi-line transformations (i.e. they usually end with `j`). This means you can record your macro and the run `n@q` where n=the number of lines you want to run it for and q=the register where your macro lives. This is useful for annoying, repetitive syntax transformation tasks.
- Nick_C 15y agoRe using the Caps key mapped to Esc. Many people are commenting they never use the Caps Lock key. I'm puzzled since I use it all the time. Do you not capitalise your constants or globals? Or maybe you don't write much C or C++; I'm not sure what the standards are for ruby etc. Autocomplete helps, but life without a CapsLock would be awkward for me.
- xiaomai 15y agoI also find it strange that so few people use caps lock, but among all my programmer associates, I am the only one that does. That said, I hit Esc way more often than Caps Lock, so I've swapped those two keys.