Peter's Blog

Redefining the Impossible

Create your own file type in VIM


This is so cool, I have to tell the world how easy it is. Suppose you want to create a new type of virtual file to edit in vim. You can set vim up to automatically call your handlers to read and write files of your magic file type. Here's how: put this in vimrc or $VIM/plugins/mynewfiletype.vim:

   1  python << EOF
   2  
   3  def WriteFile( strFile):
   4      """
   5      Write File
   6      """
   7      #
   8      # Do whatever, send file wherever you like
   9      #
  10      pass
  11  
  12  def ReadFile( strFile):
  13      """
  14      Read file
  15      """
  16      #
  17      # Do whatever, read file from wherever you like
  18      #
  19      pass
  20  EOF
  21  
  22  :au BufWriteCmd blog/* py WriteFile( vim.eval( "expand('<afile>')"))
  23  :au BufReadCmd blog/* py ReadFile( vim.eval( "expand('<afile>')"))
  24  
Toggle Line Numbers

In the example above I have said that any file name that starts with 'blog/' is to be handled by my read and write functions instead of being read/written to disk.

Once this is done:

:e blog/blah

will cause vim to call the ReadFile function in order to edit the file 'blog/blah' and

:w

will cause vim to call the WriteFile function to write it.

ReadFile and WriteFile can do whatever you like: go over networks, send email, climb mountains, send morse code, whatever you can code in python.

One little word of warning: under windows, the file names get automatically converted to have backslashes, i.e. strFile above will hold blog\\\\blah instead of blog/blah even if you type in

:e blog/blah

to open the file.


Filed under: python vim

2 Comments

Ran Moshe Says:

over 3 years ago

Hi Peter,

I'm new to vim as well as python, so excuse the basic question: To have this script work, you have to have a python enabled vim, right? How do you enable vim for python? How do you check if vim is indeed enabled for python?

Thanks, Ran

Peter Says:

over 3 years ago

Vim has to be compiled with python support enabled. I haven't found anywhere that has precompiled binaries with python enabled, I always build mine.

To see if vim has python support the easiest way is to use the command:

:py print 'hi'

If this says 'hi' then you have python, otherwise you get an error about an unrecognised command.

The official way is to use the command

:version

which will list (amongst other stuff) the compile time flags. +python means you have python, -python means you don't.

Peter

Sorry but comments on this post are now closed.