How to Use Vim Text Editor in Linux
Vim, an enhanced version of the Vi editor, is a versatile and open-source text editor available across multiple platforms. It utilizes a modal editing approach, enabling efficient text navigation and modification through keyboard commands. Widely used in Linux for tasks like configuring system files, programming, and scripting, Vim offers advanced functionalities, including multi-level undo, syntax highlighting, command-line editing, and visual text selection.
This guide walks you through using Vim on a Linux system to create, manage, and modify files effectively.
Prerequisites
Before getting started, ensure the following:
- You have access to a Linux environment.
Vim Modes and Essential Commands
Understanding Vim’s modes and associated functions is key to using the editor efficiently. Each mode is designed for specific operations like navigating, editing, selecting, or executing commands. Below are the primary modes in Vim:
Normal Mode
Vim opens in Normal mode by default. In this mode, you can move the cursor, delete or copy lines, and run commands. Press Esc to return to Normal mode from any other mode.
Common Normal mode commands:
- h, j, k, l: Move the cursor left, down, up, and right.
- dd: Delete the current line.
- yy: Copy the current line.
- p: Paste a copied line.
- u: Undo the last action.
- Ctrl + r: Redo the last undone action.
- gg: Go to the beginning of the file.
- G: Go to the end of the file.
Insert Mode
Insert mode allows text input and editing. Switch to this mode from Normal mode using one of the following commands:
- i: Begin inserting text before the cursor.
- a: Append text after the cursor.
- o: Open a new line below the current line.
- O: Open a new line above the current line.
Visual Mode
Visual mode is used for selecting and modifying blocks of text. Activate it from Normal mode using one of these commands:
- v: Start character-wise selection.
- V: Start line-wise selection.
- Ctrl + v: Start block-wise selection.
In Visual mode, the following commands are available:
- h, j, k, l or Arrow keys: Move the cursor and adjust the selection.
- d: Delete selected text.
- y: Copy selected text.
- x: Cut selected text.
- p: Paste over the selected area.
- >: Indent selected lines.
- <: Unindent selected lines.
Command-line Mode
Command-line mode is used for administrative operations like saving, quitting, and changing settings. To enter this mode, press : from Normal mode.
Useful command-line mode commands include:
- :w: Save the current file.
- :q: Exit Vim.
- :wq: Save and exit.
- :q!: Exit without saving.
- :set number: Show line numbers.
- :set nonumber: Hide line numbers.
- :/word: Search for “word” in the file.
Create Files Using Vim
Vim lets you create files directly by specifying the file name when launching the editor. Use the following command format to create a new file with Vim:
$ vim FILENAME
For instance, the command below creates a new file named vimExample
:
$ vim vimExample
This command opens a blank Vim editor where you can write content and then save the file to complete its creation.
After adding your content, press Esc to exit insert mode, then type :wq to save and close Vim.
Open Files Using Vim
Vim is a powerful tool for opening and managing one or more files. Here’s how you can open files and navigate between them using Vim.
To open a file, specify its name after the vim
command as shown below:
$ vim existingFile
This command opens the file named existingFile
for editing. If the file is not present, Vim opens an empty buffer so you can create it.
You can also open multiple files at once by listing them in the command:
$ vim file1 file2
This opens file1
and file2
in separate buffers within Vim.
To navigate between multiple files in Vim, use the following commands:
- :n or :next: Switches to the next file.
- :prev or :previous: Goes back to the previous file.
Edit Files Using Vim
Vim offers flexible tools for editing text, reversing mistakes, and saving changes. You can write or modify content in Insert mode, undo or redo edits, and save files with or without administrative access. The steps below guide you through these actions.
Add Text to the File
To input text, you first need to enter Insert mode. The process below outlines how to begin editing a file:
Open the file using Vim:
$ vim filename
Then press i to enter Insert mode and start typing your content.
Press Esc to return to Normal mode when you’re done editing.
Undo and Redo Changes
You can easily undo and redo changes in Vim, which helps fix errors or revert recent modifications:
- Press u in Normal mode to undo the most recent change.
- Press Ctrl + r to redo the last undone change.
Save Files Using Vim
Once you’ve made changes, save your file by entering command-line mode and using the following command:
:w
To save a file that requires elevated privileges, use the command below:
:w !sudo tee %
This saves the file using superuser permissions. After saving, exit Vim by typing :q and pressing Enter.
Find and Replace Text Using Vim
Vim includes powerful commands for locating and replacing text, making it easy to update or manage content within a file.
Find Text
To search for specific text patterns, use the following command in command-line mode, replacing pattern
with your search term:
:/pattern
To highlight all matches of a pattern:
:set hlsearch
To remove the highlighting:
:nohlsearch
Replace Text
To replace a specific string throughout the entire file, use the following command. Replace old
with the text you want to find and new
with the replacement:
:%s/old/new/g
To restrict the replacement to a specific range of lines, prefix the command with the starting and ending line numbers:
:6,8s/old/new/g
To display line numbers in the file, use:
:set number
If you want to be prompted for confirmation before each replacement, use the c
option:
:%s/old/new/gc
This command will ask for confirmation on each match (press y to replace, a for all, n to skip).
Cut, Copy, and Paste Text Using Vim
This section shows you how to effectively cut, copy, and paste content in Vim. These operations allow you to move or duplicate text quickly and accurately.
Cut Text
To cut text in Vim:
- Press v to enter Visual mode.
- Use arrow keys or h, j, k, l to select the text.
- Press d to cut the selected portion.
Additional cutting methods:
- To cut a single line, press dd in Normal mode.
- To cut several lines, use d followed by a movement. For instance, 3j cuts the current line and the next two lines.
Copy (Yank) Text
To copy text in Vim:
- Press v to enter Visual mode.
- Select the text with arrow keys or h, j, k, l.
- Press y to copy the selected portion.
More ways to copy:
- To copy a single line, use yy in Normal mode.
- To copy multiple lines, press y followed by a movement like 3j to copy the current line and the next two.
Paste Text
To paste previously copied or cut text:
- Press p to paste after the cursor.
- Press P to paste before the cursor.
- To paste multiple times, press a number followed by p (e.g., 3p to paste three times).
Delete Lines in Vim
Vim offers various ways to delete lines. Normally, deleted content is saved in a register, so you can paste it later. To discard it without saving, use the black hole register "_
.
Delete a Single Line
- Place the cursor anywhere on the line and press dd to delete it.
- To delete the line without saving it, use “_dd.
Delete Multiple Lines
- Use ndd to remove multiple lines from the current position (replace n with a number). For example, 3dd deletes the current and next two lines.
- To delete without saving, use “_ndd, like “_3dd.
Delete Lines to the End of File
- Press dG to delete from the current line to the file’s end.
- Use “_dG to delete without saving the content.
Delete Lines at the Beginning of a File
- Press dgg to delete from the current line to the start of the file.
- Use “_dgg to remove lines without saving them.
Customize Vim
Vim provides extensive customization through settings, key mappings, and plugins. The .vimrc
file is the central place to define these configurations, allowing you to adjust the editor’s behavior and interface.
Modify the .vimrc File
The .vimrc
file stores user-specific settings for Vim. Open the file using the following command:
$ vim ~/.vimrc
Add desired settings to tailor Vim to your needs. Below are a few examples:
Show line numbers:
set number
Enable syntax highlighting:
syntax on
Highlight matching brackets:
set showmatch
Highlight the current cursor line:
set cursorline
Customize Colors and Themes in Vim
Vim supports different color schemes to personalize the editor’s appearance. Use the following command to see which theme is active:
:colorscheme
To list all available color schemes, type :colorscheme
followed by a space and press Ctrl + D. You will see a list like:
blue, delek, evening, koehler, murphy, quiet, shine, torte, zellner, darkblue, desert, habamax, lunaperche, pablo, retrobox, slate, wildcharm, default, elflord, industry, morning, peachpuff, ron, sorbet, zaibatsu
To apply a color scheme, use:
:colorscheme habamax
To make the color scheme permanent, add it to your .vimrc
:
colorscheme habamax
Map Custom Keys in Vim
You can create key shortcuts in Vim by mapping keys in your .vimrc
file.
Open .vimrc
:
$ vim ~/.vimrc
Map qq
in Insert mode to switch to Normal mode:
inoremap qq
Map Ctrl + S
to save a file:
nnoremap :w<CR>
inoremap :w<CR>a
Map q
to quit Vim:
nnoremap q :q<CR>
Map Ctrl + V
to paste from the system clipboard:
nnoremap <C-v> "+p
inoremap <C-v> <Esc>"+pi"
Install and Manage Plugins in Vim
Plugins extend Vim’s capabilities. You can manage plugins using a tool like vim-plug
. Follow these steps to install and use it:
Install vim-plug
:
$ curl -fLo ~/.vim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
Edit .vimrc
and define plugins:
call plug#begin('~/.vim/plugged')
Plug 'vim-airline/vim-airline' " Status bar enhancement
Plug 'tpope/vim-commentary' " Easy commenting
call plug#end()
This configuration adds the vim-airline
and vim-commentary
plugins.
Install plugins from within Vim:
:PlugInstall
Managing Plugins Using vim-plug
- Update plugins:
:PlugUpdate
- Remove unused plugins:
:PlugClean
- Check plugin status:
:PlugStatus
To explore more plugins, visit the Vim Awesome website and browse available tools for enhancing your Vim experience.
Exit Vim
There are multiple ways to exit Vim based on whether or not you wish to save changes. Use the following commands depending on your situation:
Save and exit Vim:
:wq
Exit without saving changes:
:q!
Exit Vim (if no changes need to be saved):
:q
Exit all open files:
:qa
Exit all open files without saving changes:
:qa!
Conclusion
You have now learned how to use Vim in Linux for file creation, editing, and navigation. You also explored syntax highlighting, color scheme customization, and key mapping to enhance your workflow. For additional configuration options and advanced usage, enter the following command to access the Vim manual:
man vim