Most programs (such as grep, git, mercurial, etc.) consider a file to be binary if it contains a NULL byte.
You can check this with Vim like so:
fun! IsBinary()
return !!search('\%u0000', 'wn')
endfun
Note that this searches the entire buffer; and won't be very fast for large files. A faster way would be to use the file utility:
fun! IsBinary2()
return system('file -ib ' . shellescape(expand('%:p'))) !~# '^text/'
endfun
file has a list known "magic" patterns it can check against, and will be a lot faster for some files. The downside is that file isn't available by default on some systems (Windows, some Linuxes).
It gets the MIME type, so you can do more advanced matching, such as:
fun! IsGzip()
return system('file -ib ' . shellescape(expand('%:p'))) =~# '^application/x-gzip'
endfun
if the file is in gzip format, I'd like to perform uncompression of it.
gzip files pretty much always end in .gz; in fact, some gzip flavours won't even work if the file doesn't end in .gz; with GNU gzip:
$ gzip z
$ mv z.gz aaaaa
$ gzip -d aaaaa
gzip: aaaaa: unknown suffix -- ignored
Exit 2
So matching the filename with an autocmd would probably be a better solution. In fact, there's already an example of this in the help: :help gzip-example.
-iflag is not specified by POSIX for thefile(1)command. In Linux and OpenBSD, it's-i(lowercase), but in OS X, it's-I(capital). Both versions accept the long form--mime, though. – 200_success May 08 '15 at 20:03text/htmlfiles would get classified incorrectly. – 200_success May 08 '15 at 20:04