protected static String formatBlockText ( String content , String languageName , Function2 < String , String , String > blockFormat ) { String replacement = Strings . nullToEmpty ( content ) ; final String [ ] lines = replacement . trim ( ) . split ( "[\n\r]+" ) ; //$NON-NLS-1$ int minIndent = Integer . MAX_VALUE ; final Pattern wpPattern = Pattern . compile ( "^(\\s*)[^\\s]" ) ; //$NON-NLS-1$ for ( int i = lines . length > 1 ? 1 : 0 ; i < lines . length ; ++ i ) { final String line = lines [ i ] ; final Matcher matcher = wpPattern . matcher ( line ) ; if ( matcher . find ( ) ) { final int n = matcher . group ( 1 ) . length ( ) ; if ( n < minIndent ) { minIndent = n ; if ( minIndent <= 0 ) { break ; } } } } final StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( lines [ 0 ] ) ; buffer . append ( "\n" ) ; //$NON-NLS-1$ for ( int i = 1 ; i < lines . length ; ++ i ) { final String line = lines [ i ] ; buffer . append ( line . replaceFirst ( "^\\s{0," + minIndent + "}" , "" ) ) ; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ buffer . append ( "\n" ) ; //$NON-NLS-1$ } replacement = buffer . toString ( ) . replaceFirst ( "[\n\r]+$" , "\n" ) ; //$NON-NLS-1$ //$NON-NLS-2$ if ( ! Strings . isNullOrEmpty ( replacement ) && ! "\n" . equals ( replacement ) ) { //$NON-NLS-1$ if ( blockFormat != null ) { return blockFormat . apply ( languageName , replacement ) ; } return replacement ; } return "" ; //$NON-NLS-1$ }
Format the given text in order to be suitable for being output as a block .