On 15/11/12 09:18, BPJ wrote:
> I regularly get files encoded in UTF16LE sent to me and want them to be
> automatically converted to UTF8 when opening them.
> I'm not sure what command to use/put in .vimrc for that though, so
> I wonder if anybody is already doing this, and how?
If a file in UTF-16le has a BOM (the codepoint U+FEFF at the very
beginning of the file, which for UTF-16le means the bytes 0xFF 0xFE),
then if you have set Vim to use UTF-8 'encoding' in your vimrc that file
will usually be opened correctly (because the default 'fileencodings'
-plural- starts with "ucs-bom"). See http://vim.wikia.com/wiki/Working_with_Unicode
about how to set Vim up
If the file has no BOM it is a little harder to detect the correct
'fileencoding'. I think there is a Chinese regular of this list who has
a plugin to do more detailed encoding matching than what Vim does out of
the box but I don't know the details.
Now, once the 'fileencoding' -singular- has been detected as UTF-16le it
is possible to convert it, even automatically, like this:
if has('multi_byte') && &encoding == 'utf-8'
autocmd VimEnter * autocmd vimrc_utf8 BufReadPost *
\ if &fenc ==? 'utf-16le' || &fenc ==? 'ucs-2le' |
\ setlocal fenc=utf-8 |
\ w! |
The exclamation mark is necessary if the file is marked readonly, but is
not on a readonly filesystem. Alternatively, if you don't want to
convert read-only files (including files opened by :view), replace the
"if" line inside the autocommand by
\ if !&ro && (&fenc ==? 'utf-16le' || &fenc ==? 'ucs-2le') |
and then the exclamation mark may be left out on the "w[rite]" line.
It may look weird to define an autocommand inside an autocommand, but I
do it like this to ensure that this BufReadPost autocommand comes last,
and in particular, after anything defined by any additional
encoding-detection plugin you might install.
The mome rath isn't born that could outgrabe me.
-- Nicol Williamson