vimmarkdownvineovimmultimarkdown

Using a file type plugin file (ftplugin) to change the file type in vim / neovim


To automate a step for creating multimarkdown notes. I'd like for neovim to change the filetype of a file based on the contents of first line. All of my multimarkdown notes begin with title E.g.

title: Euclidean Distance

Ideally i'd like to keep this out of my init.vim (.vimrc) file, however neovim does not update the buffer upon read/open when I place the following in my ../ftplugin/txt.vim file.

" Change the file type to markdown
if getline(1) =~ '^title:'
   set ft=markdown
endif

How can I get neovim to check the first line of the file and change its type or at least change its syntax. Thx.

I understand that the runtime doesn't watch all the files. Is the only way to automatically check the file type and make changes is by using autocmd and source the ftplugin/txt.vim file via init.vim (.vimrc)


Solution

  • This blows into the same horn as @PeterRincker's answer, but I think you should follow :help new-filetype-scripts, as the description (if your filetype can only be detected by inspecting the contents of the file) matches your use case perfectly.

    With that, you put the following contents into ~/.vim/scripts.vim:

    if did_filetype()   " filetype already set..
        finish      " ..don't do these checks
    endif
    if getline(1) =~ '^title:'
        setfiletype markdown
    endif