2

Is there any way to determine within Vim that the file which I'm editing is either in text or binary format?

For example:

vim http://example.com/

vs:

vim http://cdn.sstatic.net/vi/img/apple-touch-icon.png

Something that would return either True or False based on the content of the current file. One possible scenario would be, if the file is in gzip format, I'd like to perform uncompression of it.

5

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/plain'
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 ;-)

2

Your mentioned automatic uncompression of ZIP files (and other archive formats) is already built into Vim, cp. :help pi_zip. The plugin sets up :autocmds that detect ZIP files based on their file extension (:au zip lists them all), not on their contents.

There's no detection built in, because it doesn't make much sense to edit non-text files with a text editor such as Vim. That said, Vim has some support via :set binary, and conversion to / from hexdump format via xxd.

  • Thanks for suggestion, I've asked another question to address that if that's ok, so if you like, you could elaborate further how to uncompress such files with some specific example. – kenorb May 8 '15 at 19:48

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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