Commits

Anonymous committed cb16276

Bugfix for inline patterns. Tables extension ported to ElementTree.

Comments (0)

Files changed (5)

 class LinkPattern (Pattern):
     """ Return a link element from the given match. """
     def handleMatch(self, m):
+
         el = etree.Element("a")
         el.text = m.group(2)
         title = m.group(11)
         href = m.group(9)
+
         if href:
             if href[0] == "<":
                 href = href[1:-1]
             data, matched, startIndex = self._applyInline(
                                              self.inlinePatterns[patternIndex],
                                              data, patternIndex, startIndex)
+            
             if not matched:
                 patternIndex += 1
+
         return data
     
     def _applyInline(self, pattern, data, patternIndex, startIndex=0):
         result = []
         prefix = self.inlineStash.prefix
         strartIndex = 0
+    
         while data:
             
             index = data.find(prefix, strartIndex)
                         linkText(text)
           
                     if not isstr(node): # it's Element
-
+                        
                         for child in [node] + node.getchildren():
             
                             if child.tail:
-                                self._processElementText(node, child, False)
+                                if child.tail.strip():
+                                    self._processElementText(node, child, False)
                             
                             if child.text:
-                                self._processElementText(child, child)
-                                
+                                if child.text.strip():
+                                    self._processElementText(child, child)
+                        
                     else: # it's just a string
                 
                         linkText(node)
         """
 
         stack = [el]
+
         while stack:
             currElement = stack.pop()
             insertQueue = []
             for child in currElement.getchildren():
                 
                 if child.tag == "inline":
-                    
+
                     lst = self._processPlaceholders(self._handleInline(
                                                     child.text), currElement)
-   
+                    stack += lst
+                    
                     pos = currElement.getchildren().index(child)
                     
                     insertQueue.append((child, pos, lst))
 """
 
 import markdown
-
+from markdown import etree
 
 class TablePattern(markdown.Pattern) :
-	def __init__ (self, md):
-		markdown.Pattern.__init__(self, r'^\|([^\n]*)\|(\n|$)')
-		self.md = md
+    def __init__ (self, md):
+        markdown.Pattern.__init__(self, r'(^|\n)\|([^\n]*)\|')
+        self.md = md
 
-	def handleMatch(self, m, doc) :
-		# a single line represents a row
-		tr = doc.createElement('tr')
-		tr.appendChild(doc.createTextNode('\n'))
-		# chunks between pipes represent cells
-		for t in m.group(2).split('|'):
-			if len(t) >= 2 and t.startswith('*') and t.endswith('*'):
-				# if a cell is bounded by asterisks, it is a <th>
-				td = doc.createElement('th')
-				t = t[1:-1]
-			else:
-				# otherwise it is a <td>
-				td = doc.createElement('td')
-			# apply inline patterns on chunks
-			for n in self.md._handleInline(t):
-				if(type(n) == unicode):
-					td.appendChild(doc.createTextNode(n))
-				else:
-					td.appendChild(n)
-			tr.appendChild(td)
-			# very long lines are evil
-			tr.appendChild(doc.createTextNode('\n'))
-		return tr
+    def handleMatch(self, m):
+
+        # a single line represents a row
+        tr = etree.Element('tr')
+        
+        # chunks between pipes represent cells
+
+        for t in m.group(3).split('|'): 
+     
+            if len(t) >= 2 and t.startswith('*') and t.endswith('*'):
+                # if a cell is bounded by asterisks, it is a <th>
+                td = etree.Element('th')
+                t = t[1:-1]
+            else:
+                # otherwise it is a <td>
+                td = etree.Element('td')
+            
+            # apply inline patterns on chunks
+            '''for n in self.md._handleInline(t):
+                if(type(n) == unicode):
+                    td.text = n
+                else:
+                    td.appendChild(n)'''
+            inline = etree.SubElement(td, "inline")
+            inline.text = t
+                    
+            tr.append(td)
+            tr.tail = "\n"
+ 
+        #print etree.tostring(tr)
+        return tr
 
 
 class TablePostprocessor:
-	def run(self, doc):
-		# markdown wrapped our <tr>s in a <p>, we fix that here
-		def test_for_p(element):
-			return element.type == 'element' and element.nodeName == 'p'
-		# replace "p > tr" with "table > tr"
-		for element in doc.find(test_for_p):
-			for node in element.childNodes:
-				if(node.type == 'text' and node.value.strip() == ''):
-					# skip leading whitespace
-					continue
-				if (node.type == 'element' and node.nodeName == 'tr'):
-					element.nodeName = 'table'
-				break
+    
+    def _findElement(self, element, name):
+        result = []
+        for child in element:
+            if child.tag == name:
+                result.append(child)
+            result += self._findElement(child, name)
+        return result
+    
+    def run(self, root):
+
+        for element in self._findElement(root, "p"):
+             for child in element:
+                 if child.tail:
+                     element.tag = "table"
+                     break
+        
+                
 
 
 class TableExtension(markdown.Extension):
-	def extendMarkdown(self, md, md_globals):
-		md.inlinePatterns.insert(0, TablePattern(md))
-		md.postprocessors.append(TablePostprocessor())
+    def extendMarkdown(self, md, md_globals):
+        md.inlinePatterns.insert(0, TablePattern(md))
+        md.postprocessors.append(TablePostprocessor())
 
 
 def makeExtension(configs):
-	return TableExtension(configs)
+    return TableExtension(configs)
 
-
 testDirectory("tests/markdown-test", measure_time=True)
 
 testDirectory("tests/misc", measure_time=True)
-testDirectory("tests/extensions-x-footnotes")
+testDirectory("tests/extensions-x-tables")
+#testDirectory("tests/extensions-x-footnotes")
 #testDirectory("tests/extensions-x-tables")
-# testDirectory("tests/extensions-x-ext1-ext2")
+#testDirectory("tests/extensions-x-ext1-ext2")
 testDirectory("tests/safe_mode", measure_time=True, safe_mode="escape")
+#testDirectory("tests/extensions-x-codehilite")
 
-#testDirectory("tests2/php-markdown-cases-new", measure_time=True)
-#testDirectory("tests2/tm-cases-new", measure_time=True) 

tests/extensions-x-tables/tables.html

-
-<p>Before
-</p>
-<table><tr>
+<p>Before</p>
+<table>
+<tr>
 <td> a </td>
 <th> b </th>
-</tr><tr>
-<td> <a href="#">c</a> </td>
-<td> <em>d</em> </td>
-</tr></table><p>Another
-</p>
-<table><tr>
+</tr>
+<tr>
+<td> 
+<a href="#link">c</a> 
+</td>
+<td> 
+<em>d</em> 
+</td>
+</tr>
+</table>
+<p>Another</p>
+<table>
+<tr>
 <td> a </td>
 <td> b </td>
-</tr><tr>
-<td> <em>a</em> </td>
+</tr>
+<tr>
+<td> 
+<em>a</em> 
+</td>
 <td> b </td>
-</tr><tr>
+</tr>
+<tr>
 <td> a </td>
 <td> b </td>
-</tr><tr>
+</tr>
+<tr>
 <td> a </td>
 <td> b </td>
-</tr><tr>
+</tr>
+<tr>
 <td> c </td>
-<td> <em>d</em> </td>
-</tr></table><p>After
-</p>
+<td> 
+<em>d</em> 
+</td>
+</tr>
+</table>
+<p>After</p>
 
 

tests/extensions-x-tables/tables.txt

 Before
 
 | a |* b *|
-| [c](#) | *d* |
+| [c](#link) | *d* |
 
 Another