Tell HN: Vim users, `:x` is like `:wq` but writes only when changes are made
:help :x
Like ":wq", but write only when changes have been made. :help :x
Like ":wq", but write only when changes have been made.After that, I switched to `:wq` (and sometimes `:w` `:q`) which is much safer against over-typing.
> 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.
FWIW, I switched to :wq for a while but I'm back to using :x instead of :wq. I'm just very careful now. :)
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>
(though I prefer ZZ)
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!
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`.
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?
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.
That said, given that neovim doesn't have this feature at all makes it less of an issue to me.
I suppose one could naively type the same thing twice, but I feel like some caution also goes a long way. Driving without looking at the road is generally dangerous
Any time I accidentally shift-mod my saves, I immediately see the encryption prompt, and back out with SIGINT. I don't really buy the problem, so to speak
I understand how it manifests... but I find it not that difficult to avoid
My answer to lacking feedback isn't moving forward headstrong - it's verify the delicate combination went through fine
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.
nnoremap <space> :
Has done wonders for my fingers.
The advantage of `ZZ` is that it can be used as a general "close this window" command. It'll work on unmodifiable buffers as well without complaining.
ZZ is just.. random?
I also think the bikeshed should be lime green :)
It is a huge learning curve, but the ease of remote editing and the speed increase is really incredible. Being able to rapidly move around a file with just a keyboard is a super power, but it just takes muscle memory which means a lot of practice and time.
It may or may not be worth it, but it definitely is not a cultist offering. There is a large value add.
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.
EDIT: Just tried it, and Z being right next to Shift is a deal breaker.
I also map <C-q> to :q to speed things up a bit.
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.
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.
\s
Been using :x from the start about 4 years ago and I never accidentally encrypted a file.
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)
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
In practice (which is what matters, ultimately), most CLI tools don't have this desirable property of "discoverable by accident".
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.
Agree! I also consider that distinction but didn't think of it when writing. Luckily we knew we were talking about the same thing :)
You're right about the GIMP example, but I think that just means that being a GUI program is not an automatic, free-pass guarantee to discoverability. GUIs make software capabilities more evident by the mere fact that they are there right in your line of sight, but of course it still needs a touch of good organization. But that becomes then a matter of visual design and information overload, which is a whole new area.
TUI programs can be perfectly discoverable, as any well written Ncurses app can show. I don't use many, but the first one that comes to mind is Aptitude. You can just run it and, again, most if not all of the possible actions and settings of the program are right there in front of you to explore or notice.
[1] Or a standard GUI. Emacs can be run as a GUI (not terminal).
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.
No, the command would simply not exist because having so many commands would take up too much screen space.
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.
both :xa and :wqa work for this though.
Shift + ZZ -> :x (save only if needed and quit)
Shift + ZQ -> :q! (quit without saving)
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.
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.
A possible correct solution is already given as an example in my previous post.
Granted, it would be nice to see more apps using the solution you described. But personally I don’t find a list of commands in a table that much different from a list of commands in a text wrt discoverability.
Another nuance discussed here https://news.ycombinator.com/item?id=34287407#34293277
That’s a real “geez, our keymap is almost exhausted!” keybind.
And actual advantage here is that `ZZ` can be your "quietly quit anything" key. It'll close quickfix, locationlist, previewwindow, etc without complaining.
Shift + ZA -> :up (save only if needed without quitting.)
by adding to your .vimrc:
nnoremap ZA :update<CR>> 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.)
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.
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 :)
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
This also appears to only write when changes have been made (according to some testing in neovim on my local machine).
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.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.
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".
That works in English on a QWERTY keyboard. Maybe not in other languages, and while it can be explained, it doesn't necessarily help to recall. I remember my father coming up with mnemonics to remember Ctrl-V.
An example of this is that new users often expect conventions they're used to; and both vim and emacs predate a lot of these, like Ctrl-S for saving.
Muscle memory can also be a sign for poorly designed software, where simple actions require a lot of repetitive steps. At least, it's easy to go fast with a keyboard. As an example, I learned by heart some sub-sub-menu items in Cadence, accessed by Alt+x,y,z (I'm thankful for these underlined letters in toolbars).
> 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".
This is a terrible example. Why is it ctrl? Why is it to the right instead of the left?
As in "escape-q-dammit"
`Ctrl + [` instead of `Esc` to save some finger travel.I just remap Caps Lock to Esc system wise (a setting in both Linuxes and MacOs) and use both shift for Caps Lock (setting on Linux, Idk about MacOS)
I have always found the "jk" solution quite elegant although I don't use it
The benefit of using it system wise is that it then works with all programs that have a vi mode (zsh, gdbtui, etc.)
Edit: apparently ^C also ignores abbreviations. :ab lhs rhs, then ilhs^[ writes rhs, but ilhs^C writes lhs.
I only knew about :x. So thus far I’ve only edited with :x, and then used :q! to quit without writing the changes.
Anyway, it would be great to have a default shortcut for this combination of keys too.
Incidentally, I find :w to be very inefficient to type (any : command really, but there are not normally the most common operations), for such a common operation. I wonder if people remap it.
Fun fact, ZQ quits without saving, like :q!
nore ; :
You can remap your keyboard as well.
`git --amend` -> `:wq` is shorter and faster to type than
`git --amend --no-edit`
Is there a way to have vim just go to the open window? Or is there a better way to manage my windows?
(I'm using MacVim if it makes a difference.)
My life just began again. Thank you
It's a 3 finger chord that I use all the time to close vi windows. Makes sense that I'd use it to close the last one too.
ZZ
:silent! waThis solves the problem mentioned by OP because I can just `:q` anytime.
Second, in a large Excel file, the auto save is constantly slowing me down because there’s a slight hang after every cell change.
Although I don't use autosave, I don't think it matters that much with vim because you can always use undotree[0]
nmap S :wall<cr>
which saves all changed buffers into their respective files.It is probably the single most productive customization in my .vimrc file. I save my files very often, and I usually have multiple files and buffers open. 'cc' is an alias for the old 'S', so I don't lose much.
`:x` is one of only like 8 commands I know!
I'm surprised that it's apparently not one of the basic commands everyone knows?
What most didn't know (myself included) is that the behavior is slightly different from wq.
silent !stty -ixon > /dev/null 2>/dev/null
nnoremap <C-q> :x<CR>
inoremap <C-q> <ESC>:x<CR>
man vim
The :help command is mentioned in the second paragraph. And repeated the third. Though most people probably just use web searches anyway nowadays.This is not me though. I love me a plug-in heavy vim for coding sessions. Maybe one of these days I’ll be stuck working with some ECMA-based language and will finally start using VS Code.
Blame my hand geometry or the keyboard or muscle memory or 10,000 other things, I just noted it was super hard and unnatural for me to type that. (The downvoting on that is pretty epic, though.)
Of course, one should make one's own risk assessment here. It's not as though visudo can read your mind and prevent you from locking yourself out or something, so if you are on a system where you can't fall back to modifying the file on the (virtual) disk directly, you might want to first open a second shell and test your changes after saving and before quitting either vim or visudo.
EDITOR=vi visudo
should let you override itexit & save
ZZ
exit without save
ZQ
these are vi(m) commands, the :x & :wq crap is there for ed-compatibility
but: whatever floats your boat ;))
Nevertheless there are such thing as adding a confirmation message in case of a dangerous operation (and, if necessary, and option to disable such warnings). For example, C compilers usually have warnings, and you can disable any warnings that you do not want.
So most people do :wq so that it saves and then quit or do :q! to quit without saving changes. Most people stop using :q.