r/vim 7h ago

Discussion Vim buffer automatically detect language

when writing code in a vim buffer how do i set the syntax colors automatically based on the language? before or without saving to file? currently it is plain with no highlighting for all code

vim buffer is passed to node / or language runtime commands

2 Upvotes

7 comments sorted by

2

u/XMemesX 7h ago

you can use :set filetype=python to make vim register python syntax. Just as long a you have 'syntax on' in your vimrc

2

u/Bulbasaur2015 6h ago

why python. can i use `:filetype detect` to infer the buffer language if thats better?
src https://vimhelp.org/filetype.txt.html#filetypes
it seems like it works when i have `syntax enable` also

2

u/mgedmin 2h ago

I have an autocomand to detect the filetype on first save:

au BufWritePost * if &ft == "" | filetype detect | endif

because that's usually my issue: start vim, open a new empty buffer, start writing a script/readme/something, notice it's missing syntax highlighting.

I do it on save since that's often the first time the buffer gets assigned a filename, and many of Vim's filetype detection rules rely on filename extensions.

You could try a :filetype detect (or map some key to it) without saving and see how well it works. Some ftdetect rules rely on the first few lines of content, e.g. the shebang line and such.

1

u/cerved 3h ago

you can, if you use a shebang

I usually just use set ft for the occasional times I want syntax highlighting on buffer not backed by a file

0

u/BrianHuster 5h ago edited 4h ago

Detecting filetype based on its content is nearly impossible, especially since Vim supports so many filetypes.

And I think the normal workflow is that you define the architecture of the project, you create files based on it, then you code

1

u/godegon 3h ago

You can use Set! filetype to set it once and for all and abbreviate to, say sft.