• +43 660 1453541
  • contact@germaniumhq.com

Assigning a Function on File Type in Vim


Assigning a Function on File Type in Vim

Ok, we have now a new function with our own code in vim. We can manually trigger it when opening a buffer. Let’s make this function automatically be called whenever opening a file, and fiddle with file types.

To achieve that we have two choices. First is to use the embedded file type detection from vim. When opening a file, the filetype is automatically set for the current buffer. Then all the plugins for that file type are going to be executed. We’ll simply save a file in the ftdetect (filetype detect) folder, such as .vim/ftdetect/yaml.vim.

Then whenever this plugin loads, we’ll call our function via our command:

Spaces2

Another more flexible option is to register just some plugin code that allow us to execute an automated command whenever a new buffer (file) is created or loaded:

au BufNewFile,BufRead *.yml,*.yaml call Spaces2

This one allows us to create a mapping that executes regardless of the filetype, and the awesome part: it even allows us to change the filetype, while we’re still opening the file.

For example a think I like is to tell vim that Jenkinsfile is a special kind of groovy file:

au BufRead,BufNewFile Jenkinsfile set filetype=X_Jenkinsfile.Jenkinsfile.groovy

Like this I get snippets for both groovy and Jenkinsfile whenever I open a new Jenkinsfile.

How sweet is that?

We can define our own multiple file types for any name/extension, and we can load plugins specifically for them.