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

Vimscript Execute command


May 24, 2021 Vim


Table of contents


execute execute command is used to execute a string as a Vimscript command. We've talked to it before in the previous chapters, but now we'll get to know it again as we get a deeper understanding of the strings in Vimscript.

execute basic usage

Execute the following command:

:execute "echom 'Hello, world!'"

Vim put echom 'Hello, world!' a s a command, and duty-thy-back messages while outputing it. Execute is a very powerful tool because it allows you to create commands with any string.

Let's try a more practical example. O pen a file in Vim as a preparation, then use :edit foo.txt create a new buffer in the same window. Now do the following command:

:execute "rightbelow vsplit " . bufname("#")

Vim opens the vertical split window of the first file to the right of the second file. Why is this happening?

First, Vim connects the results of the "rightbelow vsplit" and bufname('#') and creates a string as a command.

It will be some time before we talk about the corresponding function, and now let's say it returns the path name of the previous buffer. You can echom with echom.

When bufname complete, Vim connects the results to "rightbelow vsplit bar.txt" execute command executes this as a Vimscript command and opens the file in a new split.

Is Execute dangerous?

The use of "eval" to construct executable strings in most programming languages is reprohensible (if not more serious consequences). For two reasons, the execute command execute Vimscript is free from this worry.

First, most Vimscript code only accepts input from the user, the only source. S uppose a user wants to enter an odd string to execute an evil command, it doesn't matter, it's their own computer anyway! I n other languages, however, programs often have to accept input from untrustworthy users. Vim is a special environment where there is no need to worry about general security issues.

The second reason is that Vimscript sometimes deals with problems in an obscure and odd way. E xecute execute the easiest and most straightforward way to complete the task. In most other languages, using "eval" doesn't save you much of your keystroke life, but in Vimscript it can be complicated.

Practice

Browse :help execute find out which commands you can implement with execute and which you can't. But when it comes to it, because we will soon be revisiting the issue.

Read: :help leftabove :help rightbelow :help :split :help :vsplit the extra sign in the last two entries).

Add ~/.vimrc that opens the previous buffer in the selected split (vertical or horizontal, up/down/left/right).