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.
Matching infrastructure at centron
No hardware needed to follow along: ccloud³ VMs with full root access start at €3.12 per month, billed by the hour and ready in seconds. Rent a cloud server →
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, lor 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 FILENAMETo create a file named vimExample, run:
$ vim vimExampleThis 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 existingFileIf the file exists, it opens for editing. If not, a new buffer appears to start a new file.
To open multiple files:
$ vim file1 file2Files open in separate buffers. Use these to toggle between them:
:nor:next: Go to the next file.:prevor: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
ito enter Insert mode. - Type your content.
- Press
Escto return to Normal mode.
Undo and Redo Edits
To revert recent changes:
uin Normal mode undoes the last change.Ctrl + rredoes 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:
:wTo 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:
:/patternTo visually highlight all matches, execute:
:set hlsearchTo turn off highlighting, run:
:nohlsearchReplacing Text
To substitute one string for another across the entire file, use:
:%s/old/new/gReplace 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/gTo show line numbers for reference, enter:
:set numberIf you prefer to confirm each substitution, include the c flag:
:%s/old/new/gcYou 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
vto enter Visual mode. - Use arrow keys or
h, j, k, lto highlight the desired text. - Press
dto cut it.
To cut an entire line:
- Use
ddin Normal mode.
To cut multiple lines:
- Type
dfollowed by a movement like3jto 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
yto copy the selection.
Copy a single line in Normal mode using:
yyTo copy multiple lines, use a command like:
y3jPasting Text
To paste copied or cut text:
- Use
pto paste after the cursor. - Use
Pto paste before the cursor.
To paste multiple times, use:
NpReplace 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:
ddTo delete a line without saving it:
"_ddRemove 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:
3ddTo delete without storing them:
"_3ddDelete Until the End of the File
To remove all lines from the current line to the file’s end:
dGWithout storing them:
"_dGDelete From Current Position to File Start
To erase lines up to the beginning of the document:
dggSkip saving by using:
"_dggPersonalizing 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 ~/.vimrcAdd these settings as needed:
Enable line numbering:
set numberTurn on syntax highlighting:
syntax onHighlight matching brackets:
set showmatchHighlight the active line:
set cursorlineUsing Color Schemes and Themes
Vim supports color profiles to improve aesthetics and readability. Check the current theme with:
:colorschemePressing 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 habamaxTo persist this color scheme across sessions, append to .vimrc:
colorscheme habamaxCreating Custom Key Bindings
Vim lets you remap keys for efficiency. Open .vimrc using:
$ vim ~/.vimrcMap qq to exit Insert mode:
inoremap qq <Esc>Map Ctrl + S to save:
nnoremap <C-s> :w<CR>
inoremap <C-s> <Esc>:w<CR>aMap 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.vimConfigure Plugins in .vimrc
Edit the configuration file:
$ vim ~/.vimrcAdd 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:
:PlugInstallManage Plugins
Update all plugins:
:PlugUpdateRemove unused plugins:
:PlugCleanList installed plugins:
:PlugStatusTo 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:
:wqTo exit and discard modifications:
:q!To exit Vim normally without saving (if no changes were made):
:qTo exit all open buffers and files:
:qaTo 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 vimTesten Sie Ihr Setup auf ccloud³
Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.