Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Mastering Vim
Mastering Vim

Mastering Vim: Build a software development environment with Vim and Neovim

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Mastering Vim

Getting Started

Welcome to Mastering Vim, a book which will teach you to get good with Vim, its plugins, and its ideological successors!

This chapter will establish a foundation for working with Vim. Every tool is built with a particular usage philosophy in mind, and Vim is not an exception. Vim introduces a different way of working with text compared to what most people are used to these days. This chapter focuses on highlighting these differences and establishing a set of healthy editing habits. It will let you approach Vim in a Vim-friendly frame of mind and will ensure you're using the right tools for the job. To make examples concrete, we will be using Vim to create a small Python application throughout this chapter.

The following topics will be covered in this chapter:

  • Modal versus modeless interfaces, and why is Vim different from other editors
  • Installing and updating Vim
  • The gVim - the graphical user interface for Vim
  • Configuring Vim for working with Python and editing your .vimrc file
  • Common file operations: opening, modifying, saving, and closing files
  • Moving around: navigating with arrow keys, hjkl, by words, paragraphs, and so on

  • Making simple edits to files and combining editing commands with movement commands
  • Persistent undo history
  • Navigating the built-in Vim manual

Technical requirements

Throughout this chapter we will be writing a basic Python application. You don't have to download any code to follow along with this chapter as we'll be creating files from scratch. However, if you ever get lost and need more guidance, you can view the resulting code on GitHub:

https://github.com/PacktPublishing/Mastering-Vim/tree/master/Chapter01

We will be using Vim to primarily write Python code throughout this book, and it is assumed that the reader is somewhat familiar with the language. Examples assume you're using Python 3 syntax.

If you must live in the past, you can convert Python 3 examples to Python 2 code by changing the print() command syntax. Change all of print('Woof!') to print 'Woof!' to make the code run in Python 2.
We will also be creating and modifying Vim configuration, which is stored in a .vimrc file. The resulting .vimrc file is available from the previously mentioned GitHub link.

Let’s start a conversation (about modal interfaces)

If you’ve ever edited text before, you are most likely to be familiar with modeless interfaces. It’s the default option chosen by modern mainstream text editors, and that’s how many of us learned to work with text.

The term modeless refers to the fact that the each interface element has only one function. Each button press results in a letter showing up on screen, or some other action being performed. Each key (or a combination of keys) always does the same thing: the application always operates in a single mode.

But it’s not the only way.

Welcome to the modal interface, where each trigger performs a different action based on context. The most common example of a modal interface that we encounter today is a smartphone. Each time we work in different applications or open different menus, a tap on the screen performs a different function.

It’s similar when it comes to text editors. Vim is a modal editor, meaning that a single button press might result in different actions, depending on context. Are you in insert mode (a mode for entering text)? Then hitting o would put the letter o on the screen. But as soon as you switch into a different mode, the letter o will change its function to adding a new line below the cursor.

Working with Vim is like having a conversation with your editor. You tell Vim to delete the next three words by pressing d3w (delete 3 words), and you ask Vim to change text inside quotes by pressing ci" (change inside " [quotes]).

You may hear very frequently that Vim is faster than other editors, but it’s not necessarily the point of Vim. Vim lets you stay in the flow when working with text. You don’t have to break the pace to reach for your mouse, you don’t have to hit a single key exactly 17 times to get to a particular spot on the page. You don’t have to drag your mouse millimeter by millimeter to ensure you capture the right set of words to copy and paste.

When working with a modeless editor, workflow is filled with interruptions.

Working with modal editors, and Vim in particular, is like having a conversation with your editor. You ask the editor to perform actions ("delete three words", "change inside quotes") in a consistent language. With Vim, editing becomes a much more deliberate exercise.

Installation

Vim is available on every platform, and comes installed on Linux and Mac OS (however, you may want to upgrade Vim to a more recent version). Find your system in the following paragraphs, and skim through the instructions to set up.

Setting up on Linux

Linux machines come with Vim installed, which is great news! However, it might be rather out of date, and Vim 8 introduces some much-needed optimizations. Pull up your Command Prompt, and run the following code:

$ git clone https://github.com/vim/vim.git
$ cd vim/src
$ make
$ sudo make install

If you're running into issues as you're installing Vim, you might be missing some dependencies. If you're using a Debian-based distribution, the following command should add common missing dependencies : $ sudo apt-get install make build-essential libncurses5-
$ sudo apt-get install make build-essential libncurses5-dev
libncursesw5-dev --fix-missing

This will make sure you’re on the latest major and minor patch of Vim. If you don’t care for being on the cutting edge, you can also update Vim using a package manager of your choice. Different Linux distributions use different package managers; the following list includes some common ones:

Distribution Command to install the latest version of Vim
Debian-based (Debian, Ubuntu, Mint)

$ sudo apt-get update

$ sudo apt-get install vim-gtk

CentOs (and Fedora prior to Fedora 22)

$sudo yum check-update

$sudo yum install vim-enhanced

Fedora 22+

$sudo dnf check-update

$sudo dnf install vim-enhanced

Arch

$sudo pacman -Syu

$sudo pacman -S gvim

FreeBSD

$sudo pkg update

$sudo pkg install vim

You can see in the preceding table that Vim uses package names for different repositories. Packages like vim-gtk on Debian-based distributions or vim-enhanced on CentOS come with more features enabled (like GUI support for instance).

Do keep in mind that package manager repositories tend to lag behind from anywhere between a few months to a few years.

That’s it, you’re now ready to dive into the world of Vim! You can start the editor by typing the following command:

$ vim

On modern systems, you can also start Vim by invoking vi. However, it's not always the case: on older systems the two are different binaries. Vi is Vim’s predecessor (Vim stands for Vi improved). Today, it’s merely an alias pointing to Vim. There are no reasons to use Vi over Vim, unless, for some reason, you're unable to install the latter.

Setting up on MacOS

MacOS comes prepackaged with Vim, but the version can be outdated. There are a few ways to install a fresh version of Vim, and this book will cover two. First, you can install Vim using Homebrew, a package manager for MacOS. You'll have to install Homebrew first, though. Second, you can download a .dmg image of MacVim. This experience would be more familiar because Mac users are used to the visual interface.

Since this book covers interactions with the Command line, I recommend taking the Homebrew route. But you're welcome to go forward with installing the image if interacting with the Command line does not interest you.

Using Homebrew

Homebrew is a third-party package manager for MacOS which makes it easy to install and keep packages up to date. Instructions on how to install Homebrew are available on https://brew.sh, and, as of the moment of writing this book, consist of a single line executed in the following Command line:

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

The following screenshot shows the list of operations you will then see Homebrew perform during installation:

Hit Enter to continue.

If you don't have XCode installed (which is often a prerequisite for any kind of development-related activity on Mac), you'll get an XCode installation pop-up. We won't be using XCode directly, and you can install it with default settings.

This should take a while to run, but you'll have Homebrew installed by the end: a fantastic tool you can use to install a lot more than Vim! You'll see Installation successful! in bold font once the installation is complete.

Let's install a new version of Vim now using the following command:

$ brew install vim

Homebrew will install all the necessary dependencies too, so you won't have to worry about a thing, as can be seen in the following screenshot:

If you already have Homebrew installed, and you have installed Vim in the past, the preceding command will produce an error. You may want to make sure you have the last version of Vim, though, so run the following command:

$ brew upgrade vim

You should now be ready to enjoy Vim; let's try opening it with the following command:

$ vim

Welcome to Vim:

Downloading a .dmg image

Navigate to https://github.com/macvim-dev/macvim/releases/latest and download MacVim.dmg.

Open MacVim.dmg, and then drag the Vim icon into the Applications directory, as can be seen in the following screenshot:

Depending on the security settings of your Mac, you might be greeted by an error when navigating to the Applications folder and trying to open the MacVim app, as demonstrated in the following screenshot:

Open your Applications folder, find MacVim, right click the icon and select Open. The following prompt will pop up:

Now hit Open, and MacVim can be opened as usual from now on. Give it a shot:

Setting up on Windows

Windows provides two primary routes for using Vim: setting up Cygwin and providing a more Unix-like command-line experience, or installing gVim—a graphical version of Vim (which supports working with cmd.exe on Windows). I recommend installing both and picking your favorite: gVim feels slightly more at home on Windows (and it is easier to install), while Cygwin might feel more at home if you're used to the Unix shell.

Unix-like experience with Cygwin

Cygwin is a Unix-like environment and a command-line interface for Windows. It aims to bring powerful Unix shell and supporting tools to a Windows machine.

Installing Cygwin

To begin the installation process, navigate to https://cygwin.com/install.html and download either setup-x86_64.exe or setup-x86.exe depending on the version of Windows you're using (64 bit or 32 bit respectively).

If you're not sure whether your system is 32 bit or 64 bit, you can open Control Panel | System and Security | System, and look at System type. For example, my Windows machine shows System type: 64-bit Operating System, x64-based processor.
Open the executable file, and you will be greeted by the following Cygwin installation window:

Hit Next > a few times, proceeding with the default settings:

  • Download source: Install from Internet
  • Root directory: C:\cygwin64 (or a recommended default)
  • Install for: all users
  • Local package directory: C:\Downloads (or a recommended default)
  • Internet connection: Use System Proxy Settings
  • Download site: http://cygwin.mirror.constant.com (or any available option)

After this, you will be greeted with the Select Packages screen. Here, we want to select the vim, gvim, and vim-doc packages. The easiest way to do this is to type vim in a search box, expand the All |Editors category, and click on the arrow-looking icons next to the desired packages, as demonstrated in the following screenshot:

The preceding screenshot shows version 8.0.1567-1. This is the only version available at the moment of writing this book, November 2018. The primary difference is the absence of the :terminal command (see Chapter 5, Build, Test, and Execute) in Vim 8.0 vs 8.1.

You may want to install curl from under the Net category, and git from under the Devel category, as we'll be using both in chapter 3. It might also be helpful to install dos2unix from under the Utils category, which is a utility used for converting Windows-style line endings to Linux-style line endings (something you might run into once in a while).

Hit Next > two more times to proceed, which will begin the installation. Installation will take some time, and now would be a great moment to prematurely congratulate yourself with some coffee!

You might get a few post-install script errors, which you can safely dismiss (unless you see any errors related to Vim—then Google is your friend: search for an error text and try to find a solution).

Hit Next > a few more times, proceeding with the defaults:

  • Create icon on Desktop
  • Add icon to Start Menu

Congratulations, you now have Cygwin installed with Vim!

If you ever need to install additional packages in Cygwin, just rerun the installer while selecting the packages you want.

Using Cygwin

Open Cygwin, the program will be called Cygwin64 Terminal or Cygwin Terminal, depending on the version of your system, as can be seen in the following screenshot:

Open it! You will see the following prompt, familiar to Linux users:

Cygwin supports all of the Unix-style commands we will be using in this book. This book will also say if any commands need to be changed to work with Cygwin. But for now, let's open Vim and proceed onto the next chapter! Type vim and hit Enter to start Vim, as demonstrated in the following screenshot:

Cygwin is a way to get a Linux-like shell experience on Windows, meaning you'll have to follow Linux specific instructions throughout this book if you decide to use Cygwin.

You'll also want to be careful with Windows-style line endings vs Linux-style line endings, as Windows and Linux treat line endings differently. If you run into an odd issue with Vim complaining about ^M characters its unable to recognize, run the dos2unix utility on the offending file to resolve the issue.

Visual Vim with gVim

In this section you can read more about the graphical version of Vim in Vanilla Vim vs GVim. As it always is with Windows, the process is slightly more visual. Navigate to www.vim.org/download.php#pc in your browser and download an executable installer. At the moment of writing this book, November 2018, the binary is called gvim81.exe, where 81 stands for version 8.1.

Open the executable and follow the prompts on the screen, as demonstrated by the following screenshot:

Let's go ahead and hit Yes, then I Agree until we arrive at the Installation Options screen. We're happy with most of the default options gVim has to offer, except that you might want to enable Create .bat files for command line use. This option will make the vim command work in Windows Command Prompt. Some examples in this book rely on having a Command Prompt, so enabling this option would help you follow along.

Here's a screenshot of the Installation Options screen with the proper boxes checked off:

Hit Next >. You'll want to continue with the following settings:

  • Select the type of install: Typical, (after Create .bat files for command line use is enabled, type of install value changes to Custom automatically).
  • Do not remap keys for Windows behavior
  • Right button has a popup menu, left button starts visual mode
  • Destination Folder: C:\Program Files (x86)\Vim (or a recommended default)

Once you're done, hit Install and then Close, as demonstrated in the following screenshot:

Say No to the request to see the README file (who needs a manual, huh?) as seen in the following command:

You will now have a few icons pop on your desktop, the most interesting one being gVim 8.1 as shown in the following screenshot:

Start it, and you're ready to proceed! Happy Vimming!

Verifying and troubleshooting the installation

Regardless of the platform you used to install Vim, it's good to make sure that, with Vim, all the right features enabled. On a command line, run the following command:

$ vim --version

You will see the following output, with a set of features having a + and a - in front of them:

In the preceding screenshot, you can see that my Vim was actually compiled with Python 2 support (+python) instead of Python 3 support (-python3). To correct the issue, I'd have to either recompile Vim with +python3 enabled or find a package which distributes a compiled version of Vim with +python3 enabled.

For a list of all features Vim can have enabled, see :help feature-list.

For instance, if we wanted to recompile Vim 8.1 with Python 3 support on Linux, we would do the following:

$ git clone https://github.com/vim/vim.git
$ cd vim/src
$ ./configure --with-features=huge --enable-python3interp
$ make
$ sudo make install
We're passing the --with-features=huge flag in order to compile Vim with most features enabled. However, --with-features=huge does not install language bindings, so we need to explicitly enable Python 3.

In general, if your Vim is not behaving like other Vim installations (including behavior described in this book), you might be missing a feature.

Depending on your system and features you require, the process might be slightly or vastly different. A quick web search along the lines of Installing Vim <version> with +<feature> on <operating system> should help.

Vanilla Vim vs gVim

Using instructions given before, you’ve installed two flavors of Vim: command-line Vim, and gVim. This is how gVim looks on Windows:

The gVim hooks up a graphical user interface (GUI) to Vim, has better mouse support, and adds more context menus. It also supports a wider range of color than many terminal emulators, and provides some quality of life features you’d expect from a modern GUI.

You can launch gVim by running gVim 8.1 executable on Windows, or on Linux and Mac OS by invoking the following command:

$ gvim

Windows users might favor gVim.

This book focuses on increasing the effectiveness of one’s text editing skills, so we will shy away from navigating multiple menus in gVim, as these are rather intuitive, and take the user out of the flow.

Hence, we will focus on a non-graphical version of Vim, but everything that’s applicable to Vim also applies to gVim. The two share configuration, and you can swap between the two as you go. Overall, gVim is slightly more newbie friendly, but it doesn’t matter which one you choose to use for the purpose of this book.

Try both!

Configuring Vim with your .vimrc

Vim reads configuration from a .vimrc file. Vim works out of the box, but there are certain options which make working with code a lot easier.

In Unix-like systems, files starting with a period . are hidden. To see them, run ls -a in a Command line.

In Linux and MacOS, .vimrc is located in your user directory (the full path would be /home/<username>/.vimrc). You can also find out your user directory by opening a Command Prompt and running the following command:

$ echo $HOME

Windows does not allow periods in file names, so the file is named _vimrc. It's usually located in C:\Users\<username>\_vimrc, but you can also locate it by opening the Windows Command Prompt and running the following command:

$ echo %USERPROFILE%
If you run into problems, open Vim and type in :echo $MYVIMRC followed by Enter. It should display where Vim is reading the .vimrc from.

Find the proper location for your OS, and place the prepared configuration file there. You can download the .vimrc used for this chapter from GitHub at https://github.com/PacktPublishing/Mastering-Vim/tree/master/Chapter01. The following code shows the contents of a .vimrc file used in this chapter:

syntax on                  " Enable syntax highlighting.
filetype plugin indent on " Enable file type based indentation.

set autoindent " Respect indentation when starting a new line.
set expandtab " Expand tabs to spaces. Essential in Python.
set tabstop=4 " Number of spaces tab is counted for.
set shiftwidth=4 " Number of spaces to use for autoindent.

set backspace=2 " Fix backspace behavior on most terminals.

colorscheme murphy " Change a colorscheme.

Lines starting with a double quote " are comments and are ignored by Vim. These settings bring in some sensible defaults, like syntax highlighting and consistent indentation. They also fix one of the common sticking points in a bare-bones Vim installation—inconsistent backspace key behavior across different environments.

When working with Vim configuration, you can try things out before adding them to your .vimrc file To do that, type : followed by a command, for example, :set autoindent (press Enter to execute). If you ever want to know the value of a setting, add ? at the end of the command: for example, :set tabstop? will tell you the current tabstop value.

I've also changed the colorscheme to make screenshots look better in print, but you don't have to.

Vim 8 comes prepackaged with the following color themes: blue, darkblue, default, delek, desert, elflord, evening, industry, koehler, morning, murhpy, pablo, peachpuff, ron, shine, slate, torte, zellner. You can try out a color theme by typing :colorscheme <name> and hitting Enter, and you can cycle through the available color scheme names by typing :colorscheme followed by a space and by hitting Tab multiple times. You can read more about configuring Vim and color schemes in chapter 7, Making Vim Your Own.

Common operations (or how to exit Vim)

We will now focus on interacting with Vim without the use of a mouse or navigational menus. Programming is a focus intensive task on its own. Hunting through context menus is nobody's idea of a good time, and keeping our hands on the home row of your keyboard helps trim constant switching between a keyboard and a mouse.

Opening files

First, start your favorite Command Prompt (Terminal in Linux and macOS, Cygwin in Windows). We'll be working on a very basic Python application. For simplicity's sake, let's make a simple square root calculator. Run the following command:

$ vim animal_farm.py
If you're using gVim—you can open a file by going into a File menu and choosing Open. Sometimes graphical interface is exactly what you need!

This opens a file named animal_farm.py. If the file existed, you'd see its contents here, but since it doesn't, we're greeted by an empty screen, as shown in the following example:

You can tell that the file doesn't exist by the [New File] text next to a file name in the status line at the bottom of the screen. Woohoo! You've just opened your first file with Vim!

Vim's status line often contains a lot of useful information. That's the primary way for Vim to communicate with a user, so do keep an eye out for messages in the status line!

If you already have Vim open—you can load a file by typing the following, and hitting Enter:

:e animal_farm.py

You have just executed your first Vim command! Pressing colon character : enters a command-line mode, which lets you enter a line of text which Vim will interpret as a command. Commands are terminated by hitting the Enter key, which allows you to perform various complex operations, as well as accessing your system's Command line. Command :e stands for edit.

Vim help often refers to the Enter key as a <CR>, which stands for carriage return.

Changing text

By default you're in Vim's normal mode, meaning that every key press corresponds to a particular command. Hit i on your keyboard to enter an insert mode. This will display -- INSERT -- in a status line (at the bottom), (and, if you're using gVim, it will change the cursor from a block to a vertical line), as can be seen in the following example:

The insert mode behaves just like any other modeless editor. Normally, we wouldn't spend a lot of time in insert mode except for adding new text.

You've already encountered three of Vim's modes: command-line mode, normal mode, and insert mode. This book will cover more modes, see Chapter 3, Follow the Leader – Plugin Management for details and explanation.

Let's create our Python application by typing in the following code. We'll be navigating this little snippet throughout this chapter:

To get back to normal mode in Vim, hit Esc on your keyboard. You'll see that -- INSERT -- has disappeared from the status line. Now, Vim is ready to take commands from you again!

The preceding code is not showing Python best practices and is provided to illustrate some of Vim's capabilities.

Saving and closing files

Let's save our file! Execute the following command:

:w
Don't forget to hit Enter at the end of a command to execute it.

:w stands for write.

The write command can also be followed by a filename, making it possible to write to a different file, other than the one that is open (:w animal_farm_2.py). To change the current open file to a new one when saving, use :saveas command: :saveas animal_farm_2.py.

Let's exit Vim and check if the file was indeed created. :q stands for quit. You can also combine write and quit commands to write and exit by executing :wq.

:q

If you made changes to a file and want to exit Vim without saving the changes, you'll have to use :q! to force Vim to quit. Exclamation mark at the end of the command forces its execution.

Many commands in Vim have shorter and longer versions. For instance, :e, :w, and :q are short versions of :edit, :write, and :quit. In the Vim manual, the optional part of the command is often annotated in square brackets ([]). For example, :w[rite] or :e[dit].

Now that we're back in our system's Command line, let's check the contents of a current directory, as seen in the following code:

$ ls
$ python3 animal_farm.py
$ python3 animal_farm.py cat dog sheep
In Unix, ls lists contents of a current directory. python3 animal_farm.py executes the script using a Python 3 interpreter, and python3 animal_farm.py cat dog sheep passes three arguments (cat, dog, sheep) to our script.

The following screenshot shows what the three preceding commands should output:

A word about swap files

By default, Vim keeps track of the changes you make to files in swap files. The swap files are created as you edit the files, and are used to recover the contents of your files in case either Vim, your SSH session, or your machine crashes. If you don't exit Vim cleanly, you'll be greeted by the following screen:

You can either hit r to recover the swap file contents, or d to delete the swap file and dismiss the changes. If you decide to recover the swap file, you can prevent the same message from showing up next time you open the file in Vim by reopening a file and running :e, and pressing d to delete the swap file.

By default, Vim creates files like <filename>.swp and .<filename>.swp in the same directory as the original file. If you don't like your file system being littered by swap files, you can change this behavior by telling Vim to place all the swap files in a single directory. To do so, add the following to your .vimrc:

set directory=$HOME/.vim/swap//
If you're on Windows, you should use set directory=%USERDATA%\.vim\swap// (note the direction of the last two slashes).

You can also choose to disable the swap files completely by adding set noswapfile to your .vimrc.

Moving around: talk to your editor

Vim allows you to navigate content a lot more efficiently than most conventional editors. Let's start with the basics.

You can move your cursor around character by character by using arrow keys or letters h, j, k, and l. This is the least efficient and the most precise way to move:

Key Alternative key Action
h Left arrow Move cursor left
j Down arrow Move cursor down
k Up arrow Move cursor up
l Right arrow Move cursor right

The following diagram is a visual representation which might be a little easier on the eyes:

Vi (Vim's predecessor) was created on an old ADM-3A terminal, which didn't have arrow keys. Keys h, j, k, and l were used as arrows.




Image by Chris Jacobs, Wikipedia (CC BY-SA 3.0)

Try it! There's a lot of value to getting used to hjkl for movement: your hands stay on the home row of your keyboard. This way you don't have to move your hands and it helps you stay in the flow. Furthermore, many applications treat hjkl as arrow keys—you'd be surprised how many tools respond to these.

Now you might be inclined to hit directional keys multiple times to get to a desired position, but there's a better way! You can prefix every command by a number, which would repeat the command that number of times. For example, hitting 5j will move the cursor five lines down, while hitting 14l will move the cursor 14 characters to the left. This works with most commands you encounter in this book.

Calculating the exact number of characters you would like to move is pretty hard (and nobody wants to do it), so there's a way to move by words. Use w to move to the beginning of the next word, and use e to get to the end of the closest word. To move backwards to the beginning of the word, hit b.

You can also capitalize these letters to treat everything but a white space as a word! This allows you to differentiate between the kind of things you'd like to traverse.

Vim has two kinds of word objects: referred to as lowercase "word" and uppercase "WORD". In Vim world, word is a sequence of letters, digits, and underscores separated by white space. WORD is a sequence of any non-blank characters separated by white space.

Let's take the following line of code from our example:

Notice the cursor position, it's hovering over the first character of add_animal.

Hitting w will move the cursor to beginning of the word add_animal, while hitting W will take you to the beginning of animal. Capitalized W, E, and B will treat any characters bundled together and separated by a space as their own words. This can be seen in the following table:

Key Action
w Move forward by word
e Move forward until the end of the word
W Move forward by WORD
E Move forward until the end of the WORD
b Move backwards to the beginning of the word
B Move backwards to the beginning of the WORD

The following screenshot shows more examples of how each command behaves:

Key Initial cursor position Resulting cursor position
w
e
b
W
E
B

Combine the movements shown with the directional movements you learned earlier to move in fewer keystrokes!

It's also really useful to move in paragraphs. Everything separated by at least two new lines is considered a paragraph, which also means each code block is a paragraph, as can be seen in the following example:

The functions add_animal and main are two separate paragraphs. Use a closing curly brace } to move forward, and an opening curly brace { to move backwards as detailed in the following table:

Command Action
{ Move back by one paragraph
} Move forward by one paragraph

Don't forget to combine these two with numbers if you need to move by more than one paragraph.

There are more ways to move around, but these are the most important basics. We'll be covering more complex ways to navigate in chapter 2, Advanced Editing and Navigation.

Making simple edits in insert mode

When working with Vim, you usually want to spend as little time as possible in the insert mode (unless you're writing and not editing). Since most text operations involve editing, we'll focus on that.

You've already learned to enter the insert mode by pressing i. There are more ways to get to the insert mode. Often times you will want to change some piece of text for another one, and there's a command just for that c. The change command allows you to remove a portion of text and immediately enter an insert mode. Change is a compound command, meaning that it needs to be followed by a command which tells Vim what needs to be changed. You can combine it with any of the movement commands you've learned before. Here are some examples:

Command Before After
cw
c3e (comma counts as a word)
cb
c4l
cW
As an odd exception, cw behaves like ce. This is a leftover from Vi, Vim's predecessor.

As you learn more complex movements commands, you can combine these with a change for quick and seamless editing. We'll also be covering a few plugins which will supercharge a change command to allow for even more powerful editing, like changing text within braces, or replacing the type of quotes on the go.

All of these examples follow the <command> <number> <movement or a text object> structure. You can put a number before or after the <command>.

For example, if you wish to change farm = add_animal(farm, animal) to farm = add_animal(farm, creature), you can execute the following set of commands:

Contents of the line Action
Start with a cursor in the beginning of the line
Hit 3W to move the cursor three WORDs forward to the beginning of animal
Press cw to delete the word animal and enter the insert mode
Type creature

Hit the Esc key to return to NORMAL mode

Sometimes we just want to cut things, without putting anything instead, and d does just that. It stands for delete. It behaves similarly to c, except that the behavior of w and e is more standard, as can be seen in the following example:

Command Before After
dw
d3e (comma counts as a word)
db
d4l
dW

There are also two more nifty shortcuts which allow you to change or delete a whole line:

Command What it does
cc Clears the whole line and enters insert mode. Preserves current indentation level, which is useful when coding.
dd Deletes an entire line.

For example, look at the following piece:

By hitting dd you will completely remove a line, as demonstrated in the following example:

Hitting cc will clear the line and enter insert mode with the proper indent, as shown in the following example:

If you run into difficulties picking the right movement commands, you can also use the visual mode to select text you want to modify. Hit v to enter the visual mode and use the usual movement commands to adjust the selection. Run the desired command (like c to change or d to delete) once you're satisfied with the selection.

Persistent undo and repeat

Like any editor, Vim keeps track of every operation. Press u to undo a last operation, and Ctrl + r to redo it.

To learn more about Vim's undo tree (Vim's undo history is not linear!) and how to navigate it, see chapter 4, Advanced Workflows.

Vim also allows you to persist undo history between sessions, which is great if you want to undo (or remember) something you've done a few days ago!

You can enable persistent undo by adding the following line to your .vimrc:

set undofile

However, this will litter your system with an undo file for each file you're editing. You can consolidate the undo files in a single directory, as seen in the following example:

" Set up persistent undo across all files.
set undofile
if !isdirectory(expand("$HOME/.vim/undodir"))
call mkdir(expand("$HOME/.vim/undodir"), "p")
endif
set undodir=$HOME/.vim/undodir

If you're using Windows, replace the directories with %USERPROFILE%\vimfiles\undodir (and you'll be making changes to _vimrc instead of .vimrc).

Now, you'll be able to undo and redo your changes across sessions.

Read the Vim manual using :help

The best learning tool Vim can offer is certainly a :help command, as can be seen in the following screenshot:

It's an enormous collection of resources and tutorials which comes installed with Vim. Scroll through using the Page Up and Page Down keys (bonus point for using Ctrl + b and Ctrl + f respectively), there is a lot of useful information there.

Whenever you are stuck, or want to learn more about a particular command, try searching it using :help (you can shorten it to :h). Let's try searching for a cc command we've learned :

:h cc

Help tells us the way the command works, as well as how different options and settings affect the command (for instance autoindent setting preserves the indentation).

:help is a command which navigates a set of help files. As you look through the help files, you'll notice that certain words are highlighted in color. These are tags, and can be searched for using the :help command. Unfortunately, not every tag name is intuitive. For instance, if we wanted to learn how to search for a string in Vim, we could try using the following:

:h search

However, it looks like this command takes us to the entry on expression evaluation, which is not exactly what we were looking for, as demonstrated by the following screenshot:

To find the right entry, type in :h search (don't hit Enter yet) followed by Ctrl + d. This will give you a list of help tags containing the substring search. One of the options shown is search-commands which is what we'd be looking for. Complete your command in the following way to get to the entry we were looking for:

:h search-commands

The following display shows the right help entry for search:

Speaking of search functionality, you can search inside help pages (or any file open in Vim) using /search term to search forward from the cursor or ?search term to search backward. See Chapter 2 , Advanced Editing and Navigation, to learn more about how to perform search operations.

Don't forget to use Vim's help system any time you have questions or want to better understand the way Vim behaves.

Summary

The original Vi was developed to work through remote terminals, when bandwidth and speed were limited. These limitations guided Vi towards establishing an efficient and deliberate editing process, which is what's at the core of Vim—Vi Improved today.

In this chapter, you've learned how to install and update Vim and it's graphical counterpart—GVim, on every major platform (in more ways than you will ever need).

You've learned to configure your Vim through tinkering with .vimrc, which is something you will often go back to as you customize the editor for your own needs.

You've picked up the basics of working with files, moving around Vim, and making changes. Vim's concept of text objects (letters, words, paragraphs) and composite commands (like d2w - delete 2 words) empower precise text operations.

And if there's one thing you could take away from this chapter, it would be :help. Vim's internal help system is incredibly detailed, and it can answer most, if not every, question you might have, as long as you know what you're looking for.

In the next chapter, we'll be looking into getting more out of Vim. You'll learn how to navigate files and get better at editing text.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Expert Vim and Vimscript techniques to work with Python and other development environment
  • Accomplish end-to-end software development tasks with Neovim and Vim plugins
  • Understand best practices for various facets of projects like version control, building, and testing

Description

Vim is a ubiquitous text editor that can be used for all programming languages. It has an extensive plugin system and integrates with many tools. Vim offers an extensible and customizable development environment for programmers, making it one of the most popular text editors in the world. Mastering Vim begins with explaining how the Vim editor will help you build applications efficiently. With the fundamentals of Vim, you will be taken through the Vim philosophy. As you make your way through the chapters, you will learn about advanced movement, text operations, and how Vim can be used as a Python (or any other language for that matter) IDE. The book will then cover essential tasks, such as refactoring, debugging, building, testing, and working with a version control system, as well as plugin configuration and management. In the concluding chapters, you will be introduced to additional mindset guidelines, learn to personalize your Vim experience, and go above and beyond with Vimscript. By the end of this book, you will be sufficiently confident to make Vim (or its fork, Neovim) your first choice when writing applications in Python and other programming languages.

Who is this book for?

Mastering Vim is written for beginner, intermediate, and expert developers.The book will teach you to effectively embed Vim in your daily workflow. No prior experience with Python or Vim is required.

What you will learn

  • Get the most recent Vim, GVim, and Neovim versions installed
  • Become efficient at navigating and editing text
  • Uncover niche Vim plugins and pick the best ones
  • Discover multiple ways of organizing plugins
  • Explore and tailor Vim UI to fit your needs
  • Organize and maintain Vim configuration across environments
  • Write scripts to complement your workflow using Vimscript
Estimated delivery fee Deliver to Portugal

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 30, 2018
Length: 330 pages
Edition : 1st
Language : English
ISBN-13 : 9781789341096
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Portugal

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Nov 30, 2018
Length: 330 pages
Edition : 1st
Language : English
ISBN-13 : 9781789341096
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 120.97
Mastering Vim
€41.99
Mastering Reverse Engineering
€36.99
Hands-On System Programming with Linux
€41.99
Total 120.97 Stars icon
Banner background image

Table of Contents

11 Chapters
Getting Started Chevron down icon Chevron up icon
Advanced Editing and Navigation Chevron down icon Chevron up icon
Follow the Leader - Plugin Management Chevron down icon Chevron up icon
Understanding the Text Chevron down icon Chevron up icon
Build, Test, and Execute Chevron down icon Chevron up icon
Refactoring Code with Regex and Macros Chevron down icon Chevron up icon
Making Vim Your Own Chevron down icon Chevron up icon
Transcending the Mundane with Vimscript Chevron down icon Chevron up icon
Neovim Chevron down icon Chevron up icon
Where to Go from Here Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(9 Ratings)
5 star 77.8%
4 star 11.1%
3 star 0%
2 star 0%
1 star 11.1%
Filter icon Filter
Top Reviews

Filter reviews by




Rick Price Apr 08, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good book about Vim. Got me going with Vim again.
Amazon Verified review Amazon
Jari Oct 15, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have been searching for a text editor and now I found it!
Amazon Verified review Amazon
Zachary L. Stauber Jul 07, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This isn't the most complete book, but honestly that's why it's so great: it's short-ish but packed with useful information. The author gives a good, thorough (not complete) run down on navigating in Vim, its most common functions (e.g., search and replace, clipboards and registers, including how to pull from the Windows/Linux/MacOS X clipboard, Vim built-in file manager, using shell commands and terminal windows without leaving Vim, etc.), customizing your .vimrc, and using and even writing plugins with vimscript. I'm an amateur programmer who's been using Vim since he was forced to use the Vi Editor in a freshman ForTran class in 1993, and it was the only universal editor on every *nix system I've ever had to use, so I wanted to learn more. I've started and quickly dropped a number of Vim books. This was the only one I finished, and so if you want to fall in love with Vim, but didn't know how to start, this is your book.
Amazon Verified review Amazon
Nicholas Sardo Apr 03, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've thus far read a few chapters, skimmed a few others-- this is the book I wish I'd had years ago. I resisted learning Vim for a long time. Finally, years ago I decided to dabble with it. I learned enough to be dangerous, and with just that level of knowledge, it increased my productivity by an order of magnitude. Everything I read after that was dry, or didn't tell me what I wanted to know in an easily findable way. Once you learn the basics, believe me, even if you move to a VSCode, Jetbrains, Sublime, or other editor-- the first thing you'll do is find a plugin to access Vim keyboarding.This book takes you from the start of installing Vim, to learning essential commands, to dealing with plugins, etc., In a very accessible way. Mr. Osipov clearly knows what he's doing, and more importantly, is able to pass on that knowledge in an understandable way. Virtually all Packt books I've purchased are weak in the editing part of things, it's just something I've come to accept. Ultimately, for me, it's the knowledge I'm paying for.If you want to learn Vim.. and, you really, really should: This. Is. Your. Book.
Amazon Verified review Amazon
Jerome Lanteri Jan 19, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Livre bien écrit, couvrant une bonne partie (et de façon très large) de ce qui peut se aire.Les concepts sont clairement exposés et sans oublier vimscript.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela