def parse(self, message): """Given a string of text in the original CIA commit format, return a <colorText> element representing it as a DOM tree. """ # Initialize our model of the current text format in the original message self.parsedState = ColorState() self.document = XML.createRootNode() # Initialize our stack of (element, ColorState) tuples representing # the state of the XML document being generated. This starts out with # our root element in it. self.elementStack = [ (XML.addElement(self.document, "colorText"), ColorState()) ] # Break up the message into lines, each with its whitespace stripped. # Run our lexical scanner on each line separately, turning it into # a stream of events. Insert <br/> tags between lines. lines = [] for line in message.split("\n"): # Ignore extra whitespace line = line.strip() # Ignore blank lines if line: lines.append(line) for i in xrange(len(lines)): if i != 0: XML.addElement(self.elementStack[-1][0], 'br') self.lex(lines[i]) self.closeTags() return self.document
def pushTag(self, name, attributes={}, stateChanges={}): """Add a new element to the elementStack, placed at the end of the children list for the tag currently at the top of the stack. name: The name of the new element attributes: A dict of attributes to set on the new element stateChanges: A dict of attributes to change in the new tag's state """ oldTag, oldState = self.elementStack[-1] newTag = XML.addElement(self.elementStack[-1][0], name) for key, value in attributes.iteritems(): newTag.setAttributeNS(None, key, value) newState = copy.deepcopy(oldState) newState.__dict__.update(stateChanges) self.elementStack.append((newTag, newState))