How do I exit Vim? - vim

I am stuck and cannot escape. It says:
type :quit<Enter> to quit VIM
But when I type that it simply appears in the object body.

Hit the Esc key to enter "Normal mode". Then you can type : to enter "Command-line mode". A colon (:) will appear at the bottom of the screen and you can type in one of the following commands. To execute a command, press the Enter key.
:q to quit (short for :quit)
:q! to quit without saving (short for :quit!)
:wq to write and quit
:wq! to write and quit, attempting to force the write if the file lacks write permission
:x to write and quit; like :wq but writes only if modified (short for :exit)
:qa to quit all (short for :quitall)
:cq to quit, without saving, with a nonzero exit code to indicate failure (short for :cquit)
You can also quit Vim directly from "Normal mode" by typing ZZ to save and quit (same as :x) or ZQ to just quit (same as :q!). (Note that case is important here. ZZ and zz do not mean the same thing.)
Vim has extensive help - that you can access with the :help command - where you can find answers to all your questions and a tutorial for beginners.

Pictures are worth a thousand Unix commands and options:
I draw this to my students each semester and they seem to grasp vi afterwards.
Vi is a finite state machine with three main states.
It starts in COMMAND mode, where you perform editor functions using very short keystroke sequences, blindly. You know what you are doing; this isn't for amateurs.
When you want to actually edit text, you should go to INSERT mode with some keystroke; common ones include:
i: insert just before the cursor
I: move to beginning of line and (i)nsert
a: append just after the cursor
A: move to end of line and (a)ppend
o: open a new line just below the current line
O: open a new line just above the current line
R: enter REPLACE mode (similar to INSERT mode)
Now, answering the question: exiting.
You can exit vi from EX mode:
q - if you haven't made any modifications, or saved them beforehand
q! - ignores any modifications and quit
wq - save and quit
x - this is similar to wq
w and x accept a file name parameter. If vi already knows the filename to use (e.g. it was started with vi file), you need not give it here again.
At last, the most important: how can you reach EX mode?
EX mode is for long commands that you can see typing at the bottom line of the screen. From COMMAND mode, you press colon, :, and a colon will appear at the bottom line, where you can type the above commands.
From INSERT mode, you need to push ESC, i.e. the Escape button, going to COMMAND mode, and then: to go to EX mode.
If you are unsure, push ESC and that will bring you to command mode.
The robust method is ESC-:-x-Enter which saves your file and quits.

Before you enter a command, hit the Esc key. After you enter it, hit the Return to confirm.
Esc finishes the current command and switches Vim to normal mode. Now if you press :, the : will appear at the bottom of the screen. This confirms that you're actually typing a command and not editing the file.
Most commands have abbreviations, with optional part enclosed in brackets: c[ommand].
Commands marked with '*' are Vim-only (not implemented in Vi).
Safe-quit (fails if there are unsaved changes):
:q[uit] Quit the current window. Quit Vim if this is the last window. This fails when changes have been made in current buffer.
:qa[ll]* Quit all windows and Vim, unless there are some buffers which have been changed.
Prompt-quit (prompts if there are unsaved changes)
:conf[irm] q[uit]* Quit, but give prompt when there are some buffers which have been changed.
:conf[irm] xa[ll]* Write all changed buffers and exit Vim. Bring up a prompt when some buffers cannot be written.
Write (save) changes and quit:
:wq Write the current file (even if it was not changed) and quit. Writing fails when the file is read-only or the buffer does not have a name. :wqa[ll]* for all windows.
:wq! The same, but writes even read-only files. :wqa[ll]!* for all windows.
:x[it], ZZ(with details). Write the file only if it was changed and quit, :xa[ll]* for all windows.
Discard changes and quit:
:q[uit]! ZQ* Quit without writing, also when visible buffers have changes. Does not exit when there are changed hidden buffers.
:qa[ll]!*, :quita[ll][!]* Quit Vim, all changes to the buffers (including hidden) are lost.
Press Return to confirm the command.
This answer doesn't reference all Vim write and quit commands and arguments. Indeed, they are referenced in the Vim documentation.
Vim has extensive built-in help, type Esc:helpReturn to open it.
This answer was inspired by the other one, originally authored by #dirvine and edited by other SO users. I've included more information from Vim reference, SO comments and some other sources. Differences for Vi and Vim are reflected too.

If you want to quit without saving in Vim and have Vim return a non-zero exit code, you can use :cq.
I use this all the time because I can't be bothered to pinky shift for !. I often pipe things to Vim which don't need to be saved in a file. We also have an odd SVN wrapper at work which must be exited with a non-zero value in order to abort a checkin.

This is the ultimate, no-nonsense, hardcore exit command for the worst-case scenarios of exiting Vim if you want out, have no idea what you've done and you don't care what will happen to the files you opened.
Ctrl-cEnterCtrl-\Ctrl-nEnter:qa!Enter
This will get you out most of the time. Most.
You might think, naively, that you can just bang Esc a few times and then do :qa!. Oh, how you would be mistaken.
See these interesting cases where hitting Esc is not enough:
iCtrl-ovg (you enter insert mode, then visual mode and then operator pending mode)
QappendEnter
iCtrl-ogQCtrl-r=Ctrl-k (thanks to porges for this case)
iCtrl-ogQCtrl-r=inputdialog('foo','bar')Enter
:set insertmode (this is a case when Ctrl-\Ctrl-n returns you to normal mode)

In case you need to exit Vim in easy mode (while using -y option) you can enter normal Vim mode by hitting Ctrl + L and then any of the normal exiting options will work.

Vim has three modes of operation: Input mode, Command mode & Ex mode.
Input mode - everything that you type, all keystrokes are echoed on the screen.
Command mode or Escape mode - everything that you type in this mode is interpreted as a command.
Ex mode - this is another editor, ex. It is a line editor. It works per line or based on a range of lines. In this mode, a : appears at the bottom of the screen. This is the ex editor.
In order to exit Vim, you can exit while you are in either the ex mode or in the command mode. You cannot exit Vim when you are in input mode.
Exiting from ex mode
You need to be sure that you are in the Command mode. To do that, simply press the Esc key.
Go to the ex mode by pressing the : key
Use any of the following combinations in ex mode to exit:
:q - quit
:q! - quit without saving
:wq - save & quit or write & quit
:wq! - same as wq, but force write in case file permissions are readonly
:x - write & quit
:qa - quit all. useful when multiple files are opened like: vim abc.txt xyz.txt
Exiting from command mode
Press the escape key. You probably have done this already if you are in command mode.
Press capital ZZ (shift zz) - save & exit
Press capital ZQ (shift zq) - exit without saving.

After hitting ESC (or cmd + C on my computer) you must hit : for the command prompt to appear. Then, you may enter quit.
You may find that the machine will not allow you to quit because your information hasn't been saved. If you'd like to quit anyway, enter ! directly after the quit (i.e. :quit!).

I got Vim by installing a Git client on Windows. :q wouldn't exit Vim for me. :exit did however...

The q command with a number closes the given split in that position.
:q<split position> or :<split position>q will close the split in that position.
Let's say your Vim window layout is as follows:
-------------------------------------------------
| | | |
-------------------------------------------------
| | | |
| | | |
| Split 1 | Split 2 | Split 3 |
| | | |
-------------------------------------------------
If you run the q1 command, it will close the first split. q2 will close the second split and vice versa.
The order of split position in the quit command does not matter. :2q or :q2 will close the second split.
If the split position you pass to the command is greater than the number of current splits, it will simply close the last split.
For example, if you run the q100 on the above window setup where there are only three splits, it will close the last split (Split 3).
The question has been asked here.

One guaranteed way is to kill the port that runs vim
! kill - 9 $(ps | grep vim | cut -d " " -f 1)

From any of four modes: insert, visual, command or command-line (ex) mode, press this to save if changed then exit vim:
Alt-Z Z
That is, press: alt + shift + z then shift + z
Why this works: From insert mode and apparently other modes, you can exit to command mode and do a command by the combination of holding Alt with any command character. The second Alt+Shift+Z is ignored, so you must let go of the Alt but keep the Shift. Work that muscle memory! :-)

Q-first vs. Colon-first
Many people know about the colon-q exit strategy. But for extra strategery and posterity, here is the q-colon-i-q method:
In Normal mode you can type:
q:iq<enter>
If you look closely and squint, you can almost read that command aloud as "quick," since this is the slow way to exit.
(Note: my attempt at humor notwithstanding, this does work!)

Related

How to document all commands that I used in Vim editor in a special file?

I need to document all commands that I used to modify text using Vim editor. When I am in the terminal and need to save all my input in a file I usually write:
history > ~/some_file.txt
However, I am not sure how to do it while using vim. Can you tell me?
Any output can be redirected with :redir. So
redir >~/vim.history|silent history|redir END
Will redirect the output of :history to the file ~/vim.history. Here silent is used to prevent a -- More -- prompt.
You could also put the history into the current buffer with
:put =execute(':history')
Note that Vims history is limited to 50 entries by default (see :help 'history).
Use startup option -w. From the docs:
All the characters that you type are recorded in the file "scriptout", until you exit Vim. This is useful if you want to create a script file to be used with "vim -s" or ":source!".
Press qx, which causes Vim to start recording your keystrokes.
Press q to finish recording.
Move your cursor to wherever you would like Vim to paste the record it has just made.
Press "xp to paste the record.
The x identifies a buffer. Buffers y, z and so on also exist, so you can use a different letter than x if you wish.
Nothing requires you to paste the record into the file you were editing when the record was made, incidentally. To paste into a different file, give the command :tabedit name-of-different-file, press [Enter], and then press "xp to paste. (Since :tabedit opens the second files in another tab, you can then press gt to toggle between the two if you wish.)

Vim :'<,'> When entering command mode

Sometimes in vim I appear to be entering a keymap unintentionally when attempting to enter command mode. For instance, when attempting to write :w I, sometimes, end up with this:
:'<,'>w
Which throws the error E481: No Range Allowed
It's mostly just a minor annoyance, and I'm more wanting to know what am I doing to initiate the command line in this way with the brackets.
:'<,'>w appears when you start a command line while being in visual mode. It allows to apply this command on a portion of your document, e.g. to sort some lines. In your case, you have accidentally hit v before entering your command.
Adding to Vincent's correct answer, if you happen to come upon a command that doesn't support a range and gives you the E481 error (though the given :write does support ranges), you can just remove the '<,'> prefilled content by pressing Ctrl + U, and then start typing the command. This is quicker than Esc and re-triggering command-line mode via :.

Keep vim always in command line mode with a ":"

Is there a way to make vim stuck in command mode with a : already typed in?
In that way, for instance:
I would type /fooEnter and the cursor would go to the beginning of the next line containing foo.
Next, I would be still on command line mode with a : already typed in for the next command.
Yes, start it in Ex mode, by invoking it either as ex or as vi -e.
You can also enter Ex mode from the normal visual mode by typing Q (must be upper case).
You can return from Ex mode to normal visual mode by using the vi command.
EDIT : This doesn't actually do what the OP is looking for. He wants to keep the visual display while keeping the cursor on the bottom command line. That may not be possible.
No, but you can map ; to : to put yourself "closer" to command mode.
I'll link to the Vim wiki instead of reposting identical information here.
http://vim.wikia.com/wiki/Map_semicolon_to_colon
You can build your own REPL, like this:
:while 1 | execute input(':') | redraw | endwhile
This is just a conceptual demo; you probably want to add a condition to quit this special mode. Also, commands like :append would need special handling to work properly.
As a last try, I could just initialize vim with -servername=FOO and then code a little script that would read from stdin and send remote-send to FOO whenever it detects(by parsing) a whole command was typed on stdin.
Then I would just use Vim and this other script side by side on different xterms/gnu screens.
EDIT
OK, I will use this one. This way I can even make :a command to enter vim's Insert mode and switch back to command mode when entering a line with a single .. This way I would also have syntax highlight on the fly when inserting text (you know, vim has a very pretty visual display of the text, I'm just too used with ed's interface). When I have so time I'll write this script and link it here.

How to use gg=G command in VIM for Windows on XML files from the gui?

I have installed VIM on Windows XP . I want to format XML files using the GUI / command line ? How to do that ?
I went though this post but where to enter that command gg=G from the gui?
Vi(m) is a modal editor, i.e. there is input mode for text input, normal mode to jump around and manipulate the text, and command-line mode, where you enter Ex commands that start with a colon, (and some more).
The gg=G is a normal mode command; since that is the default mode, just type it after opening the XML file. For it to properly work, the filetype must have been detected, but for a default installation, that should not be a problem. You then can save the reformatted file via :w (followed by Enter), and quit Vim via :q.
Vim is a different kind of editor, and very powerful once you learn its ways. If you're interested in it, I would recommend the built-in vimtutor (%ProgramFiles%\Vim\vim73\vimtutor.bat) as a good start.
Open the file in Vim and just press the characters. You don't need a special prompt for it. For example, you can also use the keys j and k to go down and up in the file.
If you want to insert new characters, you first need to go into "insert" mode by e.g. pressing i. Everything you enter now is interpreted as ordinary content input. If you want to leave insert mode, press ESC key and return to command mode.
Besides insert and command mode, there are a few more modes. You can access a command line by pressing : while you are in command mode. You can enter visual mode by pressing v while you are in command mode.
And just in case you are lost and want to leave vim, go from command mode to the command line by pressing : and enter q followed by return or just press ZZ while in command mode ;-)

Vim "show my last command" command?

Is there a command which shows what was the last command in normal mode?
Suppose I accidently hit random key and got some unexpected result.
Sure I can undo it, but could I reveal what key was pressed and how it was interpreted?
Hit the colon (:) and then use the up arrow to start going back through previous commands. You can use the up/down arrows too to move around the list.
q: will show you command history in Vim.
q/ will show you history of searches.
And must importantly, :q will quit the mode.
The text from the last command is stored in the . register. You can see all registers by :display. Unfortunately it doesn't say what the started the normal command.
To see commands from : (command mode) you can use :hist or q: which is limited to the last 20 (by default).
Another ability is to save the undo buffer :wundo undo.bin -- but the undo buffer is binary.
But none of these actually answer your question. I'm curious if it can be done.
Entering colon : then ctrl+p shows your previous command, i.e., moving backward through your vim command history. ctrl+n moves forward.
This is very convenient if you're used to using the command line and prefer not to change your keyboard hand positioning to use arrow keys.
It is difficult to know it. You can play with the variables:
v:operator
v:count (and v:prevcount)
v:register
But you cannot fully get the last normal mode command issued.
However if you want to systematically record everything you type while in Vim, you can launch vim -W ~/.vim-last-scriptout (a Windows version: vim -W "%HOMEPATH%\Vim\.last-scriptout) You can alias it in your shell on a UNIX machine. Every single key, or control-key, will be recorded into that file. Note that if you happen to use gvim or vim -g (the GUI) you might encounter this bug.
If you want to replay this file you can use :source! (with the exclamation mark) or the -s option from the command line.
On Windows I have set gvimportable.exe -W gvim_directory\last_scriptout as my default editor in my Commander program (FreeCommander). This way I can always remember what I have typed to do something and repeat a sequence of commands on another file. Of course I have another shortcut for opening Vim and playing the scriptout.
Note that the file might be written only when Vim exits, so you have to lose your session to know what you've done.

Resources