private void writeTextCollapseWhiteSpace(final int end, final int depth) throws IOException {
   // sets index to end
   // assert index < end
   boolean lastWasWhiteSpace = false;
   updateNextTag();
   while (index < end) {
     while (nextTag != null && index == nextTag.begin) {
       if (lastWasWhiteSpace) {
         writer.write(' ');
         lastWasWhiteSpace = false;
       }
       writeTag(nextTag, depth, end);
       if (index == end) return;
     }
     final char ch = sourceText.charAt(index++);
     if (Segment.isWhiteSpace(ch)) {
       lastWasWhiteSpace = true;
     } else {
       if (lastWasWhiteSpace) {
         writer.write(' ');
         lastWasWhiteSpace = false;
       }
       writer.write(ch);
     }
   }
   if (lastWasWhiteSpace) writer.write(' ');
 }
 private void writeText(final int end, int depth) throws IOException {
   // sets index to end
   if (index == end) return;
   while (Segment.isWhiteSpace(sourceText.charAt(index)))
     if (++index == end) return; // trim whitespace.
   writeIndent(depth);
   if (collapseWhiteSpace) {
     writeTextCollapseWhiteSpace(end, depth);
   } else {
     writeTextInline(end, depth, false);
   }
   writeFormattingNewLine();
 }
 private void writeSpecifiedTextInline(final CharSequence text, int depth) throws IOException {
   final int textLength = text.length();
   int i = writeSpecifiedLine(text, 0);
   if (i < textLength) {
     final int subsequentLineDepth = depth + 1;
     do {
       while (Segment.isWhiteSpace(text.charAt(i)))
         if (++i >= textLength) return; // trim whitespace.
       writeEssentialNewLine();
       writeIndent(subsequentLineDepth);
       i = writeSpecifiedLine(text, i);
     } while (i < textLength);
   }
 }
 private boolean writeTextInline(
     final int end, int depth, final boolean increaseIndentAfterFirstLineBreak)
     throws IOException {
   // returns true if all text was on one line, otherwise false
   // sets index to end
   // assert index < end
   writeLineKeepWhiteSpace(end, depth);
   if (index == end) return true;
   final int subsequentLineDepth = increaseIndentAfterFirstLineBreak ? depth + 1 : depth;
   do {
     while (Segment.isWhiteSpace(sourceText.charAt(index)))
       if (++index == end) return false; // trim whitespace.
     writeEssentialNewLine(); // essential because we might be inside a tag attribute value.  If
     // new lines in normal text aren't required this method wouldn't
     // have been called.
     writeIndent(subsequentLineDepth);
     writeLineKeepWhiteSpace(end, subsequentLineDepth);
   } while (index < end);
   return false;
 }