3 * @copyright Copyright (c) 2014 Carsten Brandt
4 * @license https://github.com/cebe/markdown/blob/master/LICENSE
5 * @link https://github.com/cebe/markdown#readme
8 namespace cebe\markdown\block;
11 * Adds the table blocks
15 private $_tableCellTag = 'td';
16 private $_tableCellCount = 0;
17 private $_tableCellAlign = [];
20 * identify a line as the beginning of a table block.
22 protected function identifyTable($line, $lines, $current)
24 return strpos($line, '|') !== false && preg_match('~|.*|~', $line) && isset($lines[$current + 1]) && preg_match('~^[\s\|\:-]+$~', $lines[$current + 1]);
28 * Consume lines for a table
30 protected function consumeTable($lines, $current)
32 // consume until newline
39 $beginsWithPipe = $lines[$current][0] === '|';
40 for ($i = $current, $count = count($lines); $i < $count; $i++) {
43 if ($i == $current+1) { // skip second line
44 $cols = explode('|', trim($line, ' |'));
45 foreach($cols as $col) {
48 $block['cols'][] = '';
51 $l = ($col[0] === ':');
52 $r = (substr($col, -1, 1) === ':');
54 $block['cols'][] = 'center';
56 $block['cols'][] = 'left';
58 $block['cols'][] = 'right';
60 $block['cols'][] = '';
66 if (trim($line) === '' || $beginsWithPipe && $line[0] !== '|') {
69 if (substr($line, -2, 2) !== '\\|' || substr($line, -3, 3) === '\\\\|') {
70 $block['rows'][] = trim($line, '| ');
72 $block['rows'][] = ltrim($line, '| ');
76 return [$block, --$i];
80 * render a table block
82 protected function renderTable($block)
85 $this->_tableCellAlign = $block['cols'];
86 $content .= "<thead>\n";
88 foreach($block['rows'] as $row) {
89 $this->_tableCellTag = $first ? 'th' : 'td';
90 $align = empty($this->_tableCellAlign[$this->_tableCellCount]) ? '' : ' align="' . $this->_tableCellAlign[$this->_tableCellCount++] . '"';
91 $tds = "<$this->_tableCellTag$align>" . $this->renderAbsy($this->parseInline($row)) . "</$this->_tableCellTag>"; // TODO move this to the consume step
92 $content .= "<tr>$tds</tr>\n";
94 $content .= "</thead>\n<tbody>\n";
97 $this->_tableCellCount = 0;
99 return "<table>\n$content</tbody>\n</table>\n";
105 protected function parseTd($markdown)
107 if (isset($this->context[1]) && $this->context[1] === 'table') {
108 $align = empty($this->_tableCellAlign[$this->_tableCellCount]) ? '' : ' align="' . $this->_tableCellAlign[$this->_tableCellCount++] . '"';
109 return [['text', "</$this->_tableCellTag><$this->_tableCellTag$align>"], isset($markdown[1]) && $markdown[1] === ' ' ? 2 : 1]; // TODO make a absy node
111 return [['text', $markdown[0]], 1];
114 abstract protected function parseInline($text);
115 abstract protected function renderAbsy($absy);