improve text warping script to programmable filter

Hello, currently one defines the script in a string and sends it to the programmable filter:
such as:

script="""import math
1+1
....
"""
programmableFilter.Script=script #or the new Set method....

this works fine.
the issue comes from when we need to set it from inside a function or if/else etc (so the script is inside an indentation).

if 1:
    script="""import math
    1+1
    ....
    """
    programmableFilter.Script=script #or the new Set method....

currently this is quite an annoyance, as the script on the programmableFilter will be like this:

import math
    1+1
    ....

the current ‘solution’ for me, (that the programmableFilter should take care of automatically) was:

if 1:
    script="""import math
    1+1
    ....
    """
    lines = script.splitlines()
    if lines and lines[0].strip() and len(lines) > 1:
        indentation = len(lines[1]) - len(lines[1].lstrip())
        lines[0] = " " * indentation + lines[0]
        script = "\n".join(lines)
    scriptCut = textwrap.dedent(script)
    if scriptCut[:1]=='\n':
        scriptCut=scriptCut[1:]
    programmableFilter.Script = scriptCut

in my tests this solves the issue completly, it can handle different possibilities:

  • one or multiple indententions levels (eg., the script is defined inside an if that is inside another if)
  • if the script is deffined by script="""import math or if there is a initial jumpline script=""".... and continues in the next line.

currently to make it work correctly, one should do like this:

if 1:
    script="""import math
1+1
....
"""
    programmableFilter.Script = script

or

if 1:
    script="""
import math
1+1
....
"""
    programmableFilter.Script = script

this breaks the indentation collapsing in a lot of the code editors, such as vscode.

I dont think this is reasonnable to do. Python is python and we should not mess with the formatting of user scripts.

personally I created this function and use it, by default:

def programmableFilterTextWrapper(script=""):
    lines = script.splitlines()
    if lines and lines[0].strip() and len(lines) > 1:
        indentation = len(lines[1]) - len(lines[1].lstrip())
        lines[0] = " " * indentation + lines[0]
        script = "\n".join(lines)
    scriptWarped = textwrap.dedent(script)
    if scriptWarped[:1]=='\n':
        scriptWarped=scriptWarped[1:]
    return scriptWarped
programmableFilter.Script=programmableFilterTextWrapper(script)

the issue is not just to make it ‘pretty’ it is more that, i had found myself getting crashes due to the text being wrongly warped quite often (until i got tired and had the time to trouble shoot and make this lazy function). but it happend to me quite often…
i tried to ‘break’ the function to find edge cases where it would be problematic or cause an issue, outside of leaving a first empty line (that i removed manually) i could not make it something that would wroke the programmable filter/ source