What is the difference between using has()
and !has()
in vimscript?
Asked
Active
Viewed 1,764 times
-1

Brandon Mercer
- 403
- 1
- 4
- 10
-
2Negation of the check? – Birei Oct 22 '13 at 13:22
-
Not sure if I follow you sir. – Brandon Mercer Oct 22 '13 at 13:26
-
`!` has same meaning that `not` in many languages. In `boolean` context it changes between `true` and `false`. – Birei Oct 22 '13 at 13:41
-
`==` and `!=` ; `exists('..')` and `!exists('..')`; `has()` and `!has()`.. you have got it, right? – Kent Oct 22 '13 at 21:19
-
In all honesty, I don't. Maybe I'm over thinking it. – Brandon Mercer Oct 22 '13 at 23:20
-
I think this is a valid question because of all the other myriad uses of `!` in vimscript! !! – JonnyRaa Oct 26 '21 at 16:51
1 Answers
3
It's probably not that you're overthinking it, just that you haven't encountered !
in programming languages before. It's pretty straightforward, though -- here's a quick explanation.
If you want to do something based on a condition, you use an if
statement, right? For example,
if has('relativenumber')
echo "Your Vim has the relative number feature!"
endif
If you want to do something if that condition is not true, you put a !
before your condition. (this is called "negating" a logical condition)
if !has('relativenumber')
echo "Your Vim does NOT have the relative number feature."
endif
You can use that in other case too. Take this, for example:
if x > 3
echo "x is greater than three"
endif
You have to include parentheses to negate it though. (Order of operations!)
if !(x > 3)
echo "x is less than or equal to three"
endif
This is equivalent to
if x <= 3
echo "x is less than or equal to three"
endif

Pandu
- 1,606
- 1
- 12
- 23
-
Okay now it makes sense. Maybe I am getting ahead of myself a bit. I'm just unable to hone on a situation where I would have to negate a value. Keep in mind I just picked up Vim about 2 months ago. – Brandon Mercer Oct 25 '13 at 04:00
-
It's not so much a Vim thing as a programming thing. You'll probably need that at some point, and now you'll know what to do. I wouldn't worry about it. – Pandu Oct 26 '13 at 08:18
-
A little bit unrelated: I'm using Vim7.4 and using has('relativenumber') did not work for me. What *did* work: if exists('&relativenumber'). – Niels Bom Jan 29 '15 at 13:09