- Как выйти из редактора Vi или Vim?
- How To Exit Vim? Multiple Ways To Quit Vim Editor
- How to exit Vim?
- Step 1: Enter the command mode by pressing Esc key
- Step 2: Quit vim using commands
- Step 3: Press enter key
- Other ways to exit Vim
- Facts and fun about exiting Vim
- How to Exit Out of Vim Editor
- How to Open Vim Tutor
- Vim Modes
- How to Open a file in Vim
- How to Exit Out of Vim Editor
- Condition 1: Save and Quit the Editor Command in Vim
- Condition 2: After Making Any Changes and Saving the File, You Can Quit the Vim Editor
- Condition 3: Exit Vim Editor, Without Changes in File
- Other Methods to Quit Vim:
- Troubleshooting While Exiting Vim
- Condition 1: If You Don’t Want to Enter the Command-Line Mode
- Condition 2: If You Lost and Want to Force Quit
- Condition 3: When “:wq” Failed
- Conclusion
- About the author
- Prateek Jangid
Как выйти из редактора Vi или Vim?
Прежде чем ввести команду, нажмите Esc . Чтобы потом подтвердить команду, нажмите Enter .
Клавиша Esc переключает Vim в нормальный режим. Если в этом режиме нажать : (проверьте, что установлена английская раскладка и снят CapsLock, затем одновременно нажмите Shift и ; ), то символ : появится в нижней части экрана, и редактор перейдёт в режим командной строки. Это гарантирует, что вы сейчас именно вводите команду, а не редактируете файл. Помните, что регистр вводимых команд важен.
У большинства команд есть укороченные версии. Необязательная часть дается в квадратных скобках: к[оманда] .
Команды, данные курсивом , подходят только для Vim (не реализованы в Vi).
Выйти безопасно (не срабатывает, если есть не сохраненные изменения)
- :q[uit] Выйти из текущего окна Vim. Если это окно — последнее, то выйти из Vim. Если в текущем буфере есть не сохраненные изменения, команда не сработает.
- :qa[ll] Закрыть все окна и выйти из Vim. Не сработает, если хотя бы в одном буфере есть не сохраненные изменения.
Выйти с подтверждением (запрашивает подтверждение, если есть не сохраненные изменения)
- :conf[irm] q[uit] Закрыть все окна и выйти из Vim. Запрашивает подтверждение, если есть буферы с не сохраненными изменениями.
- :conf[irm] xa[ll] Сохранить все изменения, закрыть все окна и выйти из Vim. Запрашивает подтверждение, если какие–либо буферы не могут быть сохранены.
Записать (сохранить) изменения и выйти
- :wq Записать текущий буфер в соответствующий ему файл (даже если изменений не было) и закрыть окно. :wqa[ll] для всех окон.
- :wq! То же самое, но записывает даже файлы, отмеченные только для чтения (read-only). :wqa[ll]! для всех окон.
- :x[it] , ZZ (но с некоторыми особенностями). Сохранить файл только если в нем есть изменения и выйти, :xa[ll] для всех окон.
Отменить (и потерять) изменения и выйти
- :q[uit]! ZQ Выйти без сохранения, в том числе когда есть изменения в видимых буферах. Не сработает, если изменения есть также и в скрытых буферах.
- :qa[ll]! , :quita[ll][!] Выйти без сохранения, отменяя все изменения как в видимых, так и в скрытых буферах.
Нажмите Enter чтобы выполнить введенную команду.
Этот ответ все-таки не охватывает все возможные способы выйти из Vim. Полный список можно найти в документации Vim.
На момент публикации все ссылки верны и ведут на англоязычную версию документации, но сайт временно недоступен. Когда он поднимется, я добавлю ссылки на русскоязычную версию.
Vim также имеет встроенную документацию. Чтобы ее открыть: Esc :help Enter . Чтобы использовать русскоязычную встроенную документацию, необходимо включить русскую локализацию в настройках Vim.
Это перевод собственного ответа на EN.SO. При написании использовалась документация Vim и, в качестве ориентира и источника вдохновения, ответы других пользователей, особенно @dirvine.
How To Exit Vim? Multiple Ways To Quit Vim Editor
These are some of the most googled questions about the Vim editor. Vim, one of the best terminal based editors, is known for its powerful features. Its ardent users swear by it, but it leaves new users baffled because of its “unusual shortcuts.” This even leaves them wondering how to exit from the Vim editor.
In this article, I’ll show you several ways to exit Vim. We’ll also see some interesting fun facts about exiting Vim.
How to exit Vim?
As you have already seen in advanced Vim tips, there are multiple ways to quit Vim. Let me list them one by one, along with the procedure.
Step 1: Enter the command mode by pressing Esc key
Press Esc key: This is very important, because you must exit the edit mode first before typing the exit command(s).
Step 2: Quit vim using commands
Next, you can type one of the following commands to exit Vim in different mode:
- :q (yes, the colon is included in the command) – This will quit the editor. It may prompt you if you are trying to exit Vim and there are unsaved changes.
- :q! – Quit Vim without saving the data file (all unsaved changes are discarded).
- :wq – Save the file and exit Vim.
Step 3: Press enter key
Once you have made your choice of the exit command, press enter to finally quit Vim and close the editor (but not the terminal).
Do note that when you press “:” the editor will have the next keystrokes displayed at the bottom left of the terminal.
Other ways to exit Vim
Normally, you should remember the above three commands and you should be good with exiting Vim. But as I said earlier, there are more shortcuts to quit Vim. These are the following:
- Esc + 😡 + Enter (Save and exit)
- Esc + :qa + Enter (Quit all open files)
- Esc + Shift ZZ (Save and exit)
- Esc + Shift ZQ (Exit without saving)
Now it is really up to you to choose how you want to quit the Vim editor. If you ask me, the first method is what you should opt for.
You save (without exiting) with :w command and then you can use :wq to save and quit (w for save and q for quit). It is easier to remember q for quit.
Facts and fun about exiting Vim
If you are feeling a little low because you didn’t know how to quit Vim, don’t, because you are not the only one. According to Stack Overflow, over a million developers worldwide searched for how to exit Vim.
In fact, exiting Vim has become a talking point in the popular culture. Take this tweet, for example. This is one of the most popular jibes at the “complexity” of exiting Vim:
But then, obvious things are not that obvious at times. It’s funny that we are so accustomed to Ctrl+S, Ctrl+X shortcuts that it baffles us when we don’t find the same “standard” shortcuts elsewhere. I mean, even the Ctrl+C keys to stop commands does not work here.
Vim is an excellent editor. If you can master its features, there will be nothing else like it. SysAdmins particularly spend a lot of time on the command line. Mastering Vim can really be beneficial. At least, you should master the basic vim commands.
How to Exit Out of Vim Editor
Vim is a programmer text editor or text editor that is an updated and improved version of Vi. It’s used for editing plain text files. You can use it to edit scripts, programs, or system configuration files in /etc/ or /usr/local/etc/ directories.
Compared to Vi, Vim is more compatible. Vim, one of the best terminal-based editors, has many exciting features. Launching and closing Vim is very simple. This article examines how you can exit out of Vim under the Unix and Linux systems.
How to Open Vim Tutor
Vimtutor is useful for new Linux and Unix developers or sysadmins. You can quickly start the Vimtutor in macOS, Linux/Unix systems by running the following command:
vimtutor
By default, vimtutor starts in English but can also be started in other languages through other commands.
You can also see all installed languages in Vimtutor by running the following ls command:
Vim Modes
Vim has seven basic modes, and there are seven additional modes. We consider these different modes as variants of basic modes. You can read the document by running:h Vim-mode to know this better. Knowing all the modes is not so important. However, there are three such modes that you should know while using it: command mode, insert mode, and normal mode.
We are in its normal mode while starting the Vim/Vi text editor. This mode allows you to navigate the file according to your needs and use the Vim command. Use the “I” key to enter insert mode here to edit the text. This way, you can edit files, such as configurations or programs. Using the Esc key again will take you back to normal mode.
How to Open a file in Vim
You can start Vim/Vi by typing the following command:
How to Exit Out of Vim Editor
There are several methods or conditions to quit the Vim editor. Let’s discuss some of them.
Condition 1: Save and Quit the Editor Command in Vim
There is a specific procedure to save a file in Vi/Vim and quit the editor.
First, open the Vi/Vim file type and run the following command with your filename:
Press the Esc key to save a file in Vi/Vim and type :w and press enter.
Your file is saved in Vi/Vim. Now, you can quit the Vi/Vim by pressing the Esc key. After that, type any of them according to your condition.
Once you decide and type any of the previous commands, press Enter key to quit the Vim editor, and your editor will be closed.
NOTE: The bottom left of the terminal will show the next keystroke when you press “:”. After that, press : (colon) and note that the cursor will appear back at the left-side bottom corner of the screen near the colon prompt.
Condition 2: After Making Any Changes and Saving the File, You Can Quit the Vim Editor
When in insert or append mode, press Esc first. Once this command has been run, press Enter to submit it.
This will save all the changes made in the document to the file and quit the editor.
Condition 3: Exit Vim Editor, Without Changes in File
If you do not want to save any changes in the file, press the Esc key as usual. After that, type :q! and press the Enter key. This will exit Vim, saving no changes.
Other Methods to Quit Vim:
By the way, the previous commands are enough to exit the Vim editor. But, like we had mentioned earlier, Vim Editor is famous because of its shortcuts. So, now we will talk about some of its shortcut keys, through which it will be easier for you to exit the Vim editor.
Condition 1: When you want to quit the Vim editor without saving the file – > Esc + Shift ZQ
Condition 2: After saving the file and then quit the editor – > Esc + Shift ZZ
Condition 3: To quit all open files – > Esc + :qa + Enter
Condition 4: Just save and exit the file – > Esc + 😡 + Enter
It depends on which method you want to adopt to quit the Vim editor.
Troubleshooting While Exiting Vim
Condition 1: If You Don’t Want to Enter the Command-Line Mode
You can press ZQ or ZZ to quit Vim in normal mode with no problem. The ZZ and ZQ characters are the same as 😡 and :q!.
Here, ZZ and ZQ are normal mode commands, where 😡 and :q! are Exit commands.
Condition 2: If You Lost and Want to Force Quit
When trying to quit Vim, you can see the previous information by pressing Control + C in Linux, Ctrl + Alt + Delete in Windows, and force quit in macOS.
The next time you try to open the same file again, review this section (here, I’m using a file named foo.txt as an example):
If you try to open the same file next time, there is nothing to worry about if you see the following image. Here, the Vim Apk helps you recover the valuable changes made that you may have lost.
You can see that a file with the extension of .swp is found by checking the directory. This is a swap file.
After pressing R, you will see that your changes have been reflected after pressing Enter. You can delete the .swp file once you have completed the recovery process of the file. When you remove it, you don’t see the previous error.
Condition 3: When “:wq” Failed
It’s not a big deal to fail “:wq” whenever the filename is missing or read-only. So, when the file is read-only, Vim does not prevent us from editing and opening the file. Maybe even then, the :wq! will not work In this situation. You can finish all the changes through :q, and with the help of sudo, you can open the same file in the prefix and make the changes again.
Conclusion
This article covered some basics on how to exit the Vim editor in different conditions through various methods. There are also several problems while exiting from Vim, due to which you cannot exit from Vim easily. We hope you found this article helpful. Check the other Linux Hint articles for more tips and tutorials.
About the author
Prateek Jangid
A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.