# Editing in the Terminal

> vim and nano survival: open, edit, save, and (the part everyone fears) quit, without losing your work or your SSH session.


---

# Editing in the Terminal

Sooner or later something puts you inside a text editor in the terminal - a config file on a server, a
commit message, a quick fix over SSH - and there's no mouse, no menus, and no obvious way out. If you've
ever opened `vim`, typed a few characters, watched nothing make sense, and then *couldn't even close it*,
this guide is for you. That panic is normal, it happens to nearly everyone once, and it ends today.

By the end you'll understand *why* people edit in the terminal at all, you'll be able to drive `nano` with
total confidence (it tells you what to do right on the screen), and you'll know vim's one big idea - modes -
which is the key that unlocks everything, including the calm, guaranteed way out.

> ⏭️ This guide assumes you're comfortable moving around in a terminal. If commands like `cd` and `ls`
> still feel shaky, start with [/guides/the-terminal-and-shell](/guides/the-terminal-and-shell) and come
> back - editing makes far more sense once driving the shell is second nature.

## How to read this

- **Scared of vim right now, or stuck in it?** Skip straight to [Phase 3: vim - the mode that traps everyone, and the way out](03-vim-modes-and-escaping.md). The escape sequence is near the top.
- **Want the whole picture?** Read in order. Phase 1 explains *why* this skill exists, Phase 2 gives you a friendly editor you can use today, and Phase 3 demystifies the scary one.

## The phases

1. **[Why edit in the terminal at all](01-why-edit-in-the-terminal.md)** - SSH, servers with no desktop,
   and the moment something drops you into an editor you didn't choose. The mental map of which editor is
   where, and which one to reach for.
2. **[nano: the gentle default](02-nano-the-gentle-default.md)** - open, type, save, and quit, with the
   shortcuts printed right on the screen the whole time. The one editor you can use the minute you learn it.
3. **[vim: the mode that traps everyone, and the way out](03-vim-modes-and-escaping.md)** - the big idea
   (normal vs. insert mode), why that design is powerful instead of cruel, and the exact keystrokes to
   save, quit, and escape - including when you've made a mess and want out clean.


---

# Why edit in the terminal at all

It's a fair question. You have a perfectly good editor on your laptop - VS Code, Notepad, whatever you
like - with a mouse and menus and a friendly Save button. So why would anyone choose to edit text inside a
terminal window, with no mouse and cryptic key combinations? The real answer is that most of the time you
*don't* choose it. Something puts you there, and you need to be able to handle it without panic.

## The moment it actually happens to you

Here's the realistic scene. You connect to a server - a machine in a data center you'll never physically
touch - to fix a setting. You open the connection over **SSH** (the standard way to get a shell on a remote
machine), and you land at a prompt:

```console
$ ssh ada@web-prod-01
ada@web-prod-01:~$ nano /etc/nginx/nginx.conf
```
*What just happened:* You logged into a remote server and asked to edit its web-server config file. There
is no desktop on that machine - no windows, no taskbar, nothing to click. The *only* interface is this text
prompt, and the only way to change that file is a text editor that also lives in the terminal. That's the
whole reason this skill exists: on the machines that run the actual internet, the terminal editor isn't a
preference, it's the only door.

This isn't an edge case. The vast majority of servers run a desktop-free version of Linux precisely *because*
a graphical interface wastes memory and adds attack surface they don't need. So the machines you'll fix,
deploy to, and debug are exactly the ones where you can't reach for a mouse.

## The three situations that drop you into an editor

You'll meet a terminal editor in three common ways. Recognizing which one you're in tells you what to do:

- **You opened it on purpose.** You typed `nano somefile` or `vim somefile` to change a file. You chose the
  editor, so you know which one you're in.
- **A tool opened it *for* you.** Some commands hand you an editor to fill in. The classic is `git commit`
  with no message - it pops you into an editor to type your commit message, and on many systems that editor
  is **vim**. This is the single most common way people end up trapped in vim without ever choosing it.
- **It's the only thing installed.** A stripped-down server might have `vi` (vim's older sibling) and
  nothing friendlier. You don't get a vote; you use what's there.

💡 **Key point.** The reason "how do I quit vim" is one of the most-asked questions on the entire internet
is situation two: a tool drops people into vim, they've never seen it, and there's no visible exit. By the
end of this guide that exact situation will be a non-event for you.

## The mental map: which editor, and which to reach for

Two editors cover almost everything you'll meet. Here's the calm version of when each shows up:

```mermaid
flowchart TD
  Q[You need to edit a file in a terminal] --> Choose{Do you get to choose?}
  Choose -->|Yes| Nano[Use nano<br/>shortcuts shown on screen]
  Choose -->|No, a tool opened it| Vim[Likely vim or vi<br/>learn the escape]
```

**nano - the gentle one.** `nano` is a small, friendly editor that works the way your instincts expect:
you type, the text appears, the arrow keys move the cursor, and a menu of shortcuts sits at the bottom of
the screen *the whole time*. There's nothing hidden. If `nano` is installed - and it usually is - it's the
right pick whenever the choice is yours. Phase 2 makes you fluent in it in about ten minutes.

**vim - the powerful one that's everywhere.** `vim` (and its ancestor `vi`) is on essentially every
Unix-like system that exists, including the most stripped-down ones. It's genuinely powerful once you learn
it, but it has a famously steep first step, because it has *modes* - and not knowing about modes is exactly
what traps people. Phase 3 explains that one idea and hands you the guaranteed way out.

⚠️ **Gotcha.** `nano` is *usually* installed but not *always*, especially on minimal servers and inside
small containers. `vi`/`vim` is the one you can count on being present everywhere. That's the practical
reason it's worth knowing at least enough vim to open a file, make a change, and quit - even if `nano` is
your daily driver.

## For builders

When you're scripting setup for a server or writing instructions for your team, prefer changing config
files with non-interactive tools - `sed`, `tee`, or writing the whole file with a redirect - rather than
telling people to "open it in an editor and change line 14." Interactive editing doesn't automate and isn't
repeatable. Save the hands-on editor for the times you're genuinely poking at one machine by hand; for
anything you'll do twice, let a command do it so it's saveable and shareable.

## Recap

1. On servers and over **SSH** there's often no desktop and no mouse - a terminal editor is the only way to
   change a file.
2. You meet one in three ways: you opened it on purpose, a tool (like `git commit`) opened it for you, or
   it's the only editor installed.
3. **nano** is the gentle default - it shows its shortcuts on screen. Reach for it whenever the choice is
   yours.
4. **vim**/`vi` is everywhere, including the most minimal machines, so it's worth knowing the basics even if
   nano is your favorite.
5. The infamous "stuck in vim" panic comes from a tool dropping you in without warning - and it ends once
   you understand modes.

Let's start with the editor you can use the moment you learn it.

```quiz
[
  {
    "q": "Why do so many servers have no graphical editor like Notepad or VS Code available?",
    "choices": ["Editing text is illegal on servers", "Many servers run desktop-free Linux to save memory and reduce attack surface", "Mice don't work over a network", "Graphical editors only exist on Windows"],
    "answer": 1,
    "explain": "Most servers deliberately skip a desktop environment, so the terminal - and a terminal editor - is the only interface available."
  },
  {
    "q": "What's the most common way people end up inside vim without ever choosing it?",
    "choices": ["The OS opens vim at startup", "A tool like `git commit` drops them into vim to type a message", "Pressing the spacebar launches vim", "vim opens whenever you log in over SSH"],
    "answer": 1,
    "explain": "Running `git commit` with no message opens an editor - often vim - which is why 'how do I quit vim' is so widely asked."
  },
  {
    "q": "Which editor can you rely on being present even on the most stripped-down servers?",
    "choices": ["nano", "VS Code", "vi/vim", "Notepad"],
    "answer": 2,
    "explain": "vi/vim ships on essentially every Unix-like system; nano is usually but not always installed."
  }
]
```


---

# nano: the gentle default

Let's start with the easy one. `nano` is the editor that behaves the way you already expect a text editor to
behave: you type and the letters appear, the arrow keys move the cursor, Backspace deletes. There's no
secret mode to be in and no hidden state. Best of all, it prints its own instructions across the bottom of
the screen at all times, so you're never guessing what to press. If you can read the screen, you can use
nano.

## Opening a file

You launch nano by giving it a filename:

```console
ada@laptop:~$ nano notes.txt
```
*What just happened:* nano opened `notes.txt` for editing. If the file already exists, you see its
contents; if it doesn't exist yet, you get an empty buffer and nano will create the file when you save. The
cursor sits at the top, ready - you can start typing immediately, no mode-switching required.

## What you're looking at

Here's the shape of the nano screen. The important part is the menu glued to the bottom:

```text
  GNU nano 7.2                       notes.txt

Buy milk
Call the plumber
Finish the report

^G Help      ^O Write Out  ^W Where Is   ^K Cut
^X Exit      ^R Read File  ^\ Replace    ^U Paste
```
*What just happened:* The top line is the editor's name and the file you're editing. The middle is your
text - edit it directly with the arrow keys and normal typing. The bottom two rows are the **menu**, and
they're the whole reason nano is friendly: every command you need is printed right there, all the time.

📝 **Reading the menu.** The `^` symbol means the **Ctrl** key. So `^O` means "hold Ctrl and press O," and
`^X` means "hold Ctrl and press X." (You don't need to use a capital letter - `Ctrl+O` and `Ctrl+o` are the
same.) On a Mac, it's still the **Ctrl** key here, *not* Command - nano follows the Unix convention. The two
you'll use constantly are `^O` to save and `^X` to quit.

## Editing: it's exactly what you'd guess

There's almost nothing to learn for basic editing, because nano works on instinct:

- **Type** anywhere to insert text at the cursor.
- **Arrow keys** move the cursor up, down, left, right.
- **Backspace / Delete** remove characters, as always.
- **Enter** makes a new line.

That's the whole everyday toolkit. No mode to enter, no command to type first. The cursor is where your
next character lands, and what you type is what you get.

## Saving: Ctrl+O ("Write Out")

To save, press **Ctrl+O**. nano calls saving "Write Out" - think *output to disk* - which is why the
shortcut is the letter O. It then asks you to confirm the filename:

```text
File Name to Write: notes.txt
^G Help          M-D DOS Format   M-A Append
^C Cancel        M-M Mac Format   M-P Prepend
```
*What just happened:* nano is confirming where to save. The filename you opened is already filled in, so
press **Enter** to accept it and write the file. (Type a different name first if you want to save a copy
elsewhere.) After you press Enter, you're back in your text with the changes safely on disk - nano stays
open so you can keep editing.

💡 **Key point.** Saving and quitting are two separate steps in nano, and that's a feature. `Ctrl+O` saves
*without leaving*, so you can save your work mid-edit as often as you like - a good habit over a flaky SSH
connection, where saving often means a dropped connection costs you seconds of work instead of an hour.

## Quitting: Ctrl+X

To leave nano, press **Ctrl+X**. If everything is already saved, nano closes immediately and drops you back
at the shell prompt. If you have *unsaved* changes, nano won't let you lose them by accident - it asks:

```text
Save modified buffer?
 Y Yes
 N No           ^C Cancel
```
*What just happened:* nano noticed unsaved changes and is protecting you. Press **Y** to save then quit,
**N** to quit and *throw away* your changes, or **Ctrl+C** to cancel and stay in the editor. If you press
**Y**, it then asks you to confirm the filename (same as `Ctrl+O`) - press **Enter** and you're done.

⚠️ **Gotcha.** Pressing **N** here means "quit *without* saving" - your edits since the last save are gone
for good. If you're not sure whether you want to keep your changes, choose **Ctrl+C** to cancel, look at
your work, and decide deliberately. There's no undo once you've quit.

## The one full workflow, start to finish

Put it together and editing a file in nano is four moves:

```text
1. nano somefile      → open it
2. (type your edits)  → arrow keys + normal typing
3. Ctrl+O, Enter      → save (Write Out, confirm filename)
4. Ctrl+X             → quit back to the shell
```
*What just happened:* That's the complete loop - open, edit, save, quit. There's no fifth secret step and
no mode to escape. Once these four are in your fingers, nano is a solved problem and you can edit any file
on any machine that has it.

## A couple of handy extras (optional)

You don't need these to be productive, but they come up:

- **Ctrl+W** ("Where Is") - search for text. Type your search term, press Enter, and the cursor jumps to the
  next match.
- **Ctrl+K** cuts the current line; **Ctrl+U** pastes it back. Press `Ctrl+K` a few times in a row to cut
  several lines, then `Ctrl+U` to drop them somewhere else.

📝 **Note.** Some nano versions show `M-` shortcuts in the menu - `M` means the **Meta** key, which is
**Alt** on most keyboards (and **Esc** pressed-then-released on many Macs). You can safely ignore all of
these while you're learning; the `Ctrl` shortcuts cover everything in this phase.

## For builders

nano respects an environment variable called `EDITOR`. If you set `export EDITOR=nano` in your shell's
startup file (like `~/.bashrc`), then tools that open an editor for you - `git commit`, `crontab -e`, and
many others - will use nano instead of vim. That one line turns the scariest "a tool opened vim" moments
into the friendly editor you already know. (If that didn't fully land, the next phase makes sure vim holds
no fear either way.)

## Recap

1. Open a file with `nano filename`; start typing immediately - there's no mode to enter.
2. The **menu at the bottom** shows every shortcut, always. `^` means **Ctrl**.
3. **Ctrl+O** saves ("Write Out") without leaving - confirm the filename with Enter.
4. **Ctrl+X** quits; if there are unsaved changes, nano asks before letting you lose them.
5. The full loop is four moves: open, edit, `Ctrl+O`, `Ctrl+X`.

nano is the easy one. Now let's defang the editor everyone fears - and it all comes down to a single idea.

```quiz
[
  {
    "q": "In nano's on-screen menu, what does `^O` mean?",
    "choices": ["Press Option then O", "Hold Ctrl and press O", "Type a caret then the letter O", "Press O twice"],
    "answer": 1,
    "explain": "The `^` symbol stands for the Ctrl key, so `^O` means Ctrl+O - nano's command for saving ('Write Out')."
  },
  {
    "q": "You've made edits and press Ctrl+X. nano asks 'Save modified buffer?'. What does pressing N do?",
    "choices": ["Saves and quits", "Quits and discards your unsaved changes", "Renames the file", "Cancels and stays in nano"],
    "answer": 1,
    "explain": "N means quit without saving - your changes since the last save are lost. Ctrl+C cancels and keeps you in the editor."
  },
  {
    "q": "Why is it useful that Ctrl+O saves without quitting?",
    "choices": ["It compresses the file", "You can save often mid-edit, so a dropped connection costs little work", "It locks the file from other users", "It automatically commits to git"],
    "answer": 1,
    "explain": "Saving and quitting being separate lets you save frequently - handy over a flaky SSH link where a drop could otherwise cost a lot of work."
  }
]
```


---

# vim: the mode that traps everyone, and the way out

If a tool dropped you into vim right now and you need out, here it is first, no theory required: press
**`Esc`**, then type **`:q!`** and press **Enter**. That quits and discards any changes. To save your work
on the way out instead, press **`Esc`**, type **`:wq`**, and press Enter. That's the famous escape, and the
rest of this phase explains *why* it works so it stops feeling like a magic spell.

## The one idea behind everything: modes

The thing nobody told you the first time, the thing that makes vim feel broken when you don't know it:
**vim has modes**. The same keys on your keyboard do *completely different things* depending on which mode
you're in.

```mermaid
flowchart LR
  Normal[NORMAL mode<br/>keys are COMMANDS<br/>h j k l move, : runs commands]
  Insert[INSERT mode<br/>keys are TEXT<br/>typing inserts characters]
  Normal -->|press i| Insert
  Insert -->|press Esc| Normal
```

**Normal mode** is where vim starts. Letter keys are *commands*, not text - `i` doesn't type "i", it means
"start inserting"; `x` deletes a character. This is why beginners panic: they start typing, the cursor jumps
around and things vanish, because vim is reading every keystroke as a command. Nothing is broken.

**Insert mode** is where you actually type text - letters appear, Backspace deletes, Enter makes a new
line, exactly as expected. This is the mode you spend your typing time in.

💡 **Key point.** The entire "vim is impossible" experience comes from not knowing you start in *normal*
mode. Switch to insert before typing, switch back to normal before giving commands. Two modes, one toggle -
learn it and vim stops fighting you.

## Switching between the two modes

Two keystrokes run the whole dance:

- **Press `i`** (in normal mode) to enter **insert mode**. Think *i* for *insert*. Now type normally.
- **Press `Esc`** (in insert mode) to return to **normal mode**. `Esc` always takes you back to normal,
  from anywhere. When in doubt, press `Esc`.

When you're in insert mode, vim usually shows `-- INSERT --` at the very bottom of the screen so you can
tell. If you don't see it, you're in normal mode.

```text
~
~
-- INSERT --
```
*What just happened:* the `-- INSERT --` marker confirms you're in insert mode, so keys now become text.
(The `~` lines just mark empty rows below the file - not content.) Press `Esc` and the marker disappears -
you're back in normal mode.

⚠️ **Gotcha.** When you're lost, your reflex should be **`Esc`**. It's harmless to press in normal mode (it
stays put) and it always escapes insert mode. Pressing `Esc` first is what makes the `:wq` / `:q!`
commands work - those commands are only understood in normal mode, so you *must* leave insert mode before
typing them.

## The colon: giving vim a command

In normal mode, pressing **`:`** moves the cursor to the bottom of the screen and lets you type a command,
ending with Enter. The colon commands you actually need are short:

```text
:w      → write (save) the file, stay open
:q      → quit (only works if there are no unsaved changes)
:wq     → write then quit (save and exit)  ← the common one
:q!     → quit, force, discarding changes   ← the escape hatch
```
*What just happened:* These four cover everything for survival. `:w` saves, `:q` quits a clean file, `:wq`
does both in one go, and `:q!` forces a quit even with unsaved changes. The `!` means "I mean it, do it
anyway" - it's what you use when you've made a mess and want to bail without saving.

📝 **Why `:q` sometimes refuses.** If you try `:q` after changing the file, vim stops you with
`E37: No write since last change` - it's refusing to silently lose your edits, the same protective instinct
nano has. Your two real answers are `:wq` (keep the changes) or `:q!` (throw them away). vim won't decide
for you.

## The full survival workflow

Put the pieces together and editing a file in vim is a clear sequence:

```console
ada@laptop:~$ vim notes.txt
```
That opens in **normal mode** - don't start typing yet. Now the loop, step by step:

```text
1. vim somefile     → opens in NORMAL mode (keys are commands)
2. press  i         → switch to INSERT mode (you see -- INSERT --)
3. type your edits  → text behaves normally now
4. press  Esc       → back to NORMAL mode
5. type  :wq  Enter → save and quit
```
*What just happened:* the complete, safe round trip - open, `i` to insert, type, `Esc`, `:wq`. The two
moments that trip everyone are step 2 (enter insert mode before typing) and step 4 (press `Esc` before
`:wq`). Once those are muscle memory, vim is just an editor with one extra concept.

## When you've made a mess and want out clean

You mashed keys in confusion and don't know what state the file is in. Here's the calm exit - the scenario
from the top of the phase, now with the *why* attached:

```text
1. Press  Esc       → guarantees you're in NORMAL mode
2. Type   :q!       → quit, discard ALL changes
3. Press  Enter     → you're back at the shell, file untouched
```
*What just happened:* `Esc` gets you to normal mode no matter what you'd been doing, and `:q!` quits while
throwing away every change since you opened the file - none of it hits disk. This is the sequence to
remember for life; it's the answer to "help, I'm stuck in vim."

## A few normal-mode moves worth knowing (optional)

You can survive on insert mode and `Esc` alone, but a handful of normal-mode commands make vim pleasant.
Press `Esc` first to be sure you're in normal mode, then:

- **`h` `j` `k` `l`** - move the cursor left, down, up, right. (The arrow keys also work in modern vim; the
  letters are the classic muscle memory.)
- **`x`** - delete the character under the cursor.
- **`dd`** - delete (cut) the whole current line.
- **`u`** - undo the last change. Press it repeatedly to walk back through your edits.
- **`/word`** then Enter - search forward for `word`; press `n` for the next match.

💡 **Key point.** That `u` for undo is the gentle companion to `:q!`. If you only damaged one thing, you
don't have to throw away everything with `:q!` - press `Esc`, tap `u` until the damage is undone, then save
normally with `:wq`. Undo first, nuke only as a last resort.

## vi vs vim - the same survival skills

On older or minimal systems the command might be `vi` rather than `vim` ("vim" stands for *vi improved*).
For everything in this guide - modes, `i`, `Esc`, `:wq`, `:q!` - they behave the same. The escape you
learned works in both. If `vim` isn't found, try `vi`; if `vi` opens, you already know what to do.

## For builders

If a tool keeps dropping you into vim and you'd rather it didn't, add `export EDITOR=nano` (or
`export EDITOR=vim`) to your shell startup file - `git commit` and `crontab -e` will honor it. Either way,
knowing the `Esc` → `:wq` / `:q!` escape means you're never trapped again, regardless of what a tool throws
at you. (Shell itself still shaky? [/guides/the-terminal-and-shell](/guides/the-terminal-and-shell) and
[/guides/linux-from-zero](/guides/linux-from-zero) are the natural next reads.)

## Recap

1. vim's one big idea is **modes**: in **normal mode** keys are commands; in **insert mode** keys are text.
2. Press **`i`** to enter insert mode (you'll see `-- INSERT --`); press **`Esc`** to return to normal mode.
3. Colon commands run in normal mode: `:w` save, `:q` quit, **`:wq`** save-and-quit, **`:q!`** quit and
   discard.
4. The universal escape: **`Esc`** then **`:q!`** then **Enter** quits and throws away every change - the
   file on disk is untouched.
5. `u` undoes one change at a time, so you can fix a small mistake instead of discarding all your work; and
   `vi` behaves like `vim` for all of this.

That's it - you can now open, edit, save, and (the part everyone feared) *quit* both editors you'll ever
meet in a terminal, on your laptop or on a server you've never seen.

```quiz
[
  {
    "q": "You opened vim and start typing your text, but the cursor jumps around and characters vanish. What's actually going on?",
    "choices": ["vim is broken and needs reinstalling", "You're in normal mode, where keys are commands, not text", "The file is read-only", "Your keyboard is in the wrong language"],
    "answer": 1,
    "explain": "vim starts in normal mode, where letters are commands. Press i to enter insert mode before typing text."
  },
  {
    "q": "You've made accidental edits and want to quit vim WITHOUT saving them. What's the sequence?",
    "choices": ["Type :wq and press Enter", "Press Esc, type :q!, press Enter", "Press Ctrl+X", "Type :save then quit"],
    "answer": 1,
    "explain": "Esc guarantees normal mode, and :q! forces a quit while discarding all changes - the file on disk stays untouched."
  },
  {
    "q": "What's the difference between :wq and :q! in vim?",
    "choices": ["They're identical", ":wq saves then quits; :q! quits and discards changes", ":wq quits without saving; :q! saves", ":wq works only in insert mode"],
    "answer": 1,
    "explain": ":wq writes (saves) and then quits, while :q! force-quits and throws away any unsaved changes."
  }
]
```
