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

Vimscript detects file types


May 24, 2021 Vim


Table of contents


Let's create a Potion file as a test sample for the plug-in.

factorial = (n):
    total = 1
    n to 1 (i):
        total *= i.
    total.

10 times (i):
    i string print
    '! is: ' print
    factorial (i) string print
    "\n" print.

This code creates a simple factor function and calls it 10 times to output the results one by one. G o ahead and execute it factorial.pn the potion factorial.pn The output should look something like this:

0! is: 0
1! is: 1
2! is: 2
3! is: 6
4! is: 24
5! is: 120
6! is: 720
7! is: 5040
8! is: 40320
9! is: 362880

If you don't get this output, or you get an error, stop and troubleshoot the problem. This code should work.

It has nothing to do with learning Vimscript, but it can make you a better program ape.

Detect Potion files

Use Vim to factorial.pn execute the following command:

:set filetype?

Vim filetype= doesn't know .pn yet. Let's solve this problem.

Create ftdetect/potion.vim Add the following lines to it:

au BufNewFile,BufRead *.pn set filetype=potion

This creates a one-line automatic command: a command that sets the fileype of the .pn file potion It's very concise.

Notice that we don't use an automatic command group as we often do before. Vim automatically wraps ftdetect/*.vim into automatic command groups, so you don't have to worry.

Close factorial.pn and reopen it. Now execute the previous command:

:set filetype?

This time Vim filetype=potion When Vim starts, it loads the automatic command group in the ~/.vim/bundle/potion/ftdetect/potion.vim and factorial.pn the automatic command takes filetype potion

Now that Vim has identified the Potion file, we can move on and do something useful.

Practice

Read: :help ft Don't worry you can't read what's inside.

Read :help setfiletype .

Modify the ftdetect/potion.vim Replace setfiletype set filetype