So i have a specific function I'd like to edit in my .vimrc, so that it work only on specific filetype (eg: .vim).

The code for this example is taken from this answer.

function OrgFold(lnum)
  let level = strlen(matchstr(getline(a:lnum), '\v^\s*\zs\"+\t'))
  if level > 0
    return '>'.level
    return '='

The above function essentially work on all files, but i want to know how to only make it work for .vim or whatever filetype i specify.

  • 2
    autocmd FileType c call OrgFold() is a fast way (this one will work with c files but you can place java, python or other filetype if you want. You can look there for more information. Jan 25, 2021 at 0:35
  • thanks! didn't thought of using call with FileType @FabriceHategekimana Jan 25, 2021 at 0:41
  • 1
    Note: this will launch the function when the filetype event is triggered (when filetype is set) but won't make it available for c files only.
    – Biggybi
    Jan 25, 2021 at 1:06

1 Answer 1


One solution is to use a filetype plugin (:h ftplugin).

First, you need to enable them with filetype plugin on (in your vimrc).

Then, you can add a file in vim/after/ftplugin/FILETYPE.vim, replacing FILETYPE with what's needed.

This file will then be sourced by vim for each file matching the filetype, allowing them to use whatever is in your plugin.

Drop your function there to make it available for this specific filetype only.

  • I see, so that's what some vim plugin are actually doing! But what if the function is in the vimrc then? any other way beside writing it in it's own plugin? Jan 24, 2021 at 23:58
  • 1
    I guess you could use a filetype autocommand as we could do for mappings, although I've never seen to define functions (and would not for mappings either). ftplugin is arguably the way to go.
    – Biggybi
    Jan 25, 2021 at 0:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.