Question

I've got a kind of polyglot filetype that can have embedded C, python, ruby, etc in it (think 'wiki page' if it helps). Is there a way to execute the autocommands for a known filetype on a region of the file?

For example, I might have:

#!bash
if [ a = b ]; then
   echo 'equal'
fi

#!python
if a = b:
    print('equal')

And I want to apply bash filetype autocommands to the first part and python filetype autocommands to the latter part.

I can get just syntax hilighting by defining a region using this method, but I don't understand autocommands enough to be able to apply them in a similar way.

Was it helpful?

Solution

Doing this automatically is challenging, as the filetype settings are buffer-local; Vim has no notion of regions, so :autocmds need to be used, as you've correctly stated.

Quick and easy

With a plugin like NrrwRgn - A Narrow Region Plugin similar to Emacs, you can clone regions to separate scratch buffers; the plugin automatically syncs them back on write. Each buffer can be given a separate filetype via :setf.

An even simpler approach is to define some mappings to quickly switch filetypes:

:nnoremap <Leader>fp :setf python<CR>
:nnoremap <Leader>fs :setf sh<CR>

Really separate regions in a single buffer

The sketch of this is easy:

:autocmd CursorMoved,CursorMovedI <buffer> if line('.') >= 6 | setf python | else | setf sh | endif

This relies on each filetype plugin doing proper cleanup (or overriding all relevant options).

How to determine the regions

You certainly don't want to specify the line numbers explicitly as in the sketch above. My OnSyntaxChange plugin might help, in case you have / can define proper syntax regions for each block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top