Question

I want Vim to change the filetype when I type a shebang line (eg. #!/bin/bash) on the first line of a new buffer.

Currently I'm using vim-shebang plugin for changing filetype, but it only works when opening a new buffer.

Clarification: I'm interested in achieving the desired result by mapping <CR> in insert mode. What I want is when I type #!/bin/bash<CR> on the first line of a buffer to automatically execute :filetype detect and return to editing.

Was it helpful?

Solution 2

I'd recommend to read the (always great) documentation of Vim (which I'm quoting bellow):

:help new-filetype-scripts

This might help you.

If your filetype can only be detected by inspecting the contents of the file.

  1. Create your user runtime directory. You would normally use the first item of the 'runtimepath' option. Example for Unix: :!mkdir ~/.vim

  2. Create a vim script file for doing this. Example:

     if did_filetype()    " filetype already set..
       finish     " ..don't do these checks
     endif
     if getline(1) =~ '^#!.*\<mine\>'
       setfiletype mine
     elseif getline(1) =~? '\<drawing\>'
       setfiletype drawing
     endif
    

    See $VIMRUNTIME/scripts.vim for more examples.

    Write this file as "scripts.vim" in your user runtime directory. For example, for Unix:

     :w ~/.vim/scripts.vim
    

Update (after the edit of the original question): I'd recommend against the mapping of , but you can do it with

:inoremap <CR> YOUR_SPECIAL_FUNCTION_WHICH_DETECS_THE_CURRENT_LINE_AND_RUNS_FILETYPE_DETECT

The above code snippet (if getline(1)... is enough to get you started. We are not the writethecodeformeforfree.com community.

OTHER TIPS

You can use

:filetype detect

to re-trigger the filetype detection after you've written the shebang line.

This can be automated with :autocmd, e.g. on the BufWritePost when &filetype is still empty.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top