Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

67 lines
1.8KB

  1. <?php
  2. /**
  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
  6. */
  7. namespace cebe\markdown\block;
  8. /**
  9. * Adds the 4 space indented code blocks
  10. */
  11. trait CodeTrait
  12. {
  13. /**
  14. * identify a line as the beginning of a code block.
  15. */
  16. protected function identifyCode($line)
  17. {
  18. // indentation >= 4 or one tab is code
  19. return ($l = $line[0]) === ' ' && $line[1] === ' ' && $line[2] === ' ' && $line[3] === ' ' || $l === "\t";
  20. }
  21. /**
  22. * Consume lines for a code block element
  23. */
  24. protected function consumeCode($lines, $current)
  25. {
  26. // consume until newline
  27. $content = [];
  28. for ($i = $current, $count = count($lines); $i < $count; $i++) {
  29. $line = $lines[$i];
  30. // a line is considered to belong to this code block as long as it is intended by 4 spaces or a tab
  31. if (isset($line[0]) && ($line[0] === "\t" || strncmp($lines[$i], ' ', 4) === 0)) {
  32. $line = $line[0] === "\t" ? substr($line, 1) : substr($line, 4);
  33. $content[] = $line;
  34. // but also if it is empty and the next line is intended by 4 spaces or a tab
  35. } elseif ((empty($line) || rtrim($line) === '') && isset($lines[$i + 1][0]) &&
  36. ($lines[$i + 1][0] === "\t" || strncmp($lines[$i + 1], ' ', 4) === 0)) {
  37. if (!empty($line)) {
  38. $line = $line[0] === "\t" ? substr($line, 1) : substr($line, 4);
  39. }
  40. $content[] = $line;
  41. } else {
  42. break;
  43. }
  44. }
  45. $block = [
  46. 'code',
  47. 'content' => implode("\n", $content),
  48. ];
  49. return [$block, --$i];
  50. }
  51. /**
  52. * Renders a code block
  53. */
  54. protected function renderCode($block)
  55. {
  56. $class = isset($block['language']) ? ' class="language-' . $block['language'] . '"' : '';
  57. return "<pre><code$class>" . htmlspecialchars($block['content'] . "\n", ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8') . "</code></pre>\n";
  58. }
  59. }