How to close vim

How to close vim

How to Exit Vim – Vim Save and Quit Command Tutorial

How to close vim. Смотреть фото How to close vim. Смотреть картинку How to close vim. Картинка про How to close vim. Фото How to close vim

I’ve been using Vim since the first year I started coding. For all the IDEs/editors that I have used, the Vim plugin is always the very first plugin that I install.

I know that Vim can be challenging to work in for people who are not familiar with it. In this article, we’ll cover some fundamental topics like how to exit Vim, rather than quitting Vim.

TL;DR – How to Exit Vim

If you want to understand in more detail how this works, let’s dive in.

What are Modes in Vim?

There are seven BASIC modes in Vim and seven additional modes that are considered variants of the BASIC modes. You may run :h vim-modes inside Vim to read the documentation if you would like to know more.

What is normal mode in Vim?

Normal Mode is crucial since it’s only in Normal Mode that we can run commands (there are exceptions but those are beyond the scope of this article).

What is insert mode in Vim?

The most common way to make this switch is by pressing i in Normal mode after navigating the cursor to the place that we are going to edit.

What is command-line mode in Vim?

Command-line Mode is normally a «short-lived» mode, which you use to run «Ex commands» (not to be confused with the «commands» in Normal Mode ).

How to Exit Vim

It does mention, though, that this command will fail «when changes have been made and Vim refuses to abandon the current buffer» (if you still remember, buffer is just opened file(s), nothing fancy).

The difference here is that :wq will save the file no matter if you made changes to it or not. 😡 won’t save the file if you didn’t make any changes. What matters here is the modification time of a file, since :wq will update the modification time but 😡 will not.

Do note that if you use this way, you WILL lose all changes that you have made to this file and there is almost no way that you can recover them.

How to Troubleshoot Exiting Vim

Here, ZZ and ZQ are considered commands of Normal Mode while 😡 and :q! are Ex commands.

What if :wq failed?

This is legit since :wq could fail when the file is read-only or the file name is missing.

Note that when a file is read-only, Vim won’t stop you from opening and editing the file. You may also find that :wq! won’t work either at that moment. You might end up discarding all changes with :q! and open the same file prefixed with sudo and do the same changes one more time.

One thing you could do is to save this file in another directory that you have write permission to, like

In order to achieve this, you can run :w

/my-backup-file which will save this file under

. Next you can use the mv command to move this file around. Also note that this is what you need to do when Vim complains that the file name is missing.

For example, :ls will list all buffers in Vim but :!ls will run the ls command from the shell and display the result. tee copies from standard input (a.k.a. stdin ) to standard output (a.k.a. stdout ). % refers to the current filename.

This means that we use the sudo command from the shell environment, copy the content of the current file (note: modified version) from Vim, and redirect the modified content to the file (which is referred to by using the filename).

How to close vim. Смотреть фото How to close vim. Смотреть картинку How to close vim. Картинка про How to close vim. Фото How to close vimWarning of file content change

You will notice the warning above. This warning happens because the file content was updated within the shell environment without Vim’s attention. So Vim considers this to be an external change and lets you know what happened.

You can just press Enter at this time since you made the external change on purpose.

What if I am lost and have to force-quit?

How to close vim. Смотреть фото How to close vim. Смотреть картинку How to close vim. Картинка про How to close vim. Фото How to close vim

Next time when you try to open the same file again, you should see this (here I am using a file named foo.txt as an example):

How to close vim. Смотреть фото How to close vim. Смотреть картинку How to close vim. Картинка про How to close vim. Фото How to close vimswap file

Don’t panic – this is as expected, since Vim is trying to help you recover your valuable changes that you might have lost.

We will see the following if we press R to recover:

How to close vim. Смотреть фото How to close vim. Смотреть картинку How to close vim. Картинка про How to close vim. Фото How to close vim.swp recover

Conclusion

In this article, we covered some fundamentals about Vim’s modes and how to exit Vim. We also learned how to solve common issues when it comes to exiting Vim.

Thanks for reading. There is lot more to learn when it comes to Vim. But feel free to explore the Vim help documentation if you would like to learn more.

Как выйти из Vim: руководство по сохранению файлов и командам выхода

Перевод статьи «How to Exit Vim – Vim Save and Quit Command Tutorial».

How to close vim. Смотреть фото How to close vim. Смотреть картинку How to close vim. Картинка про How to close vim. Фото How to close vim

Я пользуюсь Vim с тех самых пор, как стал учиться программированию. Во всех других редакторах и IDE я сразу же ставлю плагин Vim.

Конечно, я знаю, что работа с Vim с непривычки может быть трудна. В этой статье мы рассмотрим некоторые основные концепции, касающиеся работы с этим редактором, и одну из базовых тем: как выйти из Vim.

TL;DR – Как выйти из Vim

Ну а если вы хотите разобраться во всем этом подробнее, читайте дальше!

Что из себя представляют режимы Vim?

К счастью, чтобы приступить к работе с редактором, все 14 режимов знать не обязательно. Но о трех знать все же следует. Это нормальный режим, режим вставки и режим командной строки.

Что такое нормальный режим Vim?

Нормальный режим имеет огромное значение. Именно в этом режиме мы можем запускать команды (есть исключения, но в этой статье мы не будем их рассматривать).

Что такое режим вставки?

Мы используем режим вставки для редактирования текущего файла (в Vim он обычно рассматривается как buffer). По умолчанию при открытии файла мы попадаем в нормальный режим. Если нужно внести изменения в файл, сначала нужно переключиться в режим вставки.

Что такое режим командной строки?

Режим командной строки обычно временный, он используется для запуска «Ex-команд» (не путать с командами в нормальном режиме!).

Любопытный факт: название Vim образовано от «Vi Improved» («улучшенный Vi»). Сам этот редактор создан на базе редактора vi. А вот vi создан на основе текстового редактора ex. И vi, и ex были созданы Биллом Джоем.

Еще один любопытный факт для пользователей macOS: в системах macOS есть только Vim, а команда vi — ссылка на vim.

Войти в режим командной строки можно, нажав : в нормальном режиме. Например, когда вы запускаете команды для просмотра документации, которые я приводил выше, сразу после ввода : вы фактически входите в режим командной строки.

Для возврата в нормальный режим нужно нажать клавишу ESC.

How to close vim. Смотреть фото How to close vim. Смотреть картинку How to close vim. Картинка про How to close vim. Фото How to close vim

Как выйти из Vim

Чтобы войти в режим командной строки, сперва нужно убедиться, что вы находитесь в нормальном режиме, а затем просто набрать двоеточие. Теперь, перейдя в режим командной строки, можно просто набрать quit и нажать Enter или return.

Однако, стоит заметить, что если вы внесли какие-либо изменения в файл, такой метод выхода не сработает.

Разница в том, что :wq сохраняет файл в любом случае, хоть меняли вы что-то в этом файле, хоть нет. А команда 😡 не будет сохранять файл, если изменений не было. Суть здесь в изменении времени модификации файла. При выполнении команды :wq время модификации точно изменится, а при выполнении 😡 — только если на самом деле были внесены какие-го правки.

Имейте в виду, что при вводе этой команды вы потеряете все внесенные изменения и у вас практически не будет шансов их восстановить.

Проблемы выхода из Vim и как их решать

Что, если я не хочу переходить в режим командной строки?

ZZ и ZQ считаются командами нормального режима, а 😡 и :q! — Ex-командами.

Что, если :wq не сработает?

Вот это, кстати, вполне возможно, если вы открыли файл, который имеете право только читать, или если у файла нет имени.

Чтобы это все проделать, выполните команду :w

Обратите внимание: так же следует поступать, когда Vim жалуется на отсутствие имени у файла.

Например, команда :ls выведет список всех буфферов (открытых файлов) в Vim, а вот :!ls запустит команду ls из оболочки и отобразит результат.

tee копирует из стандартного ввода (stdin) в стандартный вывод (stdout).

% означает имя текущего файла.

Таким образом, мы можем использовать команду sudo из оболочки, скопировать содержимое текущего файла из Vim (в модифицированном виде) и перенаправить модифицированный контент в тот же файл (он указан путем использования % ).

Вы увидите предупреждение, как в примере выше. Оно выводится, потому что содержимое файла было обновлено в оболочке, без участия самого Vim. Поэтому Vim рассматривает это изменение как внешнее и предупреждает вас о нем.

Вы можете просто нажать Enter, потому что это внешнее изменение вы сделали намеренно.

Что, если я заблудился и мне нужно немедленно выйти?

Но вы можете это обойти, нажав Ctrl + Alt + Delete в Windows или Force Quit… в macOS.

Когда вы в следующий раз откроете этот файл, вы, по идее, увидите это (я использую файл foo.txt в качестве примера):

Без паники! Это нормально. Vim пытается помочь вам восстановить ценные изменения, которые вы, возможно, потеряли.

Если нажать R для восстановления, мы увидим следующее:

How to close vim. Смотреть фото How to close vim. Смотреть картинку How to close vim. Картинка про How to close vim. Фото How to close vim

Заключение

В этой статье мы рассмотрели некоторые базовые вещи относительно режимов Vim, а также подробно разобрали, как можно выйти из этого редактора. Также мы научились разрешать распространенные проблемы, связанные с выходом из Vim.

How to close vim

How to exit vim

Below are some simple methods for exiting vim.

For real vim (and hacking) tips, follow hakluke and tomnomnom on twitter.

How to close vim. Смотреть фото How to close vim. Смотреть картинку How to close vim. Картинка про How to close vim. Фото How to close vim

The ps-less way using status files

The ps-less process tree way

The first contact way

Credit: @caseyjohnellis How to close vim. Смотреть фото How to close vim. Смотреть картинку How to close vim. Картинка про How to close vim. Фото How to close vim

The lazy pythonic using shell way

The pythonic way

The pure perl way

The Rustacean’s way

The lazy rubist using shell way

The Colon-less way

vi will eventually exit

Locally (the cheaty, lazy way, why even bother):

The hardware way

Pull the plug out

The hardware expert way

Use VIMKiller! The most practical physical solution to all your VIM troubles. It only costs 500,000 USD!

The timeout way

Before running vim, make sure to set a timeout:

Never forget to set a timeout again:

Make sure to save regularly.

The Russian Roulette timeout way

When you want to spice things up a bit:

The Shoot First, Ask Questions Later way

The using vim against itself way (executing the buffer)

Open Vim to empty buffer and type:

The AppleScript way

Credit: @dbalatero In Mac terminal vi :

Replace «iTerm» with your terminal application of choice:

The Mac Activity Monitor way

The MacBook Pro Touch Bar way

Touch quit vim text in your touch bar

The Mac Terminal way

Press ⌘ + q > Click Terminate

The Passive Way

Walk away.

The Passive-Aggressive Way

. then walk away. (n.b. That’s a fork bomb, please don’t try at home.)

The Microsoft Way

The Client-Server way

Don’t run this, it could break your computer.

The layered Method

Bonus: still stuck if multiple vim instances are running

The epileptic Method

May the magnificent colors help you to forget the emotional damage caused by exiting vim!

The Abstinence Method

The Passive-Aggressive Abstinence Method

The shortest way

The suspend way

The Minimal, Open-Source way

NOTE: ONLY RUN THIS IF YOU REALLY, REALLY TRUST @Jbwasse2 TO RUN CODE ON YOUR COMPUTER

The Acceptance Way

Just stay in Vim 😊 🤘🏻

The Webmaster Way

If you run Vim in a docker container like:

then you would normally exit vim by stopping the associated container:

run vim as root and run this when you want to exit:

The even more Extreme Kernel Way

Warning, this may break your entire computer

The Android way

Close the Termux app.

The extreme Android way

Run vim inside Termux and run this when you want to exit:

The JavaScript way

The Kubernetes way

If you run Vim in Kubernetes pod like:

then you would normally exit Vim by deleting the associated Kubernetes pod:

The Vim inside of Vim inside of Vim inside of Vim. inside of Vim way

Let «automatic garbage collector» do it for you

Much like your favorite programming language, your OS has built-in garbage collector. It will close stuff for you, so you don’t have to.

Now it’s not your problem anymore. Process will close automatically upon next reboot/shutdown.

The Product Manager way

The Experienced Product Manager way

The spiritual way

Inside a tmux session:

Note that Ctrl+B is the default prefix. For different prefixes, the command must be adjusted accordingly.

The Mathematician’s way

Define yourself outside vim.

How To Exit Vim? Multiple Ways To Quit Vim Editor

“How to exit Vim?” “How to quit Vim?” “How do you exit Vi editor?” “How to save and quit Vim?”

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:

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.

How to close vim. Смотреть фото How to close vim. Смотреть картинку How to close vim. Картинка про How to close vim. Фото How to close vim

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:

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:

I’ve been using Vim for about 2 years now, mostly because I can’t figure out how to exit it.

The widespread difficulty is somewhat surprising, because if you run Vim you’ll see the information about how to exit it at the splash screen:

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.

I hope this tutorial helped you to save and exit from Vim. Do share your views and thoughts on it.

Creator of It’s FOSS. An ardent Linux user & open source promoter. Huge fan of classic detective mysteries ranging from Agatha Christie and Sherlock Holmes to Detective Columbo & Ellery Queen. Also a movie buff with a soft corner for film noir.

How to close vim from the command line?

I know this is more of a general linux question but w/e. So when I enter a program like vim in the command prompt it displays all the text in the file and I can edit it etc. But I can’t figure out how to close or save the file and get back to the command prompt without killing the process. Any help is appreciated.

6 Answers 6

In vim there are 3 different modes:

Once you are at Normal mode Press : to begin your command (you’ll see it appear in the bottom left). The following commands are related to quiting vim:

First, hit the escape key. 1

Alternately, you can type :q (a.k.a, «quit, please«) This will exit only if you haven’t made edits.

If you’ve made edits, and you want to discard them and leave, type :q! (a.k.a «quit, damn it!»)

1 : This ensures you are in «command» mode. Which you want for typing commands, like those needed to exit.

How to close vim. Смотреть фото How to close vim. Смотреть картинку How to close vim. Картинка про How to close vim. Фото How to close vim

Much to our inconvenience, there is no general method for exiting command-line programs like there is the «X» button for graphical programs.

Many command-line programs follow the theme of using either Q (e.g. man and top ) or Ctrl + C (e.g. ping and watch ) to exit, but this varies considerably, especially among text editors:

Editors like this are traps for the inexperienced. My personal preference and recommendation is to, when forced to edit text on the command-line, use instead the more self-explanatory Joe’s Own Editor (JOE).

Alongside jondavidjohn’s answer, here are two links that have indispensable information about using vim.

This is a keyboard graphic that shows you what each key does depending on if you’re in edit mode, command mode, or visual mode:

This is the best vim tutorial I’ve ever worked through. It’s conversational and easy to understand, which is due to it’s IRC/instant-messaging format.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *