Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I noticed that most of the time, when using some encoding other than 'the standard english', vim doesn't recognize and does not display characters correctly.
This is most easily seen by opening some ascii graphics, or similar files off the net, which use cp437 code page.

Is there a way to make vim check for encoding when opening a file, and open it with a correct one ?

What encodings do you use, as the most "portable" ones (the ones which the largest amount of users will have least problems with) ?

like image 902
Thomas Geritzma Avatar asked Jun 17 '09 10:06

Thomas Geritzma


2 Answers

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.

like image 102
Brian Agnew Avatar answered Sep 30 '22 03:09

Brian Agnew


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.

like image 44
Michael Scheper Avatar answered Sep 30 '22 02:09

Michael Scheper