Movatterモバイル変換


[0]ホーム

URL:


Packt
Search iconClose icon
Search icon CANCEL
Subscription
0
Cart icon
Your Cart(0 item)
Close icon
You have no products in your basket yet
Save more on your purchases!discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Profile icon
Account
Close icon

Change country

Modal Close icon
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timerSALE ENDS IN
0Days
:
00Hours
:
00Minutes
:
00Seconds
Home> Programming> Programming Language> Mastering Vim
Mastering Vim
Mastering Vim

Mastering Vim: Efficient and effortless editing with Vim and Vimscript , Second Edition

Arrow left icon
Profile Icon Osipov
Arrow right icon
$29.99$33.99
Full star iconFull star iconFull star iconFull star iconFull star icon5(1 Ratings)
eBookJul 2024300 pages2nd Edition
eBook
$29.99 $33.99
Paperback
$41.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$29.99 $33.99
Paperback
$41.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Table of content iconView table of contentsPreview 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 itsideological 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 throughoutthis chapter.

The following topics will be covered inthis chapter:

  • The difference between majorVim versions
  • Modal versus modeless interfaces, and why is Vim different fromother editors
  • Installing andupdating Vim
  • The gVim – the graphical user interfacefor Vim
  • Configuring Vim for working with Python and editingyour configuration
  • Common file operations – opening, modifying, saving, andclosing files
  • Moving around – navigating with arrow keys and cursor movement keys, by words, paragraphs, andso on
  • Making simple edits to files and combining editing commands withmovement commands
  • Persistentundo history
  • Navigating the built-inVim 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 codeon 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 usingPython3 syntax.

Working with Python 2 code

If you must live in the past, you can convert Python 3 examples toPython 2 code by changing theprint() command syntax. Change all ofprint('Woof!') toprint 'Woof!' to make the code run inPython 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 mentionedGitHub 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 theTeletype ASR-33 (1963) teleprinter – a fancy typewriter that was used as an interface and an input device for acomputing 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))

Theonly way to engage with the text through teleprinters was line by line, so line editors such ased (developed by Ken Thompson) or its successor – Bill Joy’sex – were used. Line editors were, just likeVim 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, teleprinterswere 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 ofex) included many quality-of-life features and even allowed you to edit multiple lines of text at once – whata luxury!

Did you know?

On many modern systems, thevi command is a symlink to a feature-limited version ofvim referred to asvim-tiny (rather than the originalvi implementation)!

Vi inspired manyclones, includingSTEVIE (ST Editor forVI Enthusiasts): andSTEVIE source code is what was eventually used as a basis forVim. The first version ofVim was released in 1991 by Bram Moolenaar. Now, you’re allcaught 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 differentVim 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 developmentsince 1991!

Major version

Years

Highlights

1.0

1991

Bram Moolenaar releasesVi Imitation for theAmiga computer.

2.0

1993

Vi Improved isreleased under itsmodern name!

3.0

1994

Multiple windows.

4.0

1996

Graphicalinterface support.

5.0 –5.8

1998 –2001

Syntax highlighting, scripting, and select modeare added.

6.0 –6.4

2001 –2005

Plugin support and folding supportare added.

7.0 –7.4

2006 –2013

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

8.0 –8.2

2016 –2019

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

9.0

2022

Introduction of thenew scriptinglanguage (Vim9script).

Just like withvi, there are many Vim clones, and some are quite successful. This book covers one of the more successful alternative implementations of Vim inChapter 9.

Ask for:help

If you’reinterested 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 inVim9!

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 werealso modeless.

The termmodeless 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 asingle mode.

However, this is not theonly way.

Welcome to themodal interface, whereeach 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 adifferent 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, hittingo would put the lettero 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 belowthecursor.

Working with Vim is like having a conversation with your editor. You tell Vim to delete the next three words by pressingd3w (delete3words), and you ask Vim to change the text inside quotes by pressingci” (changeinside [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 copyand 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 moredeliberate exercise.

Installation

Vim isavailable 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 morecommon 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 setit 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 chapterfor 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 theA 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 thesource 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 aboutCompilation options in thenext 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 commonmissing dependencies:

$ sudo apt-get install makebuild-essential \

libncurses5-devlibncursesw5-dev --fix-missing

This willmake 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 somecommon ones:

Distribution/System

Command to install the latest versionof Vim

Debian-based (Debian,Ubuntu, Mint)

$ sudoapt-get update

$ sudo apt-getinstall vim-gtk

CentOS (and Fedora prior toFedora 22)

$ sudoyum check-update

$ sudo yuminstall vim-enhanced

Fedora 22+

$ sudodnf check-update

$ sudo dnfinstall vim-enhanced

Arch

$ sudopacman -Syu

$ sudo pacman -S gvim

FreeBSD

$ sudopkg update

$ sudo pkginstall vim

Pay attention to names

You can see in the preceding table that Vim uses different package names for different repositories. Packages such asvim-gtk on Debian-based distributions orvim-enhanced on CentOS come with more features enabled (such as GUI supportfor instance).

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

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

$ vim

vim versusvi

Vi is Vim’s predecessor (Vim stands forVi Improved) andis available to be invoked via thevi command. On some distributions, thevi command links to a feature-stripped version of Vim (akavim-tiny), while on some it’s merely a symlink to afeature-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 commoncompilation 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 desiredcompilation options:

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

You can control installation locationwith --prefix:

  • --prefix=/usr/local as a reasonable default for asystem-wide installation
  • --prefix=$HOME/.local will make the newly installed Vim only available toyour 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 includethe following:

  • --with-features=huge includes all possible features, includingexperimental ones
  • --with-features=normal includes a reasonable feature set, which is mostly covered inthis book
  • --with-features=tiny only offers bare-bones essentials, without syntax highlighting orplugin 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 includethe following:

  • --enable-luainterp=yes enablesLua support
  • --enable-perlinterp=yes enablesPerl support
  • --enable-python3interp=yes enables Python3 support
  • --enable-rubyinterp=yes enablesRuby 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 usesudo apt install libx11-dev libxtst-dev if you’re using theaptpackage 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 thevisual 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 notinterestyou.

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 areavailable onhttps://brew.sh, and, as of the moment of writing this book, consist of a single line executed in the followingcommand line:

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

Once you run that prompt, hitEnter to continue (as many times as youneed 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 withdefault 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 theInstallation successful! message in bold font once the installationis complete.

Let’s install a new version of Vim now using thefollowing command:

$ brew install vim

Homebrewwill install all the necessary dependencies too, so you won’t have to worry abouta 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 thefollowing command:

$ brew upgrade vim

You should now be ready to enjoy Vim; let’s try opening it with thefollowing command:

$ vim

Welcometo 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.dmgimage.

Downloading a .dmg image

Navigatetohttps://github.com/macvim-dev/macvim/releases/latest anddownloadMacVim.dmg.

OpenMacVim.dmg, and then drag the Vim icon into theApplications directory, as can be seen in thefollowing 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

Dependingon the security settings of your Mac, you might be greeted by an error when navigating to theApplications folder and trying to open theMacVim app, as demonstrated in thefollowing screenshot:

Figure 1.6 – The default “unidentified developer” prompt

Figure 1.6 – The default “unidentified developer” prompt

Open yourApplications folder, findMacVim, right-click the icon, and selectOpen. The following prompt willpop 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, hitOpen, andMacVim can be opened as usual from now on. Give itashot:

Figure 1.8 – MacVim on macOS

Figure 1.8 – MacVim onmacOS

Setting up on Windows

Windows provides twoprimary routes for using Vim: setting up Cygwin and providing a more Unix-like command-line experience, orinstallinggVim – agraphical version of Vim (which supports working withcmd.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 theUnix 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 aWindows 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 aboutWSLathttps://learn.microsoft.com/windows/wsl.

Installing Cygwin

To beginthe installation process, navigate tohttps://cygwin.com/install.html and download eithersetup-x86_64.exe orsetup-x86.exe, depending on the version of Windows you’re using (64-bit or32-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 openControl Panel |System and Security |System, and look atSystem type. For example, my Windows machine showsSystem type: 64-bit Operating System,x64-based processor.

Open the executable file, and you will be greeted by the following Cygwininstallation window:

Figure 1.9 – The Cygwin Setup screen on Windows

Figure 1.9 – The Cygwin Setup screen on Windows

HitNext > a few times, proceeding with thedefault settings:

  • Download source:Installfrom Internet
  • Root directory:C:\cygwin64 (or arecommended default)
  • Install for:all users
  • Local package directory:C:\Downloads (or arecommended default)
  • Internet connection:Use SystemProxy Settings
  • Download site:http://cygwin.mirror.constant.com (or anyavailable option)

After this, you will be greeted with theSelect Packages screen. Here, we want to select thevim,gvim, andvim-doc packages. The easiest way to do this is to typevim in a search box, expand theAll |Editors category, and click on the arrow-looking icons next to the desired packages, as demonstrated in thefollowing 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 version8.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, whichintroducesVim9script (you can learn more about version differences in theA brief historylesson 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 theSetting up on Linux section we covered earlier in this chapter for the instructions. If you’d like to do that, you’ll want to installgit andmake utilitiesin Cygwin.

You might need additional utilities

You may want to installcurl from under the Net category, andgit from under the Devel category, as we’ll be using both inChapter 3. It might also be helpful to installdos2unix 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 ina while).

HitNext > 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 withsome 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 finda solution).

HitNext > a few more times, proceeding withthe defaults:

  • Create iconon Desktop
  • Add icon toStart Menu

Congratulations – you now have Cygwin installedwith Vim!

Installing Cygwin packages

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

Using Cygwin

Open Cygwin – the program will be calledCygwin64 Terminal orCygwin Terminal, depending on the version of your system, as can be seen in thefollowing 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 toLinux 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 workwith Cygwin.

Typevim and hitEnter to start Vim, as demonstrated in thefollowing 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 <cygwin@cygwin.com>)

Cygwinis 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 touse 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 thedos2unix utility on the offending file to resolvethe issue.

Visual Vim with gVim

You can read moreabout the graphical version of Vim in theVanilla Vim versus gVim section later inthis chapter.

As it always is with Windows, the process is slightly more visual. Navigate togithub.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 Gvimis9.0.

You can usewinget instead

Alternatively, if you’re familiar with thewinget tool, you can runwinget install -e --id vim.vim (substitute withvim.vim.nightly if you’d like to live on thebleeding edge).

Open the executableand follow the prompts on the screen, as demonstrated by thefollowing screenshot:

Figure 1.14 – gVim 9.0 setup welcome screen

Figure 1.14 – gVim 9.0 setup welcome screen

Let’s go ahead and hitNext, thenI Agree until we arrive at theInstallation Options screen. We’re happy with most of the default options gVim has to offer, except that you might want to enableCreate .bat files for command line use. This option will make thevim command work in the Windows Command Prompt. Some examples in this book rely on having a Command Prompt, so, enabling this option would help youfollow along.

Here’s a screenshot of theInstallation Options screen with the proper boxeschecked 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

HitNext >. You’llwant to continue with thefollowing settings:

  • Select the type of install:Typical (afterCreate .bat files for command line use is enabled, the type of install value changes toCustom automatically)
  • Do not remap keys forWindows behavior
  • Right button has a popup menu, left button startsvisual mode
  • Destination Folder:C:\Program Files (x86)\Vim (or arecommended default)

Once you’re done, hitInstall and thenClose. SayNo to the request to see theREADME file (or sayYes – I’m a book, nota cop).

You will now have a few icons pop up on your desktop, the most interesting one beinggVim 9.0 as shown in thefollowing 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 hasbecome 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 choicefor 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 aLinux 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 theSettings app and searching forLinux. If this yields no results, you won’t be able to use Vim on yourChromeOS device.

First, set up Linux to run on ChromeOS by opening theSettings app, and navigating through theAdvanced |Developers |Linux development environment |Turnon 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. HitNext to continue. The default settings are sufficient, as demonstrated in thefollowing 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

HitInstall, and the whole setup should be over in under a coupleof minutes.

The newly installed Debian Linux environment is accessible through theTerminal app. The default environment name ispenguin, so you just need toselect 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) Linuxcommand-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 comespreinstalled on a vast majority of Linux machines, and this one is not an exception: you should already have accessto 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 theSetting up on Linux section earlier in this chapter for instructions on installing the latestVim version.

Now, you can launch Vim by invoking it fromthe terminal:

$ vim

This is the output asshown 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 thecd ~ command from theTerminal window) via the ChromeOSFiles app:

Figure 1.22 – You can access Linux files through the ChromeOSFiles app

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

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

$ vim --version

You will see the following output, with a set of features having a+ and a- in frontof 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 runPython 3.

Ask for:help

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

For instance, if wewanted to recompile Vim with Python 3 support on Linux, we would dothe 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 enablePython 3.

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

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

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

Vanilla Vim versus gVim

Using the instructionsgiven before, you’ve installed two flavors of Vim: command-line Vim, andgVim. This is how gVim looksin Windows:

Figure 1.24 – gVim interface in Windows

Figure 1.24 – gVim interface in Windows

The gVim hooks up agraphical 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 amodern GUI.

You can launch gVim by running thegVim 9.0 executable on Windows, or on Linux and macOS by invoking thefollowing command:

$ gvim

Windows users mightfavor 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 ofthe 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 ofthis 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 alot easier.

Spot hidden files

In Unix-like systems, files that start with a period (.) are hidden. To see them, runls -a in aCommand line.

In Linux and macOS,.vimrc is located in youruser directory (the full path would be/home/<username>/.vimrc). You can also find youruser directory by opening a Command Prompt and running thefollowing 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 inC:\Users\<username>\_vimrc, but you can also locate it by opening the Windows Command Prompt and running thefollowing command:

$ echo %USERPROFILE%

Locating.vimrc

If you run into problems, open Vim and type in:echo $MYVIMRC followed byEnter. 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 athttps://github.com/PacktPublishing/Mastering-Vim-Second-Edition/tree/main/Chapter01. The following code shows the contents of a.vimrc file used inthis 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 withautocmd filetype python, which will only apply options toPython files:

autocmd filetype pythonset expandtab

autocmd filetype pythonset tabstop=4

autocmd filetype pythonset 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 acrossdifferent 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 (pressEnter 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 currenttabstop value.

I’ve alsochangedcolorscheme to make screenshots look better in print, but you don’t have to (unless you’re writing a book about Vim – then youprobably 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 hittingEnter, and you can cycle through the available color scheme names by typing:colorscheme followed by a space and by hittingTab multiple times. You can read more about configuring Vim and color schemes (including using color schemes you find online) inChapter 7.

You’ve configured Vim, and now it’s time to learn how to actuallyuse 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 someyears 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 anda mouse.

In this section, we’ll learn how to open (and, more importantly, close) Vim, save files, and makebasic 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 thefollowing command:

$ vim spam.py

GUI for the win!

If you’re using gVim, you can open a file by going into aFile menu and choosingOpen. Sometimes, a graphical interface is exactly whatyou need!

This opens a file namedspam.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 thefollowing 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 filewith Vim!

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

: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 theEnter key, which allows you to perform various complex operations, as well as accessing your system’s Command line. The:e command standsforedit.

Vim help often refers to theEnter key as a<CR>, which stands forcarriage return.

Changing text

By default, you’re in Vim’s normalmode, meaning that every key press corresponds to a particular command. Hiti 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 thefollowing 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 addingnew 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 – seeChapter 3 for detailsand explanation.

Let’s create our Python application by typing in the following code. We’ll be navigating this little snippet throughoutthis 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, hitEsc on your keyboard. You’ll see that-- INSERT -- has disappeared from the status line. Now, Vim is ready to take commands fromyou again!

This code isn’t very good

The preceding code does not display Python best practices and is provided to illustrate some ofVim’s capabilities.

Saving and closing files

Let’s save our file! Executethefollowing command:

:w

Don’t forget to execute the command!

Don’t forget to hitEnter at the end of a command toexecute it.

:w standsforwrite.

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 andcheck whether the file was indeed created.:q stands forquit. You can also combine write and quit commands to write and exit byexecuting: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 forcesits 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 thefollowing code:

$ ls$ python3 spam.py

The following screenshot shows what the two preceding commandsshould 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 Python3 interpreter.

A word about swap files

By default, Vim keeps track of the changes you make to filesin 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 thefollowing 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 hitr to recover the swap file contents ord 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 pressingd to delete the swap file (although Vim won’t let you delete the swap file if the file in question is currently open in anotherVim 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 toyour.vimrc:

set directory=$HOME/.vim/swap//

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

For Windows users

If you’re on Windows, you should useset directory=%USERDATA%\.vim\swap// (note the direction of the lasttwo slashes).

You can also choose to disable the swap files completely by addingset noswapfile toyour.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 aroundwhat youjust wrote.

Moving around – talk to your editor

Vim allows you tonavigate content a lot more efficiently than most conventional editors. Let’s start withthe basics.

You can move your cursor around, character by character, by using arrow keys or theh,j,k, andl keys. This is the least efficient and the most precise wayto move:

Key

Alternative key

Action

h

Left arrow

Movecursor left

j

Down arrow

Movecursor down

k

Up arrow

Movecursor up

l

Right arrow

Movecursor right

The following diagram is a visual representation that might be a little easier onthe 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) wascreated on an old ADM-3A terminal, which didn’t have arrow keys. Theh,j,k, andl keys were usedas 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 theh,j,k, andl 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 treath,j,k, andl as arrow keys – you’d be surprised how many tools respondto 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, hitting5 +j will move the cursor five lines down, while hitting1 +4 +l will move the cursor 14 characters to the right. This works with most commands you encounter inthis 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. Usew to move to the beginning of the nextword, and usee to get to theend of the closest word. To movebackward to the beginning of the word,hitb.

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 liketo traverse.

Vim has twokinds 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 ifyou’re curious).

Let’s take the following line of code fromour example:

Note

Notice the cursor position – it’s hovering over the first characterofingredient.

Hittingw will move the cursor to the next comma while hittingW will take you to the beginning ofwith_spam. CapitalizedW,E, andB will treat any characters bundled together and separated by a space as their own words. This can be seen in thefollowing table:

Key

Action

w

Move forwardbyword

e

Move forward until the end oftheword

W

Move forwardbyWORD

E

Move forward until the end oftheWORD

b

Move backward to the beginning oftheword

B

Move backward to the beginning oftheWORD

The following screenshot shows more examples of how eachcommand behaves:

Key

Initialcursor position

Resultingcursor position

w

e

b

W

E

B

Combine the movements shown with the directional movements you learned earlier to move infewer 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 thefollowing example:

Figure 1.33 – You can see three paragraphs here

Figure 1.33 – You can see three paragraphs here

TheINGREDIENTS constant, and theprepare_menu_item andmain functions are three separate paragraphs. Use a closing curly brace,}, to move forward, and an opening curly brace,{, to move backward, as detailed in thefollowing table:

Command

Action

{

Move back byone paragraph

}

Move forward byone paragraph

Don’t forget to combine these two with numbers if you need to move by more thanone 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 inChapter 2.

Making simple edits in insert mode

Whenworking 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 focuson that.

You’ve already learned to enter the insert mode by pressingi. 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 aresome examples:

Command

Before

After

Cw

c3e

Cb

c4l

cW

words versusWORDS

Remember, non-alphanumeric characters (including punctuation) are treated aswords. For example,prepare_menu_item(ingredient, has_spam) will be considered sixwords (but only oneWORD):prepare_menu_item,(,ingredient,, (comma),has_spam,and).

Exception

As an odd exception,cw behaves likece. 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 onthe 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 orafter<command>.

For example, say you wish to change thefollowing line:

prepare_menu_item(ingredient, with_spam=has_spam)

Say you want to change theingredientto'egg':

prepare_menu_item('egg', with_spam=has_spam)

To accomplish that, you can execute the following setof commands:

Contents ofthe line

Action

Start with a cursor at the beginning ofthe line

Hit2w to move the cursor threewords forward to the beginningofingredient

Presscw to delete theingredient word and enter theinsert mode

Type'egg'

Hit theEsc key to return toNORMAL mode

Sometimes, we just want to cut things, without putting anything instead, andd does just that. It stands for delete. It behaves similarly toc, except that the behavior ofw ande is more standard, as can be seen in thefollowing example:

Command

Before

After

dw

d3e

db

d5l

dW

There are also two more nifty shortcuts that allow you to change or delete awhole line:

Command

Whatit does

cc

Clears the whole line and enters insert mode. Preserves current indentation level, which is usefulwhen coding.

dd

Deletes anentire line.

For example, look at thefollowing 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 hittingdd you will completely remove a line, as demonstrated in thefollowing 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

Hittingcc will clear the line and enter insert mode with the proper indent, as shown in thefollowing 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. Hitv to enter the visual mode and use the usual movement commands to adjust the selection. Run the desired command (such asc to change ord to delete) once you’re satisfied withthe selection.

Persistent undo and repeat

Like any editor, Vim keeps track of every operation. Pressu to undo a last operation, andCtrl+r toredo it.

Undo tree

To learn more about Vim’s undo tree (Vim’s undo history is not linear) and how to navigate it, seeChapter 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 fewdays ago!

You can enable persistent undo by adding the following line toyour.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 thefollowing example:

" Set up persistent undo across all files.set undofilelet my_undo_dir = expand('$HOME/.vim/undodir')if !isdirectory(my_undo_dir))  call mkdir(my_undo_dir, "p")endifset 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 insteadof.vimrc).

Now, you’ll be able to undo and redo your changesacross sessions.

Read the Vim manual using :help

Thebest learning tool Vim can offer is certainly a:help command, as can be seen in thefollowing 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 thePage Up andPage Down keys (bonus point for usingCtrl +b andCtrl +f instead), there is a lot of usefulinformation there.

:help help-summary

Consider reading through thehelp-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 fromhelp-summary in this section, but thereare 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 modecc commandwe’ve learned:

:h cc

Here’s the output ofthis 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, theautoindent setting preservesthe indentation).

Searching for options

In Vim help, options are always denoted with single quotation marks. For example, if you wanted to look for theautoindent option (rememberset 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 usingthe following:

:h search

However, it looks like this command takes us to theentry on expression evaluation, which is not exactly what we were looking for, as demonstrated by thefollowing 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 hitEnter yet) followed byCtrl +d. This will give you a list of help tags containing thesearch substring. One of the options shown issearch-commands, which is what we’d be looking for. Complete your command in the following way to get to the entry we werelooking for:

:h search-commands

The following display shows the right help entryfor 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 pressCtrl +] to jump to the definition of the keyword, andCtrl +o to jump back. Give ita 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. SeeChapter 2 to learn more about how to performsearch operations.

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

Don’t forget to use Vim’s help system any time you have questions or want to better understand the wayVim 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—ViImproved today.

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

You’ve learned how to install and update Vim and its graphical counterpart – gVim – on every major platform (in more ways than you willever 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 yourown 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 asd2w -delete2words) empower precisetext 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’relooking 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 atediting text.

Left arrow icon

Page1 of 13

Right arrow icon
Download code iconDownload 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

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 :9781835080436
Category :
Languages :
Tools :

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Product Details

Publication date :Jul 31, 2024
Length:300 pages
Edition :2nd
Language :English
ISBN-13 :9781835080436
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99billed monthly
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconSimple pricing, no contract
$199.99billed annually
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick iconExclusive print discounts
$279.99billed in 18 months
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick iconExclusive print discounts

Frequently bought together


Hands-On Genetic Algorithms with Python
Hands-On Genetic Algorithms with Python
Read more
Jul 2024418 pages
Full star icon4.8 (6)
eBook
eBook
$27.99$31.99
$39.99
Modern Python Cookbook
Modern Python Cookbook
Read more
Jul 2024818 pages
Full star icon4.9 (21)
eBook
eBook
$38.99$43.99
$54.99
Mastering Vim
Mastering Vim
Read more
Jul 2024300 pages
Full star icon5 (1)
eBook
eBook
$29.99$33.99
$41.99
Stars icon
Total$136.97
Hands-On Genetic Algorithms with Python
$39.99
Modern Python Cookbook
$54.99
Mastering Vim
$41.99
Total$136.97Stars icon

Table of Contents

10 Chapters
Chapter 1: Getting StartedChevron down iconChevron up icon
Chapter 1: Getting Started
Technical requirements
A brief history lesson
Let’s start a conversation (about modal interfaces)
Installation
Vanilla Vim versus gVim
Configuring Vim with your .vimrc
Common operations (or, how to exit Vim)
Moving around – talk to your editor
Making simple edits in insert mode
Persistent undo and repeat
Read the Vim manual using :help
Summary
Chapter 2: Advanced Editing and NavigationChevron down iconChevron up icon
Chapter 2: Advanced Editing and Navigation
Technical requirements
Installing plugins
Organizing the workspace
Navigating file trees
Navigating text
Copying and pasting with registers
Summary
Chapter 3: Follow the Leader Plugin ManagementChevron down iconChevron up icon
Chapter 3: Follow the Leader Plugin Management
Technical requirements
Managing plugins
Deeper dive into modes
Remapping commands
The leader key
Configuring plugins
Summary
Chapter 4: Understanding Structured TextChevron down iconChevron up icon
Chapter 4: Understanding Structured Text
Technical requirements
Code autocomplete
Navigating the code base with tags
Visualizing the undo tree
Summary
Chapter 5: Build, Test, and ExecuteChevron down iconChevron up icon
Chapter 5: Build, Test, and Execute
Technical requirements
Working with version control
Resolving conflicts with vimdiff
tmux, screen, and Vim terminal mode
Building and testing
Summary
Chapter 6: Refactoring Code with Regex and MacrosChevron down iconChevron up icon
Chapter 6: Refactoring Code with Regex and Macros
Technical requirements
Search or replace with regular expressions
Recording and playing macros
Using plugins to do the job
Summary
Chapter 7: Making Vim Your OwnChevron down iconChevron up icon
Chapter 7: Making Vim Your Own
Technical requirements
Playing with the Vim UI
Keeping track of configuration files
Healthy Vim customization habits
Summary
Chapter 8: Transcending the Mundane with VimscriptChevron down iconChevron up icon
Chapter 8: Transcending the Mundane with Vimscript
Technical requirements
Why Vimscript?
How to execute Vimscript
Major changes in Vimscript 9
Learning the syntax
A word about style guides
Let’s build a plugin
Further reading
Summary
Chapter 9: Where to Go from HereChevron down iconChevron up icon
Chapter 9: Where to Go from Here
Seven habits of effective text editing
Modal interfaces everywhere
Neovim
Recommended reading and communities
A word about Uganda
Summary
IndexChevron down iconChevron up icon
Index
Why subscribe?
Packt is searching for authors like you
Share Your Thoughts
Download a free PDF copy of this book

Recommendations for you

Left arrow icon
Debunking C++ Myths
Debunking C++ Myths
Read more
Dec 2024226 pages
Full star icon5 (1)
eBook
eBook
$27.99$31.99
$39.99
Go Recipes for Developers
Go Recipes for Developers
Read more
Dec 2024350 pages
eBook
eBook
$27.99$31.99
$39.99
50 Algorithms Every Programmer Should Know
50 Algorithms Every Programmer Should Know
Read more
Sep 2023538 pages
Full star icon4.5 (68)
eBook
eBook
$35.98$39.99
$49.99
$49.99
Asynchronous Programming with C++
Asynchronous Programming with C++
Read more
Nov 2024424 pages
Full star icon5 (1)
eBook
eBook
$29.99$33.99
$41.99
Modern CMake for C++
Modern CMake for C++
Read more
May 2024504 pages
Full star icon4.7 (12)
eBook
eBook
$35.98$39.99
$49.99
Learn Python Programming
Learn Python Programming
Read more
Nov 2024616 pages
Full star icon5 (1)
eBook
eBook
$31.99$35.99
$39.99
Learn to Code with Rust
Learn to Code with Rust
Read more
Nov 202457hrs 40mins
Video
Video
$74.99
Modern Python Cookbook
Modern Python Cookbook
Read more
Jul 2024818 pages
Full star icon4.9 (21)
eBook
eBook
$38.99$43.99
$54.99
Right arrow icon

Customer reviews

Rating distribution
Full star iconFull star iconFull star iconFull star iconFull star icon5
(1 Ratings)
5 star100%
4 star0%
3 star0%
2 star0%
1 star0%
TinyAug 26, 2024
Full star iconFull star iconFull star iconFull star iconFull star icon5
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 reviewAmazon

About the author

Profile icon Osipov
Osipov
LinkedIn iconGithub icon
Ruslan Osipov is a software engineering manager at Google, and the author of the bestselling “Mastering Vim” (first edition, 2018). Passionate about developer productivity and workflow optimization, he continues to refine his Vim expertise and share his knowledge with the community in this expanded second edition.
Read more
See other products by Osipov
Getfree access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook?Chevron down iconChevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website?Chevron down iconChevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook?Chevron down iconChevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support?Chevron down iconChevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks?Chevron down iconChevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook?Chevron down iconChevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.


[8]ページ先頭

©2009-2025 Movatter.jp