Synchronizing text with changes from outside

Hi all!

I’m writing myself a plugin (learning purposes) and I’m using an external python editor, because Blender internal text editor is not really nice to work with. When I’m about to test the changes I made, I want to be able to synchronise all the updates I did externally to all my files with a in-memory script, because doing it individually becomes tedious, like so:


for t in bpy.data.texts:
    if t.is_modified and not t.is_in_memory:
        bpy.ops.text.resolve_conflict(resolution='RELOAD')

But when I run this script in Blender (click on the Run Script button) it gives me this error:

SystemError: Operator bpy.ops.text.resolve_conflict.poll() failed, context is incorrect

I don’t get it why it needs to be “in some context”, I want only to reload the text files programmatically.
It’s possible to do this with a script?

Thanks.

Actually I’m confused as how to use the text operator functions (bpy.ops.text) on text datablocks (bpy.types.Text) Some functions that don’t need an active datablock work (like new()), but most of them complain abut incorrect context. I understand how to use operator function on objects, but text is not an object, so it’s not possible to make a text datablock active by assigning it to bpy.context.active_object

So, how do you set a specific text datablock active and use the operator functions on it?

Thanks to Help from IRC-Channel here is a working solution:


import bpy


for t in bpy.data.texts:
    if t.is_modified and not t.is_in_memory:
        ctx = bpy.context.copy()
        ctx['edit_text'] = t
        bpy.ops.text.resolve_conflict(ctx, resolution='RELOAD')

thanks for help in irc-channel, here is a working solution


import bpy


for t in bpy.data.texts:
    if t.is_modified and not t.is_in_memory:
        ctx = bpy.context.copy()
        ctx['edit_text'] = t
        bpy.ops.text.resolve_conflict(ctx, resolution='RELOAD')

The previous script works only if the current area is of type ‘TEXT_EDITOR’.
I had to adapt it to ensure that it runs on other conditions (a python script which run in blender -b -p )
so my solution is:


def updateExternalTexts():
    """ Check modified external scripts in the scene and update if possible
    """
    ctx = bpy.context.copy()
    #Ensure  context area is not None
    ctx['area'] = ctx['screen'].areas[0]
    for t in bpy.data.texts:
        if t.is_modified and not t.is_in_memory:
            print("  * Warning: Updating external script", t.name)
            # Change current context to contain a TEXT_EDITOR
            oldAreaType = ctx['area'].type
            ctx['area'].type = 'TEXT_EDITOR'
            ctx['edit_text'] = t
            bpy.ops.text.resolve_conflict(ctx, resolution='RELOAD')
            #Restore context
            ctx['area'].type = oldAreaType