Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Vim: ZZ and zz: Do you know the difference? (programmerhat.com)
230 points by xrayarx on Jan 9, 2023 | hide | past | favorite | 132 comments


Of all the z’s my favorite by far is Ctrl-z, which send the current application to sleep and drops you back to the terminal, where you can do whatever you need before using ‘fg’ to return the slept process to the foreground.

It works with everything but I use it with vi most of all.

You can even sleep as many processes as you like and choose which one to return to the foreground as needed.


I have the following in my .zshrc that I'm sure I copied from somewhere. It allows the use of Ctrl-z to also resume programs runnings in the background instead of manually typing fg.

  # Allow Ctrl-z to toggle between suspend and resume
  function Resume {
    fg
    zle push-input
    BUFFER=""
    zle accept-line
  }
  zle -N Resume
  bindkey "^Z" Resume


This is really neat!

Threw it in my .zshrc right away. Thank you sir.


Here's how to do it in fish:

    bind \cz 'fg 2>/dev/null; commandline -f repaint'
from: https://github.com/fish-shell/fish-shell/issues/7152#issueco...


FWIW, after a quick Google search, I think this may have been the original source.

https://www.reddit.com/r/vim/comments/9bm3x0/ctrlz_binding/


Solution for bash anyone?

Saw this in the internets

if [[ $- == i ]]; then

  stty susp undef

  bind '"\C-z":" fg\015"'
fi


s/fg/bg/ ?


No. When a program is running in the shell, the default behavior is for Ctrl-z to suspend the program. Nothing needs to be done for that to happen. This snippet runs `fg` when you're back in the shell and press Ctrl-z.

That said, if you wanted to continue running in the background with `bg`, you could make that substitution to allow you to double tap Ctrl-z to do so.


Oh wow I totally misunderstood this snippet; I thought it was in fact the opposite (i.e. a shortcut to send a job to the background). Toggling back to the foreground is even better with the same shortcut! Neat!


I almost never suspend vim, because I run it exclusively inside tmux, and it's a lot easier to just open a new window/pane, run something, and close it when done.


It's useful running vim in git bash on Windows. I'll switch, though, if I ever figure out how to install tmux in that environment then I'll switch.


If you need to run tmux in git bash, this worked for me:

1. Installs msys2 (which includes pacman package manager) # can be done separately from your git installation

2. pacman -S tmux # install tmux to msys2 within msys2

3. Copy tmux.exe and msys-event-2-1-7*.dll from msys2 to C:\Program Files\Git\usr\bin # may be a different version msys-event

4. Uninstall msys2! This was important to me because I found edge cases where msys2 did not honor directory links as "not msys files" and it borked things. YMMV


Thank you - that worked!! I haven't done step 4 yet, though, but will keep it in mind if I run into any weird issues.


Thank you, I'll give it a shot ... I'd like to try this before using WSL for the situation I have in mind.


There's no good reason to run git bash on Windows anymore either, since you can use WSL!


Actually, when I tried to use git on Win10 it worked at first but then at some point stopped functioning.

Now that I'm on Win11, I definitely need to revisit that - thanks for the reminder!

The only downside, though, is the clipboard won't be as easily accessible. I'm thinking of things like piping text to clip.


clip works in WSL


Not out of the box. When I try it I get this:

  $ ls -al | clip

  Command 'clip' not found, but can be installed with:

  sudo apt install geomview
"geomview" has something to do with 3D images.

I tried this with Ubuntu 18 and 20 ...


WSL has absolute dogshit I/O so that's not true


I think that's what I ran into ... but not at first, only later, which was weird ...


yap... same here


Ctrl-z is useful to be sure but nowadays (n)vim has terminal emulators built-in.

I use this plugin: https://github.com/akinsho/toggleterm.nvim

Nvim also has a new --listen flag (if you ever tried nvr this is now built in). So no matter where you are the file will open in your main nvim instance.

No need to exit.


Yo dawg, I heard you like terminals...


Why on earth would I want to open a terminal emulator in vim when I'm already in a terminal emulator?


to use visual mode on the terminal, yank, paste etc.


If you're using zsh with plugins, then your shell startup time is already high. Ctrl+z drops you back to an existing shell, but toggleterm spawns a new shell which can be annoying.


I do but this plugin is a vim one. Both my vim and zsh start instantly (<100ms).


Its not exiting, its suspended. But yeah


It's also a footgun for new terminal users, hehe. Wan't to undo something, instead you think you've suddenly nuked your program and lost all progress. So start a new one instead.


Hah, not really, the real foot gun is Ctrl-s on a session (Ctrl-q to unlock it)


Or whatever the key shortcut is that puts gnome-terminal in "read only" mode, that I kept doing by accident for years, before I found out how to undo it (right-click, toggle "read only"), thinking it was an obscure gnome-terminal bug.


Bothered me enough to turn it off once and for all with a /etc/profile.d/stty-flow.sh:

#!/bin/sh

# turn off stupid flow control and shut up.

stty -ixon -ixoff 2>/dev/null


Except when you forget all about this ancient single-tasking terminal convenience, and accidentally enter ctrl-z, and can't remember how to get back again (nope, not ctrl-d).


Yes you need to remember 'fg', but the argument 'you have a big problem if you forget how to do this' could be said for half of how Vim works.


LOL, true. I still sometimes blow everything up or activate some weird corner of functionality with a slip of the finger.


Sorry, remembering fg isn’t that hard.

The real issue is when you do ctrl-z from muscle memory on Windows while running nvim from cmd (through wsl runner but not from an actual shell) and then it just disappears and takes your data with it.


I hate this


I hate Windows


I use ":sh" for this purpose, but it has the problems that:

- you get a new shell, so your history is lost

- if you have a "stack" of vim's you have to return to them in stack order

- I develop a habit of typing Ctrl-d when I want to get back to vim, which means I accidentally log out of SSH sessions all the time if I actually haven't still got vim open

I think getting in the habit of using Ctrl-z instead would be a big improvement.


> - you get a new shell, so your history is lost

To prevent that from happening you can add this to your .bashrc

    #write to history file at each shell prompt
    export PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"


Note that this can slow down your shell. Also it mingles histories from different sessions. Stop doing this myself for these reasons


Yes, these are good points but I've found the benefit outweighs the annoyance. fzf for a history searcher really helps. BUT not being able to 'up arrow' the previous command is annoying at times.

So far it's a 6/10 Slightly better then not doing it. =)


Heh, don’t get me started. I personally rarely used ^Z, I simply banged out.

However shelling out was intrinsic to my workflow. We didn’t have screen or any of the other common multi session terminal programs at the time.

One day I decided to log out. I rarely logged out. If anything I was kicked off by a system restart.

So to log out I started closing sessions. Turns out I was at least 30 deep. Some files were being edited more than once, I even had shells within shells (which typically did to play ENV shenanigans).


That’s an OG unix command, not a vi command.


Shell job control actually originated in Bill Joy's csh as part of BSD (as did vi).

It was adopted by the Korn shell, then codified into the POSIX shell.

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/j...


Yep I know, but it’s a core part of my vim workflow.


If you just need a single shell command you can do :!<command>. Example:

:!ack "stupid_structure->who_wrote_this_crap.oooohhhhh\s+="

(and if you wonder what "ack" means: https://beyondgrep.com/)


And if you need the output of your shell command in your buffer you can do :r !<command>


Unfortunately, many modern shells like Nushell or Elvish don't implement this feature for some reason.


My shell, https://GitHub.com/lmorg/murex does.

It’s not a trivial thing to support though. ‘jobs’, ‘bg’ and ‘fg’ need to be shell builtins. Other shell builtins might not work if they’re not POSIX fork()s and you need to handle STDIN a little more carefully.

It’s a lot of work for a feature that many alt shell users might not even be aware of.


I'm glad I've never heard of them. What do they offer?


Huh, I wouldn't have been able to say what zz does from memory despite using it all the time. I think this is because I am on my phone, away from a keyboard and it's the sort of motion where I don't ever even think about what key I'm hitting, I just do it. I'd need to be at a keyboard to access my muscle memory.


I had the exact same experience, but if I pictured pressing them in my mind's eye, I realized what they did.

It reminds me of some bilingual kids I know that can understand their dad's language perfectly, but they have a really hard time speaking it (since they always reply in their mom's language). You only learn what you practice.


I was thinking about writing down some visual keybindings map precisely for that reason, I have gathered a bunch of muscle memory about shortcuts I set up but it would take a bit of effort to remember what one was if I didn't use it for a while


I'd recommend against trying to memorize Vim keybindings by position.

1. If you want to learn a non-QWERTY layout (e.g. Dvorak or Colemak), you're going to have trouble. (Although some users to try and go to the effort of remapping to suit the layout).

2. Similarly, you might also have trouble if you get a fancy keyboard that doesn't use a row-stagger, like a kinesis, moonlander, crkbd etc.


3. Many of vim's keybindings accreted mnemonically in the first place. There's often a mnemonic explanation or back-explanation for every single keybind. Many people communicate with them ("just yank those four lines"), and they form a sort of vocabulary to the "language" of vim normal and visual modes.


I really wish the article would give easy to remember explanations. E.g. it mentions :wq means "exit after saving". Explaining :wq as "write and quit" makes it a lot easier for new vim users to remember.


But that only goes so far. Some of the key combination do have a nice mneumonic attached to it. But it definetly can't scale. ZZ is one of those, which is the case with most key combinations :/


My experience someone somewhere generally has a mnemonic for even the weirdest vim key combinations. Even ZZ probably has a mnemonic at least one person uses. Mnemonics sometimes have a lot of brains to scale on.


Gah. I never used ZZ, despite using zz all the time, so I went to my editor and started hammering the Z key and ended up closing most of my files.

Well played. This is a nice way to check whether you read the article first or last.

What's up with thirty different ways to exit vim? ZZ, :q, :wq, :x, good lord! Vim must be the most effective editor as long as you want to not use it. :)


I think you'd enjoy this then: https://github.com/hakluke/how-to-exit-vim.


This is far funnier, and informative, than I expected. Love the time out approach when aliased to 'vim'.


Hahaha. The emacs way is awesome.


Just use as little or much as you like. You don’t have to use every variant of a type of command.

Shift-zz is great as it uses only one hand and can be done in a rolling sort of movement.


In fairness, now that I know about ZZ I'm unlikely to use anything else.

Makes me wonder what'll happen if I type QQ, WW, EE, until getting through the whole keyboard. It'll probably summon Moloch.


Now you know how the pandemic happened.


It really should use two hands since z is a left pinky key (on qwerty, colemak, workman, qgmlwb) and left shift as well (so you should use right shift with it), but I'm aware many people don't use their right shift key. I only learned to a few years ago when relearning to type anyway.


:wq is still :q, just saving before exiting. The flavors are just different ways to deal with changes, with ZZ (:x) and ZQ (:q!) being aliases to the most useful ones.

This is not unique to vim, other editors handle it with prompts and buttons.


Then there's also :wqa and :xa, which are like :wq and :x except they apply to all open buffers instead of just the current one.


Getting a database connection error when I try to reach that page but this works ...

https://web.archive.org/web/20230109091524/https://www.progr...


Since I learned this the other day on HN, Ill add a minor nitpick: "ZZ" doesn't save and quit the article suggests, but saves if modified and quits.


I use zz a lot, I also like C-d and C-u which scroll the document up and down without moving the cursor. I've mapped these to C-j and C-k to make them easier to use:

  nnoremap <C-j> 4<C-d>
  nnoremap <C-k> 4<C-u>
  vnoremap <C-j> 4<C-d>
  vnoremap <C-k> 4<C-u>
I set it to scroll 4 lines at a time but you can tweak the number to make it scroll faster or slower.

Unrelated but I also have a command to remove highlighting from search results:

  nnoremap <silent> <C-l> :nohl<CR><C-l>


zz is a neat command, however I find it a little cumbersome to use.

I prefer to use the scroll offset[0] to keep the cursor line always at the center of the screen.

I've been using 'so=20' for a long time now and it feels great.

[0] - https://vim.fandom.com/wiki/Keep_your_cursor_centered_vertic...


Same here. I didn't know about zz and while reading the comments here I didn't understand what all the fuss was about.

Then I realized that I use some alternative setting that makes zz kinda redundant. I use `set scrolloff=3`.


The only problem with this is when you are actually at the bottom of the file. But great tip in general!


Quick pro tip for zz, I pair zz with search/jumps, so the next match/jump location ends up centered.

Edit: more elegant solution https://news.ycombinator.com/item?id=34308688

  " Center screen on next/previous selection.
  nmap n /<CR>zz
  nmap N ?<CR>zz
  " Last and next jump should center too.
  nnoremap <C-o> <C-o>zz
  nnoremap <C-i> <C-i>zz


The source you copied this from offers a simpler version:

  " Center screen on next/previous selection.
  nnoremap n nzz
  nnoremap N Nzz
  " Last and next jump should center too.
  nnoremap <C-o> <C-o>zz
  nnoremap <C-i> <C-i>zz


I copied it from my vimrc, I don't recall after many years where it came from :)


I pair it with half-page ups/downs. The cursor is always on the center line for easier vertical movements after scrolling

nnoremap <C-d> <C-d>zz

nnoremap <C-u> <C-u>zz


Very cool!


I use zz regularly, especially when taking notes, which tend to move the cursor towards the bottom of whatever you're using to write in. This is bad for your posture, so a regular 'zz' helps to keep my neck from straining. Another nice thing about vim is that it will scroll beyond where there is text. Once you have more than a screen of text in almost any text editor or word processor, it is often hard to get the bottom of the file to the top of the screen.


I'm often surprised and intrigued by what makes it to the front page.


It takes the minority of users like me who visit https://news.ycombinator.com/newest often and upvote new stories that look interesting. If it gets 4-5 votes early (like within 30-45 minutes), it usually makes it to the front page.

BTW I did not upvote this story.


Would be very interesting to see how many hits the newest page gets relative to the main pages.


Tips for developers' most loved editor gets a lot of positive attention.


Same here. You would think editor-related content would make the front page more frequently.


I almost never use zz. I prefer setting scrolloff to a fairly high number like 50.

Scrolloff short for scroll offset is the number of lines vim ensures between the cursor and the modeline, as well as between the cursor and the top of the screen.

Super useful for always keeping a good amount of context visible. You can even set it so high the cursor is always centered.


The previous post about ':x' was posted by the author of the article in the OP. I suspect the author of the article using multiple HN accounts to shill this.


I only use zz and have no use for ZZ. I guess it's funny from the outside that these are so similar but different.

zz: Center view vertically on the cursor line. ZZ: save and close.


I've been using vim for 20 years and never knew about this. It's a life changer! (I should have looked it up ages ago...)


You may also want to know about zt and zb, which move the current line to the top and bottom of the screen respectively.


Yeah, saw them in the post!


There are a lot of us dinos out there who haven't even used hjkl to navigate. All I do is yy, dd, p, ctrl-v to rectangle select, shift-v to line select, g or G to navigate c and the occasional s/^/#


And it's a perfectly fine way to use vi or vim as a basic editor present on every POSIX system.

Yet, as a long time user, I regret that beginners are often presented with a list of commandes to memorize and are never introduced to what makes vim actually nice: composing scopes and actions.

I have the same issue with the s command. Most people treat the parameters as something slightly magical to be googled when needed. Meanwhile, reading the ed manual was eyes-opening for me. It really helped me understand both where vim comes from and what sed does.


> hjkl

These movement keys are at least 40% the reason I love and use vim or vim plugins. Not having to move my hand, and being able to “drive” with only one hand are immensely beneficial.

With cursor keys, it feels like half of my editing time is spent finding the arrow keys and then finding the home typing position.

Emacs ctrl n/p/f/b are better than cursor keys often, but they require two hands.


C-f, C-e, C-b, C-a only require one hand. But I see your point.

The best part of evil-mode in Emacs is that I get to use Emacs bindings in insert mode, and then vim keys in normal mode. For instance when writing function signatures, I can hit C-f to easily jump over the closing parenthesis, or C-e to easily jump to the end of line, usually also to skip the closing parenthesis. I'm not sure how you would do that in vim without exiting back into normal mode and using for instance S-a to append at the end of the line.


You can use this plugin to get the same mappings in insert mode for Vim:

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


I'm a long-term emacs user who recently learned vim for fun. Deciding when to exit insert mode has been part of the learning curve.

From insert mode, vim lets you run one command without explicitly switching back to normal mode. :he i_ctrl-o for details. It's very handy for positioning the cursor for more input, for example ctrl-o f)

Also works in evil.


And other dinos who use "hjkl" because they are significantly faster than arrow keys over a 120cps terminal...


I use ZZ all the time, but it's so wired into my memory muscle that i had to read the article to realize I was actually using it.

Also, zz is _so_ practical, it's probably the shortcut I miss the most when I'm not using a vi-compatible editor...


Most editors have zz functionality. Ctrl+L for VSCode, JetBrains tools, and SublimeText, for example.


All of whom copied it, in turn, from emacs :)


And somehow after 30 years of vi use, I never knew of or used zz.

I use ma, mb, etc and ‘a ‘b and ‘’ to mark and jump around, beyond the other options.


Here's a vim pain point: a lot of commands should be case insensitive

Because it is deeply frustrating when Vim complains about :Wq "not existing" well, duh. A lot of people remap those to lower case so that Wq works (also Q!, etc)


You might know it, but all of vim's built-in commands start with lowercase letters, but it's impossible for users to define new commands starting with lowercase letters. Kind of a namespacing I guess.


Hah, I thought I was the only one who lifts shift too late and gets :Wq.


I set up my vim so that :W is "save as root"


I'm a native Portuguese speaker. ZZ makes a nice pun in our language: "Zalva e Zai", from the words "salva" (save) and "sai" (exit). It might work for Spanish too.


And zz could be “zzentro?”


`ZZ` is great when you want to save. If you're looking at a read-only file, or just want to quit a file without unsaved changes, I personally prefer `Ctrl-w q`. I do a lot of windowing in Vim (controlled with `Ctrl-w`), and if you follow that with `q` (and you're on the last window of the session), it will quit Vim. I have Ctrl mapped to Caps Lock, so I can do this quite quickly.


> Do you waste a lot of time trying to bring the current line of code to the center, going all the way down and then all the way up to reposition the editor’s viewport? Well, I used to do that too…

But then I switched to nano.


Just be careful and don't accidentally mash :X<junk><CR> otherwise you'd have encrypted the file and thrown away the key :)


I mostly use zz paired with g for broad movement, I'm thinking of incorporating marks for working with large files.


I find marks tricky to work with. I've made several attempts to get used to them over the years and it never really stuck or felt intuitive.


zzg doesn't do anything differently than just zz (the g needs an argument). Care to share an example of what you meant?


I just meant the G, gg, 22G etc. commands. There are other z commands like zt and zb, but I don't really have a use for them.


Also useful are ctrl-e and ctrl-y to shift the whole screen up or down while keeping the cursor on the same line.


There is actually one more way to quit vim. If you only have one window open in vim, Ctrl-W Q will exit.


what’s the mneumonic here? ZZ = sleeping zb = zoom bottom zt = zoom top z. = zoom end of line (like a period)

but it’s not really “zooming” it’s scrolling or panning.


been using neovim for years now and I didn't know this.

I've only recently started using ctrl+c to move from input mode to normal mode


I set scrolloff=8


Yes, I have read :help.


cool! didn't know z. z-


I have a feeling to author doesn't know what "parsing" means.


Yes, what is meant by 'parsing the commands with a search'? Just performing zz after the search, ie 'pairing'? I couldn't figure it out otherwise.


That last example is also completely unhelpful for figuring out what he’s talking about because it doesn’t actually show you the keystrokes it uses.


Why are vim/neovim tricks/plugins/basic commands being spammed on hn recently??


I like those "spams". This is the real value of HN. Don't you think? Or we have to cope with "the usefulness" of the new reddit like trend?


I can empathize with the parent comment and understand why basic commands about Vim can be bothering them. Many of us (and perhaps the parent commenter is one of them too) come to HN to look for interesting news and articles. Something interesting that has happened in the tech world. Or some interesting knowledge about the technology tools we work with or the real life world we live in.

It so happens that rehashing of Vim's documentation on basic commands does not make it interesting enough. When articles on these basic commands (that are easily and better learnt from Vim :help) come on HN again and again, it can lead to a boring reading experience. It stops being interesting. For some people, this can reduce the real value of HN.

I'll confess that my comment may appear as elitist. But hey, at least I am being honest, from my high-horse, elitism and all. If you can get past the thorny issue of elitism, perhaps you can see my point. My point is that I appreciate why these articles appearing too often can be bothering to some. I hope you can appreciate it too.

That's not to say that there is anything wrong with these posts. If the community likes it and upvotes it enough, so be it. There is a "hide" link to hide the story if it is really bothering someone. A few basic Vim articles every week is not really a big problem even if it ends up bothering some people. I can live with it and I hope the parent commenter can live with it too.


There is nothing elitist in pointing people to freely available and easy to follow documentation. Quite the contrary.


I‘m sorry you feel spammed.

Among others, I personally enjoy the basic commands stories, because, as can be seen in the comments, it is often news even to long term users.


Because enough users consider them to be useful and upvote them.




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

Search: