How to fix slow Typescript syntax highlighting in Vim

πŸ‘‰
TLDR; make sure you set re=0 in your vimrc or Typescript syntax highlighting will be painfully slow

The Problem

In Vim 8, Typescript syntax highlighting is insanely slow, to the point of being unusable. Opening a typescript file can result in several seconds of editor freeze, an enormous node process running in the background, and finally a failure message 'redrawtime' exceeded, syntax highlighting disabled. Needless to say, this is not conducive to a productive development experience.

The Solution

The issue is syntax highlighting, more specifically the regex engine Vim uses under the hood to facilitate it. Using the 'old' regex engine incurs major performance penalties, as I found to my cost.

In a nutshell you must set re=0 explicitly in your vimrc or you're gonna have a bad time:

# .vimrc
syntax on
" Use new regular expression engine
set re=0

HT to this post on slow syntax highlighting in Vim which pointed me in the right direction.

Bonus: Finding slow Vim plugins

While debugging this issue I spent some time profiling vim to see what was up. This profiling method mentioned in this SO thread was particularly useful.

Step 1. Profile

:profile start profile.log
:profile func *
:profile file *
" Do the 'slow' stuff in Vim
:profile pause
:noautocmd qall!

This creates a new file called profile.log.

Step 2. Open profile.log

FUNCTION  <SNR>69_Highlight_Matching_Pair()
    Defined: /usr/local/Cellar/vim/8.2.1900/share/vim/vim82/plugin/matchparen.vim:40
Called 39 times
Total time:  81.354370
 Self time:  81.353935

Open profile.log and move to the bottom of the file. You'll see a list of functions, ordered by execution time. If Vim is slow, it's a useful starting point.

James Chambers
Good morning. I'm James.

I send a twice-monthly newsletter about building indie software products. It's called Build Notes, and you can sign up below.

Β© 2014-2021 James Chambers