TIP

If you want to learn vim, you can fully ignore this lecture and just enter vimtutor in your terminal.

Introduction

When writing English text, we often use tools like Google Docs or LibreOffice, which are designed for the writing and formatting of natural language documents.

In contrast, when writing code, we use specialized tools such as IntelliJ IDEA, Visual Studio Code, or Vim. These code editors are optimized for programming languages and offer features like syntax highlighting, code completion, and debugging support.

Investing time in mastering a code editor is crucial because it can significantly enhance your productivity and efficiency as a programmer.

A powerful editor allows you to

  • write code faster,
  • navigate through codebases more efficiently,
  • reduce errors by leveraging advanced features tailored for coding.

Learning a New Editor

To effectively learn a new code editor, consider the following steps:

  • Start with a Tutorial: Begin by going through any tutorials or guided introductions that the editor offers. This foundational knowledge will help you understand the basic operations and features.
  • Use the Editor for All Text Editing: Make the new editor your default tool for all text-related tasks, not just coding. This constant use will help you become more familiar with its interface and capabilities.
  • Look Up Better Ways to Do Tasks: Whenever you find yourself performing repetitive or cumbersome tasks, search for more efficient methods or shortcuts within the editor. Many editors have documentation and active communities where you can learn advanced techniques.

Choosing an Editor

Selecting the right code editor is a personal decision that can greatly impact your coding experience.

Factors to consider include functionality, extensibility, community support, and personal comfort.


Editor Wars

Programmers often have strong opinions about their preferred text editors, leading to debates known as “editor wars.” These discussions highlight the passionate preferences developers have for tools that best fit their workflow.

Some popular editors today include:

  • Visual Studio Code: A modern, feature-rich editor developed by Microsoft. It supports many programming languages and has a vast ecosystem of extensions.
  • Vim: A highly configurable text editor built to enable efficient text editing. It is known for its powerful modal editing and extensive customization options.
  • Fleet: A newer editor aiming to provide an intelligent and collaborative coding environment.

Vim

Vim (Vi IMproved) is a text editor with a rich history dating back to the original Vi editor from the 1970s. Despite its age, Vim is still actively developed and remains popular among programmers for its efficiency and versatility.

Key points about Vim:

  • Rich History: Vim has evolved over decades, incorporating features that enhance text editing efficiency.
  • Active Development: It continues to receive updates and improvements, ensuring it stays relevant with modern development practices.
  • Vim Emulation Modes: Many modern editors and IDEs offer Vim emulation modes, allowing users to benefit from Vim’s powerful editing capabilities within other environments.

Philosophy of Vim

Vim’s Design

Vim is designed with a focus on efficiency and productivity:

  • Reading and Editing Over Writing: Vim emphasizes the ability to quickly navigate and manipulate existing text rather than just writing new text. This reflects the reality that developers often spend more time reading and modifying code than writing it from scratch.
  • Modal Editor: Vim operates in different modes, primarily Normal mode and Insert mode. This design allows for a vast array of shortcuts and commands for text manipulation without the need for multiple key combinations.
  • Programmable and Mouse-Free: Vim can be customized and extended using its scripting language. It is optimized for keyboard use, minimizing reliance on the mouse, which speeds up editing tasks.

Modal Editing in Vim

Different Operating Modes

Vim’s efficiency comes from its use of modes, each serving a specific purpose:

  • Normal Mode: The default mode for navigation and executing commands to manipulate text. In this mode, keys correspond to actions rather than characters.

  • Insert Mode: Used for inserting new text into the document. In this mode, the keyboard behaves like a traditional text editor.

  • Other Modes:

    • Replace Mode: Allows you to overwrite existing text.
    • Visual Mode: Enables text selection for operations like copying or deleting.
    • Command-line Mode: Accessed by pressing :, used for executing commands like saving or quitting.

Mode Switching

Understanding how to switch between modes is essential:

  • Switch to Normal Mode: Press <ESC> at any time to return to Normal mode from any other mode.
  • Enter Insert Mode: Press i to start inserting text before the cursor position.
  • Enter Replace Mode: Press R to begin overwriting text from the cursor position.
  • Enter Visual Modes:
    • Character-wise Visual Mode: Press v.
    • Line-wise Visual Mode: Press V.
    • Block Visual Mode: Press <C-v> (Ctrl + v).
  • Enter Command-line Mode: Press : to execute commands.

These mode switches allow you to perform a wide range of operations efficiently.


Basics of Vim


Inserting Text

To insert text in Vim:

  • Enter Insert Mode: From Normal mode, press i to begin inserting text at the cursor’s current position.
  • Return to Normal Mode: Press <ESC> to exit Insert mode and return to Normal mode, where you can navigate and execute commands.

Buffers, Tabs, and Windows

Vim manages files and views using:

  • Buffers: In-memory versions of opened files. Each file you edit is stored in a buffer.
  • Windows: Viewports into buffers. You can split your screen to view multiple buffers or different parts of the same buffer.
  • Tabs: Collections of windows. Tabs can contain multiple windows, allowing you to organize your workspace.

Understanding how to use buffers, windows, and tabs helps in managing multiple files and views effectively.


Command-line Mode

Command-line mode allows you to execute more complex commands:

  • Entering Command-line Mode: Press : from Normal mode.
  • Common Commands:
    • Save File: :w writes the current buffer to disk.
    • Quit Vim: :q exits Vim. Use :q! to force quit without saving changes.
    • Save and Quit: :wq or :x saves changes and exits.

Using command-line mode gives you access to a wide range of powerful Vim commands.


Movement Commands

Efficient navigation is a key advantage of Vim:

  • Basic Movements:
    • h: Move left.
    • j: Move down.
    • k: Move up.
    • l: Move right.
  • Word Movements:
    • w: Move to the beginning of the next word.
    • b: Move to the beginning of the previous word.
    • e: Move to the end of the current word.
  • Line Movements:
    • 0: Move to the beginning of the line.
    • $: Move to the end of the line.
  • Screen Movements:
    • Ctrl + f: Move forward one screen.
    • Ctrl + b: Move backward one screen.
  • File Movements:
    • gg: Go to the first line of the file.
    • G: Go to the last line of the file.
    • :<line number>: Go to a specific line number.
  • Search Movements:
    • /pattern: Search forward for a pattern.
    • ?pattern: Search backward for a pattern.
    • n: Repeat the search in the same direction.
    • N: Repeat the search in the opposite direction.

Selection in Visual Modes

Visual modes enable you to select text for editing:

  • Visual Mode (v): Select text character by character.
  • Visual Line Mode (V): Select entire lines.
  • Visual Block Mode (Ctrl + v): Select columns of text, useful for editing multiple lines simultaneously.

Once you’ve made a selection, you can perform operations like deleting, yanking (copying), or changing the selected text.


Editing Commands

Vim provides powerful commands for manipulating text:

  • Delete Commands:
    • d{motion}: Delete text that is specified by the motion command.
      • Example: dw deletes from the cursor to the end of the word.
      • Example: dd deletes the entire current line.
  • Change Commands:
    • c{motion}: Change text specified by the motion command (deletes and enters Insert mode).
      • Example: cw changes the word from the cursor onward.
  • Other Commands:
    • x: Delete the character under the cursor.
    • s: Delete the character under the cursor and enter Insert mode.
    • u: Undo the last action.
    • Ctrl + r: Redo the undone action.
    • y: Yank (copy) text specified by a motion.
      • Example: yy yanks the entire line.
    • p: Paste the yanked or deleted text after the cursor.

Counts and Modifiers

You can modify commands with counts and use text objects for more precise editing:

  • Counts:
    • Precede a command with a number to repeat it.
      • Example: 3w moves forward three words.
      • Example: 5j moves down five lines.
  • Modifiers:
    • i (inner): Targets the inside of a text object.
    • a (around): Targets the text object including its surrounding characters (like parentheses or quotes).
  • Examples:
    • ciw: Change inner word (replace the word under the cursor).
    • di(: Delete inside the parentheses.
    • da": Delete around double quotes, including the quotes themselves.

Customizing Vim

Vim is highly customizable to suit your preferences:

  • Configuration File: The main configuration file is ~/.vimrc.

  • Starting Point:

    • Begin with a basic configuration that includes common settings, such as:
      • Enabling syntax highlighting.
      • Setting indentation preferences.
      • Custom key mappings.
  • Example .vimrc Entry:

    syntax on
    set number
    set tabstop=4
    set shiftwidth=4
    set expandtab

If you want some pre-made configuration, consider setting up LazyVim.


Extending Vim with Plugins

Vim’s functionality can be extended with plugins:

  • Package Management:
    • Vim has built-in support for plugins, which can be managed in the ~/.vim/pack directory.
  • Popular Plugins:
    • ctrlp.vim: A fuzzy file finder to quickly open files.
    • ack.vim: Integrates with the ack tool for searching text within files.
    • nerdtree: Provides a file system explorer within Vim.
    • vim-easymotion: Enhances navigation by allowing quick jumps to locations in the file.
  • Installing Plugins:
    • Plugins can be installed manually or using plugin managers like Vundle or Pathogen for easier management.

Vim-mode in Other Programs

Vim’s modal editing can be used in various other applications:

  • Shell Integration:
    • Bash: Enable Vi editing mode with set -o vi.
    • Zsh: Similarly, use bindkey -v to enable Vi mode.
    • Fish: Use fish_vi_key_bindings.
  • GNU Readline Library:
    • Applications that use Readline (like the Python REPL or the MySQL client) can be set to Vi mode by adding set editing-mode vi in the ~/.inputrc file.
  • Other Software:
    • Many IDEs and editors offer Vim emulation plugins or modes, such as:
      • Visual Studio Code: Install the Vim extension.
      • IntelliJ IDEA: Enable IdeaVim plugin.
      • Sublime Text: Use the Vintage mode.

Advanced Vim

Vim offers advanced features for complex editing tasks:

  • Search and Replace:
    • Perform substitutions with :s command.
      • Example: :%s/old/new/g replaces all occurrences of “old” with “new” in the entire file.
    • Supports regular expressions for powerful pattern matching.
  • Multiple Windows:
    • Split the window horizontally with :split or Ctrl + w s.
    • Split vertically with :vsplit or Ctrl + w v.
    • Navigate between windows using Ctrl + w followed by an arrow key or h, j, k, l.
  • Macros:
    • Record repetitive actions:
      • Start recording with q followed by a register (e.g., qa).
      • Perform the desired actions.
      • Stop recording with q.
      • Replay the macro with @ followed by the register (@a).
      • Repeat the macro multiple times with a count (e.g., 10@a).

Resources for Learning Vim