Full Code of iggredible/Learn-Vim for AI

master 89f06e90e6f8 cached
37 files
412.1 KB
109.6k tokens
1 requests
Download .txt
Showing preview only (428K chars total). Download the full file or copy to clipboard to get everything.
Repository: iggredible/Learn-Vim
Branch: master
Commit: 89f06e90e6f8
Files: 37
Total size: 412.1 KB

Directory structure:
gitextract_66irgrv6/

├── .gitignore
├── LICENSE.txt
├── README.md
├── book/
│   ├── Dockerfile
│   ├── book.toml
│   ├── docker-compose.yml
│   └── src/
│       └── SUMMARY.md
├── ch00_read_this_first.md
├── ch01_starting_vim.md
├── ch02_buffers_windows_tabs.md
├── ch03_searching_files.md
├── ch04_vim_grammar.md
├── ch05_moving_in_file.md
├── ch06_insert_mode.md
├── ch07_the_dot_command.md
├── ch08_registers.md
├── ch09_macros.md
├── ch10_undo.md
├── ch11_visual_mode.md
├── ch12_search_and_substitute.md
├── ch13_the_global_command.md
├── ch14_external_commands.md
├── ch15_command-line_mode.md
├── ch16_tags.md
├── ch17_fold.md
├── ch18_git.md
├── ch19_compile.md
├── ch20_views_sessions_viminfo.md
├── ch21_multiple_file_operations.md
├── ch22_vimrc.md
├── ch23_vim_packages.md
├── ch24_vim_runtime.md
├── ch25_vimscript_basic_data_types.md
├── ch26_vimscript_conditionals_and_loops.md
├── ch27_vimscript_variable_scopes.md
├── ch28_vimscript_functions.md
└── ch29_plugin_example_writing-a-titlecase-plugin.md

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Created by https://www.toptal.com/developers/gitignore/api/vim
# Edit at https://www.toptal.com/developers/gitignore?templates=vim

### Vim ###
# Swap
[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-rt-v][a-z]
[._]ss[a-gi-z]
[._]sw[a-p]

# Session
Session.vim

# Temporary
.netrwhist
*~
# Auto-generated tag files
tags
# Persistent undo
[._]*.un~

# End of https://www.toptal.com/developers/gitignore/api/vim

# mdBook build output
book/output/


================================================
FILE: LICENSE.txt
================================================
Attribution-NonCommercial-ShareAlike 4.0 International

=======================================================================

Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.

Using Creative Commons Public Licenses

Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.

     Considerations for licensors: Our public licenses are
     intended for use by those authorized to give the public
     permission to use material in ways otherwise restricted by
     copyright and certain other rights. Our licenses are
     irrevocable. Licensors should read and understand the terms
     and conditions of the license they choose before applying it.
     Licensors should also secure all rights necessary before
     applying our licenses so that the public can reuse the
     material as expected. Licensors should clearly mark any
     material not subject to the license. This includes other CC-
     licensed material, or material used under an exception or
     limitation to copyright. More considerations for licensors:
    wiki.creativecommons.org/Considerations_for_licensors

     Considerations for the public: By using one of our public
     licenses, a licensor grants the public permission to use the
     licensed material under specified terms and conditions. If
     the licensor's permission is not necessary for any reason--for
     example, because of any applicable exception or limitation to
     copyright--then that use is not regulated by the license. Our
     licenses grant only permissions under copyright and certain
     other rights that a licensor has authority to grant. Use of
     the licensed material may still be restricted for other
     reasons, including because others have copyright or other
     rights in the material. A licensor may make special requests,
     such as asking that all changes be marked or described.
     Although not required by our licenses, you are encouraged to
     respect those requests where reasonable. More considerations
     for the public:
    wiki.creativecommons.org/Considerations_for_licensees

=======================================================================

Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
Public License

By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International Public License
("Public License"). To the extent this Public License may be
interpreted as a contract, You are granted the Licensed Rights in
consideration of Your acceptance of these terms and conditions, and the
Licensor grants You such rights in consideration of benefits the
Licensor receives from making the Licensed Material available under
these terms and conditions.


Section 1 -- Definitions.

  a. Adapted Material means material subject to Copyright and Similar
     Rights that is derived from or based upon the Licensed Material
     and in which the Licensed Material is translated, altered,
     arranged, transformed, or otherwise modified in a manner requiring
     permission under the Copyright and Similar Rights held by the
     Licensor. For purposes of this Public License, where the Licensed
     Material is a musical work, performance, or sound recording,
     Adapted Material is always produced where the Licensed Material is
     synched in timed relation with a moving image.

  b. Adapter's License means the license You apply to Your Copyright
     and Similar Rights in Your contributions to Adapted Material in
     accordance with the terms and conditions of this Public License.

  c. BY-NC-SA Compatible License means a license listed at
     creativecommons.org/compatiblelicenses, approved by Creative
     Commons as essentially the equivalent of this Public License.

  d. Copyright and Similar Rights means copyright and/or similar rights
     closely related to copyright including, without limitation,
     performance, broadcast, sound recording, and Sui Generis Database
     Rights, without regard to how the rights are labeled or
     categorized. For purposes of this Public License, the rights
     specified in Section 2(b)(1)-(2) are not Copyright and Similar
     Rights.

  e. Effective Technological Measures means those measures that, in the
     absence of proper authority, may not be circumvented under laws
     fulfilling obligations under Article 11 of the WIPO Copyright
     Treaty adopted on December 20, 1996, and/or similar international
     agreements.

  f. Exceptions and Limitations means fair use, fair dealing, and/or
     any other exception or limitation to Copyright and Similar Rights
     that applies to Your use of the Licensed Material.

  g. License Elements means the license attributes listed in the name
     of a Creative Commons Public License. The License Elements of this
     Public License are Attribution, NonCommercial, and ShareAlike.

  h. Licensed Material means the artistic or literary work, database,
     or other material to which the Licensor applied this Public
     License.

  i. Licensed Rights means the rights granted to You subject to the
     terms and conditions of this Public License, which are limited to
     all Copyright and Similar Rights that apply to Your use of the
     Licensed Material and that the Licensor has authority to license.

  j. Licensor means the individual(s) or entity(ies) granting rights
     under this Public License.

  k. NonCommercial means not primarily intended for or directed towards
     commercial advantage or monetary compensation. For purposes of
     this Public License, the exchange of the Licensed Material for
     other material subject to Copyright and Similar Rights by digital
     file-sharing or similar means is NonCommercial provided there is
     no payment of monetary compensation in connection with the
     exchange.

  l. Share means to provide material to the public by any means or
     process that requires permission under the Licensed Rights, such
     as reproduction, public display, public performance, distribution,
     dissemination, communication, or importation, and to make material
     available to the public including in ways that members of the
     public may access the material from a place and at a time
     individually chosen by them.

  m. Sui Generis Database Rights means rights other than copyright
     resulting from Directive 96/9/EC of the European Parliament and of
     the Council of 11 March 1996 on the legal protection of databases,
     as amended and/or succeeded, as well as other essentially
     equivalent rights anywhere in the world.

  n. You means the individual or entity exercising the Licensed Rights
     under this Public License. Your has a corresponding meaning.


Section 2 -- Scope.

  a. License grant.

       1. Subject to the terms and conditions of this Public License,
          the Licensor hereby grants You a worldwide, royalty-free,
          non-sublicensable, non-exclusive, irrevocable license to
          exercise the Licensed Rights in the Licensed Material to:

            a. reproduce and Share the Licensed Material, in whole or
               in part, for NonCommercial purposes only; and

            b. produce, reproduce, and Share Adapted Material for
               NonCommercial purposes only.

       2. Exceptions and Limitations. For the avoidance of doubt, where
          Exceptions and Limitations apply to Your use, this Public
          License does not apply, and You do not need to comply with
          its terms and conditions.

       3. Term. The term of this Public License is specified in Section
          6(a).

       4. Media and formats; technical modifications allowed. The
          Licensor authorizes You to exercise the Licensed Rights in
          all media and formats whether now known or hereafter created,
          and to make technical modifications necessary to do so. The
          Licensor waives and/or agrees not to assert any right or
          authority to forbid You from making technical modifications
          necessary to exercise the Licensed Rights, including
          technical modifications necessary to circumvent Effective
          Technological Measures. For purposes of this Public License,
          simply making modifications authorized by this Section 2(a)
          (4) never produces Adapted Material.

       5. Downstream recipients.

            a. Offer from the Licensor -- Licensed Material. Every
               recipient of the Licensed Material automatically
               receives an offer from the Licensor to exercise the
               Licensed Rights under the terms and conditions of this
               Public License.

            b. Additional offer from the Licensor -- Adapted Material.
               Every recipient of Adapted Material from You
               automatically receives an offer from the Licensor to
               exercise the Licensed Rights in the Adapted Material
               under the conditions of the Adapter's License You apply.

            c. No downstream restrictions. You may not offer or impose
               any additional or different terms or conditions on, or
               apply any Effective Technological Measures to, the
               Licensed Material if doing so restricts exercise of the
               Licensed Rights by any recipient of the Licensed
               Material.

       6. No endorsement. Nothing in this Public License constitutes or
          may be construed as permission to assert or imply that You
          are, or that Your use of the Licensed Material is, connected
          with, or sponsored, endorsed, or granted official status by,
          the Licensor or others designated to receive attribution as
          provided in Section 3(a)(1)(A)(i).

  b. Other rights.

       1. Moral rights, such as the right of integrity, are not
          licensed under this Public License, nor are publicity,
          privacy, and/or other similar personality rights; however, to
          the extent possible, the Licensor waives and/or agrees not to
          assert any such rights held by the Licensor to the limited
          extent necessary to allow You to exercise the Licensed
          Rights, but not otherwise.

       2. Patent and trademark rights are not licensed under this
          Public License.

       3. To the extent possible, the Licensor waives any right to
          collect royalties from You for the exercise of the Licensed
          Rights, whether directly or through a collecting society
          under any voluntary or waivable statutory or compulsory
          licensing scheme. In all other cases the Licensor expressly
          reserves any right to collect such royalties, including when
          the Licensed Material is used other than for NonCommercial
          purposes.


Section 3 -- License Conditions.

Your exercise of the Licensed Rights is expressly made subject to the
following conditions.

  a. Attribution.

       1. If You Share the Licensed Material (including in modified
          form), You must:

            a. retain the following if it is supplied by the Licensor
               with the Licensed Material:

                 i. identification of the creator(s) of the Licensed
                    Material and any others designated to receive
                    attribution, in any reasonable manner requested by
                    the Licensor (including by pseudonym if
                    designated);

                ii. a copyright notice;

               iii. a notice that refers to this Public License;

                iv. a notice that refers to the disclaimer of
                    warranties;

                 v. a URI or hyperlink to the Licensed Material to the
                    extent reasonably practicable;

            b. indicate if You modified the Licensed Material and
               retain an indication of any previous modifications; and

            c. indicate the Licensed Material is licensed under this
               Public License, and include the text of, or the URI or
               hyperlink to, this Public License.

       2. You may satisfy the conditions in Section 3(a)(1) in any
          reasonable manner based on the medium, means, and context in
          which You Share the Licensed Material. For example, it may be
          reasonable to satisfy the conditions by providing a URI or
          hyperlink to a resource that includes the required
          information.
       3. If requested by the Licensor, You must remove any of the
          information required by Section 3(a)(1)(A) to the extent
          reasonably practicable.

  b. ShareAlike.

     In addition to the conditions in Section 3(a), if You Share
     Adapted Material You produce, the following conditions also apply.

       1. The Adapter's License You apply must be a Creative Commons
          license with the same License Elements, this version or
          later, or a BY-NC-SA Compatible License.

       2. You must include the text of, or the URI or hyperlink to, the
          Adapter's License You apply. You may satisfy this condition
          in any reasonable manner based on the medium, means, and
          context in which You Share Adapted Material.

       3. You may not offer or impose any additional or different terms
          or conditions on, or apply any Effective Technological
          Measures to, Adapted Material that restrict exercise of the
          rights granted under the Adapter's License You apply.


Section 4 -- Sui Generis Database Rights.

Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:

  a. for the avoidance of doubt, Section 2(a)(1) grants You the right
     to extract, reuse, reproduce, and Share all or a substantial
     portion of the contents of the database for NonCommercial purposes
     only;

  b. if You include all or a substantial portion of the database
     contents in a database in which You have Sui Generis Database
     Rights, then the database in which You have Sui Generis Database
     Rights (but not its individual contents) is Adapted Material,
     including for purposes of Section 3(b); and

  c. You must comply with the conditions in Section 3(a) if You Share
     all or a substantial portion of the contents of the database.

For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.


Section 5 -- Disclaimer of Warranties and Limitation of Liability.

  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.

  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.

  c. The disclaimer of warranties and limitation of liability provided
     above shall be interpreted in a manner that, to the extent
     possible, most closely approximates an absolute disclaimer and
     waiver of all liability.


Section 6 -- Term and Termination.

  a. This Public License applies for the term of the Copyright and
     Similar Rights licensed here. However, if You fail to comply with
     this Public License, then Your rights under this Public License
     terminate automatically.

  b. Where Your right to use the Licensed Material has terminated under
     Section 6(a), it reinstates:

       1. automatically as of the date the violation is cured, provided
          it is cured within 30 days of Your discovery of the
          violation; or

       2. upon express reinstatement by the Licensor.

     For the avoidance of doubt, this Section 6(b) does not affect any
     right the Licensor may have to seek remedies for Your violations
     of this Public License.

  c. For the avoidance of doubt, the Licensor may also offer the
     Licensed Material under separate terms or conditions or stop
     distributing the Licensed Material at any time; however, doing so
     will not terminate this Public License.

  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
     License.


Section 7 -- Other Terms and Conditions.

  a. The Licensor shall not be bound by any additional or different
     terms or conditions communicated by You unless expressly agreed.

  b. Any arrangements, understandings, or agreements regarding the
     Licensed Material not stated herein are separate from and
     independent of the terms and conditions of this Public License.


Section 8 -- Interpretation.

  a. For the avoidance of doubt, this Public License does not, and
     shall not be interpreted to, reduce, limit, restrict, or impose
     conditions on any use of the Licensed Material that could lawfully
     be made without permission under this Public License.

  b. To the extent possible, if any provision of this Public License is
     deemed unenforceable, it shall be automatically reformed to the
     minimum extent necessary to make it enforceable. If the provision
     cannot be reformed, it shall be severed from this Public License
     without affecting the enforceability of the remaining terms and
     conditions.

  c. No term or condition of this Public License will be waived and no
     failure to comply consented to unless expressly agreed to by the
     Licensor.

  d. Nothing in this Public License constitutes or may be interpreted
     as a limitation upon, or waiver of, any privileges and immunities
     that apply to the Licensor or You, including from the legal
     processes of any jurisdiction or authority.

=======================================================================

Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.

Creative Commons may be contacted at creativecommons.org.



================================================
FILE: README.md
================================================
# Learn Vim (the Smart Way)

## What's This?

*Learn Vim (the Smart Way)* is a guide to learn the good parts of Vim.

There are many places to learn Vim: the `vimtutor` is a great place to start and the `help` manual has all the references you will ever need. However, the average user needs something more than `vimtutor` and less than the `help` manual. This guide attempts to bridge that gap by highlighting only the key features to learn the most useful parts of Vim in the least amount of time possible.

This guide is written for both beginner and advanced Vimmers. It starts out with broad and simple concepts and ends with specific and advanced concepts. If you're an advanced user already, I encourage you to read this guide from start to finish anyway, because you may learn something new!

## Read Locally (with Docker)

You can read this book locally with Docker. Just run:

```bash
docker compose -f book/docker-compose.yml up --build
```

Then open [http://localhost:8080](http://localhost:8080).

## I Want More Vim Tips!

Follow [@learnvim](https://twitter.com/learnvim) for updates, Vim tips, etc.

## Support This Project

This guide is and will always be free.

If you want to financially support this project, you can either [purchase this guide on Leanpub](https://leanpub.com/learnvim) or [buy me a coffee](https://www.buymeacoffee.com/iggredible)!

<a href="https://leanpub.com/learnvim"><img src="images/learn-vim-cover.png" width="100"></a>

<a href="https://www.buymeacoffee.com/iggredible" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-green.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>


## Table Of Contents

### Prologue

- [Ch 0     - Read This First](./ch00_read_this_first.md)

### Part 1: Learn Vim the Smart Way

- [Ch 1     - Starting Vim](./ch01_starting_vim.md)
- [Ch 2     - Buffers, Windows, and Tabs](./ch02_buffers_windows_tabs.md)
- [Ch 3     - Opening and Searching Files](./ch03_searching_files.md)
- [Ch 4     - Vim Grammar](./ch04_vim_grammar.md)
- [Ch 5     - Moving in a File](./ch05_moving_in_file.md)
- [Ch 6     - Insert Mode](./ch06_insert_mode.md)
- [Ch 7     - The Dot command](./ch07_the_dot_command.md)
- [Ch 8     - Registers](./ch08_registers.md)
- [Ch 9     - Macros](./ch09_macros.md)
- [Ch 10    - Undo](./ch10_undo.md)
- [Ch 11    - Visual Mode](./ch11_visual_mode.md)
- [Ch 12    - Search and Substitute](./ch12_search_and_substitute.md)
- [Ch 13    - The Global Command](./ch13_the_global_command.md)
- [Ch 14    - External Commands](./ch14_external_commands.md)
- [Ch 15    - Command-line Mode](./ch15_command-line_mode.md)
- [Ch 16    - Tags](./ch16_tags.md)
- [Ch 17    - Fold](./ch17_fold.md)
- [Ch 18    - Git](./ch18_git.md)
- [Ch 19    - Compile](./ch19_compile.md)
- [Ch 20    - Views, Sessions, and Viminfo](./ch20_views_sessions_viminfo.md)
- [Ch 21    - Multiple File Operations](./ch21_multiple_file_operations.md)

### Part 2: Customize Vim the Smart Way

- [Ch 22 - Vimrc](./ch22_vimrc.md)
- [Ch 23 - Vim Packages](./ch23_vim_packages.md)
- [Ch 24 - Vim Runtime](./ch24_vim_runtime.md)

### Part 3: Learn Vimscript the Smart Way

- [Ch 25 - Vimscript Basic Data Types](./ch25_vimscript_basic_data_types.md)
- [Ch 26 - Vimscript Conditionals And Loops](./ch26_vimscript_conditionals_and_loops.md)
- [Ch 27 - Vimscript Variable Scopes](./ch27_vimscript_variable_scopes.md)
- [Ch 28 - Vimscript Functions](./ch28_vimscript_functions.md)
- [Ch 29 - Plugin Example: Writing a Titlecase Plugin](./ch29_plugin_example_writing-a-titlecase-plugin.md)

## Translations
- [Learn-Vim 中文翻译](https://wsdjeg.net/wiki/learn-vim/)(`zh-CN`)
- [Learn-Vim Spanish](https://github.com/victorhck/learn-Vim-es)(`es`)

## License & Copyright
The materials here are all © 2020-2021 Igor Irianto.

<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://licensebuttons.net/l/by-nc-sa/4.0/88x31.png" /></a><br />

This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International</a>.


================================================
FILE: book/Dockerfile
================================================
# Stage 1: Build the book
FROM peaceiris/mdbook:latest AS builder

WORKDIR /book

# Copy mdBook config and table of contents
COPY book/book.toml .
COPY book/src/SUMMARY.md src/SUMMARY.md

# Copy all chapter files into the mdBook src directory
COPY ch*.md src/

# Build the book
RUN mdbook build

# Stage 2: Serve with nginx
FROM nginx:alpine

COPY --from=builder /book/output /usr/share/nginx/html

EXPOSE 80


================================================
FILE: book/book.toml
================================================
[book]
title = "Learn Vim (the Smart Way)"
authors = ["Igor Irianto"]
language = "en"
src = "src"

[build]
build-dir = "output"

[output.html]
default-theme = "light"
preferred-dark-theme = "ayu"
git-repository-url = "https://github.com/iggredible/learn-vim"


================================================
FILE: book/docker-compose.yml
================================================
services:
  book:
    build:
      context: ..
      dockerfile: book/Dockerfile
    ports:
      - "8080:80"


================================================
FILE: book/src/SUMMARY.md
================================================
# Summary

# Prologue

- [Read This First](./ch00_read_this_first.md)

# Part 1: Learn Vim the Smart Way

- [Starting Vim](./ch01_starting_vim.md)
- [Buffers, Windows, and Tabs](./ch02_buffers_windows_tabs.md)
- [Opening and Searching Files](./ch03_searching_files.md)
- [Vim Grammar](./ch04_vim_grammar.md)
- [Moving in a File](./ch05_moving_in_file.md)
- [Insert Mode](./ch06_insert_mode.md)
- [The Dot Command](./ch07_the_dot_command.md)
- [Registers](./ch08_registers.md)
- [Macros](./ch09_macros.md)
- [Undo](./ch10_undo.md)
- [Visual Mode](./ch11_visual_mode.md)
- [Search and Substitute](./ch12_search_and_substitute.md)
- [The Global Command](./ch13_the_global_command.md)
- [External Commands](./ch14_external_commands.md)
- [Command-line Mode](./ch15_command-line_mode.md)
- [Tags](./ch16_tags.md)
- [Fold](./ch17_fold.md)
- [Git](./ch18_git.md)
- [Compile](./ch19_compile.md)
- [Views, Sessions, and Viminfo](./ch20_views_sessions_viminfo.md)
- [Multiple File Operations](./ch21_multiple_file_operations.md)

# Part 2: Customize Vim the Smart Way

- [Vimrc](./ch22_vimrc.md)
- [Vim Packages](./ch23_vim_packages.md)
- [Vim Runtime](./ch24_vim_runtime.md)

# Part 3: Learn Vimscript the Smart Way

- [Vimscript Basic Data Types](./ch25_vimscript_basic_data_types.md)
- [Vimscript Conditionals And Loops](./ch26_vimscript_conditionals_and_loops.md)
- [Vimscript Variable Scopes](./ch27_vimscript_variable_scopes.md)
- [Vimscript Functions](./ch28_vimscript_functions.md)
- [Plugin Example: Writing a Titlecase Plugin](./ch29_plugin_example_writing-a-titlecase-plugin.md)


================================================
FILE: ch00_read_this_first.md
================================================
# Ch00. Read This First

## Why This Guide Was Written

There are many places to learn Vim: the `vimtutor` is a great place to start and the `:help` manual has all the references you will ever need.

However, the average user needs something more than `vimtutor` and less than the `:help` manual. This guide attempts to bridge that gap by highlighting only the key features to learn the most useful parts of Vim in the least amount of time possible.

Chances are you won't need all of Vim features. You probably only need to know about 20% of them to become a powerful Vimmer. This guide will show you which Vim features you will find most useful.

This is an opinionated guide. It covers techniques that I often use when using Vim. The chapters are sequenced based on which Vim topics I think would make the most logical sense for a beginner to learn.

This guide is example-heavy. When learning new concepts, examples are indispensable, and having numerous examples will solidify these concepts more effectively.

Some of you may be wondering: 'Why do I need to learn Vimscript?' In my first year of using Vim, I was content with just knowing how to use Vim. Time passed and I started needing Vimscript more and more to write custom commands for my specific editing needs. As you are mastering Vim, you will find that, sooner or later, you will need to learn Vimscript. So why not sooner? Vimscript is a small language. You can learn its basics in just four chapters of this guide.

You can go far using Vim without knowing any Vimscript, but knowing it will help you excel even further.

This guide is written for both beginner and advanced Vimmers. It starts out with broad and simple concepts and ends with specific and advanced concepts. If you're an advanced user already, I encourage you to read this guide from start to finish anyway, because you may learn something new!

## How to Transition to Vim From Using a Different Text Editor

Learning Vim is a satisfying experience, albeit hard. There are two main approaches to learn Vim:

1. Cold turkey
2. Gradual

Going cold turkey means to stop using whatever editor / IDE you were using and to use Vim exclusively starting now. The downside of this method is you will have a serious productivity loss during the first week or two. If you're a full-time programmer, this method may not be feasible. That's why for most people, I believe the best way to transition to Vim is to use it gradually.

To gradually use Vim, during the first two weeks, spend an hour a day using Vim as your editor while the rest of the time you can use other editors. Many modern editors come with Vim plugins. When I first started, I used VSCode's popular Vim plugin for an hour per day. I gradually increased the time with the Vim plugin until I finally used it all day. Keep in mind that these plugins can only emulate a fraction of Vim features. To experience the full power of Vim like Vimscript, Command-line (Ex) Commands, and external commands integration, you will need to use Vim itself.

There were two pivotal moments that made me start to use Vim 100%: when I grasped that Vim has a grammar-like structure (see chapter 4) and the [fzf.vim](https://github.com/junegunn/fzf.vim) plugin (see chapter 3).

The first, when I realized Vim's grammar-like structure, was the defining moment that I finally understood what these Vim users were talking about. I didn't need to learn hundreds of unique commands. I only had to learn a small handful of commands and I could chain in a very intuitive way to do many things.

The second, the ability to quickly run a fuzzy file-search was the IDE feature that I used most. When I learned how to do that in Vim, I gained a major speed boost and never looked back ever since.

Everyone programs differently. Upon introspection, you will find that there are one or two features from your favorite editor / IDE that you use all the time. Maybe it was fuzzy-search, jump-to-definition, or quick compilation. Whatever they may be, identify them quickly and learn how to implement those in Vim (chances are Vim can probably do them too). Your editing speed will receive a huge boost.

Once you can edit at 50% of the original speed, it's time to go full-time Vim.

## How to Read This Guide

This is a practical guide. To become good in Vim you need to develop your muscle memory, not head knowledge.

You don't learn how to ride a bike by reading a guide about how to ride a bike. You need to actually ride a bike.

You need to type every command referred in this guide. Not only that, but you need to repeat them several times and try different combinations. Look up what other features the command you just learned has. The `:help` command and search engines are your best friends. Your goal is not to know everything about a command, but to be able to execute that command naturally and instinctively.

As much as I try to fashion this guide to be linear, some concepts in this guide have to be presented out-of-order. For example in chapter 1, I mention the substitute command (`:s`), even though it won't be covered until chapter 12. To remedy this, whenever a new concept that has not been covered yet is mentioned early, I will provide a quick how-to guide without a detailed explanation. So please bear with me :).

## More Help

Here's one extra tip to use the help manual: suppose you want to learn more about what `Ctrl-P` does in insert mode. If you merely search for `:h CTRL-P`, you will be directed to normal mode's `Ctrl-P`. This is not the `Ctrl-P` help that you're looking for. In this case, search instead for `:h i_CTRL-P`. The appended `i_` represents the insert mode. Pay attention to which mode it belongs to.

## Syntax

Most of the command or code-related phrases are in code-case (`like this`).

Strings are surrounded by a pair of double-quotes ("like this").

Vim commands can be abbreviated. For example, `:join` can be abbreviated as `:j`. Throughout the guide, I will be mixing the shorthand and the longhand descriptions. For commands that are not frequently used in this guide, I will use the longhand version. For commands that are frequently used, I will use the shorthand version. I apologize for the inconsistencies. In general, whenever you spot a new command, always check it on `:help` to see its abbreviations.

## Vimrc

At various points in the guide, I will refer to vimrc options. If you're new to Vim, a vimrc is like a config file.

Vimrc won't be covered until chapter 22. For the sake of clarity, I will show briefly here how to set it up.

Suppose you need to set the number options (`set number`). If you don't have a vimrc already, create one. It is usually placed in your home directory and named `.vimrc`. Depending on your OS, the location may differ. In macOS, I have it on `~/.vimrc`. To see where you should put yours, check out `:h vimrc`.

Inside it, add `set number`. Save it (`:w`), then source it (`:source %`). You should now see line numbers displayed on the left side.

Alternatively, if you don't want to make a permanent setting change, you can always run the `set` command inline, by running `:set number`. The downside of this approach is that this setting is temporary. When you close Vim, the option disappears.

Since we are learning about Vim and not Vi, a setting that you must have is the `nocompatible` option. Add `set nocompatible` in your vimrc. Many Vim-specific features are disabled when it is running on `compatible` option.

In general, whenever a passage mentions a vimrc option, just add that option into vimrc, save it, and source it.

## Future, Errors, Questions

Expect more updates in the future. If you find any errors or have any questions, please feel free to reach out.

I also have planned a few more upcoming chapters, so stay tuned!

## I Want More Vim Tricks

To learn more about Vim, please follow [@learnvim](https://twitter.com/learnvim).

## Thank Yous

This guide wouldn't be possible without Bram Molenaar for creating Vim, my wife who had been very patient and supportive throughout the journey, all the [contributors](https://github.com/iggredible/Learn-Vim/graphs/contributors) of the learn-vim project, the Vim community, and many, many others that weren't mentioned.

Thank you. You all help make text editing fun :)


## Link
- Next [Ch01. Starting Vim](./ch01_starting_vim.md)


================================================
FILE: ch01_starting_vim.md
================================================
# Ch01. Starting Vim

In this chapter, you will learn different ways to start Vim from the terminal. I was using Vim 8.2 when writing this guide. If you use Neovim or an older version of Vim, you should be mostly fine, but be aware that some commands might not be available.

## Installing

I won't go through the detailed instructions on how to install Vim on a specific machine. The good news is that most Unix-based computers should come with Vim installed already. If not, most distros should have some instructions on how to install Vim.

To download more information about the Vim installation process, check out the official download website or the official GitHub repository:
- [Vim website](https://www.vim.org/download.php)
- [Vim GitHub](https://github.com/vim/vim)

## The Vim Command

Now that you have Vim installed, run this from the terminal:

```bash
vim
```

You should see an intro screen. This is where you will be working on your new file. Unlike most text editors and IDEs, Vim is a modal editor. If you want to type "hello", you need to switch to insert mode with `i`. Input `ihello<Esc>` to insert the text, "hello".

## Exiting Vim

There are several ways to exit Vim. The most common one is to type:

```
:quit
```

You can type `:q` for short. This command is a command for command-line mode (another one of Vim modes). If you type `:` in normal mode, the cursor will move to the bottom of the screen, where you can type some commands. You will learn about command-line mode later in chapter 15. If you are in insert mode, typing `:` will literally produce the character ":" on the screen. In this case, you need to switch back to normal mode. Type `<Esc>` to switch to normal mode. By the way, you can also return to normal mode from command-line mode by pressing `<Esc>`. You will notice that you can "escape" out of several Vim modes back to normal mode by pressing `<Esc>`.

## Saving a File

To save your changes, type:

```
:write
```

You can also type `:w` for short. If this is a new file, you will need to give it a name before you can save it. Let's name it `file.txt`. Run:

```
:w file.txt
```

To save and quit, you can combine the `:w` and `:q` commands:

```
:wq
```

To quit without saving any changes, add `!` after `:q` to force quit:

```
:q!
```

There are other ways to exit Vim, but these are the ones you will use on a daily basis.

## Help

Throughout this guide, I will refer you to various Vim help pages. You can go to the help page by typing `:help {some-command}` (`:h` for short). You can pass to the `:h` command a topic or a command name as an argument. For example, to learn about different ways to quit Vim, type:

```
:h write-quit
```

How did I know to search for "write-quit"? I actually didn't. I just typed `:h`, then "quit", then `<Tab>`. Vim displayed relevant keywords to choose from. If you ever need to look up something ("I wish Vim can do this..."), just type `:h` and try inputting some keywords, then press `<Tab>`.

## Opening a File

To open a file (`hello1.txt`) on Vim from the terminal, run:

```bash
vim hello1.txt
```

You can also open multiple files at once:

```bash
vim hello1.txt hello2.txt hello3.txt
```

Vim opens `hello1.txt`, `hello2.txt`, and `hello3.txt` in separate buffers. You will learn about buffers in the next chapter.

## Arguments

You can pass different flags and options to the `vim` terminal command.

To check the current Vim version, run:

```bash
vim --version
```

This tells you the current Vim version and all available features, which will be prefixed by either `+` or `-`. Some features in this guide require certain features to be available. For example, you will explore Vim's command-line history in a later chapter using the `:history` command. Your installation of Vim needs to have the `+cmdline_history` feature for the command to work. There is a good chance that your installation of Vim has all the necessary features, especially if it came from a popular download source.

Many things you do from the terminal can also be done from inside Vim. To see the version from *inside* Vim, you can run this: 

```
:version
```

If you want to open the file `hello.txt` and immediately execute a Vim command, you can pass to the `vim` command the `+{cmd}` option.

In Vim, you can substitute strings with the `:s` command (short for `:substitute`). If you want to open `hello.txt` and substitute all instances of "pancake" with "bagel", run:

```bash
vim +%s/pancake/bagel/g hello.txt
```

These Vim commands can be stacked:

```bash
vim +%s/pancake/bagel/g +%s/bagel/egg/g +%s/egg/donut/g hello.txt
```

Vim will:
1. Replace all instances of "pancake" with "bagel"
2. Then it will replace "bagel" with "egg"
3. Then it will replace "egg" with "donut"
You will learn substitution in a later chapter.

You can also pass the `-c` option followed by a Vim command, instead of using the `+` syntax:

```bash
vim -c %s/pancake/bagel/g hello.txt
vim -c %s/pancake/bagel/g -c %s/bagel/egg/g -c %s/egg/donut/g hello.txt
```

## Opening Multiple Windows

You can launch Vim on split horizontal and vertical windows using the `-o` and `-O` options, respectively.

To open Vim with 2 horizontal windows, run:

```bash
vim -o2
```

To open Vim with 5 horizontal windows, run:

```bash
vim -o5
```

To open Vim with 5 horizontal windows and fill up the first two with `hello1.txt` and `hello2.txt`, run:

```bash
vim -o5 hello1.txt hello2.txt
```

To open Vim with 2 vertical windows, 5 vertical windows, and 5 vertical windows with two files, `hello1.txt` and `hello2.txt`:

```bash
vim -O2
vim -O5
vim -O5 hello1.txt hello2.txt
```

## Suspending

If you need to suspend Vim while in the middle of editing, you can press `Ctrl-z`. You can also run either the `:stop` or `:suspend` command. To return to the suspended Vim, run `fg` from the terminal.

## Starting Vim the Smart Way

The `vim` command can take many different options, just like any other terminal command. Two options allow you to pass a Vim command-line mode command as a parameter: `+{cmd}` and `-c cmd`. As you learn more commands throughout this guide, see if you can execute them when starting Vim. Also, being a terminal command, `vim` can be combined with many other terminal commands. For example, you can redirect the output of the `ls` command to be edited in Vim with `ls -l | vim -`.

To learn more about `vim` command in the terminal, check out `man vim`. To learn more about the Vim editor, continue reading this guide and use the `:help` command.

## Link
- Prev [Ch00. Read This First](./ch00_read_this_first.md)
- Next [Ch02. Buffers, Windows, and Tabs](./ch02_buffers_windows_tabs.md)


================================================
FILE: ch02_buffers_windows_tabs.md
================================================
# Ch02. Buffers, Windows, and Tabs

If you've used a modern text editor before, you are probably familiar with windows and tabs. Vim uses three display abstractions instead of two:
- buffers
- windows
- tabs.
In this chapter, I will explain what buffers, windows, and tabs are and how they work in Vim.

Before you start, make sure you have the `set hidden` option in your vimrc. Without it, you will be prompted to save your file whenever you try to switch out of any unsaved buffers (you don't want that if you want to move quickly). I haven't covered what a vimrc is yet. A vimrc file can usually be found in your home directory and is named `.vimrc` (i.e., the full path to this file `~/.vimrc`). I have my vimrc on `~/.vimrc`. To see where you should create your vimrc, check out `:h vimrc`. If you don't have a vimrc already, create one by running `vim +w ~/.vimrc` in your terminal. Inside it, add:

```
set hidden
```

Save it, then source it (run `:source %` from inside the vimrc).

## Buffers

What is a *buffer*?

A buffer is an in-memory space where you can write and edit text. When you open a file in Vim, the data in that file is bound to a buffer. When you open 3 files in Vim, 3 buffers will be created for each of them.

Have two empty files, `file1.js` and `file2.js` available (if possible, create them with Vim by running, say, `vim +wn file1.js +wq file2.js` in the terminal). Run this in the terminal:

```bash
vim file1.js
```

What you are seeing is the *buffer* for `file1.js`. Whenever you open a new file, Vim creates a new buffer.

Exit Vim. This time, open two new files:

```bash
vim file1.js file2.js
```

Vim is currently displaying the `file1.js` buffer, but it actually creates two buffers: the `file1.js` buffer and the `file2.js` buffer. Run `:buffers` to see all the buffers (alternatively, you can use `:ls` or `:files` too). You should see *both* `file1.js` and `file2.js` listed. Running `vim file1 file2 file3 ... filen` creates `n` buffers. Each time you open a new file, Vim creates a new buffer for that file.

There are several ways you can traverse buffers:
- `:bnext` to go to the next buffer (`:bprevious` to go to the previous buffer).
- `:buffer` + filename. Vim can autocomplete any filename for you if you press `<Tab>`.
- `:buffer` + `n`, where `n` is the buffer number. For example, typing `:buffer 2` will take you to buffer #2.
- Jump to the older position in the jump list with `Ctrl-O` and to the newer position with `Ctrl-I`. These are not buffer-specific methods, but they can be used to jump between different buffers. I will explain jumps in further detail in chapter 5.
- Go to the previously edited buffer with `Ctrl-^`.

Once Vim creates a buffer, it will remain in your buffer list. To remove the current buffer, you can type `:bdelete`. This command also accepts a buffer number as a parameter (e.g., `:bdelete 3` to delete buffer #3) or a filename (`:bdelete` then use `<Tab>` to autocomplete).

For me, the hardest part of learning about buffers was visualizing how they worked, because my mind was so used to the windows of a mainstream text editor I had been using. Buffers can be analogized to a deck of playing cards. If I have 2 buffers, I have a stack of 2 cards. The card on top is the only card I see, but I know there is another card below it. If I see `file1.js` buffer displayed then the `file1.js` card is on the top of the deck. I can't see the other card, `file2.js` here, but it's there. If I switch buffers to `file2.js`, that `file2.js` card is now on the top of the deck and `file1.js` card is below it.

If you haven't used Vim before, this is a new concept. Take your time to understand it.

## Exiting Vim

By the way, if you have multiple buffers opened, you can close all of them with quit-all:

```
:qall
```

If you want to close without saving your changes, just add `!` at the end:

```
:qall!
```

To save and quit all, run:

```
:wqall
```

## Windows

A window is a viewport on a buffer. If you're coming from a mainstream editor, this concept may be familiar to you. Most text editors have the ability to display multiple windows. In Vim, you can also have multiple windows.

Let's open `file1.js` from the terminal again:

```bash
vim file1.js
```

Earlier I wrote that you're looking at the `file1.js` buffer. While that was correct, it was also incomplete. You are looking at the `file1.js` buffer, displayed through **a window**. A window is what you are viewing a buffer through.

Don't quit Vim yet. Run:

```
:split file2.js
```

Now you are looking at two buffers through **two windows**. The top window displays the `file2.js` buffer. The bottom window displays the `file1.js` buffer.

If you want to navigate between windows, use these shortcuts:

```
Ctrl-W h    Moves the cursor to the left window
Ctrl-W j    Moves the cursor to the lower window
Ctrl-W k    Moves the cursor to the upper window
Ctrl-W l    Moves the cursor to the right window
```

Now run:

```
:vsplit file3.js
```

You are now seeing three windows displaying three buffers. One window displays the `file3.js` buffer, another window displays the `file2.js` buffer, and another window displays the `file1.js` buffer.

You can have multiple windows display the same buffer. While you're on the top left window, type:

```
:buffer file2.js
```

Now both of the top windows are displaying the `file2.js` buffer. If you start typing on either of the `file2.js` windows, both windows containing the `file2.js` buffer will be updated in real-time.

To close the current window, you can run `Ctrl-W C` or type `:quit`. When you close a window, the buffer will still be there (run `:buffers` to confirm this).

Here are some useful normal-mode window commands:

```
Ctrl-W V    Opens a new vertical split
Ctrl-W S    Opens a new horizontal split
Ctrl-W C    Closes a window
Ctrl-W O    Makes the current window the only one on screen and closes other windows
```

And here is a list of useful window command-line commands:

```
:vsplit filename    Split window vertically
:split filename     Split window horizontally
:new filename       Create new window
```

Take your time to understand them. For more information, check out `:h window`.

## Tabs

A tab is a collection of windows. Think of it like a layout for windows. In most modern text editors (and modern internet browsers), a tab means an open file / page; when you close it, that file / page goes away. In Vim, a tab does not represent an opened file. When you close a tab in Vim, you are not closing a file; you are only closing the layout. The files opened in that layout are still not closed; they are still open in their buffers.

Let's see Vim tabs in action. Open `file1.js`:

```bash
vim file1.js
```

To open `file2.js` in a new tab:

```
:tabnew file2.js
```

You can also let Vim autocomplete the file you want to open in a *new tab* by pressing `<Tab>` (no pun intended).

Below is a list of useful tab navigations:

```
:tabnew file.txt    Open file.txt in a new tab
:tabclose           Close the current tab
:tabnext            Go to next tab
:tabprevious        Go to previous tab
:tablast            Go to last tab
:tabfirst           Go to first tab
```

You can also run `gt` to go to next tab page (you can go to previous tab with `gT`). You can pass count as argument to `gt`, where count is the tab number; for example, to go to the third tab, do `3gt`.

One advantage of having multiple tabs is you can have different window arrangements in different tabs. Maybe you want your first tab to have 3 vertical windows, and your second tab to have a layout consisting of horizontal and vertical windows mixed together. Tab is the perfect tool for this job!

To start Vim with multiple tabs, you can run this from the terminal:

```bash
vim -p file1.js file2.js file3.js
```

## Moving in 3D

Moving between windows is like traveling two-dimensionally along the X-Y axis in a Cartesian coordinate system. You can move to the top, right, bottom, and left window with `Ctrl-W K/L/J/H`, respectively.

Moving between buffers is like traveling across the Z axis in a Cartesian coordinate system. Imagine your buffer files lining up across the Z axis. You can traverse the Z axis one buffer at a time using `:bnext` and `:bprevious`. You can jump to any coordinate in the Z axis with `:buffer filename/buffernumber`.

You can move in *three-dimensional space* by combining window and buffer movements. You can move to the top, right, bottom, or left window (X-Y navigations) with window movements. Since each window contains a set of buffers, you can move forward and backward (Z navigations) with buffer movements.

## Using Buffers, Windows, and Tabs the Smart Way

You have learned what buffers, windows, and tabs are and how they work in Vim. Now that you understand them better, you can use them in your own workflow.

Everyone has a different workflow. Here is mine for example:
- First, I use buffers to store all the required files for the current task. Vim can handle many opened buffers before it starts slowing down. Plus having many buffers open won't crowd my screen. I am only seeing one buffer (assuming I only have one window) at any time, allowing me to focus on one screen. When I need to go somewhere, I can quickly fly to any open buffer anytime.
- I use multiple windows to view multiple buffers at once, usually when diffing files, reading docs, or following a code flow. I try to keep the number of windows opened to no more than three, because my screen will get crowded (I use a small laptop). When I am done, I close any extra windows. Fewer windows means fewer distractions.
- Instead of tabs, I use [tmux](https://github.com/tmux/tmux/wiki) windows. I usually use multiple tmux windows at once. For example, one tmux window for client-side code and another for backend code.

My workflow may look different from yours based on your editing style, and that's fine. Experiment to discover your own flow and what suits your coding style.

## Link
- Prev [Ch01. Starting Vim](./ch01_starting_vim.md)
- Next [Ch03. Searching Files](./ch03_searching_files.md)


================================================
FILE: ch03_searching_files.md
================================================
# Ch03. Searching Files

The goal of this chapter is to give you an introduction on how to search quickly in Vim. Being able to search quickly is a great way to jump-start your Vim productivity. When I figured out how to search files quickly, I made the switch to use Vim full-time.

This chapter is divided into two parts: how to search without plugins and how to search with [fzf.vim](https://github.com/junegunn/fzf.vim) plugin. Let's get started!

## Opening and Editing Files

To open a file in Vim, you can use `:edit`.

```
:edit file.txt
```

If `file.txt` exists, it opens the `file.txt` buffer. If `file.txt` doesn't exist, it creates a new buffer for `file.txt`.

Autocomplete with `<Tab>` works with `:edit`. For example, if your file is inside a [Rails](https://rubyonrails.org/) *a*pp *c*ontroller *u*sers controller directory `./app/controllers/users_controllers.rb`, you can use `<Tab>` to expand the terms quickly:

```
:edit a<Tab>c<Tab>u<Tab>
```

`:edit` accepts wildcards arguments. `*` matches any file in the current directory. If you are only looking for files with `.yml` extension in the current directory:

```
:edit *.yml<Tab>
```

Vim will give you a list of all `.yml` files in the current directory to choose from.

You can use `**` to search recursively. If you want to look for all `*.md` files in your project, but you are not sure in which directories, you can do this:

```
:edit **/*.md<Tab>
```

`:edit` can be used to run `netrw`, Vim's built-in file explorer. To do that, give `:edit` a directory argument instead of file:

```
:edit .
:edit test/unit/
```

## Searching Files With Find

You can find files with `:find`. For example:

```
:find package.json
:find app/controllers/users_controller.rb
```

Autocomplete also works with `:find`:

```
:find p<Tab>                " to find package.json
:find a<Tab>c<Tab>u<Tab>    " to find app/controllers/users_controller.rb
```

You may notice that `:find` looks like `:edit`. What's the difference?

## Find and Path

The difference is that `:find` finds file in `path`, `:edit` doesn't. Let's learn a little bit about `path`. Once you learn how to modify your paths, `:find` can become a powerful searching tool. To check what your paths are, do:

```
:set path?
```

By default, yours probably look like this:

```
path=.,/usr/include,,
```

- `.` means to search in the directory of the currently opened file.
- `,` means to search in the current directory.
- `/usr/include` is the typical directory for C libraries header files.

The first two are important in our context and the third one can be ignored for now. The takeaway here is that you can modify your own paths, where Vim will look for files. Let's assume this is your project structure:

```
app/
  assets/
  controllers/
    application_controller.rb
    comments_controller.rb
    users_controller.rb
    ...
```

If you want to go to `users_controller.rb` from the root directory, you have to go through several directories (and pressing a considerable amount of tabs). Often when working with a framework, you spend 90% of your time in a particular directory. In this situation, you only care about going to the `controllers/` directory with the least amount of keystrokes. The `path` setting can shorten that journey.

You need to add the `app/controllers/` to the current `path`. Here is how you can do it:

```
:set path+=app/controllers/
```

Now that your path is updated, when you type `:find u<Tab>`, Vim will now search inside `app/controllers/` directory for files starting with "u".

If you have a nested `controllers/` directory, like `app/controllers/account/users_controller.rb`, Vim won't find `users_controllers`. Instead, you need to add  `:set path+=app/controllers/**`  in order for autocompletion to find `users_controller.rb`. This is great! Now you can find the users controller with 1 press of tab instead of 3.

You might be thinking to add the entire project directories so when you press `tab`, Vim will search everywhere for that file, like this:

```
:set path+=$PWD/**
```

`$PWD` is the current working directory. If you try to add your entire project to `path` hoping to make all files reachable upon a `tab` press, although this may work for a small project, doing this will slow down your search significantly if you have a large number of files in your project. I recommend adding only the `path` of your most visited files / directories.

You can add the `set path+={your-path-here}` in your vimrc. Updating `path` takes only a few seconds and doing so can save you a lot of time.

## Searching in Files With Grep

If you need to find in files (find phrases in files), you can use grep. Vim has two ways of doing that:

- Internal grep (`:vim`. Yes, it is spelled `:vim`. It is short for `:vimgrep`).
- External grep (`:grep`).

Let's go through internal grep first. `:vim` has the following syntax:

```
:vim /pattern/ file
```

- `/pattern/` is a regex pattern of your search term.
- `file` is the file argument. You can pass multiple arguments. Vim will search for the pattern inside the file argument. Similar to `:find`, you can pass it `*` and `**` wildcards.

For example, to look for all occurrences of "breakfast" string inside all ruby files (`.rb`) inside `app/controllers/` directory:

```
:vim /breakfast/ app/controllers/**/*.rb
```

After running that, you will be redirected to the first result. Vim's `vim` search command uses `quickfix` operation. To see all search results, run `:copen`. This opens a `quickfix` window. Here are some useful quickfix commands to get you productive immediately:

```
:copen        Open the quickfix window
:cclose       Close the quickfix window
:cnext        Go to the next error
:cprevious    Go to the previous error
:colder       Go to the older error list
:cnewer       Go to the newer error list
```

To learn more about quickfix, check out `:h quickfix`.

You may notice that running internal grep (`:vim`) can get slow if you have a large number of matches. This is because Vim loads each matching file into memory, as if it were being edited. If Vim finds a large number of files matching your search, it will load them all and therefore consume a large amount of memory.

Let's talk about external grep. By default, it uses `grep` terminal command. To search for "lunch" inside a ruby file inside `app/controllers/` directory, you can do this:

```
:grep -R "lunch" app/controllers/
```

Note that instead of using `/pattern/`, it follows the terminal grep syntax `"pattern"`. It also displays all matches using `quickfix`.

Vim defines the `grepprg` variable to determine which external program to run when running the `:grep` Vim command so that you don't have to close Vim and invoke the terminal `grep` command. Later, I will show you how to change the default program invoked when using the `:grep` Vim command.

## Browsing Files With Netrw

`netrw` is Vim's built-in file explorer. It is useful to see a project's hierarchy. To run `netrw`, you need these two settings in your `.vimrc`:

```
set nocp
filetype plugin on
```

Since `netrw` is a vast topic, I will only cover the basic usage, but it should be enough to get you started. You can start `netrw` when you launch Vim by passing it a directory as a parameter instead of a file. For example:

```
vim .
vim src/client/
vim app/controllers/
```

To launch `netrw` from inside Vim, you can use the `:edit` command and pass it a directory parameter instead of a filename:

```
:edit .
:edit src/client/
:edit app/controllers/
```

There are other ways to launch `netrw` window without passing a directory:

```
:Explore     Starts netrw on current file
:Sexplore    No kidding. Starts netrw on split top half of the screen
:Vexplore    Starts netrw on split left half of the screen
```

You can navigate `netrw` with Vim motions (motions will be covered in depth in a later chapter). If you need to create, delete, or rename a file or directory, here is a list of useful `netrw` commands:

```
%    Create a new file
d    Create a new directory
R    Rename a file or directory
D    Delete a file or directory
```

`:h netrw` is very comprehensive. Check it out if you have time.

If you find `netrw` too bland and need more flavor, [vim-vinegar](https://github.com/tpope/vim-vinegar) is a good plugin to improve `netrw`. If you're looking for a different file explorer, [NERDTree](https://github.com/preservim/nerdtree) is a good alternative. Check them out!

## Fzf

Now that you've learned how to search files in Vim with built-in tools, let's learn how to do it with plugins.

One thing that modern text editors get right and that Vim didn't is how easy it is to find files, especially via fuzzy search. In this second half of the chapter, I will show you how to use [fzf.vim](https://github.com/junegunn/fzf.vim) to make searching in Vim easy and powerful.

## Setup

First, make sure you have [fzf](https://github.com/junegunn/fzf) and [ripgrep](https://github.com/BurntSushi/ripgrep) downloaded. Follow the instructions on their GitHub repo. The commands `fzf` and `rg` should now be available after successful installs.

Ripgrep is a search tool much like grep (hence the name). It is generally faster than grep and has many useful features. Fzf is a general-purpose command-line fuzzy finder. You can use it with any commands, including ripgrep. Together, they make a powerful search tool combination.

Fzf does not use ripgrep by default, so we need to tell fzf to use ripgrep by defining a `FZF_DEFAULT_COMMAND` variable. In my `.zshrc` (`.bashrc` if you use bash), I have these:

```
if type rg &> /dev/null; then
  export FZF_DEFAULT_COMMAND='rg --files'
  export FZF_DEFAULT_OPTS='-m'
fi
```

Pay attention to `-m` in `FZF_DEFAULT_OPTS`. This option allows us to make multiple selections with `<Tab>` or `<Shift-Tab>`. You don't need this line to make fzf work with Vim, but I think it is a useful option to have. It will come in handy when you want to perform search and replace in multiple files which I'll cover in just a little. The fzf command accepts many more options, but I won't cover them here. To learn more, check out [fzf's repo](https://github.com/junegunn/fzf#usage) or `man fzf`. At minimum you should have `export FZF_DEFAULT_COMMAND='rg'`.

After installing fzf and ripgrep, let's set up the fzf plugin. I am using [vim-plug](https://github.com/junegunn/vim-plug) plugin manager in this example, but you can use any plugin managers.

Add these inside your `.vimrc` plugins. You need to use [fzf.vim](https://github.com/junegunn/fzf.vim) plugin (created by the same fzf author).

```
call plug#begin()
Plug 'junegunn/fzf.vim'
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
call plug#end()
```

After adding these lines, you will need to open `vim` and run `:PlugInstall`. It will install all plugins that are defined in your `vimrc` file and are not installed. In our case, it will install `fzf.vim` and `fzf`. 

For more info about this plugin, you can check out [fzf.vim repo](https://github.com/junegunn/fzf/blob/master/README-VIM.md).

## Fzf Syntax

To use fzf efficiently, you should learn some basic fzf syntax. Fortunately, the list is short:

- `^` is a prefix exact match. To search for a phrase starting with "welcome": `^welcome`.
- `$` is a suffix exact match. To search for a phrase ending with "my friends": `friends$`.
- `'` is an exact match. To search for the phrase "welcome my friends": `'welcome my friends`.
- `|` is an "or" match. To search for either "friends" or "foes": `friends | foes`.
- `!` is an inverse match. To search for phrase containing "welcome" and not "friends": `welcome !friends`

You can mix and match these options. For example, `^hello | ^welcome friends$` will search for the phrase starting with either "welcome" or "hello" and ending with "friends".

## Finding Files

To search for files inside Vim using fzf.vim plugin, you can use the `:Files` method. Run `:Files` from Vim and you will be prompted with fzf search prompt.

Since you will be using this command frequently, it is good to have this mapped to a keyboard shortcut. I map mine to `Ctrl-f`. In my vimrc, I have this:

```
nnoremap <silent> <C-f> :Files<CR>
```

## Finding in Files

To search inside files, you can use the `:Rg` command.

Again, since you will probably use this frequently, let's map it to a keyboard shortcut. I map mine to `<Leader>f`. The `<Leader>` key is mapped to `\` by default.

```
nnoremap <silent> <Leader>f :Rg<CR>
```

## Other Searches

Fzf.vim provides many other search commands. I won't go through each one of them here, but you can check them out [here](https://github.com/junegunn/fzf.vim#commands).

Here's what my fzf maps look like:

```
nnoremap <silent> <Leader>b :Buffers<CR>
nnoremap <silent> <C-f> :Files<CR>
nnoremap <silent> <Leader>f :Rg<CR>
nnoremap <silent> <Leader>/ :BLines<CR>
nnoremap <silent> <Leader>' :Marks<CR>
nnoremap <silent> <Leader>g :Commits<CR>
nnoremap <silent> <Leader>H :Helptags<CR>
nnoremap <silent> <Leader>hh :History<CR>
nnoremap <silent> <Leader>h: :History:<CR>
nnoremap <silent> <Leader>h/ :History/<CR>
```

## Replacing Grep With Rg

As mentioned earlier, Vim has two ways to search in files: `:vim` and `:grep`. `:grep` uses external search tool that you can reassign using the `grepprg` keyword. I will show you how to configure Vim to use ripgrep instead of terminal grep when running the `:grep` command.

Now let's setup `grepprg` so that the `:grep` Vim command uses ripgrep. Add this in your vimrc:

```
set grepprg=rg\ --vimgrep\ --smart-case\ --follow
```

Feel free to modify some of the options above! For more information on what the options above mean, check out `man rg`.

After you updated `grepprg`, now when you run `:grep`, it runs `rg --vimgrep --smart-case --follow` instead of `grep`.  If you want to search for "donut" using ripgrep, you can now run a more succinct command `:grep "donut"` instead of `:grep "donut" . -R` 

Just like the old `:grep`, this new `:grep` also uses quickfix to display results.

You might wonder, "Well, this is nice but I never used `:grep` in Vim, plus can't I just use `:Rg` to find phrases in files? When will I ever need to use `:grep`?

That is a very good question. You may need to use `:grep` in Vim to do search and replace in multiple files, which I will cover next.

## Search and Replace in Multiple Files

Modern text editors like VSCode make it very easy to search and replace a string across multiple files. In this section, I will show you two different methods to easily do that in Vim.

The first method is to replace *all* matching phrases in your project. You will need to use `:grep`. If you want to replace all instances of "pizza" with "donut", here's what you do:

```
:grep "pizza"
:cfdo %s/pizza/donut/g | update
```

Let's break down the commands:

1. `:grep pizza` uses ripgrep to search for all instances of "pizza" (by the way, this would still work even if you didn't reassign `grepprg` to use ripgrep. You would have to do `:grep "pizza" . -R` instead of `:grep "pizza"`).
2. `:cfdo` executes any command you pass to all files in your quickfix list. In this case, your command is the substitution command `%s/pizza/donut/g`. The pipe (`|`) is a chain operator. The `update` command saves each file after substitution. I will cover the substitute command in more depth in a later chapter.

The second method is to search and replace in selected files. With this method, you can manually choose which files you want to perform select-and-replace on. Here is what you do:

1. Clear your buffers first. It is imperative that your buffer list contains only the files you want to apply the replace on. You can either restart Vim or run `:%bd | e#` command (`%bd` deletes all the buffers and `e#` opens the file you were just on).
2. Run `:Files`.
3. Select all files you want to perform search-and-replace on. To select multiple files, use `<Tab>` / `<Shift-Tab>`. This is only possible if you have the multiple flag (`-m`) in `FZF_DEFAULT_OPTS`.
4. Run `:bufdo %s/pizza/donut/g | update`. The command `:bufdo %s/pizza/donut/g | update` looks similar to the earlier `:cfdo %s/pizza/donut/g | update` command. The difference is instead of substituting all quickfix entries (`:cfdo`), you are substituting all buffer entries (`:bufdo`).

## Learn Search the Smart Way

Searching is the bread-and-butter of text editing. Learning how to search well in Vim will improve your text editing workflow significantly.

Fzf.vim is a game-changer. I can't imagine using Vim without it. I think it is very important to have a good search tool when starting Vim. I've seen people struggling to transition to Vim because it seems to be missing critical features modern text editors have, like an easy and powerful search feature. I hope this chapter will help you to make the transition to Vim easier. 

You also just saw Vim's extensibility in action - the ability to extend search functionality with a plugin and an external program. In the future, keep in mind what other features you wish to extend Vim with. Chances are, it's already in Vim, someone has created a plugin or there is a program for it already. Next, you'll learn about a very important topic in Vim: Vim grammar.

## Link
- Prev [Ch02. Buffers, Windows, and Tabs](./ch02_buffers_windows_tabs.md)
- Next [Ch04. Vim Grammar](./ch04_vim_grammar.md)


================================================
FILE: ch04_vim_grammar.md
================================================
# Ch04. Vim Grammar

It is easy to get intimidated by the complexity of Vim commands. If you see a Vim user doing `gUfV` or `1GdG`, you may not immediately know what these commands do. In this chapter, I will break down the general structure of Vim commands into a simple grammar rule.

This is the most important chapter in the entire guide. Once you understand the underlying grammatical structure, you will be able to "speak" to Vim. By the way, when I say *Vim language* in this chapter, I am not talking about Vimscript language (Vim's built-in programming language, you will learn that in later chapters).

## How to Learn a Language

I am not a native English speaker. I learned English when I was 13 when I moved to the US. There are three things you need to do to learn to speak a new language:

1. Learn grammar rules.
2. Increase vocabulary.
3. Practice, practice, practice.

Likewise, to speak Vim language, you need to learn the grammar rules, increase vocabulary, and practice until you can run the commands without thinking.

## Grammar Rule

There is only one grammar rule in Vim language:

```
verb + noun
```

That's it!

This is like saying these English phrases:

- *"Eat (verb) a donut (noun)"*
- *"Kick (verb) a ball (noun)"*
- *"Learn (verb) the Vim editor (noun)"*

Now you need to build up your vocabulary with basic Vim verbs and nouns.

## Nouns (Motions)

Nouns are Vim motions. Motions are used to move around in Vim. Below is a list of some of Vim motions:

```
h    Left
j    Down
k    Up
l    Right
w    Move forward to the beginning of the next word
}    Jump to the next paragraph
$    Go to the end of the line
```

You will learn more about motions in the next chapter, so don't worry too much if you don't understand some of them.

## Verbs (Operators)

According to `:h operator`, Vim has 16 operators. However, in my experience, learning these 3 operators is enough for 80% of my editing needs:

```
y    Yank text (copy)
d    Delete text and save to register
c    Delete text, save to register, and start insert mode
```

Btw, after you yank a text, you can paste it with `p` (after the cursor) or `P` (before the cursor).

## Verb and Noun

Now that you know basic nouns and verbs, let's apply the grammar rule, verb + noun! Suppose you have this expression:

```javascript
const learn = "vim";
```

- To yank everything from your current location to the end of the line: `y$`.
- To delete from your current location to the beginning of the next word: `dw`.
- To change from your current location to the end of the current paragraph, say `c}`.

Motions also accept count number as arguments (I will discuss this in the next chapter). If you need to go up 3 lines, instead of pressing `k` 3 times, you can do `3k`. Count works with Vim grammar.
- To yank two characters to the left: `y2h`.
- To delete the next two words: `d2w`.
- To change the next two lines: `c2j`.

Right now, you may have to think long and hard to execute even a simple command. You're not alone. When I first started, I had similar struggles but I got faster in time. So will you. Repetition, repetition, repetition.

As a side note, linewise operations (operations affecting the entire line) are common operations in text editing. In general, by typing an operator command twice, Vim performs a linewise operation for that action. For example, `dd`, `yy`, and `cc` perform **deletion**, **yank**, and **change** on the entire line. Try this with other operators!

This is really cool. I am seeing a pattern here. But I am not quite done yet. Vim has one more type of noun: text objects.

## More Nouns (Text Objects)

Imagine you are somewhere inside a pair of parentheses like `(hello Vim)` and you need to delete the entire phrase inside the parentheses. How can you quickly do it? Is there a way to delete the "group" you are inside of?

The answer is yes. Texts often come structured. They often contain parentheses, quotes, brackets, braces, and more. Vim has a way to capture this structure with text objects.

Text objects are used with operators. There are two types of text objects: inner and outer text objects.

```
i + object    Inner text object
a + object    Outer text object
```

Inner text object selects the object inside *without* the white space or the surrounding objects. Outer text object selects the object inside *including* the white space or the surrounding objects. Generally, an outer text object always selects more text than an inner text object. If your cursor is somewhere inside the parentheses in the expression `(hello Vim)`:
- To delete the text inside the parentheses without deleting the parentheses: `di(`.
- To delete the parentheses and the text inside: `da(`.

Let's look at a different example. Suppose you have this Javascript function and your cursor is on the "H" in "Hello":

```javascript
const hello = function() {
  console.log("Hello Vim");
  return true;
}
```

- To delete the entire "Hello Vim": `di(`.
- To delete the content of function (surrounded by `{}`): `di{`.
- To delete the "Hello" string: `diw`.

Text objects are powerful because you can target different objects from one location. You can delete the objects inside the parentheses, the function block, or the current word. Mnemonically, when you see `di(`, `di{`, and `diw`, you get a pretty good idea which text objects they represent: a pair of parentheses, a pair of braces, and a word.

Let's look at one last example. Suppose you have these HTML tags:

```html
<div>
  <h1>Header1</h1>
  <p>Paragraph1</p>
  <p>Paragraph2</p>
</div>
```

If your cursor is on "Header1" text:
- To delete "Header1": `dit`.
- To delete `<h1>Header1</h1>`: `dat`.

If your cursor is on "div":
- To delete `h1` and both `p` lines: `dit`.
- To delete everything: `dat`.
- To delete "div": `di<`.

Below is a list of common text objects:

```
w         A word
p         A paragraph
s         A sentence
( or )    A pair of ( )
{ or }    A pair of { }
[ or ]    A pair of [ ]
< or >    A pair of < >
t         XML tags
"         A pair of " "
'         A Pair of ' '
`         A pair of ` `
```

To learn more, check out `:h text-objects`.

## Composability and Grammar

Vim grammar is a subset of Vim's composability feature. Let's discuss composability in Vim and why this is a great feature to have in a text editor.

Composability means having a set of general commands that can be combined (composed) to perform more complex commands. Just like in programming where you can create more complex abstractions from simpler abstractions, in Vim you can execute complex commands from simpler commands. Vim grammar is the manifestation of Vim's composable nature.

The true power of Vim's composability shines when it integrates with external programs. Vim has a filter operator (`!`) to use external programs as filters for our texts. Suppose you have this messy text below and you want to tabularize it:

```
Id|Name|Cuteness
01|Puppy|Very
02|Kitten|Ok
03|Bunny|Ok
```

This cannot be easily done with Vim commands, but you can get it done quickly with `column` terminal command (assuming your terminal has `column` command). With your cursor on "Id", run `!}column -t -s "|"`. Voila! Now you have this pretty tabular data with just one quick command.

```
Id  Name    Cuteness
01  Puppy   Very
02  Kitten  Ok
03  Bunny   Ok
```

Let's break down the command. The verb was `!` (filter operator) and the noun was `}` (go to next paragraph). The filter operator `!` accepted another argument, a terminal command, so I gave it `column -t -s "|"`. I won't go through how `column` worked, but in effect, it tabularized the text.

Suppose you want to not only tabularize your text, but to display only the rows with "Ok". You know that `awk` can do the job easily. You can do this instead:

```
!}column -t -s "|" | awk 'NR > 1 && /Ok/ {print $0}'
```

Result:

```
02  Kitten  Ok
03  Bunny   Ok
```

Great! The external command operator can also use pipe (`|`).

This is the power of Vim's composability. The more you know your operators, motions, and terminal commands, your ability to compose complex actions is *multiplied*.

Suppose you only know four motions, `w, $, }, G` and only one operator, `d`. You can do 8 actions: *move* 4 different ways (`w, $, }, G`) and *delete* 4 different targets (`dw, d$, d}, dG`). Then one day you learn about the uppercase (`gU`) operator. You have added not just one new ability to your Vim tool belt, but *four*: `gUw, gU$, gU}, gUG`. That makes 12 tools in your Vim tool belt. Each new knowledge is a multiplier to your current abilities. If you know 10 motions and 5 operators, you have 60 moves (50 operations + 10 motions) in your arsenal. Vim has a line-number motion (`nG`) that gives you `n` motions, where `n` is how many lines you have in your file (to go to line 5, run `5G`). The search motion (`/`) practically gives you near unlimited number of motions because you can search for anything. External command operator (`!`) gives you as many filtering tools as the number of terminal commands you know. Using a composable tool like Vim, everything you know can be linked together to do operations with increasing complexity. The more you know, the more powerful you become.

This composable behavior echoes Unix philosophy: *do one thing well*. An operator has one job: do Y. A motion has one job: go to X. By combining an operator with a motion, you predictably get YX: do Y on X.

Motions and operators are extendable. You can create custom motions and operators to add to your Vim toolbelt. The [`vim-textobj-user`](https://github.com/kana/vim-textobj-user) plugin allows you to create your own text objects. It also contains a [list](https://github.com/kana/vim-textobj-user/wiki) of user-made custom text objects.

## Learn Vim Grammar the Smart Way

You just learned about Vim grammar's rule: `verb + noun`. One of my biggest Vim "AHA!" moment was when I had just learned about the uppercase (`gU`) operator and wanted to uppercase the current word, I *instinctively* ran `gUiw` and it worked! The word was uppercased. At that moment, I finally began to understand Vim. My hope is that you will have your own "AHA!" moment soon, if not already.

The goal of this chapter is to show you the `verb + noun` pattern in Vim so you will approach learning Vim like learning a new language instead of memorizing every command combination.

Learn the pattern and understand the implications. That's the smart way to learn.

## Link
- Prev [Ch03. Searching Files](./ch03_searching_files.md)
- Next [Ch05. Moving in a File](./ch05_moving_in_file.md)


================================================
FILE: ch05_moving_in_file.md
================================================
# Ch05. Moving in a File

In the beginning, moving with a keyboard feels slow and awkward but don't give up! Once you get used to it, you can go anywhere in a file faster than using a mouse.

In this chapter, you will learn the essential motions and how to use them efficiently. Keep in mind that this is **not** the entire motion that Vim has. The goal here is to introduce useful motions to become productive quickly. If you need to learn more, check out `:h motion.txt`.

## Character Navigation

The most basic motion unit is moving one character left, down, up, and right.

```
h   Left
j   Down
k   Up
l   Right
gj  Down in a soft-wrapped line
gk  Up in a soft-wrapped line
```

You can also move with directional arrows. If you are just starting, feel free to use any method you're most comfortable with.

I prefer `hjkl` because my right hand can stay in the home row. Doing this gives me shorter reach to surrounding keys. To get used to `hjkl`, I actually disabled the arrow buttons when starting out by adding these in `~/.vimrc`:

```
noremap <Up> <NOP>
noremap <Down> <NOP>
noremap <Left> <NOP>
noremap <Right> <NOP>
```

There are also plugins to help break this bad habit. One of them is [vim-hardtime](https://github.com/takac/vim-hardtime). To my surprise, it took me less than a week to get used to `hjkl`.

If you wonder why Vim uses `hjkl` to move, this is because Lear-Siegler ADM-3A terminal where Bill Joy wrote Vi, didn't have arrow keys and used `hjkl` as left/down/up/right.

## Relative Numbering

I think it is helpful to have `number` and `relativenumber` set. You can do it by having this on `.vimrc`:

```
set relativenumber number
```

This displays my current line number and relative line numbers.

It is easy why having a number on the left column is useful, but some of you may ask how having relative numbers on the left column may be useful. Having a relative number allows me to quickly see how many lines apart my cursor is from the target text. With this, I can easily spot that my target text is 12 lines below me so I can do `d12j` to delete them. Otherwise, if I'm on line 69 and my target is on line 81, I have to do mental calculation (81 - 69 = 12). Doing math while editing takes too much mental resources. The less I have to think about where I need to go, the better.

This is 100% personal preference. Experiment with `relativenumber` / `norelativenumber`, `number` / `nonumber` and use whatever you find most useful!

## Count Your Move

Let's talk about the "count" argument. Vim motions accept a preceding numerical argument. I mentioned above that you can go down 12 lines with `12j`. The 12 in `12j` is the count number.

The syntax to use count with your motion is:

```
[count] + motion
```

You can apply this to all motions. If you want to move 9 characters to the right, instead of pressing `l` 9 times, you can do `9l`.

## Word Navigation

Let's move to a larger motion unit: *word*. You can move to the beginning of the next word (`w`), to the end of the next word (`e`), to the beginning of the previous word (`b`), and to the end of the previous word (`ge`).

In addition, there is *WORD*, distinct from word. You can move to the beginning of the next WORD (`W`), to the end of the next WORD (`E`), to the beginning of the previous WORD (`B`), and to the end of the previous WORD (`gE`). To make it easy to remember, WORD uses the same letters as word, only uppercased.

```
w     Move forward to the beginning of the next word
W     Move forward to the beginning of the next WORD
e     Move forward one word to the end of the next word
E     Move forward one word to the end of the next WORD
b     Move backward to beginning of the previous word
B     Move backward to beginning of the previous WORD
ge    Move backward to end of the previous word
gE    Move backward to end of the previous WORD
```

So what are the similarities and differences between a word and a WORD? Both word and WORD are separated by blank characters. A word is a sequence of characters containing *only* `a-zA-Z0-9_`. A WORD is a sequence of all characters except white space (a white space means either space, tab, and EOL). To learn more, check out `:h word` and `:h WORD`.

For example, suppose you have:

```
const hello = "world";
```

With your cursor at the start of the line, to go to the end of the line with `l`, it will take you 21 key presses. Using `w`, it will take 6. Using `W`, it will only take 4. Both word and WORD are good options to travel short distance.

However, you can get from "c" to ";" in one keystroke with current line navigation.

## Current Line Navigation

When editing, you often need to navigate horizontally in a line. To jump to the first character in current line, use `0`. To go to the last character in the current line, use `$`. Additionally, you can use `^` to go to the first non-blank character in the current line and `g_` to go to the last non-blank character in the current line. If you want to go to the column `n` in the current line, you can use `n|`.

```
0     Go to the first character in the current line
^     Go to the first nonblank char in the current line
g_    Go to the last non-blank char in the current line
$     Go to the last char in the current line
n|    Go to the column n in the current line
```

You can do current line search with `f` and `t`. The difference between `f` and `t` is that `f` takes you to the first letter of the match and `t` takes you till (right before) the first letter of the match. So if you want to search for "h" and land on "h", use `fh`. If you want to search for first "h" and land right before the match, use `th`. If you want to go to the *next* occurrence of the last current line search, use `;`. To go to the previous occurrence of the last current line match, use `,`.

`F` and `T` are the backward counterparts of `f` and `t`. To search backwards for "h", run `Fh`. To keep searching for "h" in the same direction, use `;`. Note that `;` after a `Fh` searches backward and `,` after `Fh` searches forward. 

```
f    Search forward for a match in the same line
F    Search backward for a match in the same line
t    Search forward for a match in the same line, stopping before match
T    Search backward for a match in the same line, stopping before match
;    Repeat the last search in the same line using the same direction
,    Repeat the last search in the same line using the opposite direction
```

Back at the previous example:

```
const hello = "world";
```

With your cursor at the start of the line, you can go to the last character in current line (";") with one keypress: `$`. If you want to go to "w" in "world", you can use `fw`. A good tip to go anywhere in a line is to look for least-common-letters like "j", "x", "z" near your target.

## Sentence and Paragraph Navigation

Next two navigation units are sentence and paragraph.

Let's talk about what a sentence is first. A sentence ends with either `. ! ?` followed by an EOL, a space, or a tab.  You can jump to the next sentence with `)` and the previous sentence with `(`.

```
(    Jump to the previous sentence
)    Jump to the next sentence
```

Let's look at some examples. Which phrases do you think are sentences and which aren't? Try navigating with `(` and `)` in Vim!

```
I am a sentence. I am another sentence because I end with a period. I am still a sentence when ending with an exclamation point! What about question mark? I am not quite a sentence because of the hyphen - and neither semicolon ; nor colon :

There is an empty line above me.
```

By the way, if you're having a problem with Vim not counting a sentence for phrases separated by `.` followed by a single line, you might be in `'compatible'` mode. Add `set nocompatible` into vimrc. In Vi, a sentence is a `.` followed by **two** spaces. You should have `nocompatible` set at all times.

Let's talk about what a paragraph is. A paragraph begins after each empty line and also at each set of a paragraph macro specified by the pairs of characters in paragraphs option.

```
{    Jump to the previous paragraph
}    Jump to the next paragraph
```

If you're not sure what a paragraph macro is, do not worry. The important thing is that a paragraph begins and ends after an empty line. This should be true most of the time.

Let's look at this example. Try navigating around with `}` and `{` (also, play around with sentence navigations `( )` to move around too!)

```
Hello. How are you? I am great, thanks!
Vim is awesome.
It may not be easy to learn it at first...- but we are in this together. Good luck!

Hello again.

Try to move around with ), (, }, and {. Feel how they work.
You got this.
```

Check out `:h sentence` and `:h paragraph` to learn more.

## Match Navigation

Programmers write and edit code. Code typically uses parentheses, braces, and brackets. You can easily get lost in them. If you're inside one, you can jump to the other pair (if it exists) with `%`. You can also use this to find out whether you have matching parentheses, braces, and brackets.

```
%    Navigate to another match, usually works for (), [], {}
```

Let's look at a Scheme code example because it uses parentheses extensively. Move around with `%` inside different parentheses.

```
(define (fib n)
  (cond ((= n 0) 0)
        ((= n 1) 1)
        (else
          (+ (fib (- n 1)) (fib (- n 2)))
        )))
```

I personally like to complement `%` with visual indicators plugins like [vim-rainbow](https://github.com/frazrepo/vim-rainbow). For more, check out `:h %`.

## Line Number Navigation

You can jump to line number `n` with `nG`. For example, if you want to jump to line 7, use `7G`. To jump to the first line, use either `1G` or `gg`. To jump to the last line, use `G`.

Often you don't know exactly what line number your target is, but you know it's approximately at 70% of the whole file. In this case, you can do `70%`. To jump halfway through the file, you can do `50%`.

```
gg    Go to the first line
G     Go to the last line
nG    Go to line n
n%    Go to n% in file
```

By the way, if you want to see total lines in a file, you can use `Ctrl-g`.

## Window Navigation

To quickly go to the top, middle, or bottom of your *window*, you can use `H`, `M`, and `L`.

You can also pass a count to `H` and `L`. If you use `10H`, you will go to 10 lines below the top of window. If you use `3L`, you will go to 3 lines above the last line of window.

```
H     Go to top of screen
M     Go to medium screen
L     Go to bottom of screen
nH    Go n line from top
nL    Go n line from bottom
```

## Scrolling

To scroll, you have 3 speed increments: full-screen (`Ctrl-F/Ctrl-B`), half-screen (`Ctrl-D/Ctrl-U`), and line (`Ctrl-E/Ctrl-Y`).

```
Ctrl-E    Scroll down a line
Ctrl-D    Scroll down half screen
Ctrl-F    Scroll down whole screen
Ctrl-Y    Scroll up a line
Ctrl-U    Scroll up half screen
Ctrl-B    Scroll up whole screen
```

You can also scroll relatively to the current line (zoom screen sight):

```
zt    Bring the current line near the top of your screen
zz    Bring the current line to the middle of your screen
zb    Bring the current line near the bottom of your screen
```

## Search Navigation

Often you know that a phrase exists inside a file. You can use search navigation to very quickly reach your target. To search for a phrase, you can use `/` to search forward and `?` to search backward. To repeat the last search you can use `n`. To repeat the last search going opposite direction, you can use `N`.

```
/    Search forward for a match
?    Search backward for a match
n    Repeat last search in same direction of previous search
N    Repeat last search in opposite direction of previous search
```

Suppose you have this text:

```
let one = 1;
let two = 2;
one = "01";
one = "one";
let onetwo = 12;
```

If you are searching for "let", run `/let`. To quickly search for "let" again, you can just do `n`. To search for "let" again in opposite direction, run `N`. If you run `?let`, it will search for "let" backwards. If you use `n`, it will now search for "let" backwards (`N` will search for "let" forwards now).

You can enable search highlight with `set hlsearch`. Now when you search for `/let`, it will highlight *all* matching phrases in the file. In addition, you can set incremental search with `set incsearch`. This will highlight the pattern while typing. By default, your matching phrases will remain highlighted until you search for another phrase. This can quickly turn into an annoyance. To disable highlight, you can run `:nohlsearch` or simply `:noh`. Because I use this no-highlight feature frequently, I created a map in vimrc:

```
nnoremap <esc><esc> :noh<return><esc>
```

You can quickly search for the text under the cursor with `*` to search forward and `#` to search backward. If your cursor is on the string "one", pressing `*` will be the same as if you had done `/\<one\>`.

Both `\<` and `\>` in `/\<one\>` mean whole word search. It does not match "one" if it is a part of a bigger word. It will match for the word "one" but not "onetwo".  If your cursor is over "one" and you want to search forward to match whole or partial words like "one" and "onetwo", you need to use `g*` instead of `*`.

```
*     Search for whole word under cursor forward
#     Search for whole word under cursor backward
g*    Search for word under cursor forward
g#    Search for word under cursor backward

```
## Marking Position

You can use marks to save your current position and return to this position later. It's like a bookmark for text editing. You can set a mark with `mx`, where `x` can be any alphabetical letter `a-zA-Z`. There are two ways to return to mark: exact (line and column) with `` `x`` and linewise (`'x`).

```
ma    Mark position with mark "a"
`a    Jump to line and column "a"
'a    Jump to line "a"
```

There is a difference between marking with lowercase letters (a-z) and uppercase letters (A-Z). Lowercase alphabets are local marks and uppercase alphabets are global marks (sometimes known as file marks).

Let's talk about local marks. Each buffer can have its own set of local marks. If I have two files opened, I can set a mark "a" (`ma`)  in the first file and another mark "a" (`ma`) in the second file.

Unlike local marks where you can have a set of marks in each buffer, you only get one set of global marks. If you set `mA` inside `myFile.txt`, the next time you run `mA` in a different file, it will overwrite the first "A" mark. One advantage of global marks is you can jump to any global mark even if you are inside a completely different project. Global marks can travel across files.

To view all marks, use `:marks`. You may notice from the marks list there are more marks other than `a-zA-Z`. Some of them are:

```
''    Jump back to the last line in current buffer before jump
``    Jump back to the last position in current buffer before jump
`[    Jump to beginning of previously changed / yanked text
`]    Jump to the ending of previously changed / yanked text
`<    Jump to the beginning of last visual selection
`>    Jump to the ending of last visual selection
`0    Jump back to the last edited file when exiting vim
```

There are more marks than the ones listed above. I won't cover them here because I think they are rarely used, but if you're curious, check out `:h marks`.

## Jump

In Vim, you can "jump" to a different file or different part of a file with some motions. Not all motions count as a jump, though. Going down with `j` does not count as a jump. Going to line 10 with `10G` counts as a jump.

Here are the commands Vim considers as "jump" commands:

```
'       Go to the marked line
`       Go to the marked position
G       Go to the line
/       Search forward
?       Search backward
n       Repeat the last search, same direction
N       Repeat the last search, opposite direction
%       Find match
(       Go to the last sentence
)       Go to the next sentence
{       Go to the last paragraph
}       Go to the next paragraph
L       Go to the last line of displayed window
M       Go to the middle line of displayed window
H       Go to the top line of displayed window
[[      Go to the previous section
]]      Go to the next section
:s      Substitute
:tag    Jump to tag definition
```

I don't recommend memorizing this list. A good rule of thumb is, any motion that moves farther than a word and current line navigation is probably a jump. Vim keeps track of where you've been when you move around and you can see this list inside `:jumps`. 

For more, check out `:h jump-motions`.

Why are jumps useful? Because you can navigate the jump list with `Ctrl-O` to move up the jump list and `Ctrl-I` to move down the jump list. `hjkl` are not "jump" commands, but you can manually add the current location to jump list with `m'` before movement. For example, `m'5j` adds current location to jump list and goes down 5 lines, and you can come back with `Ctrl-O`. You can jump across different files, which I will discuss more in the next part.

## Learn Navigation the Smart Way

If you are new to Vim, this is a lot to learn. I do not expect anyone to remember everything immediately. It takes time before you can execute them without thinking.

I think the best way to get started is to memorize a few essential motions. I recommend starting out with these 10 motions: `h, j, k, l, w, b, G, /, ?, n`. Repeat them sufficiently until you can use them without thinking.

To improve your navigation skill, here are my suggestions:
1. Watch for repeated actions. If you find yourself doing `l` repeatedly, look for a motion that will take you forward faster. You will find that you can use `w`. If you catch yourself repeatedly doing `w`, look if there is a motion that will take you across the current line quickly. You will find that you can use the `f`. If you can describe your need succinctly, there is a good chance Vim has a way to do it.
2. Whenever you learn a new move, spend some time until you can do it without thinking.

Finally, realize that you do not need to know every single Vim command to be productive. Most Vim users don't. I don't. Learn the commands that will help you accomplish your task at that moment.

Take your time. Navigation skill is a very important skill in Vim. Learn one small thing every day and learn it well.

## Link
- Prev [Ch04. Vim Grammar](./ch04_vim_grammar.md)
- Next [Ch06. Insert Mode](./ch06_insert_mode.md)


================================================
FILE: ch06_insert_mode.md
================================================
# Ch06. Insert Mode

Insert mode is the default mode of many text editors. In this mode, what you type is what you get.

However, that does not mean there isn't much to learn. Vim's insert mode contains many useful features. In this chapter, you will learn how to use these insert mode features in Vim to improve your typing efficiency.

## Ways to Go to Insert Mode

There are many ways to get into insert mode from the normal mode. Here are some of them:

```
i    Insert text before the cursor
I    Insert text before the first non-blank character of the line
a    Append text after the cursor
A    Append text at the end of line
o    Starts a new line below the cursor and insert text
O    Starts a new line above the cursor and insert text
s    Delete the character under the cursor and insert text
S    Delete the current line and insert text, synonym for "cc"
gi   Insert text in same position where the last insert mode was stopped
gI   Insert text at the start of line (column 1)
```

Notice the lowercase / uppercase pattern. For each lowercase command, there is an uppercase counterpart. If you are new, don't worry if you don't remember the whole list above. Start with `i` and `o`. They should be enough to get you started. Gradually learn more over time.

## Different Ways to Exit Insert Mode

There are a few different ways to return to the normal mode while in the insert mode:

```
<Esc>     Exits insert mode and go to normal mode
Ctrl-[    Exits insert mode and go to normal mode
Ctrl-C    Like Ctrl-[ and <Esc>, but does not check for abbreviation
```

I find `<Esc>` key too far to reach, so I map my computer `<Caps-Lock>` to behave like `<Esc>`. If you search for Bill Joy's ADM-3A keyboard (Vi creator), you will see that the `<Esc>` key is not located on far top left like modern keyboards, but to the left of `q` key. This is why I think it makes sense to map  `<Caps lock>` to `<Esc>`.

Another common convention I have seen Vim users do is mapping `<Esc>` to `jj` or `jk` in insert mode. If you prefer this option, add one of those lines (or both) in your vimrc file.

```
inoremap jj <Esc>
inoremap jk <Esc>
```

## Repeating Insert Mode

You can pass a count parameter before entering insert mode. For example:

```
10i
```

If you type "hello world!" and exit insert mode, Vim will repeat the text 10 times. This will work with any insert mode method (ex: `10I`, `11a`, `12o`).

## Deleting Chunks in Insert Mode

When you make a typing mistake, it can be cumbersome to type `<Backspace>` repeatedly. It may make more sense to go to normal mode and delete your mistake. You can also delete several characters at a time while in insert mode.

```
Ctrl-h    Delete one character
Ctrl-w    Delete one word
Ctrl-u    Delete the entire line
```

## Insert From Register

Vim registers can store texts for future use. To insert a text from any named register while in insert mode, type `Ctrl-R` plus the register symbol. There are many symbols you can use, but for this section, let's cover only the named registers (a-z).

To see it in action, first you need to yank a word to register a. Move your cursor on any word. Then type:

```
"ayiw
```

- `"a` tells Vim that the target of your next action will go to register a.
- `yiw` yanks inner word. Review the chapter on Vim grammar for a refresher.

Register a now contains the word you just yanked. While in insert mode, to paste the text stored in register a:

```
Ctrl-R a
```

There are multiple types of registers in Vim. I will cover them in greater detail in a later chapter.

## Scrolling

Did you know that you can scroll while inside insert mode? While in insert mode, if you go to `Ctrl-X` sub-mode, you can do additional operations. Scrolling is one of them.

```
Ctrl-X Ctrl-Y    Scroll up
Ctrl-X Ctrl-E    Scroll down
```

## Autocompletion

As mentioned above, if you press `Ctrl-X` from insert mode, Vim will enter a sub-mode. You can do text autocompletion while in this insert mode sub-mode. Although it is not as good as [intellisense](https://code.visualstudio.com/docs/editor/intellisense) or any other Language Server Protocol (LSP), for something that is available right out of the box, it is a very capable feature.

Here are some useful autocomplete commands to get started:

```
Ctrl-X Ctrl-L	   Insert a whole line
Ctrl-X Ctrl-N	   Insert a text from current file
Ctrl-X Ctrl-I	   Insert a text from included files
Ctrl-X Ctrl-F	   Insert a file name
```

When you trigger autocompletion, Vim will display a pop-up window. To navigate up and down the pop-up window, use `Ctrl-N` and `Ctrl-P`.

Vim also has two autocompletion shortcuts that don't involve the `Ctrl-X` sub-mode:

```
Ctrl-N             Find the next word match
Ctrl-P             Find the previous word match
```

In general, Vim looks at the text in all available buffers for autocompletion source. If you have an open buffer with a line that says "Chocolate donuts are the best":
- When you type "Choco" and do `Ctrl-X Ctrl-L`, it will match and print the entire line.
- When you type "Choco" and do `Ctrl-P`, it will match and print the word "Chocolate".

Autocomplete is a vast topic in Vim. This is just the tip of the iceberg. To learn more, check out `:h ins-completion`.

## Executing a Normal Mode Command

Did you know Vim can execute a normal mode command while in insert mode?

While in insert mode, if you press `Ctrl-O`, you'll be in insert-normal sub-mode. If you look at the mode indicator on bottom left, normally you will see `-- INSERT --`, but pressing `Ctrl-O`  changes it to `-- (insert) --`. In this mode, you can do *one* normal mode command. Some things you can do:

**Centering and jumping**

```
Ctrl-O zz       Center window
Ctrl-O H/M/L    Jump to top/middle/bottom window
Ctrl-O 'a       Jump to mark a
```

**Repeating text**

```
Ctrl-O 100ihello    Insert "hello" 100 times
```

**Executing terminal commands**

```
Ctrl-O !! curl https://google.com    Run curl
Ctrl-O !! pwd                        Run pwd
```

**Deleting faster**

```
Ctrl-O dtz    Delete from current location till the letter "z"
Ctrl-O D      Delete from current location to the end of the line
```

## Learn Insert Mode the Smart Way

If you are like me and you come from another text editor, it can be tempting to stay in insert mode. However, staying in insert mode when you're not entering a text is an anti-pattern. Develop a habit to go to normal mode when your fingers aren't typing new text.

When you need to insert a text, first ask yourself if that text already exists. If it does, try to yank or move that text instead of typing it. If you have to use insert mode, see if you can autocomplete that text whenever possible. Avoid typing the same word more than once if you can.

## Link
- Prev [Ch05. Moving in a File](./ch05_moving_in_file.md)
- Next [Ch07. The Dot Command](./ch07_the_dot_command.md)


================================================
FILE: ch07_the_dot_command.md
================================================
# Ch07. The Dot Command

In general, you should try to avoid redoing what you just did whenever possible. In this chapter, you will learn how to use the dot command to easily redo the previous change. It is a versatile command for reducing simple repetitions.

## Usage

Just like its name, you can use the dot command by pressing the dot key (`.`).

For example, if you want to replace all "let" with "const" in the following expressions:

```
let one = "1";
let two = "2";
let three = "3";
```

- Search with `/let` to go to the match.
- Change with `cwconst<Esc>` to replace "let" with "const".
- Navigate with `n` to find the next match using the previous search.
- Repeat what you just did with the dot command (`.`).
- Continue pressing `n . n .` until you replace every word.

Here the dot command repeated the `cwconst<Esc>` sequence. It saved you from typing eight keystrokes in exchange for just one.

## What Is a Change?

If you look at the definition of the dot command (`:h .`), it says that the dot command repeats the last change. What is a change?

Any time you update (add, modify, or delete) the content of the current buffer, you are making a change. The exceptions are updates done by command-line commands (the commands starting with `:`), which do not count as a change.

In the first example, `cwconst<Esc>` was the change. Now suppose you have this text:

```
pancake, potatoes, fruit-juice,
```

To delete the text from the start of the line to the next occurrence of a comma, first delete to the comma, then repeat it twice with `df,..`. 

Let's try another example:

```
pancake, potatoes, fruit-juice,
```

This time, your task is to delete the comma, not the breakfast items. With the cursor at the beginning of the line, go to the first comma, delete it, then repeat two more times with `f,x..` Easy, right? Wait a minute, it didn't work! Why?

A change excludes motions because it does not update buffer content. The command `f,x` consisted of two actions: the command `f,` to move the cursor to "," and `x` to delete a character. Only the latter, `x`, caused a change. Contrast that with `df,` from the earlier example. In it, `f,` is a directive to the delete operator `d`, not a motion to move the cursor. The `f,` in `df,` and `f,x` have two very different roles.

Let's finish the last task. After you run `f,` then `x`, go to the next comma with `;` to repeat the latest `f`. Finally, use `.` to delete the character under the cursor. Repeat `; . ; .` until everything is deleted. The full command is `f,x;.;.`.

Let's try another one:

```
pancake
potatoes
fruit-juice
```

Let's add a comma at the end of each line. Starting at the first line, do `A,<Esc>j`. By now, you realize that `j` does not cause a change. The change here is only `A,`. You can move and repeat the change with `j . j .`. The full command is `A,<Esc>j.j.`.

Every action from the moment you press the insert command operator (`A`) until you exit the insert command (`<Esc>`) is considered as a change.

## Multi-line Repeat

Suppose you have this text:

```
let one = "1";
let two = "2";
let three = "3";
const foo = "bar';
let four = "4";
let five = "5";
let six = "6";
let seven = "7";
let eight = "8";
let nine = "9";
```

Your goal is to delete all lines except the "foo" line. First, delete the first three lines with `d2j`, then to the line below the "foo" line. On the next line, use the dot command twice. The full command is `d2jj..`.

Here the change was `d2j`. In this context, `2j` was not a motion, but a part of the delete operator.

Let's look at another example:

```
zlet zzone = "1";
zlet zztwo = "2";
zlet zzthree = "3";
let four = "4";
```

Let's remove all the z's. Starting from the first character on the first line, visually select only the first z from the first three lines with blockwise visual mode (`Ctrl-Vjj`). If you're not familiar with blockwise visual mode, I will cover them in a later chapter. Once you have the three z's visually selected, delete them with the delete operator (`d`). Then move to the next word (`w`) to the next z. Repeat the change two more times (`..`). The full command is `Ctrl-vjjdw..`.

When you deleted a column of three z's (`Ctrl-vjjd`), it was counted as a change. Visual mode operation can be used to target multiple lines as part of a change.

If `Ctrl-V` doesn't switch the window to VISUAL BLOCK mode, you can try (`Ctrl-Q`), read more at: [Ctrl-V don't work in WLS](https://vi.stackexchange.com/questions/12227/vim-v-visual-block-mode-not-working).

## Including a Motion in a Change

Let's revisit the first example in this chapter. Recall that the command `/letcwconst<Esc>` followed by `n . n .`  replaced all "let" with "const" in the following expressions:

```
let one = "1";
let two = "2";
let three = "3";
```

There is a faster way to accomplish this. After you searched `/let`, run `cgnconst<Esc>` then `. .`.

`gn` is a motion that searches forward for the last search pattern (in this case, `/let`) and automatically does a visual highlight. To replace the next occurrence, you no longer have to move and repeat the change ( `n . n .`), but only repeat (`. .`). You do not have to use search motions anymore because searching the next match is now part of the change!

When you are editing, always be on the lookout for motions that can do several things at once like `gn` whenever possible.

## Learn the Dot Command the Smart Way

The dot command's power comes from exchanging several keystrokes for one. It is probably not a profitable exchange to use the dot command for single key operations like `x`. If your last change requires a complex operation like `cgnconst<Esc>`, the dot command reduces nine keypresses into one, a very profitable trade-off.

When editing, think about repeatability. For example, if I need to remove the next three words, is it more economical to use `d3w` or to do `dw` then `.` two times? Will you be deleting a word again? If so, then it makes sense to use `dw` and repeat it several times instead of `d3w` because `dw` is more reusable than `d3w`. 

The dot command is a versatile command for automating single changes. In a later chapter, you will learn how to automate more complex actions with Vim macros. But first, let's learn about registers to store and retrieve text.

## Link
- Prev [Ch06. Insert Mode](./ch06_insert_mode.md)
- Next [Ch08. Registers](./ch08_registers.md)


================================================
FILE: ch08_registers.md
================================================
# Ch08. Registers

Learning Vim registers is like learning algebra for the first time. You didn't think you needed it until you needed it.

You've probably used Vim registers when you yanked or deleted a text then pasted it with `p` or `P`. However, did you know that Vim has 10 different types of registers? Used correctly, Vim registers can save you from repetitive typing.

In this chapter, I will go over all Vim register types and how to use them efficiently.

## The Ten Register Types

Here are the 10 Vim register types:

1. The unnamed register (`""`).
2. The numbered registers (`"0-9`).
3. The small delete register (`"-`).
4. The named registers (`"a-z`).
5. The read-only registers (`":`, `".`, and `"%`).
6. The alternate file register (`"#`).
7. The expression register (`"=`).
8. The selection registers (`"*` and `"+`).
9. The black hole register (`"_`).
10. The last search pattern register (`"/`).


## Register Operators

To use registers, you need to first store them with operators. Here are some operators that store values to registers:

```
y    Yank (copy)
c    Delete text and start insert mode
d    Delete text
```

There are more operators (like `s` or `x`), but the above are the useful ones. The rule of thumb is, if an operator can remove a text, it probably stores the text to registers.

To paste a text from registers, you can use:

```
p    Paste the text after the cursor
P    Paste the text before the cursor
```

Both `p` and `P` accept a count and a register symbol as arguments. For example, to paste ten times, do `10p`. To paste the text from register a, do `"ap`. To paste the text from register a ten times, do `10"ap`. By the way, the `p` actually technically stands for "put", not "paste", but I figure paste is a more conventional word.

The general syntax to get the content from a specific register is `"a`, where `a` is the register symbol.

## Calling Registers From Insert Mode

Everything you learn in this chapter can also be executed in insert mode. To get the text from register a, normally you do `"ap`. But if you are in insert mode, run `Ctrl-R a`. The syntax to call registers from insert mode is:

```
Ctrl-R a
```

Where `a` is the register symbol. Now that you know how to store and retrieve registers, let's dive in!


## The Unnamed Register

To get the text from the unnamed register, do `""p`. It stores the last text you yanked, changed, or deleted. If you do another yank, change, or delete, Vim will automatically replace the old text. The unnamed register is like a computer's standard copy / paste operation.

By default, `p` (or `P`) is connected to the unnamed register (from now on I will refer to the unnamed register with `p` instead of `""p`).

## The Numbered Registers

Numbered registers automatically fill themselves up in ascending order. There are 2 different numbered registers: the yanked register (`0`) and the numbered registers (`1-9`). Let's discuss the yanked register first.

### The Yanked Register

If you yank, Vim actually saves that text in two registers:

1. The unnamed register (`p`).
2. The yanked register (`"0p`).

When you yank a different text, Vim will update both the yanked register and the unnamed register. Any other operations (like delete) will not be stored in register 0. This can be used to your advantage, because unless you do another yank, the yanked text will always be there, no matter how many changes and deletions you do.

For example, if you:
1. Yank a line (`yy`)
2. Delete a line (`dd`)
3. Delete another line (`dd`)

The yanked register will have the text from step one.

If you:
1. Yank a line (`yy`)
2. Delete a line (`dd`)
3. Yank a word (`yw`)

The yanked register will have the text from step three.

One last tip, while in insert mode, you can quickly paste the text you just yanked using `Ctrl-R 0`.

### The Non-zero Numbered Registers

When you change or delete a text that is at least one line long, that text will be stored in the numbered registers 1-9 sorted by the most recent.

For example, if you have these lines:

```
line three
line two
line one
```

With your cursor on "line three", delete them one by one with `dd`. Once all lines are deleted, register 1 should contain "line one" (most recent), register two "line two" (second most recent), and register three "line three" (oldest). To get the content from register one, do `"1p`.

As a side note, these numbered registers are automatically incremented when using the dot command. If your numbered register one (`"1`) contains "line one", register two (`"2`) "line two", and register three (`"3`) "line three", you can paste them sequentially with this trick:
- Do `"1P` to paste the content from the numbered register one ("1).
- Do `.` to paste the content from the numbered register two ("2).
- Do `.` to paste the content from the numbered register three ("3).

This trick works with any numbered register. If you started with `"5P`,  `.`  would do `"6P`, `.` again would do `"7P`, and so on.

Small deletions like a word deletion (`dw`) or word change (`cw`) do not get stored in the numbered registers. They are stored in the small delete register (`"-`), which I will discuss next.

## The Small Delete Register

Changes or deletions less than one line are not stored in the numbered registers 0-9, but in the small delete register (`"-`).

For example:
1. Delete a word (`diw`)
2. Delete a line (`dd`)
3. Delete a line (`dd`)

`"-p` gives you the deleted word from step one.

Another example:
1. I delete a word (`diw`)
2. I delete a line (`dd`)
3. I delete a word (`diw`)

`"-p` gives you the deleted word from step three. `"1p` gives you the deleted line from step two. Unfortunately, there is no way to retrieve the deleted word from step one because the small delete register only stores one item. However, if you want to preserve the text from step one, you can do it with the named registers.

## The Named Register

The named registers are Vim's most versatile register. It can store yanked, changed, and deleted texts into registers a-z. Unlike the previous 3 register types you've seen which automatically stores texts into registers, you have to explicitly tell Vim to use the named register, giving you full control.

To yank a word into register a, you can do it with `"ayiw`.
- `"a` tells Vim that the next action (delete / change / yank) will be stored in register a.
- `yiw` yanks the word.

To get the text from register a, run `"ap`. You can use all twenty-six alphabetical characters to store twenty-six different texts with named registers.

Sometimes you may want to add to your existing named register. In this case, you can append your text instead of starting all over. To do that, you can use the uppercase version of that register. For example, suppose you have the word "Hello " already stored in register a. If you want to add "world" into register a, you can find the text "world" and yank it using A register (`"Ayiw`).

## The Read-only Registers

Vim has three read-only registers: `.`, `:`, and `%`. They are pretty simple to use:

```
.    Stores the last inserted text
:    Stores the last executed command-line
%    Stores the name of current file
```

If the last text you wrote was "Hello Vim", running `".p` will print out the text "Hello Vim". If you want to get the name of current file, run `"%p`. If you run `:s/foo/bar/g` command, running `":p` will print out the literal text "s/foo/bar/g".

## The Alternate File Register

In Vim, `#` usually represents the alternate file. An alternative file is the last file you opened. To insert the name of the alternate file, you can use `"#p`.

## The Expression Register

Vim has an expression register, `"=`, to evaluate expressions.

To evaluate mathematical expressions `1 + 1`, run:

```
"=1+1<Enter>p
```

Here, you are telling Vim that you are using the expression register with `"=`. Your expression is (`1 + 1`). You need to type `p` to get the result. As mentioned earlier, you can also access the register from insert mode. To evaluate mathematical expression from insert mode, you can do:

```
Ctrl-R =1+1
```

You can also get the values from any register via the expression register when appended with `@`. If you wish to get the text from register a:

```
"=@a
```

Then press `<Enter>`, then `p`. Similarly, to get values from register a while in insert mode:

```
Ctrl-r =@a
```

Expression is a vast topic in Vim, so I will only cover the basics here. I will address expressions in more detail in later Vimscript chapters.

## The Selection Registers

Don't you sometimes wish that you can copy a text from external programs and paste it locally in Vim, and vice versa? With Vim's selection registers, you can. Vim has two selection registers: `quotestar` (`"*`) and `quoteplus` (`"+`). You can use them to access copied text from external programs.

If you are on an external program (like Chrome browser) and you copy a block of text with `Ctrl-C` (or `Cmd-C`, depending on your OS), normally you wouldn't be able to use `p` to paste the text in Vim. However, both Vim's `"+` and `"*` are connected to your clipboard, so you can actually paste the text with  `"+p` or `"*p`. Conversely, if you yank a word from Vim with `"+yiw` or `"*yiw`, you can paste that text in the external program with `Ctrl-V` (or `Cmd-V`). Note that this only works if your Vim program comes with the `+clipboard` option (to check it, run `:version`).

You may wonder if `"*` and `"+` do the same thing, why does Vim have two different registers? Some machines use X11 window system. This system has 3 types of selections: primary, secondary, and clipboard. If your machine uses X11, Vim uses X11's *primary* selection with the `quotestar` (`"*`) register and X11's *clipboard* selection with the `quoteplus` (`"+`) register. This is only applicable if you have `+xterm_clipboard` option available in your Vim build. If your Vim doesn't have `xterm_clipboard`, it's not a big deal. It just means that both `quotestar` and `quoteplus` are interchangeable (mine doesn't either).

I find doing `=*p` or `=+p` (or `"*p` or `"+p`) to be cumbersome. To make Vim paste copied text from the external program with just `p`, you can add this in your vimrc:

```
set clipboard=unnamed
 ```

Now when I copy a text from an external program, I can paste it with the unnamed register, `p`. I can also copy a text from Vim and paste it to an external program. If you have `+xterm_clipboard` on, you may want to use both `unnamed` and `unnamedplus` clipboard options.

## The Black Hole Register

Each time you delete or change a text, that text is stored in Vim register automatically. There will be times when you don't want to save anything into the register. How can you do that?

You can use the black hole register (`"_`). To delete a line and not have Vim store the deleted line into any register, use `"_dd`.

The black hole register is like the `/dev/null` of registers.

## The Last Search Pattern Register

To paste your last search (`/` or `?`), you can use the last search pattern register (`"/`). To paste the last search term, use `"/p`.

## Viewing the Registers

To view all your registers, use the `:register` command. To view only registers "a, "1, and "-, use `:register a 1 -`.

There is a plugin called [vim-peekaboo](https://github.com/junegunn/vim-peekaboo) that lets you peek into the contents of the registers when you hit `"` or `@` in normal mode and `Ctrl-R` in insert mode. I find this plugin very useful because most times, I can't remember the content in my registers. Give it a try!

## Executing a Register

The named registers are not just for storing texts. They can also execute macros with `@`. I will go over macros in the next chapter.

Keep in mind since macros are stored inside Vim registers, you can accidentally overwrite the stored text with macros. If you store the text "Hello Vim" in register a and you later record a macro in the same register (`qa{macro-sequence}q`), that macro will overwrite your "Hello Vim" text stored earlier.

## Clearing a Register

Technically, there is no need to clear any register because the next text that you store under the same register name will overwrite it. However, you can quickly clear any named register by recording an empty macro. For example, if you run `qaq`, Vim will record an empty macro in the register a.

Another alternative is to run the command `:call setreg('a', 'hello register a')` where a is the register a and "hello register a" is the text that you want to store.

One more way to clear register is to set the content of "a register to an empty string with the expression `:let @a = ''`.

## Putting the Content of a Register

You can use the `:put` command to paste the content of any one register. For example, if you run `:put a`, Vim will print the content of register a below the current line. This behaves much like `"ap`, with the difference that the normal mode command `p` prints the register content after the cursor and the command `:put` prints the register content at newline.

Since `:put` is a command-line command, you can pass it an address. `:10put a` will paste text from register a to below line 10.

One cool trick to pass `:put` with the black hole register (`"_`). Since the black hole register does not store any text, `:put _` will insert a blank line instead. You can combine this with the global command to insert multiple blank lines. For example, to insert blank lines below all lines that contain the text "end", run `:g/end/put _`. You will learn about the global command later.

## Learning Registers the Smart Way

You made it to the end. Congratulations! If you are feeling overwhelmed by the sheer information, you are not alone. When I first started learning about Vim registers, there was way too much information to take in at once.

I don't think you should memorize all the registers immediately. To become productive, you can start by using only these 3 registers:
1. The unnamed register (`""`).
2. The named registers (`"a-z`).
3. The numbered registers (`"0-9`).

Since the unnamed register defaults to `p` and `P`, you only have to learn two registers: the named registers and the numbered registers. Gradually learn more registers when you need them. Take your time.

The average human has a limited short-term memory capacity, about 5 - 7 items at once. That is why in my everyday editing, I only use about 5 -  7 named registers. There is no way I can remember all twenty-six in my head. I normally start with register a, then b, ascending the alphabetical order. Try it and experiment around to see what technique works best for you.

Vim registers are powerful. Used strategically, it can save you from typing countless repeating texts. Next, let's learn about macros.

## Link
- Prev [Ch07. The Dot Command](./ch07_the_dot_command.md)
- Next [Ch09. Macros](./ch09_macros.md)


================================================
FILE: ch09_macros.md
================================================
# Ch09. Macros

When editing files, you may find yourself repeating the same actions. Wouldn't it be nice if you could do those actions once and replay them whenever you need it? With Vim macros, you can record actions and store them inside Vim registers to be executed whenever you need it.

In this chapter, you will learn how to use macros to automate mundane tasks (plus it looks cool to watch your file edit itself).

## Basic Macros

Here is the basic syntax of a Vim macro:

```
qa                     Start recording a macro in register a
q (while recording)    Stop recording macro
```

You can choose any lowercase letters (a-z) to store macros. Here is how you can execute a macro:

```
@a    Execute macro from register a
@@    Execute the last executed macros
```

Suppose you have this text and you want to uppercase everything on each line:

```
hello
vim
macros
are
awesome
```

With your cursor at the start of the line "hello", run:

```
qa0gU$jq
```

The breakdown:
- `qa` starts recording a macro in the a register.
- `0` goes to beginning of the line.
- `gU$` uppercases the text from your current location to the end of the line.
- `j` goes down one line.
- `q` stops recording.

To replay it, run `@a`. Just like many other Vim commands, you can pass a count argument to macros. For example, running `3@a` executes the macro three times.

## Safety Guard

Macro execution automatically ends when it encounters an error. Suppose you have this text:

```
a. chocolate donut
b. mochi donut
c. powdered sugar donut
d. plain donut
```

If you want to uppercase the first word on each line, this macro should work:

```
qa0W~jq
```

Here's the breakdown of the command above:
- `qa` starts recording a macro in the a register.
- `0` goes to the beginning of the line.
- `W` goes to the next WORD.
- `~` toggles the case of the character under the cursor.
- `j` goes down one line.
- `q` stops recording.

I prefer to overcount my macro execution than undercount it, so I usually call it ninety-nine times (`99@a`). With this command, Vim does not actually run this macro ninety-nine times. When Vim reaches the last line and runs `j` motion, it finds no more line to go down to, throws an error, and stops the macro execution.

The fact that macro execution stops upon the first error encounter is a good feature, otherwise Vim will continue to execute this macro ninety-nine times even though it already reaches the end of the line.

## Command Line Macro

Running `@a` in normal mode is not the only way you can execute macros in Vim. You can also run `:normal @a` command line. `:normal` allows the user to execute any normal mode command passed as argument. In the case above, it is the same as running `@a` from normal mode.

The `:normal` command accepts range as arguments. You can use this to run macro in select ranges. If you want to execute your macro between lines 2 and 3, you can run `:2,3 normal @a`.

## Executing a Macro Across Multiple Files

Suppose you have multiple `.txt` files, each contains some texts. Your task is to uppercase the first word only on lines containing the word "donut". Assume you have `0W~j` in register a (the same macro as before). How can you quickly accomplish this?

First file:

```
## savory.txt
a. cheddar jalapeno donut
b. mac n cheese donut
c. fried dumpling
```

Second file:

```
## sweet.txt
a. chocolate donut
b. chocolate pancake
c. powdered sugar donut
```

Third file:

```
## plain.txt
a. wheat bread
b. plain donut
```

Here is how you can do it:
- `:args *.txt` to find all `.txt` files in your current directory.
- `:argdo g/donut/normal @a` executes the global command `g/donut/normal @a` on each file inside `:args`.
- `:argdo update` executes `update` command to save each file inside `:args` when the buffer has been modified.

If you are not familiar with the global command `:g/donut/normal @a`, it executes the command you give (`normal @a`) on lines that match the pattern (`/donut/`). I will go over the global command in a later chapter.

## Recursive Macro

You can recursively execute a macro by calling the same macro register while recording that macro. Suppose you have this list again and you need to toggle the case of the first word:

```
a. chocolate donut
b. mochi donut
c. powdered sugar donut
d. plain donut
```

This time, let's do it recursively. Run:

```
qaqqa0W~j@aq
```

Here is the breakdown of the steps:
- `qaq` records an empty macro a. It is necessary to start with an empty register because when you recursively call the macro, it will run whatever is in that register.
- `qa` starts recording on register a.
- `0` goes to the first character in the current line.
- `W` goes to the next WORD.
- `~` toggles the case of the character under the cursor.
- `j` goes down one line.
- `@a` executes macro a.
- `q` stops recording.

Now you can just run `@a` and watch Vim execute the macro recursively.

How did the macro know when to stop? When the macro was on the last line, it tried to run `j`, since there was no more line to go to, it stopped the macro execution.

## Appending a Macro

If you need to add actions to an existing macro, instead of recreating the macro from scratch, you can append actions to an existing one. In the register chapter, you learned that you can append a named register by using its uppercased symbol. The same rule applies. To append actions to register a macro, use register A.

Record a macro in register a: `qa0W~q` (this sequence toggles the case of the next WORD in a line). If you want to append a new sequence to also add a dot at the end of the line, run:

```
qAA.<Esc>q
```

The breakdown:
- `qA` starts recording the macro in register A.
- `A.<Esc>` inserts at the end of the line (here `A` is the insert mode command, not to be confused with the macro A) a dot, then exits insert mode.
- `q` stops recording macro.

Now when you execute `@a`, it not only toggles the case of the next WORD, it also adds a dot at the end of the line.

## Amending a Macro

What if you need to add new actions in the middle of a macro?

Assume that you have a macro that toggles the first actual word and adds a period at the end of the line, `0W~A.<Esc>` in register a. Suppose that between uppercasing the first word and adding a period at the end of the line, you need to add the word "deep fried" right before the word "donut" *(because the only thing better than regular donuts are deep fried donuts)*.

I will reuse the text from earlier section:
```
a. chocolate donut
b. mochi donut
c. powdered sugar donut
d. plain donut
```

First, let's call the existing macro (assume you have kept the macro from the previous section in register a) with `:put a`:

```
0W~A.^[
```

What is this `^[`? Didn't you do `0W~A.<Esc>`? Where is the `<Esc>`? `^[` is Vim's *internal code* representation of `<Esc>`. With certain special keys, Vim prints the representation of those keys in the form of internal codes. Some common keys that have internal code representations are `<Esc>`, `<Backspace>`, and `<Enter>`. There are more special keys, but they are not within the scope of this chapter.

Back to the macro, right after the toggle case operator (`~`), let's add the instructions to go to the end of the line (`$`), go back one word (`b`), go to the insert mode (`i`), type "deep fried " (don't forget the space after "fried "), and exit insert mode (`<Esc>`).

Here is what you will end up with:

```
0W~$bideep fried <Esc>A.^[
```

There is a small problem. Vim does not understand `<Esc>`. You can't literally type `<Esc>`. You will have to write the internal code representation for the `<Esc>` key. While in insert mode, you press `Ctrl-V` followed by `<Esc>`. Vim will print `^[`.` Ctrl-V` is an insert mode operator to insert the next non-digit character *literally*. Your macro code should look like this now:

```
0W~$bideep fried ^[A.^[
```

To add the amended instruction into register a, you can do it the same way as adding a new entry into a named register. At the start of the line, run `"ay$` to store the yanked text in register a.

Now when you execute `@a`, your macro will toggle the case of the first word, add "deep fried " before "donut", and add a "." at the end of the line. Yum!

An alternative way to amend a macro is to use a command line expression. Do `:let @a="`, then do `Ctrl-R a`, this will literally paste the content of register a. Finally, don't forget to close the double quotes (`"`). You might have something like `:let @a="0W~$bideep fried ^[A.^["`.

## Macro Redundancy

You can easily duplicate macros from one register to another. For example, to duplicate a macro in register a to register z, you can do `:let @z = @a`. `@a` represents the content of register a. Now if you run `@z`, it does the exact same actions as `@a`.

I find creating a redundancy useful on my most frequently used macros. In my workflow, I usually record macros in the first seven alphabetical letters (a-g) and I often replace them without much thought. If I move the useful macros towards the end of the alphabets, I can preserve them without worrying that I might accidentally replace them.

## Series vs Parallel Macro

Vim can execute macros in series and parallel. Suppose you have this text:

```
import { FUNC1 } from "library1";
import { FUNC2 } from "library2";
import { FUNC3 } from "library3";
import { FUNC4 } from "library4";
import { FUNC5 } from "library5";
```

If you want to record a macro to lowercase all the uppercased "FUNC", this macro should work:

```
qa0f{gui{jq
```

The breakdown:
- `qa` starts recording in register a.
- `0` goes to first line.
- `f{` finds the first instance of "{".
- `gui{` lowercases (`gu`) the text inside the bracket text-object (`i{`).
- `j` goes down one line.
- `q` stops macro recording.

Now you can run `99@a` to execute it on the remaining lines. However, what if you have this import expression inside your file?

```
import { FUNC1 } from "library1";
import { FUNC2 } from "library2";
import { FUNC3 } from "library3";
import foo from "bar";
import { FUNC4 } from "library4";
import { FUNC5 } from "library5";
```

Running `99@a`, only executes the macro three times. It does not execute the macro on last two lines because the execution fails to run `f{` on the "foo" line. This is expected when running the macro in series. You can always go to the next line where "FUNC4" is and replay that macro again. But what if you want to get everything done in one go?

Run the macro in parallel.

Recall from earlier section that macros can be executed using the  command line command `:normal` (ex: `:3,5 normal @a` executes macro a on lines 3-5). If you run `:1,$ normal @a`, you will see that the macro is being executed on all lines except the "foo" line. It works!

Although internally Vim does not actually run the macros in parallel, outwardly, it behaves like it. Vim executes `@a` *independently* on each line from the first to the last line (`1,$`). Since Vim executes these macros independently, each line does not know that one of the macro executions had failed on the "foo" line.

## Learn Macros the Smart Way

Many things you do in editing are repetitive. To get better at editing, get into the habit of detecting repetitive actions. Use macros (or dot command) so you don't have to perform the same action twice. Almost everything that you can do in Vim can be replicated with macros.

In the beginning, I find it very awkward to write macros, but don't give up. With enough practice, you will get into the habit of automating everything.

You might find it helpful to use mnemonics to help remember your macros. If you have a macro that creates a function, use the "f register (`qf`). If you have a macro for numerical operations, the "n register should work (`qn`). Name it with the *first named register* that comes to your mind when you think of that operation. I also find that the "q register makes a good default macro register because `qq` requires less brain power to come up with. Lastly, I also like to increment my macros in alphabetical orders, like `qa`, then `qb`, then `qc`, and so on.

Find a method that works best for you.

## Link
- Prev [Ch08. Registers](./ch08_registers.md)
- Next [Ch10. Undo](./ch10_undo.md)


================================================
FILE: ch10_undo.md
================================================
# Ch10. Undo

We all make all sorts of typing mistakes. That's why undo is an essential feature in any modern software. Vim's undo system is not only capable of undoing and redoing simple mistakes, but also accessing different text states, giving you control over all the texts you have ever typed. In this chapter, you will learn how to undo, redo, navigate an undo branch, persist undo, and travel across time.

## Undo, Redo, and UNDO

To perform a basic undo, you can use `u` or run `:undo`.

If you have this text (note the empty line below "one"):

```
one

```

Then you add another text:

```
one
two
```

If you press `u`, Vim undoes the text "two".

How does Vim know how much to undo? Vim undoes a single "change" at a time, similar to a dot command's change (unlike the dot command, command-line command also count as a change).

To redo the last change, press `Ctrl-R` or run `:redo`. After you undo the text above to remove "two", running `Ctrl-R` will get the removed text back.

Vim also has UNDO that you can run with `U`. It undoes all latest changes.

How is `U` different from `u`? First, `U` removes *all* the changes on the latest changed line, while `u` only removes one change at a time. Second, while doing `u` does not count as a change, doing `U` counts as a change.

Back to this example:

```
one
two
```

Change the second line to "three":

```
one
three
```

Change the second line again and replace it with "four":

```
one
four
```

If you press `u`, you will see "three". If you press  `u` again, you'll see "two". If instead of pressing `u` when you still had the text "four", you had pressed `U`, you will see:

```
one

```

`U` bypasses all the intermediary changes and goes to the original state when you started (an empty line). In addition, since UNDO actually creates a new change in Vim, you can UNDO your UNDO. `U` followed by `U` will undo itself. You can press `U`, then `U`, then `U`, etc. You will see the same two text states toggling back and forth.

I personally do not use `U` because it is hard to remember the original state (I seldom ever need it).

Vim sets a maximum number of how many times you can undo in `undolevels` option variable. You can check it with `:echo &undolevels`. I have mine set to be 1000. To change yours to 1000, run `:set undolevels=1000`. Feel free to set it to any number you like.

## Breaking the Blocks

I mentioned earlier that `u` undoes a single "change" similar to the dot command's change: the texts inserted from when you enter the insert mode until you exit it count as a change.

If you do `ione two three<Esc>` then press `u`, Vim removes the entire "one two three" text because the whole thing counts as a change. This is not a big deal if you have written short texts, but what if you have written several paragraphs within one insert mode session without exiting and later you realized you made a mistake? If you press `u`, everything you had written would be removed. Wouldn't it be useful if you can press `u` to remove only a section of your text?

Luckily, you can break the undo blocks. When you are typing in insert mode, pressing `Ctrl-G u` creates an undo breakpoint. For example, if you do `ione <Ctrl-G u>two <Ctrl-G u>three<Esc>`, then press `u`, you will only lose the text "three" (press `u` one more time to remove "two"). When you write a long text, use `Ctrl-G u` strategically. The end of each sentence, between two paragraphs, or after each line of code are prime locations to add undo breakpoints to make it easier to undo your mistakes if you ever make one.

It is also useful to create an undo breakpoint when deleting chunks in insert mode with `Ctrl-W` (delete the word before the cursor) and `Ctrl-U` (delete all text before the cursor). A friend suggested to use the following maps:

```
inoremap <c-u> <c-g>u<c-u>
inoremap <c-w> <c-g>u<c-w>
```

With these, you can easily recover the deleted texts.

## Undo Tree

Vim stores every change ever written in an undo tree. Start a new empty file. Then add a new text:

```
one

```

Add a new text:

```
one
two
```

Undo once:

```
one

```

Add a different text:

```
one
three
```

Undo again:

```
one

```

And add another different text:

```
one
four
```


Now if you undo, you will lose the text "four" you just added:

```
one

```

If you undo one more time:

```

```

You will lose the text "one". In most text editor, getting the texts "two" and "three" back would have been impossible, but not with Vim! Press `g+` and you'll get your text "one" back:

```
one

```

Type `g+` again and you will see an old friend:

```
one
two
```

Let's keep going. Press `g+` again:

```
one
three
```

Press `g+` one more time:

```
one
four
```

In Vim, every time you press `u` and then make a different change, Vim stores the previous state's text by creating an "undo branch". In this example, after you typed "two", then pressed `u`, then typed "three", you created a leaf branch that stores the state containing the text "two". At that moment, the undo tree contained at least two leaf nodes: the main node containing the text "three" (most recent) and the undo branch node containing the text "two". If you had done another undo and typed the text "four", you would have at least three nodes: a main node containing the text "four" and two nodes containing the texts "three" and "two".

To traverse each undo tree nodes, you can use `g+` to go to a newer state and `g-` to go to an older state. The difference between `u`, `Ctrl-R`, `g+`, and `g-` is that both `u` and `Ctrl-R` traverse only the *main* nodes in undo tree while `g+` and `g-` traverse *all* nodes in the undo tree.

Undo tree is not easy to visualize. I find [vim-mundo](https://github.com/simnalamburt/vim-mundo) plugin to be very useful to help visualize Vim's undo tree. Give it some time to play around with it.

## Persistent Undo

If you start Vim, open a file, and immediately press `u`, Vim will probably display "*Already at oldest change*" warning. There is nothing to undo because you haven't made any changes. 

To rollover the undo history from the last editing session, Vim can preserve your undo history with an undo file with `:wundo`.

Create a file `mynumbers.txt`. Type:

```
one
```

Then type another line (make sure each line counts as a change):

```
one
two
```

Type another line:

```
one
two
three
```

Now create your undo file with `:wundo {my-undo-file}`. If you need to overwrite an existing undo file, you can add `!` after `wundo`.

```
:wundo! mynumbers.undo
```

Then exit Vim.

By now you should have `mynumbers.txt` and `mynumbers.undo` files in your directory. Open up `mynumbers.txt` again and try pressing `u`. You can't. You haven't made any changes since you opened the file. Now load your undo history by reading the undo file with `:rundo`:

```
:rundo mynumbers.undo
```

Now if you press `u`, Vim removes "three". Press `u` again to remove "two". It is like you never even closed Vim!

If you want to have an automatic undo persistence, one way to do it is by adding these in vimrc:

```
set undodir=~/.vim/undo_dir
set undofile
```

The setting above will put all the undofile in one centralized directory, the `~/.vim` directory. The name `undo_dir` is arbitrary. `set undofile` tells Vim to turn on `undofile` feature because it is off by default. Now whenever you save, Vim automatically creates and updates the relevant file inside the `undo_dir` directory (make sure that you create the actual `undo_dir` directory inside `~/.vim` directory before running this).

## Time Travel

Who says that time travel doesn't exist? Vim can travel to a text state in the past with `:earlier` command-line command.

If you have this text:

```
one

```
Then later you add:

```
one
two
```

If you had typed "two" less than ten seconds ago, you can go back to the state where "two" didn't exist ten seconds ago with:

```
:earlier 10s
```

You can use `:undolist` to see when the last change was made. `:earlier` also accepts different arguments:

```
:earlier 10s    Go to the state 10 seconds before
:earlier 10m    Go to the state 10 minutes before
:earlier 10h    Go to the state 10 hours before
:earlier 10d    Go to the state 10 days before
```

In addition, it also accepts a regular `count` as argument to tell Vim to go to the older state `count` times. For example, if you do `:earlier 2`, Vim will go back to an older text state two changes ago. It is the same as doing `g-` twice. You can also tell it to go to the older text state 10 saves ago with `:earlier 10f`.

The same set of arguments work with `:earlier` counterpart: `:later`.

```
:later 10s    go to the state 10 seconds later
:later 10m    go to the state 10 minutes later
:later 10h    go to the state 10 hours later
:later 10d    go to the state 10 days later
:later 10     go to the newer state 10 times
:later 10f    go to the state 10 saves later
```

## Learn Undo the Smart Way

`u` and `Ctrl-R` are two indispensable Vim commands for correcting mistakes. Learn them first. Next, learn how to use `:earlier` and `:later` using the time arguments first. After that, take your time to understand the undo tree. The [vim-mundo](https://github.com/simnalamburt/vim-mundo) plugin helped me a lot. Type along the texts in this chapter and check the undo tree as you make each change. Once you grasp it, you will never see the undo system the same way again.

Prior to this chapter, you learned how to find any text in a project space, with undo, you can now find any text in a time dimension. You are now able to search for any text by its location and time written. You have achieved Vim-omnipresence.


## Link
- Prev [Ch09. Macros](./ch09_macros.md)
- Next [Ch11. Visual Mode](./ch11_visual_mode.md)


================================================
FILE: ch11_visual_mode.md
================================================
# Ch11. Visual Mode

Highlighting and applying changes to a body of text is a common feature in many text editors and word processors. Vim can do this using visual mode. In this chapter, you will learn how to use the visual mode to manipulate texts efficiently.

## The Three Types of Visual Modes

Vim has three different visual modes. They are:

```
v         Character-wise visual mode
V         Line-wise visual mode
Ctrl-V    Block-wise visual mode
```

If you have the text:

```
one
two
three
```

Character-wise visual mode works with individual characters. Press `v` on the first character. Then go down to the next line with `j`. It highlights all texts from "one" up to your cursor location. If you press `gU`, Vim uppercases the highlighted characters.

Line-wise visual mode works with lines. Press `V` and watch Vim selects the entire line your cursor is on. Just like character-wise visual mode, if you run `gU`, Vim uppercases the highlighted characters.

Block-wise visual mode works with rows and columns. It gives you more freedom of movement than the other two modes. If you press `Ctrl-V`, Vim highlights the character under the cursor just like character-wise visual mode, except instead of highlighting each character until the end of the line before going down to the next line, it goes to the next line with minimal highlighting. Try moving around with `h/j/k/l` and watch the cursor move.

On the bottom left of your Vim window, you will see either `-- VISUAL --`, `-- VISUAL LINE --`, or `-- VISUAL BLOCK --` displayed to indicate which visual mode you are in.

While you are inside a visual mode, you can switch to another visual mode by pressing either `v`, `V`, or `Ctrl-V`. For example, if you are in line-wise visual mode and you want to switch to block-wise visual mode, run `Ctrl-V`. Try it!

There are three ways to exit the visual mode: `<Esc>`, `Ctrl-C`, and the same key as your current visual mode. What the latter means is if you are currently in the line-wise visual mode (`V`), you can exit it by pressing `V` again. If you are in the character-wise visual mode, you can exit it by pressing `v`.

There is actually one more way to enter the visual mode:

```
gv    Go to the previous visual mode
```

It will start the same visual mode on the same highlighted text block as you did last time.

## Visual Mode Navigation

While in a visual mode, you can expand the highlighted text block with Vim motions.

Let's use the same text you used earlier:

```
one
two
three
```

This time let's start from the line "two". Press `v` to go to the character-wise visual mode (here the square brackets `[]` represent the character highlights):

```
one
[t]wo
three
```

Press `j` and Vim will highlight all the text from the line "two" down to the first character of the line "three".

```
one
[two
t]hree
```

Assume from this position, you want to add the line "one" too. If you press `k`, to your dismay, the highlight moves away from the line "three". 

```
one
[t]wo
three
```

Is there a way to freely expand visual selection to move in any direction you want? Definitely. Let's back up a little bit to where you have the line "two" and "three" highlighted.

```
one
[two
t]hree    <-- cursor
```

Visual highlight follows the cursor movement. If you want to expand it upward to the line "one", you need to move the cursor up to the line "two". Right now the cursor is on the line "three". You can toggle the cursor location with either `o` or `O`.

```
one
[two     <-- cursor
t]hree
```

Now when you press `k`, it no longer reduces the selection, but expands it upward.

```
[one
two
t]hree
```

With `o` or `O` in visual mode, the cursor jumps from the beginning to the end of the highlighted block, allowing you to expand the highlight area.

## Visual Mode Grammar

The visual mode shares many operations with normal mode.

For example, if you have the following text and you want to delete the first two lines from visual mode:

```
one
two
three
```

Highlight the lines "one" and "two" with the line-wise visual mode (`V`):

```
[one
two]
three
```

Pressing `d` will delete the selection, similar to normal mode. Notice the grammar rule from normal mode, verb + noun, does not apply. The same verb is still there (`d`), but there is no noun in visual mode. The grammar rule in visual mode is noun + verb, where noun is the highlighted text. Select the text block first, then the command follows.

In normal mode, there are some commands that do not require a motion, like `x` to delete a single character under the cursor and `r` to replace the character under the cursor (`rx` replaces the character under the cursor with "x"). In visual mode, these commands are now being applied to the entire highlighted text instead of a single character. Back at the highlighted text:

```
[one
two]
three
```

Running `x` deletes all highlighted texts.

You can use this behavior to quickly create a header in markdown text. Suppose you need to quickly turn the following text into a first-level markdown header ("==="):

```
Chapter One
```

First, copy the text with `yy`, then paste it with `p`:

```
Chapter One
Chapter One
```

Now, go to the second line and select it with line-wise visual mode:

```
Chapter One
[Chapter One]
```

A first-level header is a series of "=" below a text. Run `r=`, voila! This saves you from typing "=" manually.

```
Chapter One
===========
```

To learn more about operators in visual mode, check out `:h visual-operators`.

## Visual Mode and Command-line Commands

You can selectively apply command-line commands on a highlighted text block. If you have these statements and you want to substitute "const" with "let" only on the first two lines:

```
const one = "one";
const two = "two";
const three = "three";
```

Highlight the first two lines with *any* visual mode and run the substitute command `:s/const/let/g`:

```
let one = "one";
let two = "two";
const three = "three";
```

Notice I said you can do this with *any* visual mode. You do not have to highlight the entire line to run the command on that line. As long as you select at least a character on each line, the command is applied.

## Adding Text on Multiple Lines

You can add text on multiple lines in Vim using the block-wise visual mode. If you need to add a semicolon at the end of each line:

```
const one = "one"
const two = "two"
const three = "three"
```

With your cursor on the first line:
- Run block-wise visual mode and go down two lines (`Ctrl-V jj`).
- Highlight to the end of the line (`$`).
- Append (`A`) then type ";".
- Exit visual mode (`<Esc>`).

You should see the appended ";" on each line now. Pretty cool! There are two ways to enter the insert mode from block-wise visual mode: `A` to enter the text after the cursor or `I` to enter the text before the cursor. Do not confuse them with `A` (append text at the end of the line) and `I` (insert text before the first non-blank line) from normal mode.

Alternatively, you can also use the `:normal` command to add text on multiple lines:
- Highlight all 3 lines (`vjj`).
- Type `:normal! A;`.

Remember, `:normal` command executes normal mode commands. You can instruct it to run `A;` to append text ";" at the end of the line.

## Incrementing Numbers

Vim has `Ctrl-X` and `Ctrl-A` commands to decrement and increment numbers. When used with visual mode, you can increment numbers across multiple lines.

If you have these HTML elements:

```
<div id="app-1"></div>
<div id="app-1"></div>
<div id="app-1"></div>
<div id="app-1"></div>
<div id="app-1"></div>
```

It is a bad practice to have several ids having the same name, so let's increment them to make them unique:
- Move your cursor to the "1" on the second line.
- Start block-wise visual mode and go down 3 lines (`Ctrl-V 3j`). This highlights the remaining  "1"s. Now all "1" should be highlighted (except the first line).
- Run `g Ctrl-A`.

You should see this result:

```
<div id="app-1"></div>
<div id="app-2"></div>
<div id="app-3"></div>
<div id="app-4"></div>
<div id="app-5"></div>
```

`g Ctrl-A` increments numbers on multiple lines. `Ctrl-X/Ctrl-A` can increment letters too, with the number formats option:

```
set nrformats+=alpha
```

The `nrformats` option instructs Vim which bases are considered as "numbers" for `Ctrl-A` and `Ctrl-X` to increment and decrement. By adding `alpha`, an alphabetical character is now considered as a number. If you have the following HTML elements:

```
<div id="app-a"></div>
<div id="app-a"></div>
<div id="app-a"></div>
<div id="app-a"></div>
<div id="app-a"></div>
```

Put your cursor on the second "app-a". Use the same technique as above (`Ctrl-V 3j` then `g Ctrl-A`) to increment the ids.

```
<div id="app-a"></div>
<div id="app-b"></div>
<div id="app-c"></div>
<div id="app-d"></div>
<div id="app-e"></div>
```

## Selecting the Last Visual Mode Area

Earlier in this chapter, I mentioned that `gv` can quickly highlight the last visual mode highlight. You can also go to the location of the start and the end of the last visual mode with these two special marks:

```
`<    Go to the first place of the previous visual mode highlight
`>    Go to the last place of the previous visual mode highlight
```

Earlier, I also mentioned that you can selectively execute command-line commands on a highlighted text, like `:s/const/let/g`. When you did that, you'd see this below:

```
:`<,`>s/const/let/g
```

You were actually executing a *ranged* `s/const/let/g` command (with the two marks as the addresses). Interesting!

You can always edit these marks anytime you wish. If instead you needed to substitute from the start of the highlighted text to the end of the file, you just change the command to:

```
:`<,$s/const/let/g
```

## Entering Visual Mode From Insert Mode

You can also enter visual mode from the insert mode. To go to character-wise visual mode while you are in insert mode:

```
Ctrl-O v
```

Recall that running `Ctrl-O` while in the insert mode lets you execute a normal mode command. While in this normal-mode-command-pending mode, run `v` to enter character-wise visual mode. Notice that on the bottom left of the screen, it says `--(insert) VISUAL--`. This trick works with any visual mode operator: `v`, `V`, and `Ctrl-V`.

## Select Mode

Vim has a mode similar to visual mode called the select mode. Like the visual mode, it also has three different modes:

```
gh         Character-wise select mode
gH         Line-wise select mode
gCtrl-h    Block-wise select mode
```

Select mode emulates a regular editor's text highlighting behavior closer than Vim's visual mode does.

In a regular editor, after you highlight a text block and type a letter, say the letter "y", it will delete the highlighted text and insert the letter "y". If you highlight a line with line-wise select mode (`gH`) and type "y", it will delete the highlighted text and insert the letter "y".

Contrast this select mode with visual mode: if you highlight a line of text with line-wise visual mode (`V`) and type "y", the highlighted text will not be deleted and replaced by the literal letter "y", it will be yanked. You can't execute normal mode commands on highlighted text in select mode.

I personally never used select mode, but it's good to know that it exists.

## Learn Visual Mode the Smart Way

The visual mode is Vim's representation of the text highlighting procedure.

If you find yourself using visual mode operation far more often than normal mode operations, be careful. This is an anti-pattern. It takes more keystrokes to run a visual mode operation than its normal mode counterpart. For example, if you need to delete an inner word, why use four keystrokes, `viwd` (visually highlight an inner word then delete), if you can accomplish it with just three keystrokes (`diw`)? The latter is more direct and concise. Of course, there will be times when visual modes are appropriate, but in general, favor a more direct approach.

## Link
- Prev [Ch10. Undo](./ch10_undo.md)
- Next [Ch12. Search and Substitute](./ch12_search_and_substitute.md)


================================================
FILE: ch12_search_and_substitute.md
================================================
# Ch12. Search and Substitute

This chapter covers two separate but related concepts: search and substitute. Often when editing, you need to search multiple texts based on their least common denominator patterns. By learning how to use regular expressions in search and substitute instead of literal strings, you will be able to target any text quickly.

As a side note, in this chapter, I will use `/` when talking about search. Everything you can do with `/` can also be done with `?`.

## Smart Case Sensitivity

It can be tricky trying to match the case of the search term. If you are searching for the text "Learn Vim", you can easily mistype the case of one letter and get a false search result. Wouldn't it be easier and safer if you could match any case? This is where the option `ignorecase` shines. Just add `set ignorecase` in your vimrc and all your search terms become case insensitive. Now you don't have to do `/Learn Vim` anymore, `/learn vim` will work.

However, there are times when you need to search for a case specific phrase. One way to do that is to turn off `ignorecase` option by running `set noignorecase`, but that is a lot of work to turn on and off each time you need to search for a case sensitive phrase.

To avoid toggling `ignorecase`, Vim has a `smartcase` option to search for case insensitive string if the search pattern *contains at least one uppercase character*. You can combine both `ignorecase` and `smartcase` to perform a case insensitive search when you enter all lowercase characters and a case sensitive search when you enter one or more uppercase characters.

Inside your vimrc, add:

```
set ignorecase smartcase
```

If you have these texts:

```
hello
HELLO
Hello
```

- `/hello` matches "hello", "HELLO", and "Hello".
- `/HELLO` matches only "HELLO".
- `/Hello` matches only "Hello".

There is one downside. What if you need to search for only a lowercase string? When you do `/hello`, Vim now does case insensitive search. You can use `\C` pattern anywhere in your search term to tell Vim that the subsequent search term will be case sensitive. If you do `/\Chello`, it will strictly match "hello", not "HELLO" or "Hello".

## First and Last Character in a Line

You can use `^` to match the first character in a line and `$` to match the last character in a line.

If you have this text:

```
hello hello
```

You can target the first "hello" with `/^hello`. The character that follows `^` must be the first character in a line. To target the last "hello", run `/hello$`. The character before `$` must be the last character in a line.

If you have this text:

```
hello hello friend
```

Running `/hello$` will not match anything because "friend" is the last term in that line, not "hello".

## Repeating Search

You can repeat the previous search with `//`. If you have just searched for `/hello`, running `//` is equivalent to running `/hello`. This shortcut can save you some keystrokes especially if you just searched for a long string. Also recall that you can use `n` and `N` to repeat the last search with the same direction and opposite direction, respectively.

What if you want to quickly recall *n* last search term? You can quickly traverse the search history by first pressing `/`, then press `up`/`down` arrow keys (or `Ctrl-N`/`Ctrl-P`) until you find the search term you need. To see all your search history, you can run `:history /`.

When you reach the end of a file while searching, Vim throws an error: `"Search hit the BOTTOM without match for: {your-search}"`. Sometimes this can be a good safeguard from oversearching, but other times you want to cycle the search back to the top again. You can use the `set wrapscan` option to make Vim search back at the top of the file when you reach the end of the file. To turn this feature off, do `set nowrapscan`.

## Searching for Alternative Words

It is common to search for multiple words at once. If you need to search for *either* "hello vim" or "hola vim", but not "salve vim" or "bonjour vim", you can use the `|` pattern.

Given this text:

```
hello vim
hola vim
salve vim
bonjour vim
```

To match both "hello" and  "hola", you can do `/hello\|hola`. You have to escape (`\`) the or (`|`) operator, otherwise Vim will literally search for the string "|".

If you don't want to type `\|` every time, you can use the `magic` syntax (`\v`) at the start of the search: `/\vhello|hola`. I will not cover `magic` in this guide, but with `\v`, you don't have to escape special characters anymore. To learn more about `\v`, feel free to check out `:h \v`.

## Setting the Start and End of a Match

Maybe you need to search for a text that is a part of a compound word. If you have these texts:

```
11vim22
vim22
11vim
vim
```

If you need to select "vim" but only when it starts with "11" and ends with "22", you can use `\zs` (starting match) and `\ze` (ending match) operators. Run:

```
/11\zsvim\ze22
```

Vim still has to match the entire pattern "11vim22", but only highlights the pattern sandwiched between `\zs` and `\ze`. Another example:

```
foobar
foobaz
```

If you need to match the "foo" in "foobaz" but not in "foobar", run:

```
/foo\zebaz
```

## Searching Character Ranges

All your search terms up to this point have been a literal word search. In real life, you may have to use a general pattern to find your text. The most basic pattern is the character range, `[ ]`.

If you need to search for any digit, you probably don't want to type `/0\|1\|2\|3\|4\|5\|6\|7\|8\|9\|0` every single time. Instead, use `/[0-9]` to match for a single digit. The `0-9` expression represents a range of numbers 0-9 that Vim will try to match, so if you are looking for digits between 1 to 5 instead, use `/[1-5]`.

Digits are not the only data types Vim can look up. You can also do `/[a-z]` to search for lowercase alphas and `/[A-Z]` to search for uppercase alphas.

You can combine these ranges together. If you need to search for digits 0-9 and both lowercase and uppercase alphas from "a" to "f" (like a hex), you can do `/[0-9a-fA-F]`.

To do a negative search, you can add `^` inside the character range brackets. To search for a non-digit, run `/[^0-9]`. Vim will match any character as long as it is not a digit. Beware that the caret (`^`) inside the range brackets is different from the beginning-of-a-line caret (ex: `/^hello`). If a caret is outside of a pair of brackets and is the first character in the search term, it means "the first character in a line". If a caret is inside a pair of brackets and it is the first character inside the brackets, it means a negative search operator. `/^abc` matches the first "abc" in a line and `/[^abc]` matches any character except for an "a", "b", or "c".

## Searching for Repeating Characters

If you need to search for double digits in this text:

```
1aa
11a
111
```

You can use `/[0-9][0-9]` to match a two-digit character, but this method is unscalable. What if you need to match twenty digits? Typing `[0-9]` twenty times is not a fun experience. That's why you need a `count` argument.

You can pass `count` to your search. It has the following syntax:

```
{n,m}
```

By the way, these `count` braces need to be escaped when you use them in Vim. The `count` operator is placed after a single character you want to increment.

Here are the four different variations of the `count` syntax:
- `{n}` is an exact match. `/[0-9]\{2\}`  matches the two digit numbers: "11" and the "11" in "111".
- `{n,m}` is a range match. `/[0-9]\{2,3\}` matches between 2 and 3 digit numbers: "11"  and "111".
- `{,m}` is an up-to match. `/[0-9]\{,3\}` matches up to 3 digit numbers: "1", "11", and "111".
- `{n,}` is an at-least match. `/[0-9]\{2,\}` matches at least a 2 or more digit numbers: "11" and "111".

The count arguments `\{0,\}` (zero or more) and `\{1,\}` (one or more) are common search patterns and Vim has special operators for them: `*` and `+` (`+` needs to be escaped while `*` works fine without the escape). If you do `/[0-9]*`, it is the same as `/[0-9]\{0,\}`. It searches for zero or more digits. It will match "", "1", "123". By the way, it will also match non-digits like "a", because there is technically zero digit in the letter "a". Think carefully before using `*`. If you do `/[0-9]\+`, it is the same as `/[0-9]\{1,\}`. It searches for one or more digits. It will match "1" and "12".

## Predefined Character Ranges

Vim has predefined ranges for common characters like digits and alphas. I will not go through every single one here, but you can find the full list inside `:h /character-classes`. Here are the useful ones:

```
\d    Digit [0-9]
\D    Non-digit [^0-9]
\s    Whitespace character (space and tab)
\S    Non-whitespace character (everything except space and tab)
\w    Word character [0-9A-Za-z_]
\l    Lowercase alphas [a-z]
\u    Uppercase character [A-Z]
```

You can use them like you would use character ranges. To search for any single digit, instead of using `/[0-9]`, you can use `/\d` for a more concise syntax.

## Search Example: Capturing a Text Between a Pair of Similar Characters

If you want to search for a phrase surrounded by a pair of double quotes:

```
"Vim is awesome!"
```

Run this:

```
/"[^"]\+"
```

Let's break it down:
- `"` is a literal double quote. It matches the first double quote.
- `[^"]` means any character except for a double quote. It matches any alphanumeric and whitespace character as long as it is not a double quote.
- `\+` means one or more. Since it is preceded by `[^"]`, Vim looks for one or more character that is not a double quote.
- `"` is a literal double quote. It matches the closing double quote.

When Vim sees the first `"`, it begins the pattern capture. The moment it sees the second double quote in a line, it matches the second `"` pattern and stops the pattern capture. Meanwhile, all non-double-quote characters inbetween are captured by the `[^"]\+` pattern, in this case, the phrase `Vim is awesome!`. This is a common pattern to capture a phrase surrounded by a pair of similar delimiters.

- To capture a phrase surrounded by single quotes, you can use `/'[^']\+'`.
- To capture a phrase surrounded by zeroes, you can use `/0[^0]\+0`.

## Search Example: Capturing a Phone Number

If you want to match a US phone number separated by a hyphen (`-`), like `123-456-7890`, you can use:

```
/\d\{3\}-\d\{3\}-\d\{4\}
```

US Phone number consists of a set of three digit number, followed by another three digits, and finally by four digits. Let's break it down:
- `\d\{3\}` matches a digit repeated exactly three times
- `-` is a literal hyphen

You can avoid typing escapes with `\v`:

```
/\v\d{3}-\d{3}-\d{4}
```

This pattern is also useful to capture any repeating digits, such as IP addresses and zip codes.

That covers the search part of this chapter. Now let's move to substitution.

## Basic Substitution

Vim's substitute command is a useful command to quickly find and replace any pattern. The substitution syntax is:

```
:s/{old-pattern}/{new-pattern}/
```

Let's start with a basic usage. If you have this text:

```
vim is good
```

Let's substitute "good" with "awesome" because Vim is awesome. Run `:s/good/awesome/`. You should see:

```
vim is awesome
```

## Repeating the Last Substitution

You can repeat the last substitute command with either the normal command `&` or by running `:s`. If you have just run `:s/good/awesome/`, running either `&` or `:s` will repeat it.

Also, earlier in this chapter I mentioned that you can use `//` to repeat the previous search pattern.  This trick works with the substitution command. If `/good` was done recently and you leave the first substitute pattern argument blank, like in `:s//awesome/`, it works the same as running `:s/good/awesome/`.

## Substitution Range

Just like many Ex commands, you can pass a range argument into the substitute command. The syntax is:

```
:[range]s/old/new/
```

If you have these expressions:

```
let one = 1;
let two = 2;
let three = 3;
let four = 4;
let five = 5;
```

To substitute the "let" into "const" on lines three to five, you can do:

```
:3,5s/let/const/
```

Here are some range variations you can pass:

- `:,3s/let/const/` - if nothing is given before the comma, it represents the current line. Substitute from current line to line 3.
- `:1,s/let/const/` - if nothing is given after the comma, it also represents the current line. Substitute from line 1 to current line.
- `:3s/let/const/` - if only one value is given as range (no comma), it does substitution on that line only.

In Vim, `%` usually means the entire file. If you run `:%s/let/const/`, it will do substitution on all lines. Keep in mind this range syntax. Many command-line commands that you will learn in the upcoming chapters will follow this form.

## Pattern Matching

The next few sections will cover basic regular expressions. A strong pattern knowledge is essential to master the substitute command.

If you have the following expressions:

```
let one = 1;
let two = 2;
let three = 3;
let four = 4;
let five = 5;
```

To add a pair of double quotes around the digits:

```
:%s/\d/"\0"/
```

The result:

```
let one = "1";
let two = "2";
let three = "3";
let four = "4";
let five = "5";
```

Let's break down the command:
- `:%s` targets the entire file to perform substitution.
- `\d` is Vim's predefined range for digits (similar to using `[0-9]`).
- `"\0"` here the double quotes are literal double quotes. `\0` is a special character representing "the whole matched pattern". The matched pattern here is a single digit number, `\d`.

Alternatively, `&` also represents the whole matched pattern like `\0`. `:s/\d/"&"/` would have also worked.

Let's consider another example. Given these expressions and you need to swap all the "let" with the variable names.

```
one let = "1";
two let = "2";
three let = "3";
four let = "4";
five let = "5";
```

To do that, run:

```
:%s/\(\w\+\) \(\w\+\)/\2 \1/
```

The command above contains too many backslashes and is hard to read. In this case it is more convenient to use the `\v` operator:

```
:%s/\v(\w+) (\w+)/\2 \1/
```

The result:

```
let one = "1";
let two = "2";
let three = "3";
let four = "4";
let five = "5";
```

Great! Let's break down that command:
- `:%s` targets all the lines in the file to perform substitution.
- `(\w+) (\w+)` is a group match. `\w` is one of Vim's predefined ranges for a word character (`[0-9A-Za-z_]`). The `( )` surrounding it captures a word character match in a group. Notice the space between the two groupings. `(\w+) (\w+)` captures two groups. The first group captures "one" and the second group captures "two".
- `\2 \1` returns the captured group in a reversed order. `\2` contains the captured string "let" and `\1` the string "one". Having `\2 \1` returns the string "let one".

Recall that `\0` represents the entire matched pattern. You can break the matched string into smaller groups with `( )`. Each group is represented by `\1`, `\2`, `\3`, etc.

Let's do one more example to solidify this group match concept. If you have these numbers:

```
123
456
789
```

To reverse the order, run:

```
:%s/\v(\d)(\d)(\d)/\3\2\1/
```

The result is:

```
321
654
987
```

Each `(\d)` matches each digit and creates a group. On the first line, the first `(\d)` has a value of 1, the second `(\d)` has a value of 2, and the third `(\d)` has a value of 3. They are stored in the variables `\1`, `\2`, and `\3`. In the second half of your substitution, the new pattern `\3\2\1` results in the "321" value on line one.

If you had run this instead:

```
:%s/\v(\d\d)(\d)/\2\1/
```
You would have gotten a different result:

```
312
645
978
```

This is because you now only have two groups. The first group, captured by `(\d\d)`, is stored within `\1` and has the value of 12. The second group, captured by `(\d)`, is stored inside `\2` and has the value of 3. `\2\1` then, returns 312.

## Substitution Flags

If you have the sentence:

```
chocolate pancake, strawberry pancake, blueberry pancake
```

To substitute all the pancakes into donuts, you cannot just run:

```
:s/pancake/donut
```

The command above will only substitute the first match, giving you:

```
chocolate donut, strawberry pancake, blueberry pancake
```

There are two ways to solve this. You can either run the substitute command twice more or you can pass it a global (`g`) flag to substitute all of the matches in a line.

Let's talk about the global flag. Run:

```
:s/pancake/donut/g
```

Vim substitutes all pancakes with donuts in one swift command. The global command is one of the several flags the substitute command accepts. You pass flags at the end of the substitute command. Here is a list of useful flags:

```
&    Reuse the flags from the previous substitute command.
g    Replace all matches in the line.
c    Ask for substitution confirmation.
e    Prevent error message from displaying when substitution fails.
i    Perform case insensitive substitution.
I    Perform case sensitive substitution.
```

There are more flags that I do not list above. To read about all the flags, check out `:h s_flags`.

By the way, the repeat-substitution commands (`&` and `:s`) do not retain the flags. Running `&` will only repeat `:s/pancake/donut/` without `g`. To quickly repeat the last substitute command with all the flags, run `:&&`.

## Changing the Delimiter

If you need to replace a URL with a long path:

```
https://mysite.com/a/b/c/d/e
```

To substitute it with the word "hello", run:

```
:s/https:\/\/mysite.com\/a\/b\/c\/d\/e/hello/
```

However, it is hard to tell which forward slashes (`/`) are part of the substitution pattern and which ones are the delimiters. You can change the delimiter with any single-byte characters (except for alphabets, numbers, or `"`, `|`, and `\`). Let's replace them with `+`. The substitution command above then can be rewritten as:

```
:s+https:\/\/mysite.com\/a\/b\/c\/d\/e+hello+
```

It is now easier to see where the delimiters are.

## Special Replace

You can also modify the case of the text you are substituting. Given the following expressions and your task is to uppercase the variables "one", "two", "three", etc.

```
let one = "1";
let two = "2";
let three = "3";
let four = "4";
let five = "5";
```

Run:

```
:%s/\v(\w+) (\w+)/\1 \U\2/
```

You will get:

```
let ONE = "1";
let TWO = "2";
let THREE = "3";
let FOUR = "4";
let FIVE = "5";
```

The breakdown:
- `(\w+) (\w+)` captures the first two matched groups, such as "let" and "one".
- `\1` returns the value of the first group, "let".
- `\U\2` uppercases (`\U`) the second group (`\2`).

The trick of this command is the expression `\U\2`. `\U` instructs the following character to be uppercased.

Let's do one more example. Suppose you are writing a Vim guide and you need to capitalize the first letter of each word in a line.

```
vim is the greatest text editor in the whole galaxy
```

You can run:

```
:s/\<./\U&/g
```

The result:

```
Vim Is The Greatest Text Editor In The Whole Galaxy
```

Here is the breakdown:
- `:s` substitutes the current line.
- `\<.` is comprised of two parts: `\<` to match the start of a word and `.` to match any character. `\<` operator makes the following character to be the first character of a word. Since `.` is the next character, it will match the first character of any word.
- `\U&`  uppercases the subsequent symbol, `&`. Recall that `&` (or `\0`) represents the whole match. It matches the first character of any word.
- `g` the global flag. Without it, this command only substitutes the first match. You need to substitute every match on this line.

To learn more of substitution's special replace symbols like `\U`, check out `:h sub-replace-special`.

## Alternative Patterns

Sometimes you need to match multiple patterns simultaneously. If you have the following greetings:

```
hello vim
hola vim
salve vim
bonjour vim
```

You need to substitute the word "vim" with "friend" but only on the lines containing the word "hello" or "hola". Recall from earlier this chapter, you can use `|` for multiple alternative patterns.

```
:%s/\v(hello|hola) vim/\1 friend/g
```

The result:

```
hello friend
hola friend
salve vim
bonjour vim
```

Here is the breakdown:
- `%s` runs the substitute command on each line in a file.
- `(hello|hola)` matches *either* "hello" or "hola" and considers it as a group.
- `vim` is the literal word "vim".
- `\1` is the first group, which is either the text "hello" or "hola".
- `friend` is the literal word "friend".

## Substituting the Start and the End of a Pattern

Recall that you can use `\zs` and `\ze` to define the start and the end of a match. This technique works in substitution too. If you have:

```
chocolate pancake
strawberry sweetcake
blueberry hotcake
```

To substitute the "cake" in "hotcake" with "dog" to get a "hotdog":

```
:%s/hot\zscake/dog/g
```

Result:

```
chocolate pancake
strawberry sweetcake
blueberry hotdog
```

## Greedy and Non-greedy

You can substitute the nth match in a line with this trick:

```
One Mississippi, two Mississippi, three Mississippi, four Mississippi, five Mississippi.
```

To substitute the third "Mississippi" with "Arkansas", run:

```
:s/\v(.{-}\zsMississippi){3}/Arkansas/g
```

The breakdown:
- `:s/` the substitute command.
- `\v` is the magic keyword so you don't have to escape special keywords.
- `.` matches any single character.
- `{-}` performs non-greedy match of 0 or more of the preceding atom.
- `\zsMississippi` makes "Mississippi" the start of the match.
- `(...){3}` looks for the third match.

You have seen the `{3}` syntax earlier in this chapter. In this case, `{3}` will match exactly the third match. The new trick here is `{-}`. It is a non-greedy match. It finds the shortest match of the given pattern. In this case, `(.{-}Mississippi)` matches the least amount of "Mississippi" preceded by any character. Contrast this with `(.*Mississippi)` where it finds the longest match of the given pattern.

If you use `(.{-}Mississippi)`, you get five matches: "One Mississippi", "Two Mississippi", etc. If you use `(.*Mississippi)`, you get one match: the last "Mississippi". `*` is a greedy matcher and `{-}` is a non-greedy matcher. To learn more check out `:h /\{-` and `:h non-greedy`.

Let's do a simpler example. If you have the string:

```
abc1de1
```

You can match "abc1de1" (greedy) with:

```
/a.*1
```

You can match "abc1" (non-greedy) with:

```
/a.\{-}1
```

So if you need to uppercase the longest match (greedy), run:

```
:s/a.*1/\U&/g
```

To get:

```
ABC1DEFG1
```

If you need to uppercase the shortest match (non-greedy), run:

```
:s/a.\{-}1/\U&/g
```

To get:

```
ABC1defg1
```

If you're new to greedy vs non-greedy concept, it can get hard to wrap your head around it. Experiment around with different combinations until you understand it.

## Substituting Across Multiple Files

Finally, let's learn how to substitute phrases across multiple files. For this section, assume that you have two files: `food.txt` and `animal.txt`.

Inside `food.txt`:

```
corndog
hotdog
chilidog
```

Inside `animal.txt`:

```
large dog
medium dog
small dog
```

Assume your directory structure looks like this:

```
- food.txt
- animal.txt
```

First, capture both `food.txt` and `animal.txt` inside `:args`. Recall from earlier chapters that `:args` can be used to create a list of file names. There are several ways to do this from inside Vim, one of them is by running this from inside Vim:

```
:args *.txt                  captures all txt files in current location
```

To test it, when you run `:args`, you should see:

```
[food.txt] animal.txt
```

Now that all the relevant files are stored inside the argument list, you can perform a multi-file substitution with the `:argdo` command. Run:

```
:argdo %s/dog/chicken/
```

This performs substitution against the all files inside the `:args` list. Finally, save the changed files with:

```
:argdo update
```

`:args` and `:argdo` are  useful tools to apply command line commands across multiple files. Try it with other commands!

## Substituting Across Multiple Files With Macros

Alternatively, you can also run the substitute command across multiple files with macros. Run:

```
:args *.txt
qq
:%s/dog/chicken/g
:wnext
q
99@q
```

The breakdown:
- `:args *.txt` adds all text files into the `:args` list.
- `qq` starts the macro in the "q" register.
- `:%s/dog/chicken/g` substitutes "dog" with "chicken" on all lines in the current file.
- `:wnext` saves the file then go to the next file on the `args` list.
- `q` stops the macro recording.
- `99@q` executes the macro ninety-nine times. Vim will stop the macro execution after it encounters the first error, so Vim won't actually execute the macro ninety-nine times.

## Learning Search and Substitution the Smart Way

The ability to do search well is a necessary skill in editing. Mastering the search lets you utilize the flexibility of regular expressions to search for any pattern in a file. Take your time to learn these. To get better with regular expression you need to be actively using regular expressions. I once read a book about regular expression without actually doing it and I forgot almost everything I read afterwards. Active coding is the best way to master any skill.

A good way to improve your pattern matching skill is whenever you need to search for a pattern (like "hello 123"), instead of querying for the literal search term (`/hello 123`), try to come up with a pattern for it (something like `/\v(\l+) (\d+)`). Many of these regular expression concepts are also applicable in general programming, not only when using Vim.

Now that you learned about advanced search and substitution in Vim, let's learn one of the most versatile commands, the global command.

## Link
- Prev [Ch11. Visual Mode](./ch11_visual_mode.md)
- Next [Ch13. The Global Command](./ch13_the_global_command.md)


================================================
FILE: ch13_the_global_command.md
================================================
# Ch13. The Global Command

So far you have learned how to repeat the last change with the dot command (`.`), to replay actions with macros (`q`), and to store texts in the registers (`"`).

In this chapter, you will learn how to repeat a command-line command with the global command.

## Global Command Overview

Vim's global command is used to run a command-line command on multiple lines simultaneously.

By the way, you may have heard of the term "Ex Commands" before. In this guide, I refer to them as command-line commands. Both Ex commands and command-line commands are the same. They are the commands that start with a colon (`:`). The substitute command in the last chapter was an example of an Ex command. They are called Ex because they originally came from the Ex text editor. I will continue to refer to them as command-line commands in this guide. For a full list of Ex commands, check out `:h ex-cmd-index`.

The global command has the following syntax:

```
:g/pattern/command
```

The `pattern` matches all lines containing that pattern, similar to the pattern in the substitute command. The `command` can be any command-line command. The global command works by executing `command` against each line that matches the `pattern`.

If you have the following expressions:

```
const one = 1;
console.log("one: ", one);

const two = 2;
console.log("two: ", two);

const three = 3;
console.log("three: ", three);
```

To remove all lines containing "console", you can run:

```
:g/console/d
```

Result:

```
const one = 1;

const two = 2;

const three = 3;
```

The global command executes the delete command (`d`) on all lines that match the "console" pattern.

When running the `g` command, Vim  makes two scans across the file. On the first run, it scans each line and marks the line that matches the `/console/` pattern. Once all the matching lines are marked, it goes for the second time and executes the `d` command on the marked lines.

If you want to delete all lines containing "const" instead, run:

```
:g/const/d
```

Result:

```
console.log("one: ", one);

console.log("two: ", two);

console.log("three: ", three);
```

## Inverse Match

To run the global command on non-matching lines, you can run:

```
:g!/pattern/command
```

or

```
:v/pattern/command
```

If you run `:v/console/d`, it will delete all lines *not* containing "console".

## Pattern

The global command uses the same pattern system as the substitute command, so this section will serve as a refresher.  Feel free to skip to the next section or read along!

If you have these expressions:

```
const one = 1;
console.log("one: ", one);

const two = 2;
console.log("two: ", two);

const three = 3;
console.log("three: ", three);
```

To delete the lines containing either "one" or "two", run:

```
:g/one\|two/d
```

To delete the lines containing any single digits, run either:

```
:g/[0-9]/d
```

or

```
:g/\d/d
```

If you have the expression:

```
const oneMillion = 1000000;
const oneThousand = 1000;
const one = 1;
```

To match the lines containing between three to six zeroes, run:

```
:g/0\{3,6\}/d
```

## Passing a Range

You can pass a range before the `g` command. Here are some ways you can do it:
- `:1,5g/console/d`  matches the string "console" between lines 1 and 5 and deletes them.
- `:,5g/console/d` if there is no address before the comma, then it starts from the current line. It looks for the string "console" between the current line and line 5 and deletes them.
- `:3,g/console/d` if there is no address after the comma, then it ends at the current line. It looks for the string "console" between line 3 and the current line and deletes them.
- `:3g/console/d` if you only pass one address without a comma, it executes the command only on line 3. It looks on line 3 and deletes it if has the string "console".

In addition to numbers, you can also use these symbols as range:
- `.` means the current line. A range of `.,3` means between the current line and line 3.
- `$` means the last line in the file. `3,$` range means between line 3 and the last line.
- `+n` means n lines after the current line. You can use it with `.` or without. `3,+1` or `3,.+1` means between line 3 and the line after the current line.

If you don't give it any range, by default it affects the entire file. This is actually not the norm. Most of Vim's command-line commands run on only the current line if you don't pass it any range. The two notable exceptions are the global (`:g`) and the save (`:w`) commands.

## Normal Command

You can run a normal command with the global command with `:normal` command-line command.

If you have this text:
```
const one = 1
console.log("one: ", one)

const two = 2
console.log("two: ", two)

const three = 3
console.log("three: ", three)
```

To add a ";" to the end of each line, run:

```
:g/./normal A;
```

Let's break it down:
- `:g` is the global command.
- `/./` is a pattern for "non-empty lines". It matches the lines with at least one character, so it matches the lines with "const" and "console" and it does not match empty lines.
- `normal A;` runs the `:normal` command-line command. `A;` is the normal mode command to insert a ";" at the end of the line.

## Executing a Macro

You can also execute a macro with the global command. A macro can be executed with the `normal` command. If you have the expressions:

```
const one = 1
console.log("one: ", one);

const two = 2
console.log("two: ", two);

const three = 3
console.log("three: ", three);
```

Notice that the lines with "const" do not have semi-colons. Let's create a macro to add a comma to the end of those lines in the register a:

```
qaA;<Esc>q
```

If you need a refresher, check out the chapter on macro. Now run:

```
:g/const/normal @a
```

Now all lines with "const" will have a ";" at the end.

```
const one = 1;
console.log("one: ", one);

const two = 2;
console.log("two: ", two);

const three = 3;
console.log("three: ", three);
```

If you followed this step-by-step, you will have two semi-colons on the first line. To avoid that, run the global command on line two onward, `:2,$g/const/normal @a`.

## Recursive Global Command

The global command itself is a type of a command-line command, so you can technically run the global command inside a global command.

Given the following expressions, if you want to delete the second `console.log` statement:

```
const one = 1;
console.log("one: ", one);

const two = 2;
console.log("two: ", two);

const three = 3;
console.log("three: ", three);
```

If you run:

```
:g/console/g/two/d
```

First, `g` will look for the lines containing the pattern "console" and will find 3 matches. Then the second `g` will look for the line containing the pattern "two" from those three matches. Finally, it will delete that match.

You can also combine `g` with `v` to find positive and negative patterns. For example:

```
:g/console/v/two/d
```

Instead of looking for the line containing the pattern "two", it will look for the lines *not* containing the pattern "two".

## Changing the Delimiter

You can change the global command's delimiter like the substitute command. The rules are the same: you can use any single byte character except for alphabets, numbers, `"`, `|`, and `\`.

To delete the lines containing "console":

```
:g@console@d
```

If you are using the substitute command with the global command, you can have two different delimiters:

```
g@one@s+const+let+g
```

Here the global command will look for all lines containing "one". The substitute command will substitute, from those matches, the string "const" with "let".

## The Default Command

What happens if you don't specify any command-line command in the global command?

The global command will use the print (`:p`) command to print the current line's text. If you run:

```
:g/console
```

It will print at the bottom of the screen all the lines containing "console".

By the way, here is one interesting fact. Because the default command used by the global command is `p`, this makes the `g` syntax to be:

```
:g/re/p
```

- `g` = the global command
- `re` = the regex pattern
- `p` = the print command

It spells *"grep"*, the same `grep` from the command line. This is **not** a coincidence. The `g/re/p` command originally came from the Ed Editor, one of the original line text editors. The `grep` command got its name from Ed.

Your computer probably still has the Ed editor. Run `ed` from the terminal (hint: to quit, type `q`).

## Reversing the Entire Buffer

To reverse the entire file, run:

```
:g/^/m 0
```

`^` is a pattern for the beginning of a line. Use `^` to match all lines, including empty lines.

If you need to reverse only a few lines, pass it a range. To reverse the lines between line five to line ten, run:

```
:5,10g/^/m 0
```

To learn more about the move command, check out `:h :move`.

## Aggregating All Todos

When coding, sometimes I would write TODOs in the file I'm editing:

```
const one = 1;
console.log("one: ", one);
// TODO: feed the puppy

const two = 2;
// TODO: feed the puppy automatically
console.log("two: ", two);

const three = 3;
console.log("three: ", three);
// TODO: create a startup selling an automatic puppy feeder
```

It can be hard to keep track of all the created TODOs. Vim has a `:t` (copy) method to copy all matches to an address. To learn more about the copy method, check out `:h :copy`.

To copy all TODOs to the end of the file for easier introspection, run:

```
:g/TODO/t $
```

Resul
Download .txt
gitextract_66irgrv6/

├── .gitignore
├── LICENSE.txt
├── README.md
├── book/
│   ├── Dockerfile
│   ├── book.toml
│   ├── docker-compose.yml
│   └── src/
│       └── SUMMARY.md
├── ch00_read_this_first.md
├── ch01_starting_vim.md
├── ch02_buffers_windows_tabs.md
├── ch03_searching_files.md
├── ch04_vim_grammar.md
├── ch05_moving_in_file.md
├── ch06_insert_mode.md
├── ch07_the_dot_command.md
├── ch08_registers.md
├── ch09_macros.md
├── ch10_undo.md
├── ch11_visual_mode.md
├── ch12_search_and_substitute.md
├── ch13_the_global_command.md
├── ch14_external_commands.md
├── ch15_command-line_mode.md
├── ch16_tags.md
├── ch17_fold.md
├── ch18_git.md
├── ch19_compile.md
├── ch20_views_sessions_viminfo.md
├── ch21_multiple_file_operations.md
├── ch22_vimrc.md
├── ch23_vim_packages.md
├── ch24_vim_runtime.md
├── ch25_vimscript_basic_data_types.md
├── ch26_vimscript_conditionals_and_loops.md
├── ch27_vimscript_variable_scopes.md
├── ch28_vimscript_functions.md
└── ch29_plugin_example_writing-a-titlecase-plugin.md
Condensed preview — 37 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (438K chars).
[
  {
    "path": ".gitignore",
    "chars": 439,
    "preview": "# Created by https://www.toptal.com/developers/gitignore/api/vim\n# Edit at https://www.toptal.com/developers/gitignore?t"
  },
  {
    "path": "LICENSE.txt",
    "chars": 20846,
    "preview": "Attribution-NonCommercial-ShareAlike 4.0 International\n\n================================================================"
  },
  {
    "path": "README.md",
    "chars": 4210,
    "preview": "# Learn Vim (the Smart Way)\n\n## What's This?\n\n*Learn Vim (the Smart Way)* is a guide to learn the good parts of Vim.\n\nTh"
  },
  {
    "path": "book/Dockerfile",
    "chars": 409,
    "preview": "# Stage 1: Build the book\nFROM peaceiris/mdbook:latest AS builder\n\nWORKDIR /book\n\n# Copy mdBook config and table of cont"
  },
  {
    "path": "book/book.toml",
    "chars": 259,
    "preview": "[book]\ntitle = \"Learn Vim (the Smart Way)\"\nauthors = [\"Igor Irianto\"]\nlanguage = \"en\"\nsrc = \"src\"\n\n[build]\nbuild-dir = \""
  },
  {
    "path": "book/docker-compose.yml",
    "chars": 110,
    "preview": "services:\n  book:\n    build:\n      context: ..\n      dockerfile: book/Dockerfile\n    ports:\n      - \"8080:80\"\n"
  },
  {
    "path": "book/src/SUMMARY.md",
    "chars": 1580,
    "preview": "# Summary\n\n# Prologue\n\n- [Read This First](./ch00_read_this_first.md)\n\n# Part 1: Learn Vim the Smart Way\n\n- [Starting Vi"
  },
  {
    "path": "ch00_read_this_first.md",
    "chars": 8369,
    "preview": "# Ch00. Read This First\n\n## Why This Guide Was Written\n\nThere are many places to learn Vim: the `vimtutor` is a great pl"
  },
  {
    "path": "ch01_starting_vim.md",
    "chars": 6675,
    "preview": "# Ch01. Starting Vim\n\nIn this chapter, you will learn different ways to start Vim from the terminal. I was using Vim 8.2"
  },
  {
    "path": "ch02_buffers_windows_tabs.md",
    "chars": 10128,
    "preview": "# Ch02. Buffers, Windows, and Tabs\n\nIf you've used a modern text editor before, you are probably familiar with windows a"
  },
  {
    "path": "ch03_searching_files.md",
    "chars": 17417,
    "preview": "# Ch03. Searching Files\n\nThe goal of this chapter is to give you an introduction on how to search quickly in Vim. Being "
  },
  {
    "path": "ch04_vim_grammar.md",
    "chars": 10606,
    "preview": "# Ch04. Vim Grammar\n\nIt is easy to get intimidated by the complexity of Vim commands. If you see a Vim user doing `gUfV`"
  },
  {
    "path": "ch05_moving_in_file.md",
    "chars": 18494,
    "preview": "# Ch05. Moving in a File\n\nIn the beginning, moving with a keyboard feels slow and awkward but don't give up! Once you ge"
  },
  {
    "path": "ch06_insert_mode.md",
    "chars": 6887,
    "preview": "# Ch06. Insert Mode\n\nInsert mode is the default mode of many text editors. In this mode, what you type is what you get.\n"
  },
  {
    "path": "ch07_the_dot_command.md",
    "chars": 6410,
    "preview": "# Ch07. The Dot Command\n\nIn general, you should try to avoid redoing what you just did whenever possible. In this chapte"
  },
  {
    "path": "ch08_registers.md",
    "chars": 14909,
    "preview": "# Ch08. Registers\n\nLearning Vim registers is like learning algebra for the first time. You didn't think you needed it un"
  },
  {
    "path": "ch09_macros.md",
    "chars": 12259,
    "preview": "# Ch09. Macros\n\nWhen editing files, you may find yourself repeating the same actions. Wouldn't it be nice if you could d"
  },
  {
    "path": "ch10_undo.md",
    "chars": 9760,
    "preview": "# Ch10. Undo\n\nWe all make all sorts of typing mistakes. That's why undo is an essential feature in any modern software. "
  },
  {
    "path": "ch11_visual_mode.md",
    "chars": 12100,
    "preview": "# Ch11. Visual Mode\n\nHighlighting and applying changes to a body of text is a common feature in many text editors and wo"
  },
  {
    "path": "ch12_search_and_substitute.md",
    "chars": 25980,
    "preview": "# Ch12. Search and Substitute\n\nThis chapter covers two separate but related concepts: search and substitute. Often when "
  },
  {
    "path": "ch13_the_global_command.md",
    "chars": 15006,
    "preview": "# Ch13. The Global Command\n\nSo far you have learned how to repeat the last change with the dot command (`.`), to replay "
  },
  {
    "path": "ch14_external_commands.md",
    "chars": 6672,
    "preview": "# Ch14. External Commands\n\nInside the Unix system, you will find many small, hyper-specialized commands that do one thin"
  },
  {
    "path": "ch15_command-line_mode.md",
    "chars": 5888,
    "preview": "# Ch15. Command-line Mode\n\nIn the last three chapters, you learned how to use the search commands (`/`, `?`), substitute"
  },
  {
    "path": "ch16_tags.md",
    "chars": 15619,
    "preview": "# Ch16. Tags\n\nOne useful feature in text editing is being able to go to any definition quickly. In this chapter, you wil"
  },
  {
    "path": "ch17_fold.md",
    "chars": 11462,
    "preview": "# Ch17. Fold\n\nWhen you read a file, often there are many irrelevant texts that hinder you from understanding what that f"
  },
  {
    "path": "ch18_git.md",
    "chars": 11412,
    "preview": "# Ch18. Git\n\nVim and git are two great tools for two different things. Git is a version control tool. Vim is a text edit"
  },
  {
    "path": "ch19_compile.md",
    "chars": 9579,
    "preview": "# Ch19. Compile\n\nCompiling is an important subject for many languages. In this chapter, you will learn how to compile fr"
  },
  {
    "path": "ch20_views_sessions_viminfo.md",
    "chars": 11621,
    "preview": "# Ch20. Views, Sessions, and Viminfo\n\nAfter you worked on a project for a while, you may find the project to gradually t"
  },
  {
    "path": "ch21_multiple_file_operations.md",
    "chars": 12367,
    "preview": "# Ch21. Multiple File Operations\n\nBeing able to update in multiple files is another useful editing tool to have. Earlier"
  },
  {
    "path": "ch22_vimrc.md",
    "chars": 15447,
    "preview": "# Ch22. Vimrc\n\nIn the previous chapters, you learned how to use Vim. In this chapter, you will learn how to organize and"
  },
  {
    "path": "ch23_vim_packages.md",
    "chars": 4895,
    "preview": "# Ch23. Vim Packages\n\nIn the previous chapter, I mentioned using an external plugin manager to install plugins. Since ve"
  },
  {
    "path": "ch24_vim_runtime.md",
    "chars": 15354,
    "preview": "# Ch24. Vim Runtime\n\nIn the previous chapters, I mentioned that Vim automatically looks for special paths like `pack/` ("
  },
  {
    "path": "ch25_vimscript_basic_data_types.md",
    "chars": 19409,
    "preview": "# Ch25. Vimscript Basic Data Types\n\nIn the next few chapters, you will learn about Vimscript, Vim's built-in programming"
  },
  {
    "path": "ch26_vimscript_conditionals_and_loops.md",
    "chars": 11701,
    "preview": "# Ch26. Vimscript Conditionals and Loops\n\nAfter learning what the basic data types are, the next step is to learn how to"
  },
  {
    "path": "ch27_vimscript_variable_scopes.md",
    "chars": 7250,
    "preview": "# Ch27. Vimscript Variable Scopes\n\nBefore diving into Vimscript functions, let's learn about the different sources and s"
  },
  {
    "path": "ch28_vimscript_functions.md",
    "chars": 17024,
    "preview": "# Ch28. Vimscript Functions\n\nFunctions are means of abstraction, the third element in learning a new language.\n\nIn the p"
  },
  {
    "path": "ch29_plugin_example_writing-a-titlecase-plugin.md",
    "chars": 43453,
    "preview": "# Ch29. Write a Plugin: Creating a Titlecase Operator\n\nWhen you start to get good at Vim, you may want to write your own"
  }
]

About this extraction

This page contains the full source code of the iggredible/Learn-Vim GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 37 files (412.1 KB), approximately 109.6k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!