I have a python editor where the user is entering a script or code, which is then put into a main method behind the scenes, while also having every line indented. The problem is that if a user has a multi line string, the indentation made to the whole script affects the string, by inserting a tab in every space. A problem script would be something so simple as:
"""foo
bar
foo2"""
So when in the main method it would look like:
def main():
"""foo
bar
foo2"""
and the string would now have an extra tab at the beginning of every line.
So if I get it correctly, you take whatever the user inputs, indent it properly and add it to the rest of your program (and then run that whole program).
So after you put the user input into your program, you could run a regex, that basically takes that forced indentation back. Something like: Within three quotes, replace all "new line markers" followed by four spaces (or a tab) with only a "new line marker".
What follows the first line of a multiline string is part of the string, and not treated as indentation by the parser. You may freely write:
and it will do the right thing.
On the other hand, that's not readable, and Python knows it. So if a docstring contains whitespace in it's second line, that amount of whitespace is stripped off when you use
help()
to view the docstring. Thus,help(main)
and the belowhelp(main2)
produce the same help info.From what I see, a better answer here might be
inspect.cleandoc
, which does functionally whattextwrap.dedent
does but also fixes the problems thattextwrap.dedent
has with the leading line. The below example shows the differences:textwrap.dedent from the standard library is there to automatically undo the wacky indentation.
The only way i see - is to strip first n tabs for each line starting with second, where n is known identation of main method.
If that identation is not known beforehand - you can add trailing newline before inserting it and strip number of tabs from the last line...
The third solution is to parse data and find beginning of multiline quote and do not add your identation to every line after until it will be closed.
Think there is a better solution..