Vimscript Comparisons Suck


Vim has a built-in scripting language. It’s what you write your vimrc in, and it’s really convenient for short one-off tasks.

It sucks otherwise.

I’ll focus on just one reason: its Boolean string comparisons are so bad as to be actively misleading. You should never use them.

  • == depends on user case-sensitivity settings. So if you’ve set ignorecase, == is case-insensitive. You need to append # and ? to every comparison operator to get case-sensitive or insensitive comparisons.

  • If a string is compared with a number, the entire string is cast to a number by looking for leading digits, using them as the number to cast to, and dropping the rest of the string. If no number can be formed this way, it’s cast to 0. Meaning 0 will always have a truthy comparison with any string that doesn’t start with numbers.

These are all true comparisons (the " is vim’s comment character. Another mistake, considering that " is also a string delimiter.)

" ignorecase is on

'a' == 'A'
'abc' == 'AbC'

0 == 'nonemptystring'
0 == ''
0 == '0f'
0 == '000000f'

1 == '01f'
1 == '01f'

These are all false.

0 == '0'

You have to use is? and is# to get proper comparisons. If you want something like python’s == for values that aren’t lists/dicts/containers, use is#. For containers, == seems to actually work properly.

Syntax is supposed to be a trade-off between terseness and readability. Vim’s comparison operators achieve neither.

Related Posts

How to Disable Disqus Ads on your Blog

Derivation of Reservoir Sampling

Fun with Python Iterators: Linked Lists Made Easy

Notes for November 11, 2018

Underrated Vim Option: undofile and undodir

Hot Take on Solo Travel: Starve

Alan Perlis

Book Notes: The Map of My Life by Goro Shimura

Prague

Way to remember the definition of local finiteness