15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
08.10.2024

How to Use Vi/Vim Editor on Ubuntu: A Complete Technical Reference

Vi and Vim (Vi Improved) are modal, keyboard-driven text editors that operate entirely within the terminal, making them indispensable for server administration, remote configuration editing, and scripting workflows on Ubuntu and other Linux distributions. Vim extends Vi with syntax highlighting, multi-level undo, split windows, plugin support, and a scriptable configuration layer — all while consuming negligible system resources.

If you manage a VPS Hosting environment or a bare-metal server, fluency in Vim is not optional — it is a foundational skill. SSH sessions do not always have GUI access, and Vim is almost universally available on every Unix-based system you will ever touch.

Why Vim Still Dominates Server Environments

Modern IDEs are powerful, but they are irrelevant when you are connected to a headless Ubuntu server over SSH at 2 AM debugging a broken Nginx configuration. Vim's modal design means every keystroke is a command — there is no mouse dependency, no rendering overhead, and no latency introduced by a graphical layer.

Key reasons system administrators rely on Vim:

  • Zero external dependencies: Works over any SSH connection, including low-bandwidth or high-latency links
  • Consistent availability: Pre-installed or trivially installable on Debian, Ubuntu, CentOS, Alpine, and virtually every Linux distribution
  • Speed at scale: Editing multi-thousand-line configuration files, log files, or scripts is faster in Vim than in any GUI editor once muscle memory is established
  • Scriptability: Vim's built-in scripting language (Vimscript) and Lua support (in Neovim) allow full automation of repetitive editing tasks

Installing Vim on Ubuntu

Ubuntu ships with a minimal `vim-tiny` package, which lacks syntax highlighting, multi-file support, and many advanced features. For full functionality, install the complete package:

“`bash

sudo apt update

sudo apt install vim -y

“`

To verify the installed version and confirm full feature support:

“`bash

vim –version

“`

Look for `+syntax`, `+clipboard`, `+python3`, and `+multi_byte` in the feature flags. A `-` prefix means that feature was compiled out of the binary. If you need those features and they are absent, install `vim-gtk3` or `vim-nox` instead:

“`bash

sudo apt install vim-nox -y # Headless full-feature build

sudo apt install vim-gtk3 -y # GTK3 build with clipboard integration

“`

Critical edge case: On minimal Ubuntu server images — such as those used in Docker containers or cloud-init bootstrapped Dedicated Servers — even `vi` may be absent. In that case, install `vim` explicitly before attempting any configuration file editing.

Opening, Creating, and Recovering Files

“`bash

vim filename.txt # Open existing file or create new one

vim /etc/nginx/nginx.conf # Open a system configuration file (use sudo if needed)

sudo vim /etc/ssh/sshd_config # Edit privileged files

vim +42 filename.txt # Open file and jump directly to line 42

vim +/searchterm file.txt # Open file with cursor on first match of searchterm

“`

Swap file recovery: Vim automatically creates a hidden swap file (`.filename.txt.swp`) during editing. If your session crashes or the SSH connection drops, reopen the same file and Vim will prompt you to recover unsaved changes. Always choose `(R)ecover` first, save the recovered content, then delete the swap file with `:e` followed by `:!rm ~/.filename.txt.swp` or by running `vim -r filename.txt`.

This recovery mechanism is particularly valuable when editing critical configuration files on production servers — a dropped connection does not mean lost work.

Understanding Vim's Modal Architecture

Vim's modal design is the single most important concept to internalize. Unlike standard editors where every keystroke inserts a character, Vim separates navigation, editing, and command execution into distinct modes.

ModeActivationPrimary Purpose
**Normal**`Esc` (default on open)Navigation, deletion, copying, pasting, macro execution
**Insert**`i`, `a`, `o`, `O`, `I`, `A`Typing and inserting text
**Visual**`v` (character), `V` (line), `Ctrl+v` (block)Selecting text ranges
**Visual Block**`Ctrl+v`Column-based selection and editing
**Command-Line**`:`File operations, search/replace, settings, external commands
**Replace**`R`Overwriting existing characters
**Ex**`Q`Batch command execution (rarely used interactively)

The most common beginner mistake is pressing keys in Normal mode expecting text to appear, then panicking when `dd` deletes a line or `gg` jumps to the top of the file. Always confirm your current mode by checking the bottom-left of the screen — Insert mode displays `– INSERT –`, Visual mode displays `– VISUAL –`, and Normal mode shows nothing.

Efficient navigation is what separates a Vim user who is merely functional from one who is genuinely fast. Learn these in order of priority:

Basic Cursor Movement

KeyAction
`h`Move left one character
`l`Move right one character
`j`Move down one line
`k`Move up one line
`w`Jump to start of next word
`b`Jump to start of previous word
`e`Jump to end of current word
`0`Jump to beginning of line
`^`Jump to first non-whitespace character of line
`$`Jump to end of line

File-Level Navigation

KeyAction
`gg`Jump to first line of file
`G`Jump to last line of file
`:42`Jump to line 42
`Ctrl+f`Scroll one full page forward
`Ctrl+b`Scroll one full page backward
`Ctrl+d`Scroll half page down
`Ctrl+u`Scroll half page up
`%`Jump to matching bracket, parenthesis, or brace
`*`Jump to next occurrence of word under cursor
`#`Jump to previous occurrence of word under cursor

Power user tip: Prefix any motion command with a number to repeat it. `5j` moves down 5 lines. `3w` jumps forward 3 words. `10dd` deletes 10 lines. This numeric multiplier applies to virtually every Normal mode command and is the key to editing at speed.

Entering and Exiting Insert Mode

KeyBehavior
`i`Insert before cursor
`a`Append after cursor
`I`Insert at beginning of line
`A`Append at end of line
`o`Open new line below and enter Insert mode
`O`Open new line above and enter Insert mode
`s`Delete character under cursor and enter Insert mode
`S`Delete entire line and enter Insert mode
`Esc` or `Ctrl+[`Return to Normal mode

Critical habit: Develop the reflex of pressing `Esc` immediately after finishing a text insertion. Staying in Insert mode when you intend to navigate is the source of most accidental edits.

Saving, Quitting, and File Management

These commands are executed from Command-Line mode (press `:` first):

CommandAction
`:w`Save (write) the current file
`:w filename.txt`Save to a new filename
`:q`Quit (only if no unsaved changes)
`:q!`Force quit, discarding all unsaved changes
`:wq` or `:x`Save and quit
`ZZ`Save and quit (Normal mode shortcut)
`ZQ`Quit without saving (Normal mode shortcut)
`:w !sudo tee %`Save a file you opened without sudo privileges

The `:w !sudo tee %` trick is essential knowledge for server administrators. When you open a system file like `/etc/fstab` without sudo and make changes, you cannot save with `:w`. This command pipes the buffer content through `sudo tee` to write the file with elevated privileges — without needing to close and reopen Vim.

Editing Operations: Delete, Copy, Paste, and Undo

Vim's editing model is built on operators + motions. An operator (like `d` for delete or `y` for yank/copy) combined with a motion (like `w` for word or `$` for end of line) creates a precise editing action.

Core Editing Commands

CommandAction
`x`Delete character under cursor
`X`Delete character before cursor
`dd`Delete (cut) entire current line
`D`Delete from cursor to end of line
`dw`Delete from cursor to end of word
`d$`Delete from cursor to end of line
`d0`Delete from cursor to beginning of line
`yy` or `Y`Yank (copy) entire current line
`yw`Yank from cursor to end of word
`p`Paste after cursor (or below current line for line-wise yanks)
`P`Paste before cursor (or above current line)
`u`Undo last change
`Ctrl+r`Redo last undone change
`.`Repeat last change (one of the most powerful commands in Vim)
`~`Toggle case of character under cursor
`>>`Indent current line one level
`<<`Dedent current line one level

The `.` (dot) command is arguably the most underutilized Vim feature among beginners. It repeats your last compound action — if you deleted a word with `dw`, pressing `.` deletes the next word. If you changed a word with `cw` and typed a replacement, `.` applies the same replacement to the next occurrence. This eliminates repetitive manual edits across large files.

Visual Mode: Precise Text Selection

Visual mode provides three selection granularities:

  • `v` — Character-wise visual selection
  • `V` — Line-wise visual selection (selects entire lines)
  • `Ctrl+v` — Block visual selection (column editing)

After making a selection, apply operators:

KeyAction on Selection
`d`Delete selected text
`y`Yank (copy) selected text
`c`Change (delete and enter Insert mode)
`>`Indent selection
`<`Dedent selection
`~`Toggle case of selection
`:`Enter Command-Line mode with range pre-filled

Block visual mode (`Ctrl+v`) real-world use case: You have a configuration file where you need to comment out 15 consecutive lines by prepending `#`. Select the first column of those lines with `Ctrl+v`, navigate down with `j`, press `I` (capital i), type `#`, then press `Esc`. Vim applies the insertion to every selected line simultaneously. This is a task that would require a regex or manual repetition in most other editors.

Search and Replace

Searching

“`

/pattern Search forward for pattern (regex supported)

?pattern Search backward for pattern

n Jump to next match

N Jump to previous match

  • Search forward for word under cursor

Search backward for word under cursor

:noh Clear search highlighting

“`

Search and Replace Syntax

“`

:%s/old/new/g Replace all occurrences in entire file

:%s/old/new/gc Replace all with confirmation prompt for each

:%s/old/new/gi Case-insensitive replace across entire file

:10,20s/old/new/g Replace only within lines 10 through 20

:'<,'>s/old/new/g Replace within visually selected range

:%s/bwordb/new/g Replace whole word only (word boundary anchors)

“`

Regex support: Vim uses its own regex dialect. The `b` word boundary, `d` for digits, `s` for whitespace, and `+` (one or more) are available. For extended regex syntax, prefix with `v`: `:%s/v(foo|bar)/baz/g` matches either "foo" or "bar" and replaces with "baz".

Working with Multiple Files, Buffers, and Split Windows

This is where Vim's power becomes most apparent for complex editing sessions.

Buffers

A buffer is an in-memory representation of a file. Vim can hold many buffers open simultaneously.

“`

:e filename Open a file into a new buffer

:ls or :buffers List all open buffers

:b2 Switch to buffer number 2

:bnext or :bn Switch to next buffer

:bprev or :bp Switch to previous buffer

:bd Delete (close) current buffer

“`

Split Windows

“`

:split filename Horizontal split, open file in upper pane

:vsplit filename Vertical split, open file in right pane

Ctrl+w h/j/k/l Navigate between split panes

Ctrl+w = Equalize split pane sizes

Ctrl+w q Close current pane

“`

Tabs

“`

:tabnew filename Open file in a new tab

:tabnext or gt Switch to next tab

:tabprev or gT Switch to previous tab

:tabclose Close current tab

“`

Practical scenario: When editing a web server's configuration on a VPS with cPanel, you might need to cross-reference the main `nginx.conf` while editing a virtual host file. Open both in a vertical split with `:vsplit /etc/nginx/nginx.conf` and navigate between panes with `Ctrl+w l` and `Ctrl+w h` — no need to close one file to consult the other.

Configuring Vim with .vimrc

The `.vimrc` file in your home directory is Vim's persistent configuration. It is executed as Vimscript every time Vim starts.

“`bash

vim ~/.vimrc

“`

“`vim

" Display settings

set number " Show absolute line numbers

set relativenumber " Show relative line numbers (great for jump commands)

set cursorline " Highlight the current line

set scrolloff=8 " Keep 8 lines visible above/below cursor when scrolling

" Indentation

set autoindent " Copy indent from current line on new line

set smartindent " Context-aware indentation for code

set expandtab " Convert tabs to spaces

set tabstop=4 " Tab width = 4 spaces

set shiftwidth=4 " Indentation width for >> and <<

" Search behavior

set hlsearch " Highlight all search matches

set incsearch " Show matches as you type

set ignorecase " Case-insensitive search

set smartcase " Override ignorecase if search contains uppercase

" Usability

set mouse=a " Enable mouse in all modes

syntax on " Enable syntax highlighting

set encoding=utf-8 " Default encoding

set clipboard=unnamedplus " Use system clipboard for yank/paste

set undofile " Persist undo history across sessions

set undodir=~/.vim/undo " Directory for persistent undo files

" Visual

set showmatch " Briefly jump to matching bracket

set laststatus=2 " Always show status line

set wildmenu " Enhanced command-line completion

“`

Important: The `set undofile` directive creates persistent undo history stored on disk. This means you can close a file, reopen it days later, and still undo changes from the previous session. Create the undo directory before enabling this:

“`bash

mkdir -p ~/.vim/undo

“`

This is particularly valuable when making incremental changes to configuration files on production systems — for example, when tuning PHP-FPM settings or adjusting SSL parameters on a server running SSL Certificates for multiple domains.

Macros: Automating Repetitive Edits

Macros are one of Vim's most powerful and least-used features. A macro records a sequence of keystrokes and replays them.

“`

qa Start recording macro into register 'a'

[actions] Perform any sequence of Normal/Insert mode commands

q Stop recording

@a Replay macro stored in register 'a'

@@ Replay the last executed macro

10@a Replay macro 'a' ten times

“`

Real-world example: You have a CSV file with 200 lines and need to wrap the second field of each line in double quotes. Record the macro on the first line, replay it 199 times with `199@a`, and the transformation is complete in under a second. No scripting required.

Marks and Jumps

Marks allow you to bookmark positions within a file and jump back to them instantly.

“`

ma Set mark 'a' at current cursor position

'a Jump to the line of mark 'a'

`a Jump to the exact position of mark 'a'

'' Jump back to position before last jump

Ctrl+o Jump to previous position in jump list

Ctrl+i Jump to next position in jump list

:marks List all current marks

“`

Vim vs. Nano vs. Emacs: Choosing the Right Terminal Editor

FeatureVimNanoEmacs
**Learning curve**Steep (modal system)MinimalVery steep
**Startup time**Near-instantNear-instantSlower
**Memory usage**Very lowVery lowModerate to high
**Syntax highlighting**FullBasicFull
**Plugin ecosystem**ExtensiveMinimalExtensive
**Macro support**Native, powerfulNoneNative
**Split windows**YesNoYes
**Remote editing**Via SSH nativelyVia SSH nativelyTRAMP protocol
**Config complexity**Moderate (.vimrc)MinimalHigh (Elisp)
**Best for**Power users, sysadminsQuick edits, beginnersDevelopers, Lisp users

For server administration tasks — editing configuration files, writing shell scripts, reviewing logs — Vim provides the best balance of power, availability, and speed. Nano is acceptable for one-off edits when you cannot afford the cognitive overhead. Emacs is a legitimate choice for developers who live in the terminal, but its resource footprint and startup time make it less practical in constrained server environments.

Common Pitfalls and How to Avoid Them

1. Editing production files without a backup

Always create a backup before editing critical system files:

“`bash

sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

sudo vim /etc/nginx/nginx.conf

“`

2. Forgetting to use sudo

If you open a privileged file without sudo and make changes, use `:w !sudo tee %` to save without losing your edits.

3. Confusing registers

When you delete text with `dd`, it goes into the default register `"`. If you then yank something with `yy`, the deleted text is overwritten. To preserve a yank before deleting, use named registers: `"ayy` yanks into register `a`, and `"ap` pastes from it.

4. Leaving swap files on shared systems

Vim swap files in `/tmp` or the working directory can confuse other users or automated processes. Configure a dedicated swap directory in `.vimrc`:

“`vim

set directory=~/.vim/swap//

“`

The double trailing slash causes Vim to encode the full file path in the swap filename, preventing collisions.

5. Line ending issues on cross-platform files

If you edit a file that originated on Windows, it may have CRLF (`rn`) line endings. Vim will display `^M` at the end of each line. Fix this with:

“`bash

:%s/r//g

“`

Practical Key-Takeaway Checklist

Use this as a quick-reference decision matrix before and during Vim sessions:

  • Before editing any production file: Create a timestamped backup with `cp file file.$(date +%Y%m%d%H%M%S).bak`
  • Mode awareness: If keystrokes are not inserting text, press `Esc` and confirm your mode
  • Quick save habit: Press `Esc` then `:w` after every significant change — do not wait until the end
  • Use `:set number` temporarily if you need to navigate to a specific line and do not have it in `.vimrc`
  • For global search/replace: Always test with `:%s/old/new/gc` (with confirmation) before running `:%s/old/new/g` blindly
  • Swap file prompt on open: Always choose `(R)ecover`, save the content, then delete the swap file
  • For column edits: Use `Ctrl+v` block visual mode instead of manual repetition
  • Persistent undo: Configure `set undofile` in `.vimrc` on any server you administer regularly
  • Clipboard integration: If `p` pastes unexpected content, check that `set clipboard=unnamedplus` is set and that `xclip` or `xsel` is installed
  • When in doubt: `:help keyword` opens the built-in documentation for any command or option

Whether you are managing configuration files on Shared Web Hosting environments or maintaining complex infrastructure on Dedicated Servers, Vim's efficiency compounds over time — every command you internalize removes friction from your workflow permanently.

FAQ

Q: What is the difference between Vi and Vim on Ubuntu?

`vi` on modern Ubuntu systems is typically a symlink to `vim` in a reduced compatibility mode, or to `vim-tiny`. True Vi is the original 1976 editor with no syntax highlighting, no multi-level undo, and no plugin support. Vim adds over 100 features on top of Vi while remaining fully backward compatible with Vi keybindings.

Q: How do I exit Vim if I am completely stuck?

Press `Esc` multiple times to ensure you are in Normal mode, then type `:q!` and press Enter. This force-quits without saving. If even that fails (rare, but possible in recursive command states), press `Ctrl+c` first, then `:q!`.

Q: Can Vim edit files over SSH without copying them locally?

Yes. Use `vim scp://user@hostname//path/to/file` to edit remote files directly via SCP. Vim handles the transfer transparently. Alternatively, use `rsync` to pull the file, edit locally, and push back — this is faster for large files.

Q: How do I enable syntax highlighting for a specific file type that Vim does not recognize?

Run `:set filetype=nginx` (or `python`, `yaml`, `bash`, etc.) to manually assign a filetype for the current session. To make it permanent for a specific file extension, add `autocmd BufRead,BufNewFile *.conf set filetype=nginx` to your `.vimrc`.

Q: Is Neovim a better choice than Vim for server use?

For pure server administration tasks, standard Vim is sufficient and more universally available. Neovim offers Lua-based configuration, better async plugin support, and a built-in LSP client — advantages that matter primarily for development workflows. On production servers where you install only what is necessary, Vim remains the pragmatic choice.

15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started