Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Vimscript conditional statement


May 24, 2021 Vim


Table of contents


Each programming language has a way of generating branching processes, which in Vimscript are if statements. if statement is the basic method of generating branches in Vimscript. There is no unless statement like unless so all judgments in the code need to be if

Before we talk about if statement, we need to spend extra time talking about syntax so that we can finish it on the same page.

A multi-line statement

Sometimes you can't write the Vimscript you need in a line. W hen it to automatic command groups, we've already come across examples like this. Here's the code we've written before:

:augroup testgroup
:    autocmd BufWrite * :echom "Baz"
:augroup END

Ideally, you can write in three separate lines. B ut when you execute commands manually, it's too long to write. I n fact, you can use the pipe | ) t o separate each line. Execute the following command:

:echom "foo" | echom "bar"

Vim treats it as two separate commands. If you don't see two lines of output, :messages to view the message log.

For the rest of the book, when you want to execute a command manually and are upset about entering new lines and colons, try to pipe them apart and finish them in one line.

The basic usage of If

Now let's get back to the subject and execute the following command:

:if 1
:    echom "ONE"
:endif

Vim ONE because 1 is "truthy". Now do the following command:

:if 0
:    echom "ZERO"
:endif

Vim will display ZERO because the integer 0 is "falsy". L et's see how strings are handled. Follow these commands:

:if "something"
:    echom "INDEED"
:endif

The results may surprise you. Vim_'t treat non-empty strings as "truthy", so nothing is displayed.

Let's break the casserole and ask the end. Execute the following command:

:if "9024"
:    echom "WHAT?!"
:endif

This Vim_ show! Why is this happening?

To understand what's going on, execute the following three commands:

:echom "hello" + 10
:echom "10hello" + 10
:echom "hello10" + 10

The first command makes Vim 10 the 20 and the third output 10

After exploring all the commands, we can conclude with Vimscript:

  • If necessary, Vim casts the type of the variable (and literally). Vim 10 + "20foo" into an "20foo" and adds it to 10 when parsing 10 20
  • Strings that begin with a number are cast to numbers, otherwise they are converted to 0
  • After all casts are complete, if statement body when the if's judgment condition is equal to a if integer.

Else and Elseif

Vim, like Python, supports "else" and "else if" sentences. Execute the following command:

:if 0
:    echom "if"
:elseif "nope!"
:    echom "elseif"
:else
:    echom "finally!"
:endif

Vim finally! because the previous judgment conditions are equal to 0, and 0 represents falsy.

Practice

Have a beer to placate your heart hurt by the string cast in Vim.