-1

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!

Amber
  • 13
  • 7

2 Answers2

1

This is a quick and dirty way to do it. Basically I just loop through the lines of the input string (cppcode) and keep track of the current indentation (tabdepth). When I encounter a brace in the input line I increment the tabdepth up or down, and then add tabdepth number of tabs to the output line.

cppcode = '''
public class Example{

public static void main (String[]args){

System.out.println("Hello");
}
}
'''


tabdepth = 0

for line in cppcode.split("\n"):
    depth_changed = False
    indentedline = ''.join(['\t'*tabdepth, line])
    for c in line:
        if c == '{':
            tabdepth += 1

        elif c == '}':
            tabdepth -= 1
            depth_changed = True

    if depth_changed: 
        indentedline = ''.join(['\t'*tabdepth, line])

    print(indentedline)
Andrew Micallef
  • 360
  • 1
  • 10
  • I had a similar thought of looping through the input string but I didn't think of keeping track of the indentation, thank you for this insight. – Amber May 16 '20 at 05:46
1

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");
     }
   }
 }
BlueLightning42
  • 344
  • 4
  • 15