How do you provide additional context or scope to injected language fragments?


I'm attempting to create an IntelliJ plugin to implement Mako templates support for Python (i.e., PY-51736). This basically involves injecting the Python language into HTML files. I've got a MultiHostInjector working which injects Python code fragments into the HTML document using getLanguagesToInject(). Each injected Python fragment is currently independent of the others. How do you provide additional context or scope to injected fragments? A bad idea I had was to scan the PSI tree, concatenate all of the Python fragments, and use the prefix and suffix support of MultiHostRegistrar.addPlace(). I don't see that being efficient because each fragment would have its own copy of most of the file's code. How is this problem generally approached with IntelliJ plugins? What classes should I be looking at? Are there any community plugins I should look at for reference?


For example, say I have a simple Mako template:

# Python module scope.
import html

# Function to be called later on.
def get_page_title():
	return "HELLO WORLD"

		<!-- The "${...}" is an inline substitution. -->

I want to make the imports, functions, etc. from the module scope block at the top to be available in the ${get_page_title()} fragment.