1

I'm using a plugin which can show the minimap for the file I'm editing. The plugin can only works with utf-8. Does anyone know how to dynamically/temporarily change the encoding in Vim, so I can make the minimap work by temporarily set the encoding to utf8?

5
  • 2
    I'm a bit confused. Why not just use UTF-8 all the time?
    – Rich
    Apr 21, 2021 at 16:03
  • Which encoding are you using? You can try to set the locale environment variables to match the file encoding, for example export LANG=zh_CN.big5 or export LANG=zh_CN.gb18030. Also consider filing a GitHub issue to the authors of code-minimap and minimap.vim to properly detect the file encoding from Vim and respect it while generating the minimap. (It might help to give them a small example file they can test it on.)
    – filbranden
    Apr 21, 2021 at 19:25
  • 1
    Not sure whether this fits your definition of "temporary" but you could simply :set fileencoding=utf-8, save the file, and then set it back again when you're done.
    – Rich
    Apr 23, 2021 at 13:01
  • @Rich: Yes it fits, you might write an answer If you're willing to. I was thinking about whether there is a way to set a fallback option, say that it will first try big5 if it cannot display all text then try utf-8. Apr 23, 2021 at 14:24
  • @job_start Yes, that's possible. The reason I haven't actually gotten around to answering your question is that I was a bit unclear on your actual requirements I'll try writing something now.
    – Rich
    Apr 23, 2021 at 14:51

2 Answers 2

3

You can change the encoding of a loaded buffer simply by setting 'fileencoding' and then saving the file:

:set fileencoding=utf-8
:w

Hopefully this will allow your plugin to work, and then if necessary you can change the encoding back afterwards using the same method. You could probably also set up a BufUnload or BufDelete autocommand to automatically change the encoding back when you are done with the buffer.

However, note that changing the encoding is not necessarily a reversible operation, and it's possible that changing it to a new encoding and then back again will result in data loss.

You also ask in the comments about setting a fallback option. This is what the 'fileencodings' option (plural, with an s!) is used for. Setting it to e.g.:

:set fileencodings=big5,utf-8

will instruct Vim first to try reading files with big5, and if that fails, try utf-8 next. You can add as many comma separated encodings as you like to the setting; if none of these succeed without error, Vim will use the value of 'encoding' for reading the file.

0

You can use the following instruction to reload the current file without reopen in VIM. :e ++enc=

++enc will affect the "fileencoding" variable, but "encoding“ variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.