1<?php 2 3namespace dokuwiki\Parsing\ParserMode; 4 5use dokuwiki\Parsing\Handler; 6use dokuwiki\Parsing\Handler\Preformatted as PreformattedHandler; 7 8class Preformatted extends AbstractMode 9{ 10 /** @inheritdoc */ 11 public function getSort() 12 { 13 return 20; 14 } 15 16 /** 17 * Number of leading spaces that trigger a preformatted block. 18 * 19 * DokuWiki's historical value is 2 spaces; Markdown uses 4. When 20 * `$conf['syntax']` is `md` or `md+dw` (Markdown preferred), 21 * we flip to 4 so indented code blocks match GFM. A single tab is 22 * always a trigger regardless of the space threshold. 23 */ 24 protected function getIndentWidth(): int 25 { 26 global $conf; 27 return in_array($conf['syntax'], ['md', 'md+dw'], true) ? 4 : 2; 28 } 29 30 /** @inheritdoc */ 31 public function connectTo($mode) 32 { 33 $indent = str_repeat(' ', $this->getIndentWidth()); 34 35 $this->Lexer->addEntryPattern('\n' . $indent, $mode, 'preformatted'); 36 $this->Lexer->addEntryPattern('\n\t', $mode, 'preformatted'); 37 38 // match continuation lines inside the preformatted block 39 $this->Lexer->addPattern('\n' . $indent, 'preformatted'); 40 $this->Lexer->addPattern('\n\t', 'preformatted'); 41 } 42 43 /** @inheritdoc */ 44 public function postConnect() 45 { 46 $this->Lexer->addExitPattern('\n', 'preformatted'); 47 } 48 49 /** @inheritdoc */ 50 public function handle($match, $state, $pos, Handler $handler) 51 { 52 switch ($state) { 53 case DOKU_LEXER_ENTER: 54 $handler->setCallWriter(new PreformattedHandler($handler->getCallWriter())); 55 $handler->addCall('preformatted_start', [], $pos); 56 break; 57 case DOKU_LEXER_EXIT: 58 $handler->addCall('preformatted_end', [], $pos); 59 /** @var PreformattedHandler $reWriter */ 60 $reWriter = $handler->getCallWriter(); 61 $handler->setCallWriter($reWriter->process()); 62 break; 63 case DOKU_LEXER_MATCHED: 64 $handler->addCall('preformatted_newline', [], $pos); 65 break; 66 case DOKU_LEXER_UNMATCHED: 67 $handler->addCall('preformatted_content', [$match], $pos); 68 break; 69 } 70 71 return true; 72 } 73} 74