public String reindent ( String code ) { try { // Remove indention from each line. StringBuilder sb = new StringBuilder ( ) ; LineReader lr = new LineReader ( new StringReader ( code ) ) ; String line = lr . readLine ( ) ; while ( line != null ) { sb . append ( line . trim ( ) ) ; line = lr . readLine ( ) ; if ( line != null ) { sb . append ( ' ' ) ; } } String strippedCode = sb . toString ( ) ; // Now indent it again. int indent = indention * DEFAULT_INDENTION ; sb . setLength ( 0 ) ; // reset buffer lr = new LineReader ( new StringReader ( strippedCode ) ) ; line = lr . readLine ( ) ; while ( line != null ) { if ( line . startsWith ( "}" ) ) { indent -= DEFAULT_INDENTION ; } if ( ! line . startsWith ( "#line" ) ) { sb . append ( pad ( indent ) ) ; } sb . append ( line ) ; if ( line . endsWith ( "{" ) ) { indent += DEFAULT_INDENTION ; } line = lr . readLine ( ) ; if ( line != null ) { sb . append ( ' ' ) ; } } return sb . toString ( ) ; } catch ( IOException e ) { // Should never happen with string readers. throw new AssertionError ( e ) ; } }
Fix line indention based on brace count .