Detect language of new files in vim (refresh syntax highlighting)

Whenever you open a file, vim performs a series of checks to determine the language of the file and applies the relevant syntax highlighting; first by checking the file extension, then by looking inside the file itself. Nothing new here.

When you create a new file including the file extension, e.g., test.sql, vim automatically highlights the SQL syntax to anything you type - again, nothing new here.

However, when you create a new file without a file extension but containing a shebang, e.g., #!/usr/bin/env python, it seems to be necessary to save the file and open it again for vim to apply the checks and decide that this is a python script.

My question is whether there is a vim command that triggers these checks, allowing a refresh of the highlighting in new (extensionless) files, avoiding the need to reopen the file.

Having a look at vim's documentation for syntax-loading I thought I would find something useful regarding my query - unfortunately I did not.


Solution 1:

Here are 3 different ways you can do it:

  • :set ft=python. The down side to this approach is that you can't add it to a keyboard shortcut since it will only work with one file type (python in this example)
  • :w+:e The down side with this is that you have to save the file before running the command since it reloads the file.
  • :filetype detect This is longer to type though.

You could add the second or third option as a shortcut with map <C-r> :filetype detect<CR> to your .vimrc to enable refreshing the file with ctrl+r