views:

1013

answers:

4

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.

I'm stumped on how to fix this. Any ideas would be appreciated!

Thanks

+1  A: 

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..

Mihail
Thanks for the reply. So you are suggesting I strip each line of the indentation that has been inserted? I'm confused...
+6  A: 

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:

def main():
    """foo
bar
foo2"""
    pass

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 below help(main2) produce the same help info.

def main2():
    """foo
    bar
    foo2"""
    pass
TokenMacGuy
Thanks for the reply. Unfortunately the indentation is completely automated, as my code reads in the script as a string (in Java) and indents every line in that string.
Ah I see. I can't use help for this though...thanks though!
+1  A: 

So if I get it correctly, you take whatever the user inputs, indent it properly and add it to the rest of your programm (and then run that whole programm).

So after you put the user input into your programm, 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".

FlorianH
yep, precisely. That's the only possible solution I've come up with. Not sure why I didn't go ahead with it...I think I might have to do this if nothing better comes up.
+4  A: 

textwrap.dedent from the standard library is there to automatically undo the wacky indentation.

thraxil
neat.. didn't know about that.. :)
Marcus Lindblom
The standard library never ceases to hold surprises.
thraxil
very cool info. I can't use it though.