/* * [CollapseBlankLines.java] * * Summary: Collapse multiple blank lines to one. * * Copyright: (c) 2002-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 4.5 2009-02-26 add both Java string quoting and plain for Java search/regexes. */ package com.mindprod.quoter; /** * Collapse multiple blank lines to one. * * @author Roedy Green, Canadian Mind Products * @version 4.5 2009-02-26 add both Java string quoting and plain for Java search/regexes. * @since 2002-06-19 */ final class CollapseBlankLines extends TextProcessor { /** * Collapse runs of blank lines to a single blank line. Leave leading and trailing spaces on each line as is. * * @param raw String to process, may contain embedded \ns. * * @return String with blank lines collapsed. */ String process( String raw ) { if ( raw == null ) { return null; } char[] ca = new char[ raw.length() ]; int j = 0; // true if next blank line should be suppressed boolean suppressBlankLines = false; // true if we are in the leading spaces of a line boolean inLeading = true; // count of how many spaces we recently suppressed int spacesSuppressed = 0; for ( int i = 0; i < raw.length(); i++ ) { char c = raw.charAt( i ); switch ( c ) { case '\t': case ' ': spacesSuppressed++; break; case '\n': if ( inLeading ) { // end of blank line if ( suppressBlankLines ) { spacesSuppressed = 0; } else { // We may have suppressed some trailing spaces we // should // not have. // put them back. for ( ; spacesSuppressed > 0; spacesSuppressed-- ) { ca[ j++ ] = ' '; } ca[ j++ ] = c; suppressBlankLines = true; } } else { // end end of normal line // We may have suppressed some trailing spaces we should // not // have. // put them back. for ( ; spacesSuppressed > 0; spacesSuppressed-- ) { ca[ j++ ] = ' '; } ca[ j++ ] = c; suppressBlankLines = false; } // end else inLeading = true; break; default: // ordinary character // We may have suppressed some spaces we should not have. // put them back. for ( ; spacesSuppressed > 0; spacesSuppressed-- ) { ca[ j++ ] = ' '; } ca[ j++ ] = c; inLeading = false; break; } // end switch } // end for // If there was no trailing \n, // we may have suppressed some trailing spaces we should not have. // put them back. if ( !( inLeading && suppressBlankLines ) ) { for ( ; spacesSuppressed > 0; spacesSuppressed-- ) { ca[ j++ ] = ' '; } } if ( j != raw.length() ) { raw = new String( ca, 0/* offset */, j/* count */ ); } return raw; } // end process } // end CollapseBlankLines