68 KiB
VIM: Zero to Hero
I. Introduction to VIM
A. What is VIM? B. Why use VIM? C. VIM's Modal Editing Philosophy
II. Getting Started with VIM
A. Installing VIM
B. Opening and Closing Files
C. Basic Navigation
1. Arrow Keys vs. hjkl
2. Word and Line Movements
3. Document Navigation
D. Modes in VIM
1. Normal Mode
2. Insert Mode
3. Visual Mode
4. Command-line Mode
III. Mastering the Basics
A. Editing Text
1. Inserting and Appending Text
2. Deleting, Changing, and Yanking (Copying)
B. Searching and Replacing
1. Basic Search
2. Find and Replace
C. Using the Clipboard
1. Copying and Pasting Lines
2. Copying and Pasting Words
D. Undo and Redo
IV. Leveraging the Power of VIM
A. Text Objects and Motions
1. Word and WORD Text Objects
2. Sentence and Paragraph Text Objects
3. Code Block Text Objects
4. Combining Text Objects with Motions
B. Visual Mode and Text Selection
1. Character-wise Visual Mode
2. Line-wise Visual Mode
3. Block-wise Visual Mode
4. Operating on Selected Text
C. Ex Commands
1. Opening and Saving Files
2. Line Manipulation
3. Searching and Replacing
4. Filtering and Executing External Commands
5. Managing Multiple Files
6. Setting Options
D. Marks and Jumps
1. Setting and Jumping to Marks
2. Using the Jumplist
E. Registers
1. Unnamed Register
2. Named Registers
3. System Clipboard Register
4. Read-Only Registers
V. Customizing VIM
A. The .vimrc File B. Basic Settings C. Key Mappings D. Plugins 1. Plugin Managers 2. Essential Plugins E. Color Schemes
VI. Useful Tips and Tricks
A. Macros
B. Abbreviations
C. Folding
D. Spell Checking
E. Indenting and Formatting Code
VII. Integrating VIM with Other Tools
A. VIM as an IDE
B. VIM and Version Control Systems
C. VIM and Terminal Multiplexers (tmux)
D. VIM and Window Managers (i3)
VIII. Conclusion
A. Embracing the VIM Philosophy
B. Continuous Learning and Improvement
C. VIM Resources and Community
This outline provides a structured path for learning VIM, starting from the basics and gradually progressing to more advanced topics. It covers the essential concepts, commands, and techniques you need to master VIM, including navigation, editing, visual mode, text objects, Ex commands, customization, and integration with other tools.
Feel free to adjust the outline based on your specific needs and learning goals. Remember to practice regularly and refer to the VIM documentation (:help) for more in-depth information on each topic.
VIM: Zero to Hero
I. Introduction to VIM
A. What is VIM?
VIM (Vi IMproved) is a powerful, highly configurable text editor built to enable efficient text editing. It is an improved version of the vi editor, which was developed by Bill Joy in 1976. VIM is designed for users who want to edit text quickly and effectively, using only the keyboard.
B. Why use VIM?
There are several compelling reasons to learn and use VIM:
- Efficiency: VIM is designed to keep your hands on the keyboard, reducing the need to reach for the mouse. This can significantly improve your editing speed and productivity.
- Ubiquity: VIM (or vi) is pre-installed on most Unix-based systems, including Linux and macOS. Knowing VIM allows you to edit text efficiently on almost any system.
- Customizability: VIM is highly configurable, allowing you to tailor the editor to your specific needs and preferences.
- Extensibility: VIM has a large ecosystem of plugins that can extend its functionality, transforming it into a full-fledged IDE for various programming languages.
- Longevity: VIM's key bindings and editing model are deeply ingrained in muscle memory, making it a valuable skill that you can carry with you throughout your career.
C. VIM's Modal Editing Philosophy
One of the key features that sets VIM apart from other text editors is its modal editing philosophy. In VIM, there are several modes, each designed for a specific purpose:
- Normal Mode: Used for navigation and text manipulation. This is the default mode in VIM.
- Insert Mode: Used for inserting new text.
- Visual Mode: Used for selecting text and performing operations on the selection.
- Command-line Mode: Used for entering Ex commands and searching.
By separating the editing process into distinct modes, VIM allows you to perform complex text manipulations efficiently, without relying on cumbersome key combinations or menus.
II. Getting Started with VIM
A. Installing VIM
VIM is pre-installed on most Unix-based systems. However, if you're using Windows or want to install the latest version of VIM, you can follow these steps:
- Windows: Download the installer from the official VIM website (https://www.vim.org) and run it.
- macOS: Use Homebrew to install VIM by running
brew install vimin the terminal. - Linux: Use your distribution's package manager (e.g.,
apt-get install vimon Debian-based systems,yum install vimon Red Hat-based systems).
B. Opening and Closing Files
To open a file in VIM, simply run vim filename in the terminal. If the file doesn't exist, VIM will create a new empty buffer for it.
To save and close a file, use the following Ex commands:
:w- Save the changes to the file.:q- Quit VIM (fails if there are unsaved changes).:wqor:x- Save the changes and quit VIM.:q!- Quit VIM without saving changes.
C. Basic Navigation
1. Arrow Keys vs. hjkl
While you can use the arrow keys to navigate in VIM, it's recommended to use the hjkl keys instead:
h- Move leftj- Move downk- Move upl- Move right
Using hjkl keeps your fingers on the home row, improving your editing efficiency.
2. Word and Line Movements
VIM provides several keys for moving by words and lines:
w- Move to the start of the next wordb- Move to the start of the previous worde- Move to the end of the current word0- Move to the start of the line^- Move to the first non-blank character of the line$- Move to the end of the line
3. Document Navigation
To navigate through the document, you can use the following keys:
gg- Go to the first line of the documentG- Go to the last line of the document:nEnter- Go to linenCtrl+f- Scroll forward one pageCtrl+b- Scroll backward one pageCtrl+d- Scroll down half a pageCtrl+u- Scroll up half a page
D. Modes in VIM
1. Normal Mode
Normal mode is the default mode in VIM. It's used for navigation and text manipulation. To enter normal mode from any other mode, press Esc.
2. Insert Mode
Insert mode is used for inserting new text. To enter insert mode from normal mode, press i. To return to normal mode, press Esc.
3. Visual Mode
Visual mode is used for selecting text and performing operations on the selection. There are three types of visual mode:
- Character-wise visual mode: Press
vto enter this mode. It allows you to select text character by character. - Line-wise visual mode: Press
Vto enter this mode. It allows you to select entire lines. - Block-wise visual mode: Press
Ctrl+vto enter this mode. It allows you to select rectangular blocks of text.
To exit visual mode and return to normal mode, press Esc.
4. Command-line Mode
Command-line mode is used for entering Ex commands and searching. To enter command-line mode from normal mode, press :. To execute a command, press Enter. To return to normal mode without executing a command, press Esc.
This covers the introduction to VIM and the basics of getting started with the editor. In the following sections, we'll dive deeper into mastering VIM's features and leveraging its power for efficient text editing.
III. Mastering the Basics
A. Editing Text
1. Inserting and Appending Text
In normal mode, you can use the following keys to enter insert mode:
i- Insert text before the cursora- Append text after the cursorI- Insert text at the beginning of the lineA- Append text at the end of the lineo- Open a new line below the current line and enter insert modeO- Open a new line above the current line and enter insert mode
2. Deleting, Changing, and Yanking (Copying)
VIM provides a set of operators for manipulating text:
d- Delete textc- Change text (delete and enter insert mode)y- Yank (copy) textp- Put (paste) yanked or deleted text after the cursorP- Put yanked or deleted text before the cursor
These operators can be combined with motions or text objects to specify the range of text to operate on. For example:
dw- Delete from the cursor to the start of the next wordc$- Change from the cursor to the end of the lineyap- Yank a paragraph
B. Searching and Replacing
1. Basic Search
To search for a pattern in VIM, use the / command followed by the pattern you want to search for. Press Enter to perform the search. To find the next occurrence, press n. To find the previous occurrence, press N.
2. Find and Replace
VIM's :substitute command allows you to find and replace text:
:s/old/new- Replace the first occurrence of "old" with "new" on the current line:s/old/new/g- Replace all occurrences of "old" with "new" on the current line:%s/old/new/g- Replace all occurrences of "old" with "new" in the entire file:%s/old/new/gc- Replace all occurrences of "old" with "new" in the entire file, with a prompt for confirmation before each replacement
C. Using the Clipboard
1. Copying and Pasting Lines
To copy (yank) a line, use the yy command in normal mode. To paste the yanked line below the current line, use the p command. To paste the yanked line above the current line, use the P command.
2. Copying and Pasting Words
To copy (yank) a word, use the yiw command in normal mode ("yank inner word"). To paste the yanked word after the cursor, use the p command. To paste the yanked word before the cursor, use the P command.
D. Undo and Redo
VIM maintains an undo tree that allows you to undo and redo changes:
u- Undo the last changeCtrl+r- Redo the last undone changeU- Undo all changes to the current line
IV. Leveraging the Power of VIM
A. Text Objects and Motions
1. Word and WORD Text Objects
VIM distinguishes between words (separated by punctuation or whitespace) and WORDs (separated by whitespace only):
w- Move to the start of the next wordb- Move to the start of the previous worde- Move to the end of the current wordW- Move to the start of the next WORDB- Move to the start of the previous WORDE- Move to the end of the current WORD
These motions can be combined with operators like d, c, and y to operate on words and WORDs.
2. Sentence and Paragraph Text Objects
VIM provides text objects for manipulating sentences and paragraphs:
(- Move to the start of the current sentence)- Move to the end of the current sentence{- Move to the start of the current paragraph}- Move to the end of the current paragraph
These text objects can be combined with operators like d, c, and y to operate on sentences and paragraphs. For example:
dis- Delete the current sentence (excluding the space after the period)cip- Change the current paragraph
3. Code Block Text Objects
VIM provides text objects for manipulating code blocks:
[{- Move to the start of the current code block]}- Move to the end of the current code block
These text objects can be combined with operators like d, c, and y to operate on code blocks. For example:
di{- Delete the contents of the current code block (excluding the braces)ya}- Yank the current code block (including the braces)
4. Combining Text Objects with Motions
Text objects can be combined with numeric arguments to operate on multiple instances. For example:
d2w- Delete the next two wordsc3s- Change the next three sentencesy4p- Yank the next four paragraphs
B. Visual Mode and Text Selection
1. Character-wise Visual Mode
Character-wise visual mode allows you to select text character by character. To enter this mode, press v in normal mode. You can then use motion commands to expand the selection. To operate on the selected text, use operators like d, c, y, p, U (uppercase), u (lowercase), > (indent), and < (unindent).
2. Line-wise Visual Mode
Line-wise visual mode allows you to select entire lines. To enter this mode, press V in normal mode. You can then use motion commands to expand the selection. The same operators mentioned above can be used to operate on the selected lines.
3. Block-wise Visual Mode
Block-wise visual mode allows you to select rectangular blocks of text. To enter this mode, press Ctrl+v in normal mode. You can then use motion commands to expand the selection. This mode is particularly useful for working with tabular data or making column-based edits.
4. Operating on Selected Text
Once you have made a selection in visual mode, you can use various operators to manipulate the selected text:
d- Delete the selected textc- Change the selected text (delete and enter insert mode)y- Yank (copy) the selected textp- Put (paste) the yanked text after the cursorU- Convert the selected text to uppercaseu- Convert the selected text to lowercase>- Indent the selected text<- Unindent the selected text
C. Ex Commands
1. Opening and Saving Files
:e filename- Open "filename" in a new buffer:w- Save the current buffer:sav filename- Save the current buffer as "filename":q- Quit the current buffer (fails if there are unsaved changes):q!- Force quit the current buffer (discards unsaved changes):wqor:x- Save the current buffer and quit:wa- Save all buffers:qa- Quit all buffers (fails if there are unsaved changes):qa!- Force quit all buffers (discards unsaved changes)
2. Line Manipulation
:n- Go to line "n":$- Go to the last line:.- Repeat the last command:m n- Move the current line to after line "n":copy nor:t n- Copy the current line and paste it after line "n":d- Delete the current line:'<,'>d- Delete the visually selected lines
3. Searching and Replacing
:/pattern- Search forward for "pattern":?pattern- Search backward for "pattern":s/old/new- Replace the first occurrence of "old" with "new" on the current line:s/old/new/g- Replace all occurrences of "old" with "new" on the current line:%s/old/new/g- Replace all occurrences of "old" with "new" in the entire file:%s/old/new/gc- Replace all occurrences of "old" with "new" in the entire file with confirmation
4. Filtering and Executing External Commands
:r filename- Insert the contents of "filename" below the cursor:r !command- Execute "command" in the shell and insert its output below the cursor:%!command- Execute "command" in the shell with the entire buffer as input and replace the buffer with the command's output
5. Managing Multiple Files
:e filename- Edit "filename" in a new buffer:bn- Go to the next buffer:bp- Go to the previous buffer:bd- Close (delete) the current buffer:ls- List all open buffers
6. Setting Options
:set option- Enable "option":set nooption- Disable "option":set option=value- Set "option" to "value":set option?- Show the current value of "option":set- Show all modified options:set all- Show all options
Some common options include:
numberornu- Show line numbersrelativenumberorrnu- Show relative line numbersignorecaseoric- Ignore case when searchingsmartcaseorscs- Override "ignorecase" when the search pattern contains uppercase charactersexpandtaboret- Use spaces instead of tabstabstop=norts=n- Set the width of a tab character to "n" spacesshiftwidth=norsw=n- Set the indentation width to "n" spacesautoindentorai- Enable automatic indentation
D. Marks and Jumps
1. Setting and Jumping to Marks
Marks allow you to quickly return to specific locations in your files:
m{a-zA-Z}- Set a mark labeled "{a-zA-Z}" at the cursor position`{a-zA-Z}- Jump to the mark labeled "{a-zA-Z}"''- Return to the last jump position
2. Using the Jumplist
VIM maintains a jumplist that remembers the previous locations you've jumped to:
Ctrl+o- Jump to the previous location in the jumplistCtrl+i- Jump to the next location in the jumplist:jumps- Show the jumplist
E. Registers
1. Unnamed Register
The unnamed register ("") is used by default when you delete, yank, or put text without specifying a register.
2. Named Registers
Named registers ("{a-zA-Z}) allow you to store and recall text:
"{a-zA-Z}d- Delete text into register "{a-zA-Z}""{a-zA-Z}y- Yank text into register "{a-zA-Z}""{a-zA-Z}p- Put the text from register "{a-zA-Z}"
3. System Clipboard Register
The system clipboard register ("+) allows you to interact with the system clipboard:
"+y- Yank text into the system clipboard"+p- Put the text from the system clipboard
4. Read-Only Registers
VIM provides several read-only registers for accessing special information:
"%- Contains the current file name"#- Contains the alternate file name".- Contains the last inserted text":- Contains the last executed command"/- Contains the last searched pattern
This section covers the essential features and commands for mastering VIM and leveraging its power for efficient text editing. In the following sections, we'll explore how to customize VIM, learn some useful tips and tricks, and integrate VIM with other tools.
V. Customizing VIM
A. The .vimrc File
The .vimrc file is used to configure VIM according to your preferences. It is a plain text file that contains VIM commands and is executed every time you start VIM. You can create or edit the .vimrc file in your home directory:
- Unix-like systems:
~/.vimrc - Windows:
%USERPROFILE%\_vimrc
B. Basic Settings
Here are some basic settings you might want to include in your .vimrc file:
" Enable syntax highlighting
syntax on
" Enable line numbers
set number
" Enable relative line numbers
set relativenumber
" Enable auto-indentation
set autoindent
" Convert tabs to spaces
set expandtab
" Set the tab width to 4 spaces
set tabstop=4
set shiftwidth=4
" Enable case-insensitive searching
set ignorecase
" Enable smart case-sensitive searching
set smartcase
" Enable highlighting of search results
set hlsearch
" Enable incremental searching
set incsearch
" Disable creating backup files
set nobackup
set nowritebackup
set noswapfile
C. Key Mappings
You can create custom key mappings in your .vimrc file to simplify common tasks or to make VIM behave more like other editors you're used to. Here are some examples:
" Map the 'jk' key sequence to escape insert mode
inoremap jk <Esc>
" Map 'Ctrl+s' to save the current file
nnoremap <C-s> :w<CR>
" Map 'Ctrl+q' to close the current buffer
nnoremap <C-q> :bd<CR>
" Map 'Ctrl+h/j/k/l' to navigate between split windows
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l
Note: inoremap is used for insert mode mappings, nnoremap is used for normal mode mappings, and <CR> represents the Enter key.
D. Plugins
1. Plugin Managers
Plugin managers make it easy to install, update, and remove VIM plugins. Some popular plugin managers include:
To use a plugin manager, follow the installation instructions in its documentation and add the necessary configuration to your .vimrc file.
2. Essential Plugins
Here are some essential plugins that can greatly enhance your VIM experience:
- NERDTree - A file explorer sidebar
- CtrlP - A fuzzy file finder
- Syntastic - A syntax checking plugin
- vim-surround - Easily manipulate surrounding characters (brackets, quotes, tags, etc.)
- vim-commentary - Easily comment and uncomment lines of code
- vim-fugitive - A Git wrapper for VIM
- vim-airline - A customizable status line and tabline
To install a plugin using a plugin manager, add the necessary configuration to your .vimrc file and run the appropriate installation command provided by the plugin manager.
E. Color Schemes
Color schemes can make your VIM experience more visually appealing and comfortable. Here's how you can install and configure color schemes:
- Download a color scheme file (
.vim) from a source like vim-colors or Vim Colors. - Place the color scheme file in the
~/.vim/colors/directory (create it if it doesn't exist). - Add the following line to your
.vimrcfile to enable the color scheme:Replacecolorscheme <scheme_name><scheme_name>with the name of the color scheme file (without the.vimextension). - Restart VIM for the changes to take effect.
Some popular color schemes include:
Customizing VIM allows you to tailor the editor to your specific needs and preferences, making it a more comfortable and efficient environment for your text editing tasks. Experiment with different settings, key mappings, plugins, and color schemes to find the configuration that works best for you.
Remember to keep your .vimrc file organized and well-commented, as it can quickly grow in complexity as you add more customizations. It's also a good idea to keep your .vimrc file under version control (e.g., in a Git repository) so that you can easily track changes and synchronize your configuration across different machines.
VI. Useful Tips and Tricks
A. Macros
Macros allow you to record a series of keystrokes and replay them later, which can be incredibly useful for automating repetitive tasks.
- To start recording a macro, press
qfollowed by a register name (a-z) in normal mode. For example,qastarts recording a macro in register "a". - Perform the desired sequence of keystrokes.
- To stop recording, press
qagain in normal mode. - To execute the macro, press
@followed by the register name. For example,@aexecutes the macro recorded in register "a". - To execute the macro multiple times, prefix the
@command with a number. For example,10@aexecutes the macro in register "a" 10 times.
Example:
qa
I// <Esc>
j
q
This macro records the following actions:
qastarts recording in register "a"Ienters insert mode at the beginning of the line//inserts "// " (useful for commenting lines in C-style languages)<Esc>exits insert modejmoves down to the next lineqstops recording
To comment out multiple lines using this macro, move the cursor to the first line and execute @a or a numbered prefix like 10@a.
B. Abbreviations
Abbreviations allow you to define shortcuts for frequently used words or phrases. When you type the abbreviation and press the expansion key (usually <Space> or <Enter>), VIM automatically expands it to the full text.
- To create an abbreviation in insert mode, use the following command:
:iabbrev <abbreviation> <expanded_text> - To create an abbreviation that works in both insert and command mode, use:
:abbrev <abbreviation> <expanded_text>
Example:
:iabbrev adr Address
:iabbrev eml example@example.com
Now, when you type "adr" in insert mode and press <Space> or <Enter>, it will expand to "Address". Similarly, "eml" will expand to "example@example.com".
C. Folding
Folding allows you to collapse and expand sections of your code or text, making it easier to navigate and understand the structure of your document.
- To enable folding based on indentation, add the following line to your
.vimrcfile:set foldmethod=indent - To open and close folds:
zoopens the fold under the cursorzccloses the fold under the cursorzRopens all foldszMcloses all folds
- To create manual folds:
zf{motion}creates a fold based on the specified motion. For example,zf2jcreates a fold spanning the current line and the next two lines.- Visual selection +
zfcreates a fold for the selected lines.
Example:
def function1():
# Code for function1
pass
def function2():
# Code for function2
pass
With set foldmethod=indent, VIM will automatically create folds for each function. You can then use zo and zc to open and close the folds, respectively.
D. Spell Checking
VIM has built-in spell checking functionality that can help you catch spelling errors in your text.
- To enable spell checking, use the following command:
:set spell - To move between spelling errors:
]smoves to the next misspelled word[smoves to the previous misspelled word
- When the cursor is on a misspelled word:
z=suggests corrections for the misspelled wordzgadds the word to the spell file as a good wordzwadds the word to the spell file as a wrong (bad) word
- To disable spell checking, use:
:set nospell
Example:
This is a sampple text with a misspeled word.
With spell checking enabled, "sampple" and "misspeled" will be highlighted as misspelled words. You can use ]s and [s to navigate between them, and z= to get suggestions for corrections.
E. Indenting and Formatting Code
VIM provides several commands and settings to help you maintain consistent indentation and formatting in your code.
- To indent lines:
>>indents the current line one level<<unindents the current line one level>{motion}indents lines based on the specified motion<{motion}unindents lines based on the specified motion- Visual selection +
>or<indents or unindents the selected lines
- To set up automatic indentation based on file type, add the following lines to your
.vimrcfile:filetype plugin indent on set autoindent set smartindent - To format an entire file according to predefined rules (e.g., for C-style languages), use:
This command applies the
gg=G=(indent) operation from the first line (gg) to the last line (G).
Example:
def example_function():
x = 10
y = 20
z = 30
return x + y + z
To fix the indentation in this Python code, you can visually select the lines inside the function and press =. VIM will automatically adjust the indentation based on the Python indentation rules.
These tips and tricks can greatly enhance your VIM workflow and make you more productive. As you continue to use VIM, you'll discover more tips and develop your own set of useful commands and configurations.
Remember to practice these techniques regularly and incorporate them into your daily VIM usage. Over time, they will become second nature, and you'll find yourself navigating and editing text with greater speed and efficiency.
VII. Integrating VIM with Other Tools
A. VIM as an IDE - Python and JavaScript
With the right plugins and configurations, VIM can be transformed into a powerful Integrated Development Environment (IDE) for various programming languages, including Python and JavaScript.
For Python:
- Install the following plugins:
- python-mode: Provides Python-specific features like code completion, syntax checking, and more.
- jedi-vim: Offers auto-completion and code navigation using the Jedi library.
- vim-flake8: Integrates the Flake8 linter for Python code style checking.
- Configure your
.vimrcfile:" Enable Python syntax highlighting syntax on filetype plugin indent on " Set up Python-mode let g:pymode_python = 'python3' let g:pymode_lint = 1 let g:pymode_lint_checkers = ['pyflakes', 'pep8'] let g:pymode_rope = 1 " Set up jedi-vim let g:jedi#auto_initialization = 1 let g:jedi#completions_enabled = 1 let g:jedi#auto_vim_configuration = 1 " Set up vim-flake8 autocmd FileType python map <buffer> <F7> :call flake8#Flake8()<CR>
For JavaScript:
- Install the following plugins:
- vim-javascript: Provides improved syntax highlighting and indentation for JavaScript.
- tern_for_vim: Offers auto-completion, function argument hints, and jump-to-definition using the Tern server.
- vim-jsx: Adds JSX syntax highlighting and indentation support.
- Configure your
.vimrcfile:" Enable JavaScript syntax highlighting syntax on filetype plugin indent on " Set up vim-javascript let g:javascript_plugin_jsdoc = 1 let g:javascript_plugin_ngdoc = 1 let g:javascript_plugin_flow = 1 " Set up tern_for_vim let g:tern_show_argument_hints = 'on_hold' let g:tern_map_keys = 1 " Set up vim-jsx let g:jsx_ext_required = 0
These configurations provide a solid foundation for using VIM as an IDE for Python and JavaScript development. You can further customize and extend your setup based on your specific needs and preferences.
B. VIM and Version Control Systems
VIM integrates well with version control systems like Git, enabling you to perform common version control tasks without leaving the editor.
- Install the vim-fugitive plugin, which provides a Git wrapper for VIM.
- Configure your
.vimrcfile:These mappings allow you to quickly access Git commands like" Set up vim-fugitive nmap <leader>gs :Gstatus<CR> nmap <leader>gc :Gcommit<CR> nmap <leader>gp :Gpush<CR> nmap <leader>gd :Gdiff<CR>Gstatus,Gcommit,Gpush, andGdiffusing leader key shortcuts. - Some useful vim-fugitive commands:
:Gstatusopens the Git status window, where you can stage, unstage, and commit changes.:Gcommitopens the commit message window for creating a new commit.:Gpushpushes the current branch to the remote repository.:Gdiffshows the diff of the current file against the last commit.
In addition to vim-fugitive, you can also use plugins like vim-gitgutter to display Git diff markers in the sign column, indicating added, modified, or removed lines.
C. VIM and Terminal Multiplexers (tmux)
Terminal multiplexers like tmux allow you to manage multiple terminal sessions within a single window. Integrating VIM with tmux can greatly enhance your workflow by enabling seamless navigation between VIM and other terminal applications.
- Install tmux on your system (e.g.,
sudo apt-get install tmuxon Ubuntu). - Configure your
.tmux.conffile to enable mouse support and vi-style key bindings:set -g mouse on setw -g mode-keys vi - Install the vim-tmux-navigator plugin, which allows you to use the same key bindings (
Ctrl+h/j/k/l) to navigate between VIM splits and tmux panes seamlessly. - Configure your
.vimrcfile:" Set up vim-tmux-navigator let g:tmux_navigator_no_mappings = 1 nnoremap <silent> <C-h> :TmuxNavigateLeft<cr> nnoremap <silent> <C-j> :TmuxNavigateDown<cr> nnoremap <silent> <C-k> :TmuxNavigateUp<cr> nnoremap <silent> <C-l> :TmuxNavigateRight<cr> - With this setup, you can use
Ctrl+h/j/k/lto navigate between VIM splits and tmux panes effortlessly.
D. VIM and Window Managers (i3)
Tiling window managers like i3 can be used in conjunction with VIM to create a highly efficient and keyboard-driven development environment.
- Install and configure i3 on your system following the official documentation.
- Configure your i3 key bindings to launch and navigate between VIM instances. For example, in your i3 configuration file:
These bindings allow you to launch VIM in a new terminal window using
bindsym $mod+v exec urxvt -e vim bindsym $mod+h focus left bindsym $mod+j focus down bindsym $mod+k focus up bindsym $mod+l focus right$mod+vand navigate between i3 windows using$mod+h/j/k/l. - You can also configure i3 to use specific workspaces for different projects or tasks, and assign VIM instances to those workspaces for quick access.
By integrating VIM with i3, you can create a highly customized and efficient development environment that maximizes screen real estate and minimizes the need for mouse usage.
Integrating VIM with other tools and platforms can significantly enhance your productivity and streamline your workflow. Experiment with different combinations and find the setup that best suits your needs and preferences.
Remember to refer to the documentation and guides specific to each tool or plugin for more detailed information on installation, configuration, and usage.
VIII. Conclusion
A. Embracing the VIM Philosophy
Learning and mastering VIM is not just about memorizing a set of commands and key bindings; it's about embracing a philosophy of efficient and keyboard-driven text editing. The VIM philosophy emphasizes:
- Modal editing: By separating the tasks of navigating, editing, and manipulating text into distinct modes, VIM allows you to perform complex operations with minimal keystrokes.
- Composability: VIM's commands and motions are designed to be composable, enabling you to combine them in countless ways to achieve your desired results.
- Repeatability: VIM's
.command and macros make it easy to repeat complex editing tasks, saving you time and effort. - Customization: VIM is highly configurable and can be extensively customized to suit your specific needs and preferences.
By embracing the VIM philosophy and incorporating it into your workflow, you can significantly improve your editing efficiency and productivity.
B. Continuous Learning and Improvement
Mastering VIM is a continuous journey of learning and improvement. As you become more comfortable with the basic commands and concepts, you'll naturally start exploring more advanced features and techniques.
- Make a habit of regularly reviewing and practicing the commands and concepts you've learned. The more you use VIM, the more ingrained the muscle memory will become.
- Explore new plugins and configurations to extend VIM's functionality and tailor it to your needs. The VIM ecosystem is vast and constantly evolving, so there's always something new to discover.
- Challenge yourself to use VIM for increasingly complex tasks and projects. As you gain confidence, you'll find yourself relying less on other editors and tools.
- Learn from others in the VIM community. Participate in forums, read blog posts and articles, and study the configurations and workflows of experienced VIM users.
Remember that becoming proficient in VIM is a gradual process, and it's okay to take your time. Focus on incorporating one new concept or technique at a time, and soon you'll be navigating and editing text with ease.
C. VIM Resources and Community
One of the greatest strengths of VIM is its vibrant and supportive community. There are numerous resources available to help you learn, troubleshoot, and connect with other VIM enthusiasts.
- Official documentation: VIM's built-in
:helpcommand provides comprehensive documentation on every aspect of the editor. It's an invaluable resource for learning and reference. - Online tutorials and guides:
- Vim Tips Wiki: A collection of tips, tricks, and best practices contributed by the VIM community.
- Vim Galore: An extensive guide to VIM, covering everything from basic usage to advanced customization.
- Vim Casts: A series of screencasts on VIM topics, ranging from beginner to advanced.
- Books:
- "Practical Vim" by Drew Neil: A comprehensive guide to VIM, focusing on practical usage and best practices.
- "Learning the vi and Vim Editors" by Arnold Robbins, Elbert Hannah, and Linda Lamb: A classic guide to vi and VIM, suitable for beginners and experienced users alike.
- Community forums and resources:
- Vim Subreddit: An active community of VIM users, offering discussions, news, and resources.
- Vim Stack Exchange: A question and answer site dedicated to VIM, where you can find solutions to common problems and learn from others' experiences.
By engaging with the VIM community and exploring the wealth of available resources, you'll find endless opportunities to learn, grow, and share your own knowledge and experiences.
Conclusion: Congratulations on taking the first steps in your journey to mastering VIM! With practice, patience, and a willingness to learn, you'll soon be navigating and editing text with unparalleled speed and efficiency.
Remember, the true power of VIM lies not just in its individual commands and features, but in how you combine and apply them to solve real-world editing challenges. As you continue to explore and customize VIM, you'll develop your own unique workflow and style.
Embrace the VIM philosophy, stay curious, and never stop learning. The more you invest in mastering VIM, the more it will reward you with a lifetime of productive and enjoyable text editing.
Happy VIMming!
Certainly! Let's add a section on best practices and common pitfalls, as well as a troubleshooting section to address common issues and provide solutions. These additions will help users avoid mistakes, develop good habits, and overcome common challenges they may encounter while using Vim.
Best Practices and Common Pitfalls
Develop a Consistent Workflow
- Establish a consistent workflow that leverages Vim's modal editing and key bindings to minimize hand movements and optimize efficiency.
- Practice using Vim's native navigation and editing commands instead of relying on arrow keys or mouse input.
- Regularly review and refine your workflow to identify areas for improvement and incorporate new techniques as you learn them.
Use Vim's Built-in Help System
- Familiarize yourself with Vim's extensive built-in help system by typing
:helpfollowed by a keyword or command. - Explore the help documentation to discover new features, commands, and options that can enhance your Vim experience.
- Consult the help system whenever you encounter an unfamiliar command or want to learn more about a specific feature.
Maintain a Well-Organized .vimrc
- Keep your
.vimrcfile well-structured and documented with comments explaining each section and setting. - Regularly review and clean up your
.vimrc, removing unused settings and plugins to keep it lean and maintainable. - Use version control (e.g., Git) to track changes to your
.vimrcand easily revert or share your configuration.
Avoid Overreliance on Plugins
- While plugins can greatly enhance Vim's functionality, be cautious not to overload your setup with too many plugins, as they can impact performance and stability.
- Thoroughly evaluate each plugin before installing it, considering its purpose, maintainability, and compatibility with your Vim version and other plugins.
- Prioritize learning Vim's built-in features and commands before relying on plugins for functionality that Vim may already provide.
Embrace Incremental Learning
- Start with the essential Vim commands and gradually incorporate more advanced techniques and customizations as you become comfortable with the basics.
- Focus on mastering a subset of commands and features that are most relevant to your workflow before moving on to more advanced topics.
- Regularly practice and reinforce your Vim skills through deliberate use and by exploring new challenges or projects.
Troubleshooting Common Issues
Issue: "I can't exit Vim!"
Solution:
- To exit Vim, ensure you are in Normal mode (press
Escto return to Normal mode). - Type
:qand pressEnterto quit Vim if you haven't made any changes, or:q!to force quit and discard any unsaved changes. - If you want to save your changes before quitting, type
:wqand pressEnter.
Issue: "My .vimrc settings aren't taking effect."
Solution:
- Ensure that your
.vimrcfile is located in the correct directory (e.g.,~/.vimrcon Unix-based systems or%USERPROFILE%\_vimrcon Windows). - Verify that the settings in your
.vimrcare correctly formatted and free of syntax errors. - Restart Vim or source your
.vimrcfile by executing:source ~/.vimrcto ensure the changes take effect.
Issue: "Vim is not displaying syntax highlighting."
Solution:
- Verify that syntax highlighting is enabled in your
.vimrcby ensuring thatsyntax onis present and uncommented. - Check that the file type is recognized correctly by Vim. You can set the file type manually using
:set filetype=languagename(e.g.,:set filetype=pythonfor Python files). - Ensure that your terminal or color scheme supports syntax highlighting and is configured correctly.
Issue: "I accidentally deleted or modified text. How do I recover it?"
Solution:
- Vim keeps track of your changes in a buffer. To undo the last change, press
uin Normal mode. To continue undoing previous changes, pressuagain. - To redo changes that were undone, press
Ctrl+rin Normal mode. - Vim also supports a persistent undo feature. Ensure that
set undofileis present in your.vimrcto enable persistent undo. You can then use:earlierand:latercommands to navigate through the undo history.
Issue: "Vim is not indenting my code correctly."
Solution:
- Ensure that the
autoindentandsmartindentoptions are enabled in your.vimrc(e.g.,set autoindent smartindent). - Check that the
tabstop,shiftwidth, andexpandtaboptions are set correctly for your desired indentation style (e.g.,set tabstop=4 shiftwidth=4 expandtabfor using spaces with a width of 4). - Verify that Vim recognizes the file type correctly. You can set the file type manually using
:set filetype=languagenameif needed.
These best practices and troubleshooting tips should help users avoid common mistakes, develop good habits, and overcome challenges they may encounter while using Vim. Remember to refer to Vim's built-in help system (:help) and online resources for more in-depth explanations and solutions to specific issues.
Vim (Vi IMproved) is an enhanced version of the original Vi (Visual) editor. While Vim and Vi share many similarities, Vim offers a wide range of additional features and improvements that make it more powerful and user-friendly. Most of the basic concepts and commands that I mentioned earlier are applicable to both Vim and Vi. However, Vim extends and builds upon Vi's functionality.
Here are some key differences between Vim and Vi:
-
Extended Command Set: Vim introduces many new commands and features that are not available in Vi. These include visual selection, text objects, extended regular expressions, spell checking, folding, and more. While the basic commands remain the same, Vim provides a richer set of tools for text manipulation.
-
Customization and Configuration: Vim offers much more extensive customization options compared to Vi. With Vim, you can configure key mappings, define custom commands, set options, and use a vimrc file to personalize your editing environment. Vim's configuration language, Vimscript, is more powerful and expressive than Vi's limited options.
-
Multiple Levels of Undo and Redo: Vim provides an unlimited undo and redo tree, allowing you to go back and forth through your editing history. Vi, on the other hand, has a more limited undo/redo functionality.
-
Syntax Highlighting and Filetype Detection: Vim has built-in syntax highlighting support for a wide range of programming languages and file formats. It can automatically detect the filetype and apply appropriate syntax highlighting. Vi has limited or no syntax highlighting capabilities.
-
Plugin Ecosystem: Vim has a large and active community that develops plugins to extend its functionality. There are plugins available for almost any task, from code completion to version control integration. Vi has a more limited plugin ecosystem.
-
Graphical User Interface (GUI): Vim has a graphical user interface version called gVim (or MacVim on macOS), which provides additional features like toolbar, menu bar, and mouse support. Vi is primarily a command-line based editor.
-
Portability: Vim is highly portable and is available on a wide range of operating systems, including Unix, Linux, macOS, and Windows. Vi, being an older editor, may have more limited portability.
-
Documentation and Help System: Vim has an extensive built-in documentation and help system. You can access detailed information on commands, options, and features using the
:helpcommand. Vi's documentation is more limited in comparison.
Despite these differences, the core editing model and basic commands remain largely compatible between Vim and Vi. If you learn Vim, you can use most of that knowledge in Vi as well. However, Vim's additional features and improvements make it a more powerful and flexible editor.
It's worth noting that on many modern systems, the vi command is often symlinked to vim, so when you run vi, you're actually running Vim in compatible mode. This mode disables some of Vim's advanced features to maintain compatibility with Vi.
In summary, while Vi and Vim share a common foundation, Vim offers a significantly expanded feature set, better customization options, and a more extensive ecosystem. It builds upon Vi's core concepts and provides a more powerful and user-friendly editing experience.
Certainly! Let me provide you with a more comprehensive overview of Vim's structure and key concepts to help you understand and use the tool more effectively.
-
Modal Editing: Vim is a modal editor, which means it has different modes for different purposes: a. Normal Mode: Used for navigation and manipulation of text. This is the default mode. b. Insert Mode: Used for inserting and modifying text. c. Visual Mode: Used for selecting text and performing operations on the selection. d. Command-line Mode: Used for entering commands and searching.
-
Text Objects: Text objects are a way to define a range of text in Vim. They allow you to perform operations on specific parts of the text, such as words, sentences, paragraphs, or even custom-defined ranges. Text objects are used in combination with operators (like delete, change, or yank) to manipulate the text.
-
Operators: Operators are commands that perform actions on text, such as deleting, changing, or copying. They are often used in combination with motions or text objects to define the range of text to be operated on. Some common operators include
d(delete),c(change), andy(yank). -
Motions: Motions are commands that move the cursor around the text. They can be used to navigate through the document or to define a range of text when combined with an operator. Some examples of motions include
w(word),b(back),j(down),k(up), and$(end of line). -
Counts: Counts are numbers that can be prefixed to a command to repeat it multiple times. For example,
3ddwill delete three lines, and5wwill move the cursor forward five words. -
Registers: Registers are like named clipboards in Vim. They store text that has been yanked (copied) or deleted. You can access registers using the
"character followed by the register name. For example,"ayyyanks the current line into register "a", and"appastes the contents of register "a". -
Macros: Macros allow you to record a series of keystrokes and replay them later. This is useful for automating repetitive tasks. To start recording a macro, press
qfollowed by a register name. To stop recording, pressqagain. To execute the macro, press@followed by the register name. -
Configurations: Vim is highly configurable and can be customized to suit your needs. The configuration file is called
.vimrc(or_vimrcon Windows) and is located in your home directory. You can use this file to set options, define mappings, and customize Vim's behavior. -
Plugins: Vim has a rich plugin ecosystem that extends its functionality. Plugins can add new features, improve existing ones, or provide integration with other tools. Some popular plugin managers include Vundle, Pathogen, and Vim-Plug.
-
Vimscript: Vimscript is Vim's built-in scripting language. It allows you to write scripts to automate tasks, define custom commands, and create plugins. Vimscript has its own syntax and can be used to interact with Vim's internals.
Understanding these concepts will give you a solid foundation for using Vim effectively. Vim has a steep learning curve, but once you master its concepts and commands, you'll be able to edit text with great speed and efficiency.
Remember to practice regularly and refer to Vim's comprehensive documentation (:help) whenever you need more information on a specific topic. The Vim community is also a great resource, with many tutorials, cheat sheets, and forums available online.
Certainly! Here's a comprehensive guide to using Vim effectively, focusing on the concept of text objects and other essential features. This guide assumes basic familiarity with Vim's modes and navigation.
-
Text Objects: a. Word:
aw: a word (includes surrounding whitespace)iw: inner word (excludes surrounding whitespace)- Example:
dawdeletes a word and its surrounding whitespace b. Sentence: as: a sentenceis: inner sentence- Example:
cischanges the current sentence c. Paragraph: ap: a paragraphip: inner paragraph- Example:
yapyanks (copies) the current paragraph d. Tag (HTML/XML): at: a tag (includes the tag itself)it: inner tag (excludes the tag)- Example:
datdeletes the entire tag and its contents e. Quotes: a",a',a`: a quoted string (includes the quotes)i",i',i`: inner quoted string (excludes the quotes)- Example:
ci"changes the contents inside double quotes f. Brackets: a),a],a}: a bracketed block (includes the brackets)i),i],i}: inner bracketed block (excludes the brackets)- Example:
yi(yanks the contents inside parentheses g. Line: al: a line (includes indentation)il: inner line (excludes indentation)- Example:
daldeletes the current line and its indentation
-
Operators: a.
d: delete b.c: change (delete and enter insert mode) c.y: yank (copy) d.p: put (paste) e.=: format (indent) f.>: indent g.<: de-indent h. Example:d2awdeletes the next two words -
Motions: a.
w: move to the start of the next word b.e: move to the end of the current word c.b: move to the start of the previous word d.f/F: find the next/previous occurrence of a character e.t/T: find the character before the next/previous occurrence f.$: move to the end of the line g.0: move to the start of the line h.^: move to the first non-blank character of the line i.%: move to the matching bracket -
Visual Mode: a.
v: character-wise visual mode b.V: line-wise visual mode c.Ctrl-v: block-wise visual mode d. Example:vipvisually selects the current paragraph -
Search and Replace: a.
/pattern: search forward for the pattern b.?pattern: search backward for the pattern c.n/N: find the next/previous occurrence of the search pattern d.:%s/old/new/g: replace all occurrences of "old" with "new" in the entire file e.:.,$s/old/new/g: replace all occurrences of "old" with "new" from the current line to the end of the file -
Macros: a.
qa: start recording a macro named "a" b.q: stop recording the macro c.@a: execute the macro named "a" d.@@: execute the last executed macro -
Undo and Redo: a.
u: undo the last change b.Ctrl-r: redo the last undone change -
Splitting Windows: a.
:split: split the current window horizontally b.:vsplit: split the current window vertically c.Ctrl-w h/j/k/l: move to the window on the left/down/up/right -
Tabs: a.
:tabnew: open a new tab b.:tabn: move to the next tab c.:tabp: move to the previous tab d.gt: move to the next tab e.gT: move to the previous tab -
Other Essential Commands: a.
:w: save the current file b.:q: quit Vim c.:wqor:x: save and quit d.:q!: quit without saving changes e.:help: open Vim's help documentation
By mastering these concepts and commands, you'll be able to navigate, manipulate, and edit text efficiently in Vim. Remember that practice is key to becoming proficient with Vim's powerful features. Don't hesitate to explore Vim's extensive documentation (:help) to learn even more advanced techniques and customization options.
Vim Guide
1. Introduction to Vim's Philosophy
Vim, renowned for its modal editing system, allows users to switch between various modes designed for specific tasks such as inserting text, navigating within files, or executing commands. This modal approach greatly enhances editing efficiency by reducing the number of keystrokes required for tasks and enabling a more intuitive control over text manipulation.
2. Quick Reference Guide
This section provides a quick lookup for the most frequently used Vim commands, categorized for easy reference:
- Navigating
h, j, k, l: Move left, down, up, right (the arrow keys of Vim).gg, G: Jump to the top or bottom of the document.
- Editing
i, a, o: Enter insert mode at cursor, after cursor, or on a new line.d, c, y: Delete, change, or yank (copy) text.
- Searching
/pattern, ?pattern: Search forward or backward for a pattern.n, N: Repeat search in the same or opposite direction.
3. Core Guides with Integrated Efficiency Tips
Basic Editing and File Management
Opening, Saving, and Exiting Files
- Commands:
vim filename,:w,:wq,:q!- Description: Open files with
vim filename. Save with:w, exit with:q!, or combine both with:wq.
- Description: Open files with
- Tip: Use
ZZas a quicker alternative to:wqwhen you need to save and exit efficiently.
Navigating Within Files
- Commands:
h, j, k, l- Description: Precisely navigate within lines or across the text.
- Tip: Pair
h, j, k, lwithCtrl(e.g.,Ctrl-fandCtrl-b) for faster document scrolling.
Efficient Navigation
Word and Line Movements
- Commands:
w, b, e, 0, ^, $- Description: Navigate efficiently by words or to specific positions within a line.
- Tip:
5wcan save significant time by jumping five words forward, reducing repeated keystrokes.
Document Navigation
- Commands:
gg, G- Description: Quickly move to the beginning or end of a document, or directly to a specific line with
50G.
- Description: Quickly move to the beginning or end of a document, or directly to a specific line with
- Tip: Use percentage jumps like
50%to reach the midpoint of a document quickly.
Advanced Text Manipulation
Editing Commands
- Commands:
dw, ciw, d$- Description: Efficient commands for deleting a word, changing inside a word, or deleting to the end of a line.
- Tip:
ci(changes content inside parentheses, a common task in programming.
Using Visual Mode for Complex Selections
- Commands:
v, V, Ctrl-v- Description: Select text for manipulation in various modes: character, line, or block.
- Tip: Use
>or<to indent selected blocks quickly, crucial in code formatting.
Search and Replace
Finding and Replacing Text
- Commands:
:s/old/new/g,/%s/old/new/g- Description: Replace 'old' text with 'new' globally or within the current line.
- Tip: Use
*to search for the word under the cursor quickly.
Navigational Searches
- Commands:
f<char>, F<char>, t<char>, T<char>- Description: Jump to the next or previous occurrence of a character on the line.
- Tip: Use
;and,to repeat the lastfortsearch efficiently.
Enhanced Motion for Programming and Structured Data
Paragraph and Section Motions
- Commands:
{,},[[,]]- Description: Navigate quickly between paragraphs or code blocks. Ideal for structured data and code structures.
Screen Motions
- Commands:
H,M,L,Ctrl-d,Ctrl-u- Description: Manage on-screen text positioning and rapid scrolling effectively.
Document Motions
- Commands:
gg,G- Description: Essential for moving quickly through large files or to specific lines, critical in debugging and reviewing.
Tips for Using Motions in Structured Data and Programming
- Combine motions with searches for efficient navigation within XML, JSON
, or YAML, especially useful in large data files or complex codebases.
- Record macros for repetitive edits across similar structures, optimizing time and ensuring consistency.
- Utilize
Ctrl-vfor block visual mode, particularly effective for column-based editing or configuration adjustments.
This expanded guide not only provides a comprehensive look at using Vim effectively but also integrates practical tips directly applicable to programming and structured data editing, ensuring users can leverage Vim's power to its fullest.
Here's a streamlined outline of the VIM guides, focusing on the most relevant and commonly used topics:
I. Copy, Paste, and Find/Replace Operations
A. Copy and Paste Lines
1. Copy a Single Line
2. Paste the Copied Line
B. Copy and Paste Words
1. Copy a Word
2. Paste the Copied Word
C. Find and Replace
1. Find and Replace in the Entire Document
2. Find and Replace in the Current Line
3. Find and Replace with Confirmation
II. Useful Tasks and How to Accomplish Them
A. Searching and Navigating
B. Indenting and Formatting
C. Folding Code
D. Working with Registers
E. Switching Between Files
III. Visual Mode and Text Selection
A. Understanding Visual Mode
B. Entering and Exiting Visual Mode
C. Selecting Text in Visual Mode
D. Operating on Selected Text
E. Visual Mode Tips and Tricks
IV. Text Objects and Motions
A. Understanding Text Objects
B. Word and WORD Text Objects
C. Sentence and Paragraph Text Objects
D. Code Block Text Objects
E. Combining Text Objects with Motions
F. Using Text Objects in Visual Mode
G. Indentation Text Objects
H. Line and Column Text Objects
I. Repeating Actions with the Dot Operator
V. Undo and Redo
A. Understanding Undo and Redo
B. Basic Undo and Redo Commands
C. Undo and Redo Tips and Tricks
VI. Buffer Management and Navigation
A. Understanding Buffers
B. Listing and Switching Buffers
C. Opening and Closing Buffers
D. Saving and Discarding Changes
E. Buffer Navigation
VII. Marks and Jumps
A. Understanding Marks
B. Setting and Jumping to Marks
C. Special Marks
D. Jumps and the Jumplist
VIII. Mastering Registers
A. Understanding Registers
B. Unnamed Register
C. Named Registers
D. System Clipboard Register
E. Read-Only Registers
IX. Customizing VIM with .vimrc
A. Understanding .vimrc
B. Basic .vimrc Settings
C. Mapping Keys in .vimrc
D. Customizing VIM Plugins in .vimrc
This streamlined outline focuses on the most essential and commonly used features of VIM that are relevant to a majority of users. It covers copy/paste operations, useful tasks, visual mode, text objects and motions, undo/redo, buffer management, marks and jumps, registers, and basic customization with .vimrc.
Less commonly used topics like persistent undo, advanced buffer management, complex text object manipulations, Vim scripting, and more specialized topics have been removed to keep the guide concise and focused on the most practical features for everyday VIM usage.
Sure! Here's a concise reference guide for the Copy, Paste, and Find/Replace Operations, as well as the Useful Tasks in VIM:
VIM Reference Guide
I. Copy, Paste, and Find/Replace Operations
Copy and Paste Lines
- Copy a line:
yy - Paste after current line:
p - Paste before current line:
P
Copy and Paste Words
- Copy a word:
yiw - Paste after cursor:
p - Paste before cursor:
P
Find and Replace
- Find and replace in the entire document:
:%s/old/new/g - Find and replace in the current line:
:s/old/new/g - Find and replace with confirmation:
:%s/old/new/gc
II. Useful Tasks
Searching and Navigating
- Search for a pattern:
/pattern - Jump to the next occurrence:
n - Jump to the previous occurrence:
N - Jump to a specific line number:
:line_number
Indenting and Formatting
- Indent a block of code:
Vto select lines, then>to indent or<to unindent - Autoindent the entire file:
gg=G - Format a paragraph:
gq}
Folding Code
- Create a fold:
zffollowed by a motion command (e.g.,zf5jto fold the next 5 lines) - Open a fold:
zo - Close a fold:
zc - Open all folds:
zR - Close all folds:
zM
Working with Registers
- Yank text into a named register:
"register_nameyfollowed by a motion command - Paste from a named register:
"register_namep - View the contents of all registers:
:reg
Switching Between Files
- Open a new file in a split window:
- Horizontal split:
:sp filename - Vertical split:
:vs filename
- Horizontal split:
- Switch between open files:
Ctrl-wfollowed byh,j,k, orl - Close the current file:
:q
This reference guide provides a quick overview of the essential copy, paste, find/replace operations, and useful tasks in VIM. Keep this guide handy for quick access to the most commonly used commands and techniques.
Sure! Here's a concise reference guide for Visual Mode and Text Selection, Text Objects and Motions, and Undo and Redo in VIM:
VIM Reference Guide
III. Visual Mode and Text Selection
Entering and Exiting Visual Mode
- Enter character-wise visual mode:
v - Enter line-wise visual mode:
V - Enter block-wise visual mode:
Ctrl-v - Exit visual mode:
EscorCtrl-c
Selecting Text
- Character-wise selection: Use motion commands (
h,j,k,l,w,b) - Line-wise selection: Use
jorkto select entire lines - Block-wise selection: Use motion commands to select a rectangular block
- Select all text:
ggVG
Operating on Selected Text
- Copy (yank) selected text:
y - Cut (delete) selected text:
d - Change selected text:
c - Indent selected text:
>to indent,<to unindent - Convert selected text to uppercase:
U - Convert selected text to lowercase:
u
Visual Mode Tips
- Switch between selection ends:
o - Reselect last visual selection:
gv
IV. Text Objects and Motions
Word and WORD Text Objects
w: word (alphanumeric characters and underscores)W: WORD (non-blank characters separated by whitespace)- Examples:
daw: delete a word (including trailing whitespace)ciW: change inner WORD (excluding surrounding whitespace)yiw: yank inner word (excluding trailing whitespace)
Sentence and Paragraph Text Objects
s: sentence (characters ending with.,!, or?, followed by whitespace or end of line)p: paragraph (block of text separated by blank lines)- Examples:
das: delete a sentence (including whitespace after the sentence)cip: change inner paragraph (excluding surrounding blank lines)yap: yank a paragraph (including surrounding blank lines)
Code Block Text Objects
(,),{,},[,],<,>: code blocks delimited by matching parentheses, braces, brackets, or angle brackets- Examples:
di(: delete inside parenthesesca{: change around curly braces (including the braces)yi[: yank inside square brackets
Combining Text Objects with Motions
- Examples:
d2aw: delete two wordsc3s: change three sentencesy4p: yank four paragraphs
V. Undo and Redo
Basic Undo and Redo Commands
- Undo last change:
u - Redo last undone change:
Ctrl-r - Undo multiple changes: Press
umultiple times - Redo multiple changes: Press
Ctrl-rmultiple times
Undo and Redo Tips
- Undo all changes to a line since entering insert mode:
U - Repeat last change:
.(dot)
This reference guide provides a quick overview of the essential commands and techniques for visual mode and text selection, text objects and motions, and undo and redo in VIM. Keep this guide handy for quick access to these powerful editing features.
Certainly! Ex commands in Vim are incredibly useful for a range of text editing tasks. Here are some basic Ex commands that you should start with:
1. Opening and Saving Files
- Open a file:
:e filename– Opensfilenamein the current buffer. - Write (save) the current file:
:w– Saves the changes you've made. - Save and quit:
:wqor:x– Saves changes and closes the editor. - Quit without saving:
:q!– Quits and discards any changes.
2. Line Manipulation
- Go to a specific line:
:#– Where#is the line number you want to go to. For example,:25takes you to line 25. - Move lines:
:#m#– Moves a line to a new position. For example,:2m5moves line 2 below line 5. - Copy lines:
:#t#– Copies a line to a new position. For example,:3t5copies line 3 below line 5.
3. Searching and Replacing
- Search for a text:
:/pattern– Finds the next occurrence ofpattern. - Global search and replace:
:%s/old/new/g– Replaces all occurrences ofoldwithnewthroughout the document. Remove thegif you only want to replace the first occurrence in each line.
4. Filtering and Executing External Commands
- Filter lines through an external command:
:#,#!command– For example,:1,10!sortsorts lines 1 to 10. - Read the output of an external command into the buffer:
:r !command– For example,:r !dateinserts the current date into the document.
5. Managing Multiple Files
- Next file:
:n– Moves to the next file in the list of files opened with Vim. - Previous file:
:prevor:p– Moves to the previous file.
6. Setting Options
- Set options:
:set option– Sets different configurations. For example,:set numberturns on line numbering,:set nonumberturns it off.
7. Undo and Redo
- Undo the last change:
:undoor justuin normal mode. - Redo the last undone change:
:redoorCtrl-rin normal mode.