java - Jython - how can I merge two LeafElements in a DefaultStyledDocument? -
i'm trying "normalise" defaultstyleddocument subclass, in sense have org.w3c.dom.node.normalize()
: is, merge adjoining text "leaves". in case of defaultstyleddocument these leaves identified merging if 2 adjacent ones have same attributes (or none).
below simple version (we don't check actual attributes: use-case either have plain text, or text 1 possible mark-up style).
def normalise( self ): # recursive function: def normalise_structure( el, depth = 0 ): indent = ' ' * depth start = el.startoffset print( '%s# el %s |%s|' % ( indent, el, self.gettext( start, el.endoffset - start ))) prev_attr_set = none in range( el.elementcount ): subelement = el.getelement( ) normalise_structure( subelement, depth + 1 ) if subelement.leaf: curr_attr_set = subelement.attributes print( '%s # leaf, attribs %s' % ( indent, curr_attr_set, )) # simple version: works if there 1 possible attribute if prev_attr_set , curr_attr_set , prev_attr_set.attributecount == curr_attr_set.attributecount: print( '%s # %s leaf needs merged previous leaf' % ( indent, 'marked-up' if prev_attr_set.attributecount == 1 else 'plain')) attr_set = prev_attr_set.getelement( 0 ) if prev_attr_set.attributecount else none prev_subelement = el.getelement( - 1 ) prev_start = prev_subelement.startoffset curr_end = subelement.endoffset merged_element = javax.swing.text.abstractdocument.leafelement( javax.swing.text.defaultstyleddocument(), el, attr_set, prev_start, curr_end ) el.replace( prev_start, curr_end - prev_start, [ merged_element ] ) prev_attr_set = curr_attr_set else: print( '%s # not leaf...' % ( indent, )) prev_attr_set = none self_el in self.rootelements: normalise_structure( self_el )
when run error:
exception in thread "awt-eventqueue-0" java.lang.arrayindexoutofboundsexception @ java.lang.system.arraycopy(native method) @ javax.swing.text.abstractdocument$branchelement.replace(abstractdocument.java:2290)
i hasten add that, before trying javax.swing.text.defaultstyleddocument()
param 1 in leafelement constructor tried "self
" (i.e. defaultstyleddocument invokes normalise
on line one): same error.
yes, possible do:
abstractdocument.branchelement.replace()
looks this:
public void replace(int offset, int length, element[] elems) ...
turns out "offset" , "length" here refer sub-elements of branchelement (typically leafelements), not offset , length of underlying text in styleddocument.
somebody cleverer me have got earlier. api documentation (java 7) might make bit clearer....
Comments
Post a Comment