How to Use Vim on Linux for File Creation and Editing
Vim, short for Vi IMproved, is a powerful and open-source text editor available across platforms. It builds on the original Vi by introducing advanced capabilities. Vim is widely used for editing config files, scripting, and coding, especially in Linux environments. It features modal editing, multi-level undo, syntax highlighting, visual selection, and command-line capabilities.
This guide covers how to utilize Vim on Linux systems to generate, handle, and edit files.
Requirements
Ensure the following before starting:
- Access to a Linux machine.
Vim Modes and Essential Functions
Understanding Vim’s modes helps streamline your editing experience. Each mode is tailored for different actions such as editing, navigation, or command execution. Below are the primary modes in Vim.
Normal Mode
By default, Vim opens in Normal mode, where you can navigate, remove lines, copy, paste, and perform other commands. Use Esc to switch back to this mode from any other.
Useful commands in Normal mode include:
h, j, k, l
: Move left, down, up, and right.dd
: Delete current line.yy
: Copy current line.p
: Paste copied line.u
: Undo last action.Ctrl + r
: Redo previously undone change.gg
: Jump to file’s beginning.G
: Jump to file’s end.
Insert Mode
Insert mode allows text input and editing. Activate it from Normal mode using:
i
: Start inserting before the cursor.a
: Start appending after the cursor.o
: Open a new line below.O
: Open a new line above.
Visual Mode
Visual mode enables text selection for manipulation. Trigger it in Normal mode using:
v
: Character-wise selection.V
: Line-wise selection.Ctrl + v
: Block selection.
Within Visual mode, use these commands:
h, j, k, l
or Arrow keys: Navigate through the selection.d
: Delete selection.y
: Copy selection.x
: Cut selection.p
: Overwrite selection with paste.>
: Indent selection.<
: Unindent selection.
Command-Line Mode
Use command-line mode for tasks like saving or quitting. Enter this mode from Normal by typing :
.
Common command-line mode inputs:
:w
: Save changes.:q
: Exit Vim.:wq
: Save and exit.:q!
: Exit without saving.:set number
: Show line numbers.:set nonumber
: Hide line numbers./word
: Search for a specific term.
Creating New Files with Vim
You can initiate new files by including a filename when launching Vim. Use this command syntax:
$ vim FILENAME
To create a file named vimExample
, run:
$ vim vimExample
This opens an empty Vim window. Press Esc to exit Insert mode, then type :wq
to save and close the editor.
Opening Files with Vim
Vim lets you access and manage files efficiently. To open an existing file, run:
$ vim existingFile
If the file exists, it opens for editing. If not, a new buffer appears to start a new file.
To open multiple files:
$ vim file1 file2
Files open in separate buffers. Use these to toggle between them:
:n
or:next
: Go to the next file.:prev
or:previous
: Go back to the previous one.
Editing Files in Vim
Vim offers various methods to modify files, undo/redo changes, and save content.
Insert New Content
To input text:
- Open the target file:
$ vim filename
- Press
i
to enter Insert mode. - Type your content.
- Press
Esc
to return to Normal mode.
Undo and Redo Edits
To revert recent changes:
u
in Normal mode undoes the last change.Ctrl + r
redoes the undone action.
Saving Files with Vim
This section outlines how to preserve your changes in Vim, including instructions for saving files that require administrator rights.
To save a file, use the following command in command-line mode:
:w
To save using elevated permissions, use this command:
:w !sudo tee %
After saving, exit by typing :q
in normal mode and pressing Enter.
Finding and Replacing Text in Vim
Vim includes effective tools to locate and replace content throughout a file. This part covers how to perform searches and replacements efficiently.
Searching for Text
Use the following command in command-line mode to search for specific terms. Replace pattern
with your desired keyword:
:/pattern
To visually highlight all matches, execute:
:set hlsearch
To turn off highlighting, run:
:nohlsearch
Replacing Text
To substitute one string for another across the entire file, use:
:%s/old/new/g
Replace old
with the target text and new
with the replacement. The g
flag ensures all occurrences are updated.
To replace content in specific lines, prefix the command with a line range. For instance, from line 6 to 8:
:6,8s/old/new/g
To show line numbers for reference, enter:
:set number
If you prefer to confirm each substitution, include the c
flag:
:%s/old/new/gc
You will be prompted to approve each change: y to replace, n to skip, and a to apply all changes.
Cutting, Copying, and Pasting Text in Vim
This part demonstrates how to quickly cut, copy, and paste content while working in Vim.
Cutting Text
To cut text:
- Press
v
to enter Visual mode. - Use arrow keys or
h, j, k, l
to highlight the desired text. - Press
d
to cut it.
To cut an entire line:
- Use
dd
in Normal mode.
To cut multiple lines:
- Type
d
followed by a movement like3j
to cut the current line and the next two.
Copying (Yanking) Text
To copy content:
- Activate Visual mode using
v
. - Select the content with arrow keys or
h, j, k, l
. - Press
y
to copy the selection.
Copy a single line in Normal mode using:
yy
To copy multiple lines, use a command like:
y3j
Pasting Text
To paste copied or cut text:
- Use
p
to paste after the cursor. - Use
P
to paste before the cursor.
To paste multiple times, use:
Np
Replace N
with the number of repetitions you want.
Deleting Lines in Vim
Vim provides multiple options to remove lines efficiently. Deleted lines are stored in a register by default, enabling later retrieval via paste. If you want to discard lines without saving them, use the black hole register ("_
).
Remove a Single Line
While in Normal mode, place the cursor on the target line and press:
dd
To delete a line without saving it:
"_dd
Remove Multiple Lines
Use the format ndd
(replace n
with a number) to remove multiple lines. For example, the following deletes three lines starting from the current line:
3dd
To delete without storing them:
"_3dd
Delete Until the End of the File
To remove all lines from the current line to the file’s end:
dG
Without storing them:
"_dG
Delete From Current Position to File Start
To erase lines up to the beginning of the document:
dgg
Skip saving by using:
"_dgg
Personalizing Vim Behavior
Vim can be tailored through custom configurations. Settings are saved in the .vimrc
file, allowing users to define preferences, shortcuts, and install plugins.
Editing the .vimrc Configuration
To edit your .vimrc
file, run:
$ vim ~/.vimrc
Add these settings as needed:
Enable line numbering:
set number
Turn on syntax highlighting:
syntax on
Highlight matching brackets:
set showmatch
Highlight the active line:
set cursorline
Using Color Schemes and Themes
Vim supports color profiles to improve aesthetics and readability. Check the current theme with:
:colorscheme
Pressing Ctrl + D
after typing :colorscheme
lists available options like:
blue, delek, evening, koehler, murphy, quiet, shine, torte, zellner, darkblue, desert, habamax, lunaperche, pablo, retrobox, slate, wildcharm, elflord, industry, morning, peachpuff, ron, sorbet, zaibatsu
Switch the theme to habamax
with:
:colorscheme habamax
To persist this color scheme across sessions, append to .vimrc
:
colorscheme habamax
Creating Custom Key Bindings
Vim lets you remap keys for efficiency. Open .vimrc
using:
$ vim ~/.vimrc
Map qq
to exit Insert mode:
inoremap qq <Esc>
Map Ctrl + S to save:
nnoremap <C-s> :w<CR>
inoremap <C-s> <Esc>:w<CR>a
Map q
to close a file:
nnoremap q :q<CR>
Enable paste via Ctrl + V:
nnoremap <C-v> "+p
inoremap <C-v> <Esc>"+pi"
Installing and Managing Plugins
Vim’s functionality can be extended through plugins. Use vim-plug
to handle installations easily.
Install vim-plug
Run the following command to download the plugin manager:
$ curl -fLo ~/.vim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
Configure Plugins in .vimrc
Edit the configuration file:
$ vim ~/.vimrc
Add the following setup to manage plugins:
call plug#begin('~/.vim/plugged')
Plug 'vim-airline/vim-airline' " Status bar enhancement
Plug 'tpope/vim-commentary' " Easy commenting
call plug#end()
Save and close. Then run the following inside Vim to install the plugins:
:PlugInstall
Manage Plugins
Update all plugins:
:PlugUpdate
Remove unused plugins:
:PlugClean
List installed plugins:
:PlugStatus
To discover more plugins, visit the Vim Awesome plugin directory online.
How to Exit Vim
Vim offers multiple options for exiting based on whether or not you wish to save changes. Below are the key methods for closing the editor.
To save changes and exit:
:wq
To exit and discard modifications:
:q!
To exit Vim normally without saving (if no changes were made):
:q
To exit all open buffers and files:
:qa
To quit all files without saving changes:
:qa!
Conclusion
You’ve successfully learned how to use Vim on a Linux system to create, open, and modify files. This included exploring syntax highlighting, applying custom color themes, and assigning personalized key mappings. For additional details on configuration and command usage, refer to the Vim manual by running the following:
man vim