KISS

Keep It Simple Stupid

Fixing % in vim in js/tsx files

| comments

I’ve started working with javascript/typescript files at work recently, and vim has been fine for my tasks. However after a while, I noticed that the % key sometimes didn’t work in js/tsx files, specifically I couldn’t jump between parenthesis ()/braces {} in a pair, e.g. in const foo = (bar) => { … };. I couldn’t find an answer to the “broken %” in vim online.

Turns out:

  1. I’m using the matchit plugin to get “extended % matching”;

  2. something (I suspect a plugin that I installed: pangloss/vim-javascript, leafgarland/typescript-vim and/or MaxMEllon/vim-jsx-pretty) is overwriting the b:match_words option in those files to be able to jump between tags:

1
2
3
<div>
  <p>foo</p>
</div>

So if your cursor is at <div>, pressing % will jump to </div>, and vice versa. That’s nice but I’d also like to jump between the corresponding < and > in the same tag, as well as other brackets.

My solution is to make sure b:match_words has the default pairs for js and tsx files as well by creating two very similar files:

  • ~/.vim/after/ftplugin/javascript.vim:
1
2
3
4
5
6
if exists("b:did_javascript_ftplugin")
  finish
end
let b:did_javascript_ftplugin = 1

let b:match_words ..= ',(:),\[:\],{:},<:>'
  • ~/.vim/after/ftplugin/typescriptreact.vim:
1
2
3
4
5
6
if exists("b:did_typescriptreact_ftplugin")
  finish
end
let b:did_typescriptreact_ftplugin = 1

let b:match_words ..= ',(:),\[:\],{:},<:>'

(I hate markdown because of the complicated and non-obvious way to add a code block in a list item, and then the syntax highlighting doesn’t work…).

A couple of links that helped me:

vim

Note: The comments in the blog are provided by disqus.com; if you don't see the comment form under the post, probably your browser or its extension (such as uBlock Origin or NoScript) blocks their scripts.

« Creating birthdays calendar

Comments