Brian Lovin
/
Hacker News

Tell HN: Vim users, `:x` is like `:wq` but writes only when changes are made

`:x` leaves the modification time of files untouched if nothing was changed.

    :help :x
        Like ":wq", but write only when changes have been made.
Daily Digest email

Get the top HN stories in your inbox every day.

waisbrot

I learned to do `:wq` after I learned that `:X` encrypts your file. When typing without really paying attention to the screen, I've twice encrypted my file with password like `cd tmp`, then saved the config file, breaking my system.

After that, I switched to `:wq` (and sometimes `:w` `:q`) which is much safer against over-typing.

kqbx

In neovim, :X (and cryptography in general) is removed https://github.com/neovim/neovim/commit/85338fe

freedomben

Thanks great link. tldr:

> vim encryption uses old, obsolete algorithms that are poorly implemented. Since insecure cryptography is worse than no cryptgraphy, the community voted in favor of removing all crypto.

jpavel2

This was in 2014. Since then, Vim has added non-obsolete encryption algorithms (some provided by libsodium), used by default.

raydiatian

This is different from :x though

isbjorn16

I think their point is sometimes their left pinky is a bit lazy and won't get off the fucking shift key

the_fury

It is, but accidentally hitting capslock instead of shift when hitting the colon is extremely easy to do.

wayne

I have computer-literate parents and grew up in the PC era, so as a child I typed my elementary school assignments in vi. Accidentally using :X, encrypting one of my school papers, and having to completely rewrite it, was one of the slightly-traumatizing moments in my childhood.

FWIW, I switched to :wq for a while but I'm back to using :x instead of :wq. I'm just very careful now. :)

chasd00

I did this same thing on a large programming assignment in college. I’m 46 and can still remember the way the lab smelled and what the people sitting next to me were wearing the moment it happened.

mattkrause

If your TA was named Matt and a bit skeptical/sarcastic about this, I am once again very sorry!

https://news.ycombinator.com/item?id=34290590

lucb1e

I get annoyed by ":W is not a valid command" errors and aliased it, and that's not even dangerous to get wrong, just have to retype ":w". Why be so careful instead of just aliasing it?

vimrc excerpt:

    command Wq wq
    command WQ wq
    command W w
    command Q q
    command Bd bd
    cnoreabbrev q1 q!
I hate having to get the shift key timing correct so much that I also aliased : to ; for commands, but that's more radical and gets me into trouble on remote systems that are not my own, not sure if I recommend it. I'd recommend vim to change the default for everyone, though (fat chance, I know).

Another annoying thing in vim is whatever the heck Q does. Try to type :q, fail, retry, and now suddenly you have an extra window to close or something. Solution: nnoremap Q <nop>

hcs

I used to use the W alias whenever I noticed myself doing it on a new setup, but I haven't had to do it recently. I suspect my "slow on the shift" issue was due in part to the lousy keyboards I used to use.

talex5

I just tried it. :X asks you to enter an encryption key, then asks you to enter it again, and only continues if the keys match. And then you're still in vim and need to save your file to overwrite anything. Seems hard to do by mistake.

(though I prefer ZZ)

mattkrause

If only!

I was a TA for an introductory CS class that taught C++ and, in passing, vi. A hour before one assignment was due, a student showed up in a panic. “I just had it working but then the computer corrupted my file. Look! Can I have an extension?” The other TA and I smirked: What a lame excuse! We offered some generic advice about starting earlier and visiting office hours. He left in a huff.

A few minutes later, a second student appeared with the same story, and then a third and fourth.

We eventually tracked the problem down to some handwritten notes, where someone had written a largish :x for “save and quit.” The students were doing things like spamming :X (since it didn’t seem to respond the first time—-and it was over a sluggish ssh connection) or a reflexive quit-and-compile cycle. I think we eventually recovered one or two assignments by guessing what they might have done.

We obviously apologized profusely and the next class started with a discussion of :x versus :X—-and emacs!

BossingAround

[flagged]

indigodaddy

Yep with shift-zz you don’t have to worry about this (I don’t think, even if you do shift-xx by mistake I don’t think that does anything— although haven’t tried)

evilbob93

I think i was 40 years into my usage of vi when i learned that ZQ was a thing. I bet someone else learns it right here.

brimwats

it's me, just learned it

manaskarekar

Thanks for bringing this up.

I'm toying with either disabling it,

    cmap X <Nop>
or, mapping it down to a lower x.

    cmap X x
1. Does anyone see anything this could interfere with?

2. Does anyone know a better way to turn off the `:X` encryption option?

Sadly, having to remap definitely dulls the shine of `:x`.

queuebert

Mapping to 'x' is dangerous since on a system where you don't have your vimrc you'll get the original behavior of 'X'. Ideally you'd map 'X' to deliver a small electric shock. ;-)

westurner

  cmap X x
  :help X
> Mapping to 'x' is dangerous since on a system where you don't have your vimrc you'll get the original behavior of 'X'.

Which is still to prompt? A person could take their chances.

Besides, wouldn't that form of intentionally aversive conditioning actually boost the learning rate and create hyperassociations to the behavior your're attempting to stimulus extinct or just learn over?

sodapopcan

Well, in fairness, `:X` brings up a prompt, so an accidental `:X` won't seamlessly masquerade itself as `:x`.

Otherwise, I feel a remap is just a valid option as any to disable it. I'm not sure there's a way (a quick skim of the docs made me think `set key=` would do it but that didn't work for me, or at least I didn't understand what it does) but either way you'd still have to add config.

But again, as I say to everyone I see using commands to quit and keeps getting brought up here: `ZZ` is the same thing.

manaskarekar

Yeah, but it's possible to quickly type the next command (that you would after exiting vim) as the encryption key.

That said, given that neovim doesn't have this feature at all makes it less of an issue to me.

tomxor

Thanks for this warning.

Even worse for me, because my laptop keyboard has some kind of horrible encoding causing latency on the shift key, so I'm constantly doing :Wq when I type fast enough... Yeah I had the suspicion it was human error - but I've tested using a single finger for shift and w, so it's definitely the keyboard.

[edit]

Looks like that feature is not necessarily built in by default though.

dunham

Yeah I do that a lot. And on macos, vi decides that :Wq is an error and returns a non-zero status code on my subsequent :wq, cancelling my git commit. So I get to type the commit message again.

DwnVoteHoneyPot

i did an alias mapping :Wq to :wq

Asooka

How I've dodged that in the decades of using vim, I don't know. Though these days I roll with space for entering command mode, so the danger is nil.

nnoremap <space> :

Has done wonders for my fingers.

jjallen

Yeah, thanks for this. `:wq` is pretty fast to write. I think I will stick to it.

sodapopcan

Or, as other have pointed out, just use `ZZ` which is even easier and equivilant to `:x`.

sshine

:q, if you didn’t make a change, is even shorter.

shp0ngle

:wq just makes more sense to me, it’s “command: write, quit”

ZZ is just.. random?

ablob

This command is no longer available in neovim, so it should be fine to use there.

sshine

I always :q when I didn’t change anything.

If I changed something intentionally, :wq and :x are equivalent. If I changed something accidentally, :x won’t catch that, and :q complaining will require me to decide if :q! or :wq is correct.

So :x does not fit my workflow of avoiding accidental writes. Just like ZZ does not.

pkulak

I use :x cus it's one less keystroke. And yes, I still use :q to make sure I don't save in case I changed something by mistake.

JelteF

ZZ is only 3 keystrokes as opposed to 4 for :x (shift + z + z = 3 and shift + ; + x + enter = 4). It also doesn't require timing the release of shift before the press of x.

pkulak

Wow! Never knew that existed. If I can undo 20 years of muscle memory, I'll use it. :D

EDIT: Just tried it, and Z being right next to Shift is a deal breaker.

julesnp

I use the 'confirm' option in my vim config, that way I can always use :q and then get a prompt on what to do if a file's been changed.

I also map <C-q> to :q to speed things up a bit.

silisili

This is precisely why I use w and q instead of x. Not knowing if it wrote is definitely not a feature I'd want.

renewiltord

It's funny but I use q when I don't intend to change things and wq in whatever state I'm seeing them and x when I'm working on clean git state.

Honestly it sounds complex, but I don't even think about it and it only struck me reading your comment.

The warning note on q is desirable.

hhjj

Can't you use :q and then :x instead of :q then :wq ?

sshine

Yes, but if I :q and it complains that the file was modified, and I decide that the change is worthwhile, :wq and :x are equivalent, since :x is only different when the file isn’t modified.

You may argue that :x is shorter, but one thing is character count and another is muscle memory distance because of mnemonic similarity between :q and :wq.

caust1c

Could alias x to wq? :-) That's what I'm doing after discovering this!

bigmadwolf

ZQ will quit without writing anything.

joeatwork

This is the first time my life has changed from just reading a Hacker News headline.

jjallen

Make sure to see this comment about :X encrypting your file instead of exiting

https://news.ycombinator.com/item?id=34288446

cassepipe

I can't help but see that argument as post rationalization from people who have bee using :wq their whole life

\s

Been using :x from the start about 4 years ago and I never accidentally encrypted a file.

dgabriel

Same (but for a longer period of time). I'm kind of surprised people don't know this.

pkulak

Same. Been using :x for about 20 years. Had no idea there was some similar encryption nonsense.

undefined

[deleted]

aidenn0

Have you learned about "ZZ" yet?

_blz2

":u" updates file (writes only if changed) instead of ":w" (which always writes).

fff3331

[dead]

j1elo

See, that's why even though I'm a terminal user first and foremost, I really like the discoverability of GUIs, and that's where a good GUI is unbeatable by CLI.

This would have just been an entry "Save if needed" in the File menu, right below "Save", and users would probably find it by accident while looking at the menu, even while not actively looking for new ways to save a file.

(Not getting into the fact that a well programmed Save function would, IMO, not do anything if there are no changes, i.e. if I was the one writing the code, the Save button would be greyed out, or in the case of vim, :wq would not write anything if no changes had been made... but that's a different discussion)

rgoulter

> even though I'm a terminal user ... I really like the discoverability of GUIs, and that's where a good GUI is unbeatable by CLI.

CLI has poor discoverability? Sure; but even on the terminal, discoverability can still be good:

A couple of nice examples of discoverability in keyboard-focused programs:

- emacs' which-key[0]; there's a vim port[1] too. This shows you (some) of the available keybindings for the next input, and a short label. So you don't have to remember what `SPC h p ...` or all the options under `SPC f...`.. but it still helps to recall that `SPC h` is for 'help' related commands, `SPC f` for file related commands.

- emacs' magit[2][3]. Magit is so good at discoverability, that I'd rate it as the best tool for using git with. I've learned more about git from using it.

[0] https://github.com/justbur/emacs-which-key

[1] https://github.com/liuchengxu/vim-which-key

[2] https://magit.vc/

[3] https://emacsair.me/2017/09/01/magit-walk-through/

j1elo

Yeah, you're right that CLI discoverability can still be good, but that's the same "can" than when talking about how "Electron apps can be responsive and fast" when putting VSCode as the prime example... yes, they can, but only with a great deal of extra effort from the devs, compared to the instantaneous visual feedback that a new entry provides on a GUI.

In practice (which is what matters, ultimately), most CLI tools don't have this desirable property of "discoverable by accident".

rgoulter

Slight nit-picking; maybe the distinctions are useful for this conversation:

I'd use "CLI" more precisely to refer to command-line invocation of programs (using some shell like bash, fish, or powershell).

For programs like vim or nano, I think "TUI" (text-based UI, or sometimes terminal UI) is more suitable.

> yes, they can, but only with a great deal of extra effort from the devs, compared to the instantaneous visual feedback that a new entry provides on a GUI.

Right.

I'd say instantaneous visual feedback is what helps discoverability. Both menus in a GUI, and the menus in a TUI like in the examples above, exhibit that.

But, I wouldn't go so far as to say that a GUI menu is inherently discoverable. e.g. The image editor GIMP doesn't have good discoverability, despite being a GUI program with menus.

Whereas e.g. nano is a TUI program, but its essential features are much more discoverable compared to vim. The new tmux-alternative zellij borrows the same "show the keymap at the bottom" feature.

avgcorrection

`which-key` is great. But that is already ubiquitous through the standard top-left drop-downs in a GUI:[1] Press `Alt-F` (File, underlined F), all options drop down, then `S` (Save, underlined S).

[1] Or a standard GUI. Emacs can be run as a GUI (not terminal).

wzdd

I agree that Vim's a mess, but I don't think a good GUI is unconditionally better because you'd need to cut down Vim's gigantic command set in order to make the GUI comprehensible.

Just in this thread we've seen options for: close unless there are changes, discard changes and close, save and close, save if changed and close, and save with encryption and close. These would not be menu items.

In a GUI, you would have close (which would always prompt if there were changes, unless you turned it off globally), save (which wouldn't do anything if there were no changes), and perhaps some extra setting somewhere about an encryption key. Which would mean you'd lose the option to unconditionally save (useful sometimes if you have something watching the file and you're testing), and you'd have an extra dialog box which pops up sometimes. In terms of discoverability, it's unconditionally better, but it's not unconditionally better in all other ways.

politician

Personally, I think Sublime Text and VSCode's feature to search for a command (Cmd-Shift-P, Ctrl-Shift-P) strikes the right balance for discoverability within a large set of commands in a GUI app. I wish the feature was standard in all GUI apps. I wish macOS provided the feature for GUI apps as part of its menu bar implementation.

motti

It does. Cmd-Shift-/ and start typing

gpvos

> This would have just been an entry "Save if needed" in the File menu

No, the command would simply not exist because having so many commands would take up too much screen space.

wruza

Right, the moment any gui app becomes command-rich or option-rich enough, ui designers and/or their fanbase start whining about bloated ui and deleting them. Or reinventing a command line, where you couldn’t see it by accident anymore. These claims that gui could be better are cool in theory but real-world guis are underwhelming, to put it mildly.

armchairhacker

programs like vim and tmux desperately need a menu which just shows all available commands (including plugins), even if it’s opt-in. AFAIK no such menu actually exists in vim or neovim because of the way some of the commands are hard-coded

Tmpod

Telescope[1] on NeoVim can provide such interface. It is not standard, but telescope is becoming really widespread.

[1]: https://github.com/nvim-telescope/telescope.nvim

earthling8118

Check out zellij in place of tmux https://github.com/zellij-org/zellij

wruza

`:<Tab>`? Or do you mean something else?

armchairhacker

Show keycodes (e.g. "<leader> f" next to "open file tree" if you have the keys mapped like that)

Asooka

GVim does have a menu which lists the commands next to the menu options. That's one area in which I feel neovim has regressed -having a default built-in discoverable interface. The various GUIs on offer for it seem aimed at the expert console user, rather than being an effort to bring good GUI to vim.

Too

A good GUI doesn't have a save button at all.

It saves automatically when you press compile or change focus to another window. This is how both VSCode and Intellij work. Together with a local history that allows you to go back in time to any point earlier during the day.

Writing things in stone or reverting to older state is something reserved for git.

aidenn0

gvim suggest :wqa for "save and quit" in the file menu, which is like ":x" but will save all changed buffers, not just the current buffer.

both :xa and :wqa work for this though.

Am4TIfIsER0ppos

A menu? WTF is that? Some sort of out-dated ui element no doubt.

photonbeam

It should be some phrase you tell a smart speaker, or perhaps a chatbot

cmeacham98

Keybinds (in normal mode):

Shift + ZZ -> :x (save only if needed and quit)

Shift + ZQ -> :q! (quit without saving)

thiht

I always use ZZ! It’s so much more convenient to type with one hand

sshine

I really like having to use both my hands to perform an irreversible change to disk. Those extra milliseconds let me think through what I’m doing.

xigoi

Irreversible? There's undo and version control.

hitpointdrew

I always preferred these over the :wq! And :q!, but for some reason seem way less popular. Most tutorials don’t even mention ZZ and ZQ.

bmn__

A good software interface must be discoverable by the user. I imply here that hardly anyone knows about ZZ because of improper design, which explains why it's not generally mentioned in tutorials.

Compare vim or its clones with any KDE application, which always has keybindings shown in menus, and always a complete list of rebindable keybindings in the settings menu.

wruza

Your implication looks strange considering that ZZ is literally the first command mentioned in “The first steps in Vim / Getting out” section. Most likely it isn’t mentioned in tutorials because these are 99% copypaste medium bullshit from wannabe teachers.

https://vimdoc.sourceforge.net/htmldoc/usr_02.html#02.7

To exit, use the "ZZ" command. This command writes the file and exits.

I remember reading about it 17 years ago in this manual. Tbf, it could have been in another section back then, but that is no excuse for seeking some “easy” tutorials instead of R-ing the TFM. There must be a name for this syndrome when people look for documentation and learning materials in anywhere but the documentation and the learning materials.

KMnO4

If you’re learning Vim, command mode instructions are a LOT better because they actually show up on the screen.

avgcorrection

> Shift + ZZ

That’s a real “geez, our keymap is almost exhausted!” keybind.

sodapopcan

I always thought of it as an "easy enough to type but hard enough to never cause an accidental quit" mapping.

amalgamated_inc

Why, it's super obvious. Put vim to sleep.

naniwaduni

It's a vi keybind, so the keymap wasn't even that exhausted yet!

CGamesPlay

Vim has way worse in its defaults. gqq, naturally, formats the current line.

avgcorrection

I use `gq<movement (mostly paragraph)>` a lot. It’s a bit of a mouthful :p

xigoi

Also g?? for… encoding the current line in ROT13.

asplake

It’s been like that since vi

codesnik

huh. I'm using ZZ all the time, but I thought it is :wq

cmeacham98

It's possible it was at some point, but my local copy of vim tells me it is 'same as ":x"' in `:help ZZ`

sodapopcan

You never accidentally used it on an unnamed buffer?

codesnik

unnamed as [No Name]? both :wq and ZZ (:x) do the same: "E32: No file name"

0x45696e6172

I like to add:

Shift + ZA -> :up (save only if needed without quitting.)

by adding to your .vimrc:

    nnoremap ZA :update<CR>

chrismorgan

The really fun part:

> This command is not supported in Vim9 script, because it is too easily confused with a variable name.

So you can’t just write “x”, but must instead go for something bland like “exit”, or something exciting like “exe'x'”. (I’m presuming “execute 'x'” will work, but my mental model of how you’d unsupport the command in Vim9 script could be wrong.)

williamsmj

`:cq` exits vim with exit code 1.

This is useful if you're in vim to write a git commit message and you realize don't actually want to commit. Or you're in vim from `fc` to edit a shell command and you realise you don't actually want to run it.

turtleyacht

Thank-you. That beats `HdG :wq` to delete everything and abort the commit.

wruza

VCSs usually abort a commit if a temporary message file remains unmodified, so :q! is fine too.

drudru

Agreed. I use this all the time.

johncoltrane

Front page and more than a hundred comments for a basic Vim command. Reddit is leaking.

Arisaka1

What do you mean by "Reddit is leaking"? Do we hold ourselves to a higher standards out of merit of posting here? Is there some sort of tribalistic exclusivity that was broken? Was there perhaps a manual of commands a Vim user who posts here must know before creating an account?

_blz2

The chances of the crowd here using emacs or vim are very high. Yes that makes it an 'elite board' if you consider basic editor commands as the standard.

NegativeLatency

I may not be an uber geek but I’ve been using vim for 10 years, even written a plug-in and I didn’t know this.

badrequest

Sorry we're not all living up to your expectations.

pungentcomment

You get that kind of response anytime the subject matter is vi or vim. Still more if it mentions nvim, nano or, god forbid, emacs(!)

flippinburgers

Hasn't it been obvious for years now that the demographic on HN has shifted?

tipsytoad

:update is like :w but only writes when changes are made.

While we're at it :earlier and :later are undo/redo but instead of using an undo stack they use change points in time, so your undo history is never overwritten :)

lucb1e

:earlier 30s is such a life saver when you've messed up the standard undo/redo order (u and ctrl+r).

I need it so rarely that I have a hard time remembering what the command was again whenever I need it. Needed it a few weeks ago, so now it's at the front of my mind again :D

messe

You can also type ZZ (no colon) while in normal mode to exit and save.

This also appears to only write when changes have been made (according to some testing in neovim on my local machine).

layer8

No need to test, it's documented: https://neovim.io/doc/user/editing.html#ZZ

Maursault

> You can also type ZZ (no colon) while in normal mode to exit and save.

That's insane. What if you need to type the following words in all caps?

     DRIZZLE
     GRIZZLY
     BUZZARD
     PIZZAZZ
The last would make that command from normal mode particularly annoying. Unless you meant when not in input mode... duh.

messe

"Normal mode" ≠ "Insert mode"

anthomtb

Normal mode in vim does not have the meaning normal people associate with a normal text editor.

shiomiru

To be fair, `normal mode' may be a vimism. Both traditional vi's and nvi's man pages refer to the vim `normal mode' as `command mode', and `insert mode' (mostly) as `input mode'. (Though :set showmode still says Insert, and `insert mode' is occasionally used on the man pages too.)

acupofnope

He did say in "Normal Mode"

simonebrunozzi

I became quite an advanced vim user in 1999, during my military service in Italy (I was stationed at the Ministry of Aerial Defense, and working on IT stuff).

It's quite incredible and a bit weird that today, in 2023, I can say "Yes, I knew this", despite non having used vim much since ~2012.

I would have never guessed I'd be able to recall things like this.

RMPR

I don't know Vim, my fingers do. More seriously sometimes I'll get a question about how I did/do something, and have to sit at the keyboard and actually perform the action to be able to provide the answer.

Cardinal7167

A sure sign of a well designed tool imo

RheingoldRiver

Really? IMO that's the sign of an extremely poorly designed tool that a lot of users have learned to use very well despite how poorly it's designed.

A tool that's designed well should have its actions all extremely intuitive, in which case one would not forget things in this manner because all of the actions would be derivable from their justifications. For example: ctrl+C is copy, and ctrl+V is the key right next to it for paste, making that not just muscle memory but also extremely easy to remember and even easier to explain: "press the the key to the right of C for paste".

SecurityMinded

Never liked ":wq" construct since I started to use vi, almost three decades ago. Always used ":x". Now realizing, it had a hidden benefit. Good for me. <pats himself on the back>

andrewshadura

Never liked ":x" construct since I started to use vi. Always used ":wq". Now realising, it had a hidden benefit. Good for me. <pats himself on the back>

lucb1e

So what's your hidden benefit

Daily Digest email

Get the top HN stories in your inbox every day.