def _insert_glsl(vertex, fragment, to_insert):
    """Insert snippets in a shader.

    to_insert is a dict `{(shader_type, location): snippet}`.

    Snippets can contain `{{ var }}` placeholders for the transformed variable
    name.

    """
    # Find the place where to insert the GLSL snippet.
    # This is "gl_Position = transform(data_var_name);" where
    # data_var_name is typically an attribute.
    vs_regex = re.compile(r'gl_Position = transform\(([\S]+)\);')
    r = vs_regex.search(vertex)
    if not r:
        logger.debug("The vertex shader doesn't contain the transform "
                     "placeholder: skipping the transform chain "
                     "GLSL insertion.")
        return vertex, fragment
    assert r
    logger.log(5, "Found transform placeholder in vertex code: `%s`",
               r.group(0))

    # Find the GLSL variable with the data (should be a `vec2`).
    var = r.group(1)
    assert var and var in vertex

    # Headers.
    vertex = to_insert['vert', 'header'] + '\n\n' + vertex
    fragment = to_insert['frag', 'header'] + '\n\n' + fragment

    # Get the pre and post transforms.
    vs_insert = to_insert['vert', 'before_transforms']
    vs_insert += to_insert['vert', 'transforms']
    vs_insert += to_insert['vert', 'after_transforms']

    # Insert the GLSL snippet in the vertex shader.
    vertex = vs_regex.sub(indent(vs_insert), vertex)

    # Now, we make the replacements in the fragment shader.
    fs_regex = re.compile(r'(void main\(\)\s*\{)')
    # NOTE: we add the `void main(){` that was removed by the regex.
    fs_insert = '\\1\n' + to_insert['frag', 'before_transforms']
    fragment = fs_regex.sub(indent(fs_insert), fragment)

    # Replace the transformed variable placeholder by its name.
    vertex = vertex.replace('{{ var }}', var)

    return vertex, fragment
Insert snippets in a shader.

    to_insert is a dict `{(shader_type, location): snippet}`.

    Snippets can contain `{{ var }}` placeholders for the transformed variable
    name.