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: Efficient and effortless editing with Vim and Vimscript , Second Edition

eBook
€17.99 €25.99
Paperback
€31.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
Product feature icon AI Assistant (beta) to help accelerate your learning
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 that will teach you how 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 no 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 with 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:

  • The difference between major Vim versions
  • 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 configuration
  • Common file operations – opening, modifying, saving, and closing files
  • Moving around – navigating with arrow keys and cursor movement keys, 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-Second-Edition/tree/main/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.

Working with Python 2 code

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 configurations, which are stored in a .vimrc file. The resulting .vimrc file is available from the previously mentioned GitHub link.

A brief history lesson

Let’s go back to the beginning of time: the middle of the twentieth century. Before personal computers and terminals, there were teleprinters. A teleprinter is a mechanical typewriter that can send and receive messages over a telecommunications channel. Here’s a photo of the Teletype ASR-33 (1963) teleprinter – a fancy typewriter that was used as an interface and an input device for a computing machine:

Figure 1.1 –  Teletype Corporation ASR-33 teleprinter (image by Arnold Reinhold, Wikipedia (CC BY-SA 3.0))

Figure 1.1 – Teletype Corporation ASR-33 teleprinter (image by Arnold Reinhold, Wikipedia (CC BY-SA 3.0))

The only way to engage with the text through teleprinters was line by line, so line editors such as ed (developed by Ken Thompson) or its successor – Bill Joy’s ex – were used. Line editors were, just like Vim is today, modal editors (more about that in a bit) but, due to aforementioned input/output limitations, were limited to working on one line at a time. Yes, really.

As technology progressed, teleprinters were replaced by terminals with screens, which enabled much more robust text editing. Vim’s direct predecessor, vi, started its life all the way back in 1976. Unlike its predecessors, vi (developed by Bill Joy, the author of ex) included many quality-of-life features and even allowed you to edit multiple lines of text at once – what a luxury!

Did you know?

On many modern systems, the vi command is a symlink to a feature-limited version of vim referred to as vim-tiny (rather than the original vi implementation)!

Vi inspired many clones, including STEVIE (ST Editor for VI Enthusiasts): and STEVIE source code is what was eventually used as a basis for Vim. The first version of Vim was released in 1991 by Bram Moolenaar. Now, you’re all caught up!

While it’s not very likely that you’ll stumble upon a device with Vim that hasn’t been updated since the late 1990s, it helps to get a basic idea of what changed between different Vim versions.

Here, you can see the (oversimplified) highlights of each major version of Vim up until the moment of writing the second edition of this book. Vim has been in some form of continuous development since 1991!

Major version

Years

Highlights

1.0

1991

Bram Moolenaar releases Vi Imitation for the Amiga computer.

2.0

1993

Vi Improved is released under its modern name!

3.0

1994

Multiple windows.

4.0

1996

Graphical interface support.

5.0 – 5.8

1998 – 2001

Syntax highlighting, scripting, and select mode are added.

6.0 – 6.4

2001 – 2005

Plugin support and folding support are added.

7.0 – 7.4

2006 – 2013

Notable new features include spell checking, code completion, tabs, branching history, and persistent undo.

8.0 – 8.2

2016 – 2019

Optimizations, asynchronous I/O support, built-in terminal, and pop-up windows are available.

9.0

2022

Introduction of the new scripting language (Vim9script).

Just like with vi, there are many Vim clones, and some are quite successful. This book covers one of the more successful alternative implementations of Vim in Chapter 9.

Ask for :help

If you’re interested in a more detailed breakdown of the differences between the versions, you can open :help (you’ll learn how to use that by the end of the chapter) and look for “Versions”. Try :help version9 to see what’s new in Vim 9!

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. If you’re old enough to remember a time before smartphones, many landlines and early mobile phones were also modeless.

The term modeless refers to the fact that 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.

However, this is 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.

Figure 1.2 – A smartphone uses a modal interface, while the traditional phone is (mostly) modeless

Figure 1.2 – A smartphone uses a modal interface, while the traditional phone is (mostly) modeless

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. However, as soon as you switch to a different mode, the letter o will change its function to add 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 the 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 has a certain sense of flow to it: you ask the editor to perform actions 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 macOS (however, you may want to upgrade Vim to a more recent version). You have different options for setting up Vim depending on your operating system and preference, and here’s a handy crude drawing showing some of the more common options:

Figure 1.3 – Options for installing Vim across different OSs

Figure 1.3 – Options for installing Vim across different OSs

Find your system in the following sections, and skim through the instructions to set it up.

Why so many screenshots?

You’ll see that I’ve included a large number of details and screenshots in the following installation instructions. While Vim is easily available on most platforms, getting the latest version of Vim installed is not as straightforward as one would expect. If you realize that you’re using the wrong version of Vim – you can always go back to the instructions in this chapter for help.

Setting up on Linux and Unix-like systems

Linux machines come with Vim installed, which is great news! However, it might be rather out of date, and a new version of Vim often includes new functionality and optimization changes (you can read more about changes between versions in the A brief history lesson section of this chapter). Pull up your Command Prompt and run the following code to build an up-to-date Vim from the latest patch (at the time of cloning the source repository):

$ git clone https://github.com/vim/vim.git
$ cd vim/src
$ ./configure --prefix=/usr/local --with-features=huge
$ make
$ sudo make install

Keep on reading to learn more about Compilation options in the next section.

Missing dependencies

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-dev libncursesw5-dev --fix-missing

This will make sure that you’re on the latest major and minor patches of Vim. If you don’t care about 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/System

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

Pay attention to names

You can see in the preceding table that Vim uses different package names for different repositories. Packages such as vim-gtk on Debian-based distributions or vim-enhanced on CentOS come with more features enabled (such as 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

vim versus vi

Vi is Vim’s predecessor (Vim stands for Vi Improved) and is available to be invoked via the vi command. On some distributions, the vi command links to a feature-stripped version of Vim (aka vim-tiny), while on some it’s merely a symlink to a feature-complete Vim.

Compilation options

Compiling from source is often the best way to receive the latest available version of Vim. If you’re not afraid to get your hands dirty, you might want to know about common compilation options.

This section will cover various options for the configure command. To compile Vim, you’ll have to run the following commands, with <options> replaced with the desired compilation options:

$ git clone https://github.com/vim/vim.git
$ cd vim/src
$ ./configure <options>
$ make
$ sudo make install

You can control installation location with --prefix:

  • --prefix=/usr/local as a reasonable default for a system-wide installation
  • --prefix=$HOME/.local will make the newly installed Vim only available to your user

Feature sets allow you to enable different sets of features to be available in Vim, with options being tiny, small, normal, big, and huge. The most interesting options include the following:

  • --with-features=huge includes all possible features, including experimental ones
  • --with-features=normal includes a reasonable feature set, which is mostly covered in this book
  • --with-features=tiny only offers bare-bones essentials, without syntax highlighting or plugin support

Language support is controlled via the --enable-<language>interp option. Note that this refers to the ability of Vim’s internals to interact with the selected programming language (e.g., in plugins or your own scripts), and not your ability to edit said files. Some options include the following:

  • --enable-luainterp=yes enables Lua support
  • --enable-perlinterp=yes enables Perl support
  • --enable-python3interp=yes enables Python 3 support
  • --enable-rubyinterp=yes enables Ruby support

Finally, to integrate the clipboard with the X11 Window System (that is, your system-wide clipboard on Linux), you might want to compile Vim with the --with-x option. Note that you might need the X development library (e.g., you can use sudo apt install libx11-dev libxtst-dev if you’re using the apt package manager).

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. However, 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:

$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Once you run that prompt, hit Enter to continue (as many times as you need to).

If you don’t have Xcode

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 popup. 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 the Installation successful! message 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.

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 latest 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:

Figure 1.4 – Vim on macOS (installed via Homebrew)

Figure 1.4 – Vim on macOS (installed via Homebrew)

Let’s move on to the next section about downloading a .dmg image.

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:

Figure 1.5 – The MacVim installation screen – drag and drop MacVim into the Applications folder

Figure 1.5 – The MacVim installation screen – drag and drop MacVim into the Applications folder

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:

Figure 1.6 – The default “unidentified developer” prompt

Figure 1.6 – The default “unidentified developer” prompt

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

Figure 1.7 – The “unidentified developer” prompt, which you can get by right-clicking and selecting Open

Figure 1.7 – The “unidentified developer” prompt, which you can get by right-clicking and selecting Open

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

Figure 1.8 – MacVim on macOS

Figure 1.8 – MacVim on macOS

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 a powerful Unix shell and supporting tools to a Windows machine.

Windows Subsystem for Linux (WSL)

WSL is a feature in Windows 10+ that allows you to run a Linux environment directly in Windows. While I personally haven’t had experience with WSL, it’s widely praised as a fast, user-friendly, and reliable way to access the Linux command line and tools on Windows. It could be a better alternative to Cygwin as it continues to be developed. You can read more about WSL at https://learn.microsoft.com/windows/wsl.

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).

How many bits are in your system?

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:

Figure 1.9 – The Cygwin Setup screen on Windows

Figure 1.9 – The Cygwin Setup screen on Windows

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:

Figure 1.10 – Cygwin package selection screen – note that gvim, vim, and vim-doc are marked to be installed, as seen in the New column

Figure 1.10 – Cygwin package selection screen – note that gvim, vim, and vim-doc are marked to be installed, as seen in the New column

The preceding screenshot shows version 8.2.4372-2. This is the latest version available at the moment of writing this chapter, July 2023. At this time, the latest version of Vim is 9.0, which introduces Vim9script (you can learn more about version differences in the A brief history lesson section).

Use Cygwin to compile Vim

If you’d like to have the latest version of Vim, I recommend using Cygwin to compile Vim from its official Git repository. After installing Cygwin, you should visit the Setting up on Linux section we covered earlier in this chapter for the instructions. If you’d like to do that, you’ll want to install git and make utilities in Cygwin.

You might need additional utilities

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. The 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!

Installing Cygwin packages

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:

Figure 1.11 – The Cygwin64 Terminal application icon

Figure 1.11 – The Cygwin64 Terminal application icon

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

Figure 1.12 – The Cygwin command prompt for the user called ruslan and the RUSLAN-DESKTOP machine

Figure 1.12 – The Cygwin command prompt for the user called ruslan and the RUSLAN-DESKTOP machine

Cygwin supports all of the Unix-style commands we will be using in this book. This book will also say whether any commands need to be changed to work with Cygwin.

Type vim and hit Enter to start Vim, as demonstrated in the following screenshot:

Figure 1.13 – Vim is installed through Cygwin (note Modified by <cygwin@cygwin.com>)

Figure 1.13 – Vim is installed through Cygwin (note Modified by <[email protected]>)

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 versus 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 it is unable to recognize, run the dos2unix utility on the offending file to resolve the issue.

Visual Vim with gVim

You can read more about the graphical version of Vim in the Vanilla Vim versus gVim section later in this chapter.

As it always is with Windows, the process is slightly more visual. Navigate to github.com/vim/vim-win32-installer in your browser and download an executable installer. At the moment of writing this chapter, July 2023, the latest available version of Gvim is 9.0.

You can use winget instead

Alternatively, if you’re familiar with the winget tool, you can run winget install -e --id vim.vim (substitute with vim.vim.nightly if you’d like to live on the bleeding edge).

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

Figure 1.14 – gVim 9.0 setup welcome screen

Figure 1.14 – gVim 9.0 setup welcome screen

Let’s go ahead and hit Next, 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 the 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:

Figure 1.15 – gVim installation screen – note that Create .bat files is selected

Figure 1.15 – gVim installation screen – note that Create .bat files is selected

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, the 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. Say No to the request to see the README file (or say Yes – I’m a book, not a cop).

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

Figure 1.16 – The gVim 9.0 application icon

Figure 1.16 – The gVim 9.0 application icon

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

Setting up on ChromeOS

ChromeOS has become increasingly popular – especially in the education sector and in a fraction of corporate settings. Chrome devices are cheap, user friendly, and can run on a potato with a couple of wires sticking out of it. I have been using a Chromebook as a daily driver for work for a couple of years now – and, thankfully, you don’t have to abandon having Vim if ChromeOS is a platform of choice for you.

To run Vim on your ChromeOS device, you need to be able to install a Linux environment alongside it. It’s not a complicated procedure, doesn’t require dual booting, and provides seamless integration between ChromeOS and a Linux environment.

Linux support in ChromeOS

Some legacy ChromeOS devices don’t support running a Linux environment, and you can check whether your device supports Linux by opening the Settings app and searching for Linux. If this yields no results, you won’t be able to use Vim on your ChromeOS device.

First, set up Linux to run on ChromeOS by opening the Settings app, and navigating through the Advanced | Developers | Linux development environment | Turn on options:

Figure 1.17 – A prompt to turn on a Linux development environment on a Chromebook

Figure 1.17 – A prompt to turn on a Linux development environment on a Chromebook

You’ll be greeted by a prompt to set up a Linux development environment. Hit Next to continue. The default settings are sufficient, as demonstrated in the following screenshot:

Figure 1.18 – The setup screen for a Linux development environment – it’s fine to go with the recommended settings

Figure 1.18 – The setup screen for a Linux development environment – it’s fine to go with the recommended settings

Hit Install, and the whole setup should be over in under a couple of minutes.

The newly installed Debian Linux environment is accessible through the Terminal app. The default environment name is penguin, so you just need to select that:

Figure 1.19 – Linux environment titled penguin installed on a ChromeOS

Figure 1.19 – Linux environment titled penguin installed on a ChromeOS

You’ll see a (hopefully familiar) Linux command-line prompt:

Figure 1.20 – Linux terminal within ChromeOS (a silly cowsay command can be installed by running $ sudo apt install cowsay)

Figure 1.20 – Linux terminal within ChromeOS (a silly cowsay command can be installed by running $ sudo apt install cowsay)

Vim comes preinstalled on a vast majority of Linux machines, and this one is not an exception: you should already have access to Vim.

Compile Vim for the latest version

If you’d like to have the latest version of Vim, I recommend compiling Vim from its official Git repository (it’s easy). Visit the Setting up on Linux section earlier in this chapter for instructions on installing the latest Vim version.

Now, you can launch Vim by invoking it from the terminal:

$ vim

This is the output as shown here:

Figure 1.21 – Vim welcome screen, as seen in the ChromeOS terminal

Figure 1.21 – Vim welcome screen, as seen in the ChromeOS terminal

Access ChromeOS files through Linux

Due to integration between ChromeOS and Linux, you can access your Linux home directory (accessible via the cd ~ command from the Terminal window) via the ChromeOS Files app:

Figure 1.22 – You can access Linux files through the ChromeOS Files app

In addition, you can share individual ChromeOS files with Linux by right-clicking on the file and selecting Share with Linux. This makes the files accessible in Linux via the /mnt/chromeos directory.

Verifying and troubleshooting the installation

Regardless of the platform you use to install Vim, it’s good to make sure that, with Vim, all the right features are 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:

Figure 1.23 – Output of the vim --version command

Figure 1.23 – Output of the vim --version command

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 (for which I’d have to install required dependencies) or find a package that distributes a compiled version of Vim with +python3 enabled.

Vim integrations

Note that +python3 and similar options refer to Python 3 integration of Vim. You can still edit any file you want (including Python 3), but it does mean your Vim instance, plugins, and scripts won’t be able to run Python 3.

Ask for :help

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

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

$ git clone https://github.com/vim/vim.git
$ cd vim/src
$ ./configure --prefix=/usr/local \
    --with-features=huge \
    --enable-python3interp
$ make
$ sudo make install

Specifying feature sets

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 the behavior described in this book), you might be missing a feature.

Depending on your system and the 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.

Now that you’re through the installation instructions, let’s look a little closer at what we’ve installed.

Vanilla Vim versus gVim

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

Figure 1.24 – gVim interface in Windows

Figure 1.24 – gVim interface in 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 colors than many terminal emulators and provides some quality-of-life features you’d expect from a modern GUI.

You can launch gVim by running the gVim 9.0 executable on Windows, or on Linux and macOS 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 configurations, 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 that make working with code a lot easier.

Spot hidden files

In Unix-like systems, files that start 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 your user directory by opening a Command Prompt and running the following command:

$ echo $HOME

Older versions of Windows Explorer did 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%

Locating .vimrc

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

Find the proper location for your OS, and place the prepared configuration file there. You can download the .vimrc file used for this chapter from GitHub at https://github.com/PacktPublishing/Mastering-Vim-Second-Edition/tree/main/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 options.
set nocompatible " Don't run in backwards compatible mode.
set autoindent " Respect indentation when starting 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.

You’ll eventually want to change these

For extra credit, you may want to limit some options to Python only – especially if you’re (hopefully) planning to use Vim as your primary editor for multiple file types. I recommend you prefix certain options with autocmd filetype python, which will only apply options to Python files:

autocmd filetype python set expandtab

autocmd filetype python set tabstop=4

autocmd filetype python set shiftwidth=4

Lines starting with a double quote (") are comments and are ignored by Vim. These settings bring in some sensible defaults, such as 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.

Trying out the configuration options

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 colorscheme to make screenshots look better in print, but you don’t have to (unless you’re writing a book about Vim – then you probably should).

The world is full of colors

Vim 9 comes prepackaged with many color themes, and the list grows with every release. 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 (including using color schemes you find online) in Chapter 7.

You’ve configured Vim, and now it’s time to learn how to actually use it!

Common operations (or, how to exit Vim)

We will now focus on interacting with Vim without the use of a mouse or navigational menus. Here’s a meme I found some years back:

Figure 1.25 – An accurate portrayal of a typical Vim user (source: https://twitter.com/iamdevloper/status/435555976687923200)

Figure 1.25 – An accurate portrayal of a typical Vim user (source: https://twitter.com/iamdevloper/status/435555976687923200)

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.

In this section, we’ll learn how to open (and, more importantly, close) Vim, save files, and make basic edits.

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 spam.py

GUI for the win!

If you’re using gVim, you can open a file by going into a File menu and choosing Open. Sometimes, a graphical interface is exactly what you need!

This opens a file named spam.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:

Figure 1.26 – Opening a new file in Vim as indicated by the [New File] text

Figure 1.26 – Opening a new file in Vim as indicated by the [New File] text

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

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

:e spam.py

You have just executed your first Vim command! Pressing the colon character (:) enters a command-line mode, which lets you enter a line of text that 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. The :e command 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:

Figure 1.27 – Vim in insert mode, as indicated by -- INSERT -- in the bottom-left corner

Figure 1.27 – Vim in insert mode, as indicated by -- INSERT -- in the bottom-left corner

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.

Modes, modes, modes

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 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:

Figure 1.28 – A simple Python 3 program referencing Monty Python’s “Spam” sketch

Figure 1.28 – A simple Python 3 program referencing Monty Python’s “Spam” sketch

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!

This code isn’t very good

The preceding code does not display 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 execute the command!

Don’t forget to hit Enter at the end of a command to execute it.

:w stands for write.

Naming files

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 spam_2.py). To change the currently open file to a new one when saving, use the :saveas command: :saveas spam_2.py.

Let’s exit Vim and check whether 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. The exclamation mark at the end of the command forces its execution.

Shortening commands

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 spam.py

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

Figure 1.29 – Output of the ls -a and python3 spam.py commands

Figure 1.29 – Output of the ls -a and python3 spam.py commands

Command spotlight

In Unix, ls lists the contents of a current directory (the –a flag shows hidden files). python3 spam.py executes the script using a Python 3 interpreter.

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, or try to edit the same file multiple times at the same time, you’ll be greeted by the following screen:

Figure 1.30 – A swap file error when attempting to open a file

Figure 1.30 – A swap file error when attempting to open a file

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 the next time you open the file in Vim by reopening a file, running :e, and pressing d to delete the swap file (although Vim won’t let you delete the swap file if the file in question is currently open in another Vim instance).

By default, Vim creates files such as <filename>.swp and .<filename>.swp in the same directory as the original file. If you don’t like your file system being littered with 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//

Note that double directory delimiter at the end; this setting won’t work correctly without it!

For Windows users

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.

“But,” I hear you say, “I spend most of my time navigating code (or text) rather than writing it top to bottom!” Never fret, as this is what sets Vim apart from conventional editors. The next section will teach you to navigate around what you just wrote.

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 the h, j, k, and l keys. 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 that might be a little easier on the eyes:

Figure 1.31 – Visual representation of the h, j, k, and l directional keys

Figure 1.31 – Visual representation of the h, j, k, and l directional keys

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

Figure 1.32 – The ADM-3A terminal (image by Chris Jacobs, Wikipedia (CC BY-SA 3.0))

Figure 1.32 – The ADM-3A terminal (image by Chris Jacobs, Wikipedia (CC BY-SA 3.0))

Try it! There’s a lot of value to getting used to the h, j, k, and l keys for movement; for example, 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 h, j, k, and l 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 with a number, which would repeat the command that number of times. For example, hitting 5 + j will move the cursor five lines down, while hitting 1 + 4 + l will move the cursor 14 characters to the right. 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 backward 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 the Vim world, word is a sequence of letters, digits, and underscores. WORD is a sequence of any non-blank characters separated by white space (it’s technically more complicated than that; see :help iskeyword if you’re curious).

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

Note

Notice the cursor position – it’s hovering over the first character of ingredient.

Hitting w will move the cursor to the next comma while hitting W will take you to the beginning of with_spam. 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 backward to the beginning of the word

B

Move backward 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:

Figure 1.33 – You can see three paragraphs here

Figure 1.33 – You can see three paragraphs here

The INGREDIENTS constant, and the prepare_menu_item and main functions are three separate paragraphs. Use a closing curly brace, }, to move forward, and an opening curly brace, {, to move backward, 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.

Figure 1.34 – A visual representation of basic movement keys in Vim

Figure 1.34 – A visual representation of basic movement keys in Vim

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.

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, 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 that 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

Cb

c4l

cW

words versus WORDS

Remember, non-alphanumeric characters (including punctuation) are treated as words. For example, prepare_menu_item(ingredient, has_spam) will be considered six words (but only one WORD): prepare_menu_item, (, ingredient, , (comma), has_spam, and ).

Exception

As an odd exception, cw behaves like ce. This is a leftover from Vi, Vim’s predecessor.

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

Just like a sentence

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

For example, say you wish to change the following line:

prepare_menu_item(ingredient, with_spam=has_spam)

Say you want to change the ingredient to 'egg':

prepare_menu_item('egg', with_spam=has_spam)

To accomplish that, you can execute the following set of commands:

Contents of the line

Action

Start with a cursor at the beginning of the line

Hit 2w to move the cursor three words forward to the beginning of ingredient

Press cw to delete the ingredient word and enter the insert mode

Type 'egg'

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

db

d5l

dW

There are also two more nifty shortcuts that 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:

Figure 1.35 – A piece of code we wrote (or copied) earlier.

Figure 1.35 – A piece of code we wrote (or copied) earlier.

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

Figure 1.36 – dd removes a line and places the cursor on the next line

Figure 1.36 – dd removes a line and places the cursor on the next line

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

Figure 1.37 – cc clears the line, and puts you into insert mode at the beginning of the line.

Figure 1.37 – cc clears the line, and puts you into insert mode at the beginning of the line.

Visual mode

If you run into difficulties picking the right movement commands, you can also use the visual mode to select the 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 (such as 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.

Undo tree

To learn more about Vim’s undo tree (Vim’s undo history is not linear) and how to navigate it, see Chapter 4.

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
let my_undo_dir = expand('$HOME/.vim/undodir')
if !isdirectory(my_undo_dir))
  call mkdir(my_undo_dir, "p")
endif
set undodir=my_undo_dir

For Windows users

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:

Figure 1.38 – The :help page – if you’ve read it, you probably wouldn’t have needed to read this book

Figure 1.38 – The :help page – if you’ve read it, you probably wouldn’t have needed to read this book

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

:help help-summary

Consider reading through the help-summary page at some point in your Vim journey. It’s short, and arms you with many tools needed to navigate Vim help effectively. I incorporated some tips from help-summary in this section, but there are more!

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 the normal mode cc command we’ve learned:

:h cc

Here’s the output of this code:

Figure 1.39 – A :help page for a cc command

Figure 1.39 – A :help page for a cc command

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

Searching for options

In Vim help, options are always denoted with single quotation marks. For example, if you wanted to look for the autoindent option (remember set autoindent in your .vimrc?), you’ll execute :help 'autoindent'.

:help is a command that 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:

Figure 1.40 – A help page for a search() expression

Figure 1.40 – A help page for a search() expression

To find the right entry, type :h search (don’t hit Enter yet) followed by Ctrl + d. This will give you a list of help tags containing the search substring. 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:

Figure 1.41 – A :help page for search commands

Navigating search files

A discerning reader might notice certain keywords adorned with various characters ([, {, |, etc.) or highlighted (depending on your color scheme) in help pages. When your cursor is over a keyword in a help file, you can press Ctrl + ] to jump to the definition of the keyword, and Ctrl + o to jump back. Give it a shot!

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 to learn more about how to perform search operations.

Finally, Vim comes with a handy vimtutor utility, which you can invoke on the command line. This book covers most things that vimtutor teaches, but it doesn’t mean you should sleep on it – vimtutor includes many exercises that can build Vim commands into your muscle memory.

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 toward establishing an efficient and deliberate editing process, which is what’s at the core of Vim—Vi Improved today.

Throughout this chapter, you’ve picked up a few (hopefully) interesting tidbits about the history of Vim and the difference between its major versions.

You’ve learned how to install and update Vim and its 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 (such as d2w - delete 2 words) empower precise text operations.

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 all, questions 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

  • Develop proficiency in Vim and Vimscript for efficient text editing
  • Integrate Vim into your daily development workflow and customize it to suit your preferences
  • Learn through examples in Python code, explore scenarios with version control, and focus on the build/test flow
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Discover what makes Vim one of the most popular text editors in the world, renowned for its blend of efficiency, customization, extensibility, and portability. With Mastering Vim, you’ll come to appreciate its extensive plugin system and seamless integration with various tools, which enable Vim to provide developers with an extensible and customizable development environment for programmers. This comprehensive guide to Vim will help you become more efficient at editing text: be it prose or code. Starting from the basics, advanced movement, and text operations, you’ll learn how Vim can be used as a full-fledged IDE. You’ll then progress to refactoring, debugging, building, testing, version control, plugins, and Vimscript through practical guidance. This second edition comes packed with fully revamped examples that are both engaging and easy to understand, complemented by drawings and diagrams that help to visualize the concepts covered in the book. Updated to cover Vim 9, this edition includes updated installation and troubleshooting instructions, along with examples in Vim9script. By the end of this Vim book, you’ll be well-versed in Vim and have the skills you need to build a complete application using this popular text editor.

Who is this book for?

This book is for software developers interested in using Vim in their workflow. Anyone new to Vim and looking to gain in-depth knowledge will find this guide useful. Basic familiarity with Python programming is beneficial but not necessary to get started.

What you will learn

  • Become more efficient at navigating and editing text
  • Install and update Vim on Linux, Mac, Windows, and ChromeOS machines
  • Identify which plugins you need and how to keep them organized
  • Explore and tailor Vim configurations to fit your needs
  • Write scripts to complement your workflow using Vimscript
  • Learn that Vim is better than Emacs
Estimated delivery fee Deliver to Greece

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 31, 2024
Length: 300 pages
Edition : 2nd
Language : English
ISBN-13 : 9781835081877
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
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Greece

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Jul 31, 2024
Length: 300 pages
Edition : 2nd
Language : English
ISBN-13 : 9781835081877
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 83.96 103.97 20.01 saved
Modern Python Cookbook
€30.99 €41.99
Mastering Vim
€31.99
Hands-On Genetic Algorithms with Python
€20.98 €29.99
Total 83.96 103.97 20.01 saved Stars icon
Banner background image

Table of Contents

10 Chapters
Chapter 1: Getting Started Chevron down icon Chevron up icon
Chapter 2: Advanced Editing and Navigation Chevron down icon Chevron up icon
Chapter 3: Follow the Leader Plugin Management Chevron down icon Chevron up icon
Chapter 4: Understanding Structured Text Chevron down icon Chevron up icon
Chapter 5: Build, Test, and Execute Chevron down icon Chevron up icon
Chapter 6: Refactoring Code with Regex and Macros Chevron down icon Chevron up icon
Chapter 7: Making Vim Your Own Chevron down icon Chevron up icon
Chapter 8: Transcending the Mundane with Vimscript Chevron down icon Chevron up icon
Chapter 9: Where to Go from Here Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Tiny Aug 26, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Reading now - an excellent review of the basic principles of VIM, a historical background, and then tips and tricks coming rapid-fire to move skills ahead.
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