Use Matchit with ReactJS and Typescript Project

Table of Contents

What is matchit plugin in vim?

Matchit plugin in VIM allows us to jump between matching tags.

For example:

  <div>
    <span>inner tag</span>
    <ol>
      <li>Ex-1</li>
      <li>Ex-2</li>
    </ol>
  </div>

Then we can jump between div tags using %. We can put cursor in div then pressing % will take us(make a jump) to it’s matching pair </div>.

This works out of the box for html, xml type of files. For files like typescriptreact (tsx), jsx we have to configure it manually. We can inform matchit with our own set of pairs to use for making such jumps.

Lets enable matchit plugin first if its not already enabled. Always see :help matchit for more information.

Enable matchit vim plugin using instruction provided in VIM help.

In VIM8.0, put this line in .vimrc.

packadd! matchit

Then restart vim so this newly loaded plugin is active.

Now, create a file typescriptreact.vim inside .vim/after/ftplugin/ folder. Create this folder if this do not exists already.

Open typescriptreact.vim file and paste these. These regular expressions were copied exactly same from matchit/xml.vim and made adjustment to work with typescript.

if exists("loaded_matchit")
    let b:match_ignorecase=0
    let b:match_words =
     \  '<:>,' .
     \  '<\@<=!--:-->,'.
     \  '<\@<=?\k\+:?>,'.
     \  '<\@<=\([^ \t>/]\+\)\%(\s\+[^>]*\%([^/]>\|$\)\|>\|$\):<\@<=/\1>,'.
     \  '<\@<=\%([^ \t>/]\+\)\%(\s\+[^/>]*\|$\):/>'
endif

Save this file and restart vim.

Now, our % should work as expected and allow us to jump between tags.

To understand more about how b:match_words work. Please refer to official doc :help matchit.vim