Hacker News new | past | comments | ask | show | jobs | submit login
Vim tricks (hillelwayne.com)
269 points by fanf2 on June 2, 2019 | hide | past | favorite | 61 comments



There's a few commands I LOVE but find frequently unmentioned.

In insert mode, <C-x> is a contextual completion. So like the normal <C-n> or <C-p> you just do <C-x><C-n> and you can keep hammering the <C-n> to fill in multiple "words". You can also complete lines, file paths, dictionary words, thesaurus words, tags, spelling, etc. See `help ins-completion`. Seriously, I can't do without this command. <C-x> needs to be in everyone's daily use.

Also in insert mode: <C-w> deletes a word back. You'll commonly find this is a lot of editors and stuff where it doesn't close a window. Similar to <C-backspace>, though I many times accidentally hit <C-w> in my browser instead of <C-backspace> because I use this so much (bad speller).

<C-[> much easier than pressing Esc

0 much easier than pressing ^ (honestly I have anything that is $,%,^,&. They aren't easy to reach)

Honestly, vim has some of the best written documentation I've read. If you really want to master vim, just read the docs on commands you already use. I guarantee you'll find something you didn't know.


can you give more examples of <C-x><C-n> in code editing? I have tested that out in vim and its cool but i cant think of times I want to repeat a series in another part of the document, perhaps I'm just very uncreative right now

Thanks


Totally. But I will tell you, <C-x> is a habit built around the other options too. So I just use <C-x> on any completion (which I frequently use <C-x><C-f>).

Here's a dumb example (dumb because there's other ways to do it that are better)

Let's say I'm overloading a function.

void foo(int a, int b) {}

I could do v<C-x><C-p> until I fill in the b, then type ", int c)". Now it'd be totally easier to do "v<C-x><C-l> backspace , int c)", but that's a different point.

Maybe this one is a little more useful

"def _<C-x><C-p><C-x><C-p>" may expand to "def __init__(self" Note that here I'm holding down ctrl and just hitting "xpxp"

Honestly I end up finding a lot of patterns in my code just because I started thinking about it this way. It is more one of those things where once you start thinking about it with it in mind you will find patterns.

It is also an easy habit to develop, if you already use <C-n>, because when you press ctrl you just also hit x and keep your pinky down on ctrl. I feel like there is just no downside to using <C-x> because in reality it is just one more keystroke, which is done with the other hand (so even less increase in work).


Dude! That is awesome... it makes sense now. I totally didn't even know bout <C-x><C-l> either!

Do you rebind your caps to control as well? That was another thing I did which is 10/10


Yeah I rebind keys and write my own functions. I have a preference for distilling things that I use out of plugins[0] and into just vanilla vim (I still use plugins). I'll share my configurations[1]. I don't document it well btw and there's frequently changes. But I find that looking at others rc files many times gives me ideas that I hadn't seen before. Also, if you have any suggestions I'd love to hear them.

[0]see my git rebindings instead of using tpope's plugin

[1]https://github.com/stevenwalton/.dotfiles


Awesome! Here's mine. I am busy atm but I will circle back and tell you my favorite tricks.

Read my README for most of my favorite tricks.

https://github.com/9mm/dotfiles

Things that come to mind

- ZSH-autocomplete is probably by far my favorite thing ever - iterm3 full overlay with <C-i> means that i have a full overlay terminal immediately available no matter what im doing. No messing with stupid windows - i made my own custom theme etc you can check out

Vim favorite things

- `gx` opens the current URL under the cursor in your browser - `gq` for word rewrapping comments on the fly - `Bda!` look in my .vimrc for Bda! which deletes all open buffers, useful when youre working and have 40 open buffers you forgot about and want to start fresh

I'll think of more later!


I forgot to mention these are also critical to know, because they apply to pretty much everywhere in OSX (even inside chrome address bar, terminal, plain text areas like the HN reply box, etc):

c-f Move forward

c-b Move backward

c-p Move up

c-n Move down

c-a Jump to beginning of line

c-e Jump to end of line

c-d Delete forward

c-h Delete backward

c-k Delete forward to end of line

c-u Delete entire line


"Exobrains, on the other hand, stuff Vim full of plugins, functions, and homebrew mappings in a vain attempt to pretend they’re using Emacs."

This is disturbingly accurate from my point of view. I keep wondering if I should finally jump ship and stop tweaking vim with questionable results. Spacemacs? Pure emacs + evil? Suggestions welcome.


I particularly prefer doom-emacs [1]. I migrated from Vim to Spacemacs, however doom-emacs is leaner, faster and has better evil integration. For example, Spacemacs has no mapping for evil-numbers, however doom-emacs maps it to Ctrl+A (increase number) and Ctrl+Shift+A (decrease number) [2].

However, you will probably need to do some customizations in doom-emacs. Spacemacs works mostly only using its internal layers, however when you try to do something that isn't included already... Well, it is less than optimal. doom-emacs assumes that you will want to customize things.

[1]: https://github.com/hlissner/doom-emacs/

[2]: And as for why it isn't Ctrl+X to decrease number like in Vim, it is because Ctrl+X is probably the most important keymapping in Emacs itself. However I find Ctrl+Shift+A quite good because it follows the Vim convention of the reverse of some operation is on Shift.


I recently moved from Spacemacs to Doom. I second, that it’s so much better, in that it’s faster, leaner, and easier to comprehend. Some of the keybindings could be more thorough. I find myself M-x’ing a lot. I take this as an acceptable trade off, as keybindings are easy to set on one’s own.


I like it because it is easier to add than remove. Spacemacs has so many language specifics keybindings that, while taking less time to be productive, also makes customization much harder thanks to the multiple conflicts that you will probably get when trying to map something.

However this is the trade-off. You have to spend more time in doom-emacs, however there is less friction to customize.


Great tip, thanks, trying it now. Seems nicer and easier to tweak than spacemacs, from my perspective.


Spacemacs is peanut butter meets chocolate. Apps like Magit and org-mode with vi's modal editing are truly superior.


Even when I am using Xcode or some ide that requires I use it, I still pop open Magit in Spacemacs. Love it.

The discover ability of Spacemacs is really second to none and makes it much faster to learn and keep learning.

Spacemacs is Nutella to keep the analogy going...


I write primarily Python. Pycharm+vim bindings has been quite a pleasure in my experience. I still primarily use straight up vim with little to no mods for editing one-offs and isolated scripts.


Interesting, I don't often use Python but recent project had few 3000+ lines .py files, which make Vim _very_ unresponsive when editing. Other languages weren't so problematic but Python code is what made me look at Emacs direction at the first place.


This surprises me. How does it make vim unresponsive? I frequently open multi-GB sql files without vim choking. Are you using some particular plugins?


I was using/am using:

    Plug 'tmhedberg/SimpylFold'
    "Plug 'python-mode/python-mode', { 'branch': 'develop' }
    "let g:pymode_python = 'python3'
... in different combinations. Deleting any char takes surprising amount of time, so much so that I usually mark block to delete instead of char by char even if it is three char block. Of course I may be using wrong plugins, however that's what I found that should be used in various articles online.


Sorry to hear that. Might be worth reporting to the plugin authors, as I don’t think it’s an inherent issue with vim. When editing the sql files I’m referring, it includes syntax highlighting, etc. so I would assume it should work just fine in other cases. But I’m not really dealing with large py files, in general, so I can’t say specifically.


I've made this request before but I would pretty interested in learning emacs the emacs way (rather than trying to emulate vim in emacs). Maybe leveraging my experience with vim in the sense that I don't need to learn what an editor is or shall basics.

Something that starts from bare(ish) emacs, includes emacs lisp, and gradually adds in plugins sort of like how this post does it but maybe more comprehensive and less individual tricks oriented.


Frankly, personally I don't see a particular reason to use Emacs bindings. Afaict it's mostly just “study this flight manual and then do what it says,” simply more hotkeys in the same old editing paradigm.

Meanwhile, there's every reason to use Vim's bindings, as they specifically sidestep the ‘move cursor and then type’ approach. Besides, with Evil you'll still have plenty of Emacs chords to do for stuff that's not in Vim.


Evil makes the transition from vim manageable, but once I was sufficiently far down the rabbit hole, I found I was consistently having to tweak and hack to keep evil working...eventually I bit the bullet and gave vanilla emacs bindings a shot, and haven’t looked back. YMMV, of course, and spacemacs comes highly rated.

But at the very least, they’re both good gateway drugs to get your first hit of the hard stuff


A different data point:

After using vim for about 20 years, I switched to emacs+evil about 10 to 15 years ago.. and spent a lot of time in the first 5 years or so tweaking stuff. Things have mostly stabilized in the last 5 years, and I still use evil.

One thing that helped me a ton was using hydra. Whenever I install a new mode or package, I bind all of its useful functions to hydras. Hydra and evil allow me to keep all virtually all my bindings vim-like.


I tried the switch a couple times. A few times with spacemacs, a few times with trying to write my own config from scratch with evil. Not sure what it is, maybe the way emacs configs are setup but I found vim just so much easier for me to manage with less magic and more predictability.


I’ve discovered q: when trying to quit vim in a hurry. You always keep finding new quirky things to do in vim but I guess the same hold true for other text editors like Emacs


That's how I found `K`. I was surprised the first time I got a man page open. Now I find it pretty useful and wish it extended to more than man pages.


I remap that to query dict in prose contexts. Mostly for mutt:

    au FileType mail set keywordprg=~/bin/dictless


Take a look at `:help 'keywordprg'`.


Can I do things like get `K` to work on python commands? Including modules? Or with other languages?

I see that I can do `set keywordprg=pydoc` but I want modules too.



I use gf (mnemonic: go file) all the time -- it will grab the string under the cursor (the cursor doesn't need to be at the start of it), then attempt to open a file with that name. You can look up the details but it uses a path type mechanism so if the name of the file isn't absolute, it will check the path.


Don't forget about its twin gx. For example on MacOS gx uses the open command to open a file in the default application. Really helpful when you want to open up a website quickly in your browser or you have the url to an image in a markdown file and want to see it. Helpful trick for relativ paths: https://www.reddit.com/r/vim/comments/7xs8x3/opening_local_r...


gf is awesome. Great for navigating scripts that run other scripts and also useful for creating links within a personal wiki of markdown files without a plugin like vim-wiki. While I do use a lot of plugins, I find it's a lot better to select plugins that add to vim's editing language (vim-eunuch, vim-surround, vim-vinegar, vim-exchange, vim-angry, vim-sexp-mappings-for-regular-people, vim-commentary) rather than plugins which agglomerate IDE features onto vim (vim-wiki, nerdtree, etc).

While I do have a few of these IDE-like plugins (undotree, for example), I think it's better to try plugins which embrace the "vim way" first before investing in a full IDE-like plugin. I don't mean to gatekeep by criticizing IDE-like plugins, but just to say that spending the time to learn normal mode as a true language (verbs, nouns, and all) and using plugins that follow this idea is a worthy investment. Then, add IDE-like plugins to work around the frustrating rough edges of vim once you've milked all that you can out of it.


":, @: ": is the register storing the last executed command. You can write ":p to print it to the buffer. @: reruns the last command.

That seems like a mouthful. I use :<up arrow> to run the last command and <up arrow> some more to run the ones before that.


And if you wanted to repeat that 10 times you would...?



Press up ten times. That's still what a lot of us do in terminal (particularly when we're on a machine without fancy shell history fuzzy-searching etc.).

I guess I might press and hold at ten.


Your machine probably has ^r for working through bash history

But that aside, if you’re into arrow pressing, a few lines in your .inputrc can go a long ways

Test this out sometime:

  # Incremental searching with Up and Down and Left and Right
  "\e[A": history-search-backward
  "\e[B": history-search-forward
Now you can type “find” and press up/down arrow to just cycle through history that starts with find


Personally, I would do 9@@ after the first @:


You can also use `:^F` to navigate your history in a horizontal split using regular motion/search keys.


> U is the same as u except it does the undo as a new change, which is functionally useless.

Unless I’m mistaken, this is the default undo behavior for emacs...What horror to only have vim’s forward and backward undo history! Said the emacser on the vimmer’s post.


Maybe misunderstood what you meant, but vim's undo is not linear but rather tree-like. You can undo, make a change, and still get back to the initial state. https://vim.fandom.com/wiki/Using_undo_branches

Edit: this also seems to be in the original post


You are definitely right, and I still find the emacs undo confusing...but I did think it was funny that one dev’s trash is another’s treasure—now that I know what to expect, I even kind of like the emacs way, but when I first switched I hated it.


vim also has "undo tree" functionality built in, the interface is just different than emacs's.

:help undo-branches http://vimdoc.sourceforge.net/htmldoc/undo.html#undo-branche...


U is not the same as u, though: u undoes the last change, U undoes all latest changes on one line.


Text objects are crucial to composing vim commands. Vim offers quite a few but honestly, there’s plenty more. I’d recommend using the vim-textobj-user as base to add appealing text objects. Personally, I can’t live without the “entire” text object which allows one to act upon the entire file. Like “indent entire file” etc.

https://github.com/kana/vim-textobj-user

https://github.com/kana/vim-textobj-entire


One I learned recently transferring some LaTeX over to rST is visual highlight => "gq". This breaks up long lines to multiple lines based on your stored text width. It can also be coupled with motions, e.g., "gq}".


Yeah. That's a really nice one. I use 'gqip' a lot when writing prose in latex, md, etc. One really cool thing is that it respects comments, so it will split long comment lines into multiline comments as necessary.


> If you’re constantly tweaking your vimrc, do yourself a favor and add a command for that:

> command! Vimrc :vs $MYVIMRC

I just use marks for this. Capital letter marks work across files, I use 'I (for init.vim, I use neovim).


Is it bad that I've used Vi/m since the early 80's, and I still don't know (or really feel like I need to know) a lot of tricks?

Sometimes efficiency is not about "tricks"


The problem is, how do you remember all of this stuff? Tabdo/bufdo is as advanced as it ever gets for me.


You have to make a deliberate attempt to learn it. What i would do is when coding I would focus on a single command and do it 5 or 6 times until it was engrained, then I would go to the next one. I spent about 15 days straight fairly intensively learning vim .. taht was 8 years ago. Best decision I have ever made in my entire programmign career. Now I pick up new vim commands like I am multilingual in 20 languages. All the commands I can usually remember without even typing them, they just stick. It definitely has the rolling snowball momentum effect


At my billing rate "15 days straight" is approximately equal to a low end BMW. So I think tabdo/bufdo will have to do for now. At least until I get a salaried job and can learn the rest at my employer's expense.

I do think there's Pareto principle at play with all this obscure stuff. Knowing 20% gets you 80% of the benefit, every additional percent gets you exponentially smaller fraction of the remaining 20%. That's how I play it anyway. I don't feel like I'm any less productive with my 20%.


It doesn’t take 100% of your time to learn vim. You just work 20% slower while you are intensely learning, then you work back at 100% for a while, then you work at 120% after you have internalized everything.


>At my billing rate "15 days straight" is approximately equal to a low end BMW.

So, you’re saying you are making too much money to learn something new?


Oh no, I learn "something new" every day. It's just not related to text editing. Don't get me wrong, I'm pretty good at editing in vim. After all, it's been my editor of choice for the last 15 years or so, and I see no reason why it would not remain in that role indefinitely. I'm just not convincing that learning the more obscure stuff is valuable.


Uh ok, what a weird answer.

Regardless, the benefit cannot be overstated. I am not exaggerating that it was the single greatest decision I ever made.


Vim is an editing language of actions, contexts, and count, with registers, trees, and buffers. The basic elements are pretty simple but in combination give tremendous power:

https://www.invidio.us/watch?v=wlR5gYd6um0

Unfortunately, this aspect is poorly documented. Thoughtbot's video is among the best I've found. And that's with 30 years' experience.


Anki. It doesn't take long.


Clickbait title conceals a decent article.


Changed now.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: