Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Essential Vim Techniques and Configuration for Efficient Operations

Tech 2

In the programming world, the choice of editor can significant impact a developer's coding efficiency. Vim, an ancient yet powerful text editor, has won the favor of countless programmers with its unique editing modes and high customizability. This article aims to summarize common methods and advanced configurations for both Vim beginners and experienced users, helping you enhance your editing efficiency.

Vim Usage Techniques

For newcomers, Vim may seem complex and difficult to master, primarily due to its multiple operation modes and reliance on intricate keyboard shortcuts, which can be challenging for beginners. However, once you grasp Vim's basic operations, you will inevitably be drawn to its power and flexibility, and you're work efficiency will see significant improvement. Below are various commonly used Vim shortcuts that we hope will assist you.

Vim's design philosophy includes "keeping your hands on the keyboard," which is fully reflected in efficient editing techniques. From quick cursor movement to complex text operations, every action is meticulously designed to minimize unnecessary movement.

1. Cursor Movement

After launching Vim, you first enter normal mode, where you perform basic editing operations such as cursor movement, copying, and pasting. At this point, you can execute operations according to a specific keyboard layout, as shown below:

k
 ↑
h ← → l
 ↓
j
  • h -- Move cursor left, l -- Move cursor right (these are easy to remember)
  • j -- Move cursor down, k -- Move cursor up (a mnemonic: imagine j protruding downward, indicating cursor movement downward)

2. Copy and Paste

  • yy (copy current line)
  • p (paste below current line)
  • P (paste above current line)

3. Visual Mode Operations

  • v (start selection, use arrow keys or h, l, k, j to navigate and specify end position)
  • y (copy selected text)
  • p (paste)

4. Deletion Operations

  • dd (delete current line)
  • x (delete character after cursor)
  • s (delete character at cursor and enter edit mode)
  • C (delete characters after cursor and enter edit mode; frequently used and highly effective)

5. Undo and Redo

  • u (undo last operation)
  • R (redo last undo)
  • Ctrl + r (redo, i.e., undo the undo)

6. Navigation

  • gg (jump to first line of file)
  • G (jump to last line of file)

7. Command-Line Mode

  • :w (save)
  • :q (quit)
  • :e (open file, followed by file path)
  • :h (help)
  • :wq (save and quit)
  • :q! (quit with out saving)
  • :ZZ (quick save and quit)

Example substitution command:

:2,5s/old/new/g
  • Matches line numbers, replaces old with new in lines 2-5; %s matches all lines, g replaces all occurrences per line.

Tip: For uppercase letters, use Shift + lowercase for easier operation.

Common Vim Configurations

To make Vim better suit your workflow, personalize it through the .vimrc file. Whether adjusting visual style or optimizing editing experience, this small configuration file holds immense power. Common configuration items are listed below:

1. Common Configuration Items

Configuration Item Purpose
set ai / noai Enable/disable auto-indent
set nu / nonu Show/hide line numbers (abbreviation for number)
set ts=2 Set tab indentation to 2 spaces
set sw=2 Set shift width to 2 spaces (differs from ai; effective in command-line mode with ">>")
set paste Preserve original format when pasting
set cursorline Enable current line highlight
set cursorcolumn Enable column highlight, useful for editing YAML and similar texts
set et Expand tabs to spaces; YAML syntax explicitly does not support tab characters

2. Global Configuration

Vim's global configuration is located at /etc/vimrc. Settings here affect all users. set configurations can be temporarily applied in command-line mode during editing; for permanent effect, write them to the configuration file.

3. File-Specific Configuration

User-specific configuration is in the hidden file ~/.vimrc in the home directory, which may need to be created manually if it doesn't exist. Settings here only affect the individual user. Vim also supports separate configurations for specific file extensions (in addition to global settings), as shown in the example below:

autocmd FileType yaml setlocal et

This code is an autocmd (automatic command) in Vim, used to automatically set options when opening or switching to a YAML file. Explanation:

  • autocmd: Indicates an automatic command that executes actions when specific events occur.
  • FileType yaml: This autocmd only takes effect when the file type is YAML.
  • setlocal: These settings apply only to the current window and do not affect others.
  • et: Expands tabs, i.e., uses spaces instead of tab characters for indentation.

The triggered function is: when opening a YAML file, automatically execute subsequent commands to set current window configurations such as auto-indent, show line numbers, convert tabs to spaces, set tab indentation to 2 characters, and set line indentation to 2 characters after line breaks. This is helpful for Ansible playbook writing, improving editing efficiency for YAML-format texts.

Efficient Operations with Ansible

When writing a series of YAML playbooks, are you still manually copying and pasting templates? There are more efficient methods. Beyond basic text editing, Vim offers many advanced features such as events, macro recording, and multi-window editing. Among these, events can better assist us in writing templates. See the example below:

---
- name:
  hosts:
  remote_user: root
  become: yes

  vars:

  roles:

  tasks:
    - name:

#   - block:
#
#     rescue:
#
#     always:
#
#  handlers:
#    - name:

From this, we can see that when opening a new .yml file, it is pre-filled with template content. How is this achieved?

Actually, by adding Vim configuration, we can achieve this effect. Let's open the /etc/vimrc configuration file and add the following code:

autocmd BufNewFile,BufReadPre /media/*,/run/media/*,/mnt/* set directory=~/tmp,/var/tmp,/tmp
" start with spec file template
autocmd BufNewFile *.spec 0r /usr/share/vim/vimfiles/template.spec

      We can see an autocmd automatic command event here. Let's copy a line and modify it as follows:
autocmd BufNewFile *.yml,*.yaml 0r /usr/share/vim/vimfiles/template.yml
  • autocmd: Indicates an automatic command.
  • BufNewFile *.yml,*.yaml: Triggers this autocmd when creating a new file with extension .yml or .yaml.
  • 0r /usr/share/vim/vimfiles/template.yml: Reads and inserts the template file located at the default path. 0r means insert file content at the current cursor position.

Through the above configuration, multiple templates for different file extensions can be set up, aiding in better text writing, such as personal information headers for Shell scripts. What other uses can you think of? Feel free to share and learn from each other in the comments!

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.