Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the character encoding for a file in VIM

Tags:

vim

encoding

I'm using :set fileencoding=utf-8 and the file is saved correctly, but the next time I open it, I get garbled characters and :set fileencoding? says the option isn't set.

From the docs I understand that I shouldn't touch the encoding option.

What's the correct way of specifying an encoding for a file in VIM?

like image 473
guillermooo Avatar asked Jul 23 '09 22:07

guillermooo


People also ask

How do I set encoding in Vim?

set encoding=utf-8 " The encoding displayed. set fileencoding=utf-8 " The encoding written to file. You may as well set both in your ~/. vimrc if you always want to work with utf-8.

How do you set character encoding?

Right-click at somewhere on web page to manually set character encoding. The selected character set will automatically apply to all pages on the same site. Select "Use page default" to cancel it.

How do I change the encoding to UTF-8?

UTF-8 Encoding in Notepad (Windows)Click File in the top-left corner of your screen. In the dialog which appears, select the following options: In the "Save as type" drop-down, select All Files. In the "Encoding" drop-down, select UTF-8.


2 Answers

Use

set fileencodings=utf-8 

(with an s at the end) which can contain a list of different encodings. Vim will try the encodings listed, from left to right, until one works and it will set fileencoding to that encoding. If none work then fileencoding is set to an empty string which will result in default behavior.

Also it would probably make sense to add that to your vimrc so you aren't constantly doing that.

like image 131
Niki Yoshiuchi Avatar answered Oct 30 '22 09:10

Niki Yoshiuchi


You should set fileencodings to the different encodings vim should try when opening a file, for example:

set fileencodings=ucs-bom,utf-8,latin1 

From :help fileencodings:

This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, fileencoding is set to it.

You best put these settings in your .vimrc file so that you don't have to input them manually each time you start vim.

like image 43
sth Avatar answered Oct 30 '22 10:10

sth