How to exit Vim?

Exiting Vim can be confusing for new users because Vim operates in modes (e.g., Normal mode, Insert mode), and quitting requires specific commands. Below is a detailed guide with examples to exit Vim gracefully.

Step-by-Step Guide to Exit Vim

1. Ensure You’re in Normal Mode

Vim commands only work in Normal mode (not Insert mode).

  • If you’re in Insert mode (where you can type text), press Esc to return to Normal mode.
  • Check the bottom-left corner of the screen: if you see -- INSERT --, you’re in Insert mode.

2. Basic Exit Commands

Once in Normal mode, use one of these commands:

CommandAction
:qQuit Vim (fails if unsaved changes exist).
:q!Force quit without saving changes (discards edits).
:wqSave changes and quit (write + quit).
:wq!Force save and quit (useful for read-only files if you have sudo).
:xSave (if changes exist) and quit (similar to :wq).
ZZ (Shift + zz)Save and quit (shortcut for :wq).
:qaQuit all open windows/tabs (if using splits or multiple files).

Examples

Example 1: Quit Without Saving Changes

  1. Press Esc to ensure you’re in Normal mode.
  2. Type :q! and press Enter.
  • This exits Vim and discards all unsaved changes.

Example 2: Save and Quit

  1. Press Esc.
  2. Type :wq and press Enter.
  • Saves changes to the file and exits.

Example 3: Save and Quit with a Filename

If you forgot to name the file when opening Vim:

  1. Press Esc.
  2. Type :wq filename.txt and press Enter.
  • Saves the file as filename.txt and exits.

Example 4: Quit Multiple Windows/Tabs

If you have split screens or tabs:

  1. Press Esc.
  2. Type :qa! and press Enter.
  • Closes all open files/windows without saving.

Common Mistakes & Fixes

  1. “E37: No write since last change”
  • You modified the file but didn’t save. Use :q! to discard changes or :wq to save.
  1. “E212: Can’t open file for writing”
  • You don’t have write permissions. Save with sudo:
    bash :w !sudo tee % # Force-save with sudo :q! # Then quit
  1. Stuck in Visual/Command Line Mode
  • Press Esc repeatedly to return to Normal mode.

Last Resort: Force-Kill Vim

If you’re truly stuck:

  1. Open a new terminal window.
  2. Find the Vim process ID:
   ps aux | grep vim
  1. Kill the process:
   kill -9 <process_id>
  • Warning: This discards all unsaved changes.

Summary Table

ScenarioCommand
Quit without changes:q
Discard changes and quit:q!
Save and quit:wq or ZZ
Save as root (permission fix):w !sudo tee %
Quit all windows/tabs:qa!

Pro Tips

  • Memorize Esc:q! as the universal “get me out of Vim” command.
  • Use :help quit in Vim to open the official documentation.
  • Practice in a safe environment (e.g., open a test file with vim test.txt).

With these commands, you’ll never be trapped in Vim again!

Leave a Reply

Your email address will not be published. Required fields are marked *