How can I make vim recognize the file's encoding?

Vim needs to detect the encoding, and that's going to be problematic, since files don't often explicitly state their encodings (an obvious exception are XML files with an encoding attribute in the header).

You can force Vim to reload a file with a different encoding thus:

:e ++enc=cp437

and you can set the default encoding in your .vimrc if you wish.

This page has more info and links, especially wrt. editing Unicode. UTF-8 is the most widely-used encoding, and the default you should probably go for.


You can use a vim modeline to set the file's encoding. This is simply a comment, in the first five lines of the file, that starts with vi: set fileencoding=cp437.

You could also start with 'vim:', instead of 'vi: set', but the latter makes it compatible with more editors. You definitely need the space between either of these prefixes and 'fileencoding', or whatever option you want to set. The fileencoding option should solve your problem, though.

So, in Python or an .rc file, you can put this at the top of your file:

# vi: set fileencoding=cp437

In Java, C, C++, JavaScript, etc. put this:

// vi: set fileencoding=cp437

For more information, in vim, type :help modeline.

Tags:

Vim