Search code examples
pythonindentationauto-indenttext-indenttkinter-text

How to auto indent next line of string


I am trying to make a program using Python that will auto indent the next line of string when it encounters certain characters such as braces.

For example:

public class Example{

--indent--> public static void main (String[]args){

--indent--> System.out.println("Hello");
}
}

I can't seem to grasp what I need to code in order to achieve that.

Any kind of help will be much appreciated!


Solution

  • honestly, the exact way you set up your code depends on if you're doing other things to it to "pretty print" it. a rough outline of something could look like this

    def pretty(s):
        start = "{"
        end = "}"
        level = 0
        skip_start = False
    
        for c in s:
            # raise or lower indent level
            if c == start:
                level += 1
            if c == end:
                level -= 1
    
            if level < 0:
                raise IndentationError("Error Indenting")
    
            if c == "\n":
                skip_start = True # I'm bad at naming just a flag to mark new lines
    
            if c.isspace() and skip_start:
                pass #skip whitspace at start of line
            else:
                if skip_start:
                    print("\n", "  " * level, end="") #print indent level
                    skip_start = False
                print(c, end = "") #print  character
    
    pretty('''
    public class Example{
    
    
    
    public static void main (String[]args){
    if (1==1){
        //do thing
    //do other thing
                 // weird messed up whitespace
    }else{
    System.out.println("Hello");
    }
    }
    }
    ''')
    
    

    would output

     public class Example{
       public static void main (String[]args){
         if (1==1){
           //do thing
           //do other thing
           // weird messed up whitespace
         }else{
           System.out.println("Hello");
         }
       }
     }