Hacker News new | past | comments | ask | show | jobs | submit login
Tell HN: Vim users, `:x` is like `:wq` but writes only when changes are made
537 points by manaskarekar on Jan 7, 2023 | hide | past | favorite | 270 comments
`:x` leaves the modification time of files untouched if nothing was changed.

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



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.


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


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.


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


This is different from :x though


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


[dead]


I've been a vim user for 15 years and I still often type `:Q` and `:W`. Everyone types differently and some people make mistakes.

Your blaming the victim instead of the software.


What parent @waisbrot is saying seems uncommon (the source of this whole conversation), but granted, perhaps common enough (or is it instead worrisome enough) that nvim community took it out.

I still type :Q and :W as well, but that is not what is being discussed.

Have you ever irrevocably bricked your system, as @waisbrot mentioned they have twice, from typing :W or :Q? Have you ever bricked your system from typing :X? If so, that isn’t a “use :x vs :wq” problem, that’s seems more of a use common sense problem.


OP said exactly "I've twice encrypted my file with password like `cd tmp`"

Not sure how you get "irrevocably bricked your system" from "encrypted my file", but you do you, I guess

You should also let the OP do the OP. They said they made a mistake. Simply, without complaining, and they do something else now. It's that simple


Parent (not OP) said more exactly

> I've twice encrypted my file with password like `cd tmp`, then saved the config file, breaking my system.

I get “irrevocably bricked system” from the fact that they “broke their system” and I am inferring it could only be something worth mentioning if it were irreversible.

I originally was trying to point out that parent was off-topic, because :x and :X are different. But a fleet of downvotes flooded in, so I defended my viewpoint for the catharsis.


The only reason the footgun is there is because vim put it there. Seems reasonable to me to be frustrated by that.


Then upgrade to nvim like everybody else idk


Some people value stability and gvim. I don't consider nvim an upgrade, it's just a fork with different priorities which may or may not suit you. I continue to use vim and gvim.


The one gripe I gave with neovim is the stability.


Me either, but that's because I type `:wq!` every single time instead. I'm not one of those who is afraid of typing more than a single character so I don't care if it's actually 3 I'm hitting. I am someone whose entire brain comes to an absolute crash if I type "wq" and it's asking me if I want to save over a RO file. It's like having a belt loop or pocket catch on a door handle and I despise it.

So, `:wq!`, or as I call it "write the fucking file and quit, _with feeling_"


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


Caps Lock is that key that's best replaced with Ctrl? ;)


Only for Emacs users. Vim users generally replace it with Escape.


Except that vim was designed on a keyboard with the Ctrl key at the place of your current capslock (for most keyboards, Japanese still have Ctrl at the "right" plac).


Why not both ;) - ESC when tapped, CTRL as a modifier key when pressed together with some other key.


Good idea! Though aborting a Ctrl-C could close a dialog window :/


I'm a vim user and replace it with Ctrl. It's much more useful and you can use ^[ to get Escape.


I like Compose on CapsLock more.


I like to have Caps Lock cycle the last two used keyboard languages. A necessity when there are five designated on the keyboard!


What the Lord intended


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. :)


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.


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


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>


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.


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)


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!


[flagged]


He was legitimately confused and panicked and we could have been more understanding (especially since this turned out not to be a one-off thing). It’s good to be kind.

The editor thing wasn’t a big deal: a few minutes of “Beware :X! If you no longer trust vi, feel free to use emacs or nano, which are also installed on our system. They work a bit differently [details, resources]. You can write your code locally too, but if so, make sure it runs on our system with the autograder. Here are a few options for that too.”


Probably apologized for dismissing the first student who went to them rather than taking him seriously.


It sounds like the "sluggish ssh connection" may have played a role here--imagine pressing ":X" like you think you should, but nothing happens, so you press enter a few times to see if the console is responsive.


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)


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.


it's me, just learned it


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`.


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. ;-)


  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?


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.


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.


On my build, I have to confirm the key -- is this not the case with yours?

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


On a laggy/slow ssh connection, if you don't notice the encryption prompt, it is quite easy to just try the exact same thing again.


Indeed - hence the tendency towards caution over what I type

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


Everyone has different responses when things don’t work out exactly how we think they will. Ideally, we write software that doesn’t surprise us, however we choose to react.


The endless battle continues, be brave


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.


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.


i did an alias mapping :Wq to :wq


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.


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


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


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


It's not shorter—there is an implied `<cr>` at the end there and as you have it written it's the same length. Also, if you did make a change, `:q` will yell at you. If that's what you want, though, that's totally cool.

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.


If you do this half the time you will have forgotten that you have edited the file and won't be able to exit


If I forgot I had edited a file and I’m leaving it as if I hadn’t, I will want to know.


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

ZZ is just.. random?


Sure, but we're talking Vim here. Is that more random than `"0p`? Or `ctl-o`? Or `ctl-6`? Mnemonics are important for operations we only perform a few times per day or every other day or less. But we're talking about a _built-in_ mapping for an operation that is performed probably as much as 1000 times per day, give or take. Convenience beats out mnemonics here because you don't need them (if you care to use it).

I also think the bikeshed should be lime green :)


It’s fine, it’s vim and it’s all random, but I just can never remember ZZ so much as I can wq. That’s all


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


The only time it has happened to me, I saw a weird prompt and I understood right away. I had almost forgotten than `:wq` was a thing


Oh, well that's good to know, I guess I'll stick to `:wq` whenever I use vim


That's a really bad affordance. It makes it possible for the user trying to do something non-destructive (only write if there are changes) to accidentally destroy and replace the file.


Thanks, this is absolutely horrible. Filing this as yet another item under “Why vim is the worst example of 1970s bullshit UX still recommended by cargo cultists everywhere.”


I don’t know, I grew up with IDEs and came into console based editing much later in my programming life. It is so much better when working with multiple systems over ssh, especially if modifying linux at all, writing drivers, etc.

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.


I like vi and use it daily, yet fully agree with that statement.


Harsh but not unwarranted. What a bizarre keybind.


better alternative is to use `ZZ' then


posix vi, ovi and nvi lack an X command


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.


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.


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.


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.


Switch to a German QWERTZ keyboard. That’ll also help with giving rusty muscle memory a fresh kick.


Why not use the other Shift if that's a problem?


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.


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.


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.


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


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.


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


Alias x to q, I think you mean?


ZQ will quit without writing anything.


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


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

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


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.


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


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


I've been using `rm` and `rm -rf` for as long without losing data, but I understand why some people like having a trash can. Different workflows are susceptible to different hazards.


If you're not parent, you will definitely be interested in : https://github.com/rushsteve1/trash-d


Have you learned about "ZZ" yet?



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


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)


> 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/


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".


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.


> I'd use "CLI" more precisely to refer to command-line invocation [...] For programs like vim or nano, I think "TUI" (text-based UI, or sometimes terminal UI) is more suitable.

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.


`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).


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.


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.


It does. Cmd-Shift-/ and start typing


> 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.


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.


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


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


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


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


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


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.


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.


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.


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


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


Keybinds (in normal mode):

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

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


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


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.


Irreversible? There's undo and version control.


Yes, and file system snapshots and remote sync. But writing to a file, in the general case, is an irreversible action.


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.


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.


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.


You need to make an effort to understand that RTFM is not the answer to the reproval of improper design, and shifting the goalpost from "discoverable user interface" to "looking for documentation and learning materials" does not do any favours to your argument.

A possible correct solution is already given as an example in my previous post.


I wasn’t shifting goalposts, only noted that the state of tutorials doesn’t explain much in the light of the described phenomenon. Apologies for this venture.

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


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


> Shift + ZZ

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


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


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


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


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


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


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


It’s been like that since vi


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


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


You never accidentally used it on an unnamed buffer?


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


Sorry, unnamed AND unmodified. My bad.

And actual advantage here is that `ZZ` can be your "quietly quit anything" key. It'll close quickfix, locationlist, previewwindow, etc without complaining.


I like to add:

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

by adding to your .vimrc:

    nnoremap ZA :update<CR>


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.)


`: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.


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


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


Agreed. I use this all the time.


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


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?


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.


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.


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


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(!)


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


: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 :)


: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


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).


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


> 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.


"Normal mode" ≠ "Insert mode"


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


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.)


He did say in "Normal Mode"


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.


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.


A sure sign of a well designed tool imo


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".


> ctrl+C is copy, and ctrl+V is the key right next to it 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.


Consider a tool where its user performs actions with such speed and intent that they occur at a layer of thought that OP had to slow down and think about what they were actually doing to explain to an outside observer. How is that not peak intuitive design?


While I agree this is the ideal, it's often hard to be newcomer-friendly while keeping a stable interface (absolutely needed to build a muscle memory). You can reduce the feature set, but then it doesn't work for power users.

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).


No, a tool can be designed well and still require training. It’s not the tool’s job to teach the user how to use it.

> 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?


Pass grandma test with that then we’ll talk, after you close that print dialog. You’re as grown used to this “easy to remember” as any Vim user or a truck driver.


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>


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>


So what's your hidden benefit


Maybe it's just me, but I find :wq a lot easier to type... For :x (or worse, ZZ), I either have to move my hand or bend my ring finger/pinky to reach the keys. On the other hand, my fingers reach both w and q at the same time with very little effort.


With a German keyboard, which I use, Z and Y are swapped - so even more reason to use :wq


I've been using `:x` successfully for years after finding it. I had no idea that `:X` actually encrypts the file and can cause havoc lol.


... and you can append `a` (`:xa`) to write out all modified buffers and quit.


I had a CS prof years ago tell us all the only thing we needed to know about vi(m) was the dammit key

As in "escape-q-dammit"


Just throwing another one out there:

    `Ctrl + [`  instead of `Esc` to save some finger travel.


Too fundamental of a key to even be a combination IMHO. I terminate each edit operation by it, like a dot at the end of a sentence, it needs to be a half a second operation so I can spend most of my time in normal mode.

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.)



ctrl+c is the same and even easier to type. I never use escape.


That’s not the exact same as Escape.


OK but as I personally see no need for escape in my use of vim, I judge it to be equivalent for my purpose (returning to normal mode).


So how is it different?


^C interrupts the current operation, while ^[ actually finishes the input sequence. The only practical difference I can think of is that when you entered input mode with a prefixed number, ^C ignores it. So 2iabc^C only writes `abc', but 2iabc^[ writes `abcabc'.

Edit: apparently ^C also ignores abbreviations. :ab lhs rhs, then ilhs^[ writes rhs, but ilhs^C writes lhs.


Also, ^C doesn't trigger InsertLeave autocommands.


Another pro tip. You can escape insert mode with alt https://news.ycombinator.com/item?id=34168031


I know maybe 4 Vim commands I use to write git commit messages as I was too lazy to change the default editor. :x is one of them. It's funny how different people learn tools differently. I've learnt by googling "Vim basic commands for git commit messages" and never spent any more time on it but apparently this is a revelation for many long time Vim users here.


ZZ for me as well and I mapped :WQ to :w !sudo tee % >/dev/null


Hold shift and press Z twice will also close and save. It's only three key presses instead of 4 for :x (shift + ; + x + enter)


TIL that :wq is like :x

I only knew about :x. So thus far I’ve only edited with :x, and then used :q! to quit without writing the changes.


I have a question about this. If I type ":w" and then immediately do Ctrl+Z to suspend the session, it seems that Vim is always able to save the file before the editor suspends. Is this by design? Or was I just lucky so far?

Anyway, it would be great to have a default shortcut for this combination of keys too.


Ctrl+Z sends a signal to the process which is purely advisory. The process can do anything or nothing. Vim's extensive and unreadable signal handling logic can be gazed upon at: https://github.com/vim/vim/blob/master/src/os_unix.c


TIL that VIM has built-in encryption.


Why is it useful? I would do ZZ to quit with saving, or :q! to quit without saving.

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.


I remap `<space>` to save because I like to obsessively spam it after every couple edits.

Fun fact, ZQ quits without saving, like :q!


I use the following in my vimrc so I can just use semicolon instead.

nore ; :


Sounds like a good idea. Any drawback that I don't see? Why not ; in the first place? perhaps to avoid hitting it accidentally.


It does mean you can't use any key bindings in normal mode that use a semicolon. But I don't have any that I use.


I like that AZERTY has colon on the lower row :)

You can remap your keyboard as well.


I've thought about remapping my keyboard before (and I do use caps lock as escape), but any significant changes just mean I'll be totally confused whenever I use a regular QWERTY keyboard.


I also have a funny related thing to Tell HN:

`git --amend` -> `:wq` is shorter and faster to type than

`git --amend --no-edit`


I often have the variant with --amend --no-edit in my bash history, so that I press up about two or three times instead of writing anyting at all.


I'm thinking if you are joking or not! You press arrow 3 times + hope it hits whereas `:wq` 3 chars with 100% certainty.


`ce` if you have fugitive


Not going to beat `wq` on keyboard position without yet another thing (alias) in existence to maintain.


Is there a good way to manage saved-but-not-exited vim windows so I don't open the same file twice? I keep running into a problem where I'm editing a dozen files, and then I try to re-open a file I already have opened. Vim gives me a warning about this but my choices are a) tab through all my open windows until I find the right one, or b) open a new editing window and hope that I didn't have unsaved changes in the first one.

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.)


setting "nohid" will cause vim to close non-active buffers, so at least then you only need to tab through active buffers. If I run into this situation, I just close all of my open vim windows, saving as needed, but you might have a good use case for many open vim windows.


Thanks for the suggestion! I also found that MacVim has tabs, which may be better than having a bunch of open windows.


WHAT

My life just began again. Thank you


I almost exclusively exit vi using CTRL_W-CTRL-Q.

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.


You might as well use emacs at that point.


Been using vi for just over 25 years now. The only thing I know how to do in emacs is exit :D vi uses the ctrl key a ton if you know what you are doing.


Ctrl-W based shortcuts are especially very useful.


See also

  ZZ
  :silent! wa


I am surprised it is not already mentioned in the comments, but I personally cannot use an editor that doesn't automatically write changes when I am done typing. I just forget to save and wonder why the app I am working on did not change. So my (neo)vim setup uses a plugin like `Pocco81/auto-save.nvim`.

This solves the problem mentioned by OP because I can just `:q` anytime.


I really hate autosave. I like using saving like a checkpoint where i have the ultimate undo button by ditching the unsaved changes.

Second, in a large Excel file, the auto save is constantly slowing me down because there’s a slight hang after every cell change.


> I really hate autosave. I like using saving like a checkpoint where i have the ultimate undo button by ditching the unsaved changes.

Although I don't use autosave, I don't think it matters that much with vim because you can always use undotree[0]

0: https://github.com/mbbill/undotree


I map 'S' to this in my .vimrc:

    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.


You can also use ZZ. It is equivalent to :x


I barely ever use vi(m), but occasionally use it when I have to or it's convenient for me to edit something at a CLI only, which in my work practice is only an occasional brief thing.

`: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?


It's pretty well-known (a bit less than :wq though).

What most didn't know (myself included) is that the behavior is slightly different from wq.


Seriously. Just type Shift-double-z in normal mode. No colon, no fuss, no mistakes, no confusion with anything else. No need to remap in case you press shift, because you press shift on purpose. Works everywhere vim is installed, even if your dotfiles aren’t.


" https://stackoverflow.com/questions/7883803

silent !stty -ixon > /dev/null 2>/dev/null

nnoremap <C-q> :x<CR>

inoremap <C-q> <ESC>:x<CR>


I learned early on that the easiest way to quit Vim without saving was ctrl-Z and then kill -9 %1


You could just reboot.


Have to post this gem [0] about creative ways to exit Vim

0: https://github.com/hakluke/how-to-exit-vim


Maybe well-known, but: Ctrl-C exits interactive mode and goes back to normal mode. Easier to reach than Esc and I usually find rebinding/aliasing keys to be too much of a hassle


Cumulatively, you've just saved quite a lot of my time - thanks!


A lot of the pain could've been avoided if they just wrote somewhere that you need to type ':' or something else to access help/commands when inside of vi/vim


I wonder where the first place is for people to look when needing help with random commands.

    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.


You could also just use a modern text editor with autosave


for me, I don't want it to write only when there are changes. I want it to error out if I try to quit without saving changes so I go and figure out if I changed something by accident before I save it and I want it to write specifically when I tell it to write. This cuts down on so many problems, at least in my use cases.


You can also just press ZZ in normal mode.


I'm rarely in a situation where I'd want to quit vim. One off config files on a remote machine perhaps?


Config files on an embedded device got me into using vim 10+ years ago. This seems to be a common use case. Eg, “I use vim for short term editing on remote machines but VS Code for any serious editing.”

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.


I knew about `:x`, but I had no idea there was an actual distinction beyond just being a shortcut for `:wq`.


Also, `ZZ` is the same as `:x`.


Which is the same as ZZ in normal mode. I don’t think I’ve hit “:wq” in years.


Try "ZZ" instead. No ":" required.


:x gang checking in


Shift Z Z will instantly save and exit, same as wq!


Isn't it like ":x"?


I just tried this and I think that in 40ish years of typing on computer keyboards, this is the most difficult thing I've ever typed. And I use emacs.


What do you mean? Super easy and fluid, I've been doing it for about a decade. Left pinky on left shift, left middle finger (you could try ring I suppose) on zz, tap twice.


I mean pretty much what I wrote. It's literally the most difficult thing I've ever typed on a keyboard.

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.)


So weird, I literally never, ever typed :wq ever again after the first time I experienced the smooth bliss of ZZ. Maybe you're right about hand geometry and it's just for me. It's satisfying in the way that whacking ESC is, but smoother and gentler.


I don't think C-x C-s + C-x C-q is any easier.


By the way, why does visudo sometimes give me another editor (like nano) on a new system. Isn't "vi" supposed to mean "vi"?


This is why I always 'sudo vim /etc/sudoers'. I don't want to have to deal with using and exiting nano somehow (that I need to edit sudoers means that the system isn't properly set up, so odds are that there won't be vim configured as default editor yet either).

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.


I think it uses whatever EDITOR is set to.

  EDITOR=vi visudo
should let you override it


You're showing that you didn't read the second paragraph of the visudo man page yet.


I've been using ZZ all these years


i have to admit, i heavily prefer

exit & 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 ;))


I just use it because it’s shorter.


How is it that this is news?


Wait, people exit vim?! ;)


ZZ gang


Why would it write if no changes have been made?


I can imagine any number of situations where it might be wanted. Keep the file open in vim, changes are made from somewhere else, but you'd like to keep the original version, so you :w. It makes sense to me the :write actually writes regardless of context (assuming sufficient permissions) and with no hidden conditions like "something must have changed". That kind of thing leads to weird user behavior like editing whitespace just to be able to re-save a file.


Vim is from an era when software was written to do exactly what you commanded it, not what you intended. It was your responsibility as a user to learn how to turn your intentions into commands.


Unfortuantely, too many modern programs are not designed to do what you commanded it and try to believe they know better than you do (which is often wrong, anyways). (The other problem is often not designed that expert users can use and can be programmed and used with other programs (e.g. using pipes).) I think that vi is better, in this way; it does do what you commanded it, and can be programmed and used with pipes, so it is better.

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.


If you tell it to write, and it doesn't write, then it is no longer your tool, but rather someone else's tool that you happen to be using.


Why would you ask it to write if you don't want it to write?


Because you told it to write.


Its one of the things about exiting Vim. If you type :q, and there are unsaved changes it will prompt you to save it first and not let you quit.

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.


Because it commands to “write”. Also related to 'autoread'.


There are strange cases which may make this a logical choice. Since vi doesn't traditionally lock the file it's editing, another process could change the file on-disk while you have it in the editing buffer. I think you'll get a message in these situations, because it's usually not what you want. Then you'd have the choice of writing out the buffer, whether it's changed or not, to restore the contents of the file from when you began your vi session.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

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

Search: