44

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?

guillermooo
  • 7,235
  • 14
  • 49
  • 56

6 Answers6

45

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.

Niki Yoshiuchi
  • 14,935
  • 1
  • 30
  • 41
22

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.

sth
  • 200,334
  • 49
  • 262
  • 354
11

You can put that directive into a comment in the file:

# vim: set fileencoding=<encoding name> :
RichieHindle
  • 244,085
  • 44
  • 340
  • 385
11

If vim doesn't display your file correctly when opened specify encoding with :set encoding=utf8

dmitri
  • 2,908
  • 18
  • 26
4
  • open:

    vim ~/.vimrc
  • add:

    set fileencodings=utf-8
    set encoding=utf-8
    
  • save and close by typing:

    :wq
Vlastimil Ovčáčík
  • 2,191
  • 24
  • 28
Marcos
  • 41
  • 1
3

I read many thread about VIM encoding. I find that the most important trick is: Before open the file ,you should open VIM first, then use the command: edit ++enc= filename.ext It can handle most questions about encoding and fileencoding.

the key points include:

  1. You must display the charset correctly! without correct display, any other operations may cause unrecoverable issue.
  2. after the file is displayed correctly, if needed , you can ":set fileencoding=UTF-8"
    : write" to let VIM can always display it correctly.

Because I am not an English mother tongue user, I think my way is able to be validate.

Steven
  • 31
  • 2
  • You can reload a file you have already opened using :e ++enc= (see http://vim.wikia.com/wiki/Reloading_a_file_using_a_different_encoding). No need to start vim first without opening the file. – akame Apr 05 '17 at 07:37