tkolleh
tkolleh

Reputation: 423

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)

Upvotes: 1

Views: 1723

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172520

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

Upvotes: 2

Peter Rincker
Peter Rincker

Reputation: 45107

According to :h new-filetype part B you can do something like the following:

augroup txt_to_markdown
    autocmd!
    autocmd BufRead * if &filetype == 'text && getline(1) =~ '^title:' | set filetype=markdown | endif
augroup END

Upvotes: 2

Related Questions