2

Does anyone know of a way to get vim to guess the programming language of a new file based on your input and use the appropriate syntax highlighting? So far the syntax highlighting only works when it knows the file extension (after I have saved it), which is good, but sometimes I am lazy and want to make a new file without saving it until later.

e.g. if I were to start a new file and type:

#include <stdlib.h>

I would like it to automatically start using C syntax highlighting, say after I hit enter, and the same goes for other languages like Python.

I am a bit of a noob with vim and don't know vimscript, so don't make it too complicated please. Any help is appreciated.

Thanks, Simon

2 Answers 2

4

Vim uses both file path / name / extension and certain characteristic file contents to detect the filetype; what is used depends on the particular type.

You can re-trigger the detection via

:filetype detect

For C / C++, the detection is based on file extensions. To add a contents-based detection, you'd have to write this yourself; see :help new-filetype-scripts for details. In practice, I'd recommend to just manually :setf c when the need arises.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I will probably end up using :setf c, but I will see if I can figure out how to make a script for it too.
1

This could be arranged, but performance could be a slight problem (depending on how clever you want to be) and it is much easier to just set the syntax manually:

:setf c

You could also set the buffer filename; this will set the syntax accordingly, normally:

:file x.c

(This does not save the file.)

If you really do want automatic guessing, you'd be using an autocmd to trigger it, and could then guess the filetype if &ft is empty (i.e. if it hasn't already done so).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.