in vim accidentally enter :w1 instead of :wq - vim

very often I accidently enter :w1 in vim and not :wq. In that case a file with the name 1 is created.
Is there any way to prevent this?

As phd commented you can create a command line abbreviation:
:cnoreab w1 wq
You can also exit using ZZ:
ZZ Write current file, if modified, and close the current
window (same as ":x").
If there are several windows for the current file,
only the current window is closed.
You can also consider the current buffer as if it was a scratch buffer and discar everything:
ZQ Quit without checking for changes (same as ":q!").

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

How to open a file or buffer in a new tab without leaving the current one and without switching edit-modes?

There got to be a way to open a newtab in background, without leaving the current tab, but i just can't find it in the docmentation.
Scenario: User Bob works on file: foo.txt. An external program updates periodically a file bar.txt. It then opens a new tab in the background of Bob's vim-session without forcing Bob to switch away from his current editing of foo.txt in his foreground tab.
All tab* commands doesn't seem to do the job. What am i missing?
You could say im looking for an equivalent to :tabnew_in_background_leave_edit_mode_as_is().
You can use
$ vim --servername BOB --remote-tab +":tabprevious" filename
edit
Vim has no command for opening a tab in the background. That's why we need the :tabprevious trick to open the new tab and go back to the previous one immediately. The drawback is that we are not in insert mode anymore.
Fortunately, we have gi, the normal mode mapping used to return to insert mode where it was last exited. This command works, here:
$ vim --servername BOB --remote-tab +":tabprevious" filename && vim --servername BOB --remote-send "gi"
Including and generalizing it in a shell script doesn't sound complicated.
Here is a second way, using the same ingredients but combined differently:
$ vim --servername BOB --remote-send "<Esc>:tabe filename | tabprevious<CR>gi"
Basically, we exit insert mode, do our "tab" business and get back to where we were. And we have another drawback: this method is tied to insert mode so we would end up in insert mode even if we were not there before.
Unfortunately I don't see a way to do that cleanly that doesn't involve writing a function.
did you check --remote-tab? or I misunderstood your question?
in vim, type :h remote-tab
--remote-tab Like --remote but open each file in a new
tabpage.
so you could try: (assume you had already a vim "server" named "SVR"):
vim --servername SVR --remote-tab foo.txt
the foo.txt will be opened in tab of SVR vim instance
Pressing SHIFT + t when the cursor is over a filename in a directory listing opens the file in a background tab.

Programatically execute command to close current buffer and switch to last state

I'm editing a file :e foo.
Now I'd like to save it, close the buffer (so I can go back to the state before I opened foo), using a command.
I have this right now:
command! GC silent execute ":wq" | silent execute ":close"
But if I didn't have any buffer open before, I get this error:
E444: Cannot close last window
How can I close the window, such that if it's the last window, it still closes it, and returns me back to the empty screen that you get when you just run vim?
I think you're looking for the :update + :bdelete command combination. The first persists changes if there are any, and the latter removes the buffer. If there are other split windows, the current one is closed. Otherwise, if you have other arguments / hidden buffers, the next one is displayed in the single window. If there is no other window, an empty buffer (like :enew) is shown.
What you see when you start Vim without a file as argument, $ vim, is just an empty buffer. If its state is not altered in any way it is discarded when you do :e file.
You can see that with :ls: the only buffer available is file.
If you want an empty buffer (and I have no idea why you would want that) you'll need to create one explicitly with:
:enew
unless there's an option that I don't know about.
Anyway, I'd suggest you to do:
$ vim file
rather than:
$ vim
:e file
Do you want to do save all files, and exit vim ? Then just type ZZ.
Or you want to do save all files if updated, and close all windows ? Then
command! GC bufdo update | windo bw

How do I exit 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!)

How do I close all open tabs at once?

If I have 10 tabs opened, I have to close each one using ":q" separately.
How can I close them all at once?
Shortest/simplest/fastest way would be:
:qa
To save work in all tabs and quit:
:wqa
I often use :tabo (:tabonly) to close all other tabs.
That can be done with the following
command (in normal or escape mode):
:tabdo :q
"tabdo" apparently executes the
command for all the open tabs.
You can use any of these Vim Ex commands to Exit Multiple Windows And Buffers:
:qa :qall
Exit Vim, unless there are some buffers which have been changed. (Use :bmod to go to the next modified buffer). When 'autowriteall' is set all changed buffers will be written, like :wqall.
:conf qa :confirm qall
Exit Vim. Bring up a prompt when some buffers have been
changed. See :confirm.
:qa! :qall!
Exit Vim. Any changes to buffers are lost. Also see :cquit, it does the same but exits with a non-zero value.
:quita :quitall :quita! :quitall!
Same as :qall.
:wqa :wqall :xa :xall
Write all changed buffers and exit Vim. If there are buffers
without a file name, which are readonly or which cannot be
written for another reason, Vim will not quit.
:conf wqa :confirm wqall :conf xa :confirm xall
Write all changed buffers and exit Vim. Bring up a prompt
when some buffers are readonly or cannot be written for
another reason. See :confirm.
:wqa! :xa! :wqall! :xall!
Write all changed buffers, even the ones that are readonly,
and exit Vim. If there are buffers without a file name or
which cannot be written for another reason, Vim will not quit.
To read about these in Vim, type the following Ex command
:help window-exit
Adding to what fuentesjr said:
:qa!
Will force quit all tabs, if you don't care about saving.
:qall
This closes all tabs and open buffers.
here is an Dark Side way of closing ALL VIM INSTANCES on Linux/Mac
:!killall vim -9
Do not use it. It does what you ask but probably not the best way but fun way
I'm using the VIM plugin in VSCode and I was looking for a way to close all the tabs open on the current window.
The commands :qa and :wqa didn't work because they closed all the tabs from all the windows.
The command :tabonly closed all the tabs from the current window except the current tab.
Because I'm usually only using 2 windows at the same time, the closer I managed to get to my need was to focus on the other window and run the command :
:on
(:only) it closes all the windows except the current one.

Resources