for (int i = offset; i < endOffset; ++i)
int segmentEnd = txt.offset + txt.count; for (int i = txt.offset; i < segmentEnd; ++i)
  protected void insertUpdate(DefaultDocumentEvent ev, AttributeSet attr)  {    super.insertUpdate(ev, attr);    int offset = ev.getOffset();    int length = ev.getLength();    int endOffset = offset + length;    Segment txt = new Segment();    try      {        getText(offset, length, txt);      }    catch (BadLocationException ex)      {        AssertionError ae = new AssertionError("Unexpected bad location");        ae.initCause(ex);        throw ae;      }    int len = 0;    Vector specs = new Vector();    Element prev = getCharacterElement(offset);    Element next = getCharacterElement(endOffset);    for (int i = offset; i < endOffset; ++i)      {        len++;        if (txt.array[i] == '\n')          {            ElementSpec spec = new ElementSpec(attr, ElementSpec.ContentType,                                               len);            // If we are at the last index, then check if we could probably be            // joined with the next element.            if (i == endOffset - 1)              {                if (next.getAttributes().isEqual(attr))                  spec.setDirection(ElementSpec.JoinNextDirection);              }            // If we are at the first new element, then check if it could be            // joined with the previous element.            else if (specs.size() == 0)              {                if (prev.getAttributes().isEqual(attr))                    spec.setDirection(ElementSpec.JoinPreviousDirection);              }            specs.add(spec);            // Add ElementSpecs for the newline.            ElementSpec endTag = new ElementSpec(null, ElementSpec.EndTagType);            specs.add(endTag);            ElementSpec startTag = new ElementSpec(null,                                                   ElementSpec.StartTagType);            startTag.setDirection(ElementSpec.JoinFractureDirection);            specs.add(startTag);            len = 0;            offset += len;          }      }    // Create last element if last character hasn't been a newline.    if (len > 0)      {        ElementSpec spec = new ElementSpec(attr, ElementSpec.ContentType, len);        // If we are at the first new element, then check if it could be        // joined with the previous element.        if (specs.size() == 0)          {            if (prev.getAttributes().isEqual(attr))              spec.setDirection(ElementSpec.JoinPreviousDirection);          }        // Check if we could probably be joined with the next element.        else if (next.getAttributes().isEqual(attr))          spec.setDirection(ElementSpec.JoinNextDirection);        specs.add(spec);      }    ElementSpec[] elSpecs =      (ElementSpec[]) specs.toArray(new ElementSpec[specs.size()]);    buffer.insert(offset, length, elSpecs, ev);  }  