Exemplo n.º 1
0
 /**
  * Create a new markua converter instance.
  */
 public function __construct()
 {
     $environment = new Environment();
     $environment->addExtension(new MarkuaExtension());
     $this->docParser = new DocParser($environment);
     $this->htmlRenderer = new HtmlRenderer($environment);
 }
Exemplo n.º 2
0
 /**
  * @param ContextInterface    $context
  * @param InlineParserContext $inlineContext
  *
  * @return bool
  */
 public function parse(ContextInterface $context, InlineParserContext $inlineContext)
 {
     $cursor = $inlineContext->getCursor();
     $startPos = $cursor->getPosition();
     $previousState = $cursor->saveState();
     // Look through stack of delimiters for a [ or !
     $opener = $inlineContext->getDelimiterStack()->searchByCharacter(['[', '!']);
     if ($opener === null) {
         return false;
     }
     if (!$opener->isActive()) {
         // no matched opener; remove from emphasis stack
         $inlineContext->getDelimiterStack()->removeDelimiter($opener);
         return false;
     }
     $isImage = $opener->getChar() === '!';
     // Instead of copying a slice, we null out the parts of inlines that don't correspond to linkText; later, we'll
     // collapse them. This is awkward, and could  be simplified if we made inlines a linked list instead
     $inlines = $inlineContext->getInlines();
     $labelInlines = new ArrayCollection($inlines->toArray());
     $this->nullify($labelInlines, 0, $opener->getPos() + 1);
     $cursor->advance();
     // Check to see if we have a link/image
     if (!($link = $this->tryParseLink($cursor, $context->getDocument()->getReferenceMap(), $opener, $startPos))) {
         // No match
         $inlineContext->getDelimiterStack()->removeDelimiter($opener);
         // Remove this opener from stack
         $cursor->restoreState($previousState);
         return false;
     }
     $delimiterStack = $inlineContext->getDelimiterStack();
     $stackBottom = $opener->getPrevious();
     foreach ($this->environment->getInlineProcessors() as $inlineProcessor) {
         $inlineProcessor->processInlines($labelInlines, $delimiterStack, $stackBottom);
     }
     if ($delimiterStack instanceof DelimiterStack) {
         $delimiterStack->removeAll($stackBottom);
     }
     // Remove the part of inlines that become link_text
     $this->nullify($inlines, $opener->getPos(), $inlines->count());
     // processEmphasis will remove this and later delimiters.
     // Now, for a link, we also remove earlier link openers (no links in links)
     if (!$isImage) {
         $inlineContext->getDelimiterStack()->removeEarlierMatches('[');
     }
     $inlines->add($this->createInline($link['url'], $labelInlines, $link['title'], $isImage));
     return true;
 }
Exemplo n.º 3
0
 /**
  * Create and return a CommonMark environment
  *
  * @return Environment CommonMark environment
  */
 protected function environment()
 {
     // Obtain a pre-configured Environment with all the CommonMark parsers/renderers ready-to-go
     $environment = Environment::createCommonMarkEnvironment();
     // Custom environment initialization
     return $this->initializeEnvironment($environment);
 }
Exemplo n.º 4
0
 /**
  * @param string $markdown
  * @param string $expected
  * @dataProvider e2eProvider
  */
 public function testFullRender($markdown, $expected)
 {
     $factory = new CliRendererFactory();
     $renderer = $factory->__invoke();
     $parser = new DocParser(Environment::createCommonMarkEnvironment());
     $this->assertEquals($expected, $renderer->renderBlock($parser->parse($markdown)));
 }
Exemplo n.º 5
0
 public function testExerciseRendererSetsCurrentExerciseAndRendersExercise()
 {
     $menu = $this->getMockBuilder(CliMenu::class)->disableOriginalConstructor()->getMock();
     $item = $this->getMock(MenuItemInterface::class);
     $item->expects($this->any())->method('getText')->will($this->returnValue('Exercise 2'));
     $menu->expects($this->once())->method('getSelectedItem')->will($this->returnValue($item));
     $menu->expects($this->once())->method('close');
     $exercise1 = $this->getMock(ExerciseInterface::class);
     $exercise2 = $this->getMock(ExerciseInterface::class);
     $exercises = [$exercise1, $exercise2];
     $exerciseRepository = $this->getMockBuilder(ExerciseRepository::class)->disableOriginalConstructor()->getMock();
     $userState = $this->getMock(UserState::class);
     $userStateSerializer = $this->getMockBuilder(UserStateSerializer::class)->disableOriginalConstructor()->getMock();
     $exerciseRepository->expects($this->once())->method('findByName')->with('Exercise 2')->will($this->returnValue($exercise2));
     $exerciseRepository->expects($this->once())->method('findAll')->will($this->returnValue($exercises));
     $userState->expects($this->once())->method('setCurrentExercise')->with('Exercise 2');
     $userStateSerializer->expects($this->once())->method('serialize')->with($userState);
     $problemFile = sprintf('%s/%s/problem.md', sys_get_temp_dir(), $this->getName());
     $exercise2->expects($this->once())->method('getProblem')->will($this->returnValue($problemFile));
     if (!is_dir(dirname($problemFile))) {
         mkdir(dirname($problemFile), 0775, true);
     }
     file_put_contents($problemFile, '### Exercise Content');
     $markdownRenderer = new MarkdownRenderer(new DocParser(Environment::createCommonMarkEnvironment()), (new CliRendererFactory())->__invoke());
     $color = new Color();
     $color->setForceStyle(true);
     $exerciseRenderer = new ExerciseRenderer('phpschool', $exerciseRepository, $userState, $userStateSerializer, $markdownRenderer, $color, new StdOutput($color, $this->getMock(TerminalInterface::class)));
     $this->expectOutputString(file_get_contents(__DIR__ . '/res/exercise-help-expected.txt'));
     $exerciseRenderer->__invoke($menu);
     unlink($problemFile);
 }
Exemplo n.º 6
0
 public function setCommonMarkEnvironment(Environment $environment = null)
 {
     if (is_null($environment)) {
         $environment = Environment::createCommonMarkEnvironment();
     }
     $this->_cmEnvironment = $environment;
 }
Exemplo n.º 7
0
 /**
  * @param AbstractBlock $block
  * @param bool          $inTightList
  *
  * @throws \RuntimeException
  *
  * @return string
  */
 public function renderBlock(AbstractBlock $block, $inTightList = false)
 {
     $renderer = $this->environment->getBlockRendererForClass(get_class($block));
     if (!$renderer) {
         throw new \RuntimeException('Unable to find corresponding renderer for block type ' . get_class($block));
     }
     return $renderer->render($block, $this, $inTightList);
 }
Exemplo n.º 8
0
 public function setUp()
 {
     $environment = Environment::createCommonMarkEnvironment();
     $environment->addInlineParser(new MentionParser());
     $parser = new DocParser($environment);
     $renderer = new HtmlRenderer($environment);
     $this->service = new CommonMarkParser($environment, $parser, $renderer);
 }
Exemplo n.º 9
0
 /**
  * @param InlineParserContext $inlineContext
  *
  * @return bool
  */
 public function parse(InlineParserContext $inlineContext)
 {
     $cursor = $inlineContext->getCursor();
     $startPos = $cursor->getPosition();
     $previousState = $cursor->saveState();
     // Look through stack of delimiters for a [ or !
     $opener = $inlineContext->getDelimiterStack()->searchByCharacter(['[', '!']);
     if ($opener === null) {
         return false;
     }
     if (!$opener->isActive()) {
         // no matched opener; remove from emphasis stack
         $inlineContext->getDelimiterStack()->removeDelimiter($opener);
         return false;
     }
     $isImage = $opener->getChar() === '!';
     $cursor->advance();
     // Check to see if we have a link/image
     if (!($link = $this->tryParseLink($cursor, $inlineContext->getReferenceMap(), $opener, $startPos))) {
         // No match
         $inlineContext->getDelimiterStack()->removeDelimiter($opener);
         // Remove this opener from stack
         $cursor->restoreState($previousState);
         return false;
     }
     $inline = $this->createInline($link['url'], $link['title'], $isImage);
     $opener->getInlineNode()->replaceWith($inline);
     while (($label = $inline->next()) !== null) {
         $inline->appendChild($label);
     }
     $delimiterStack = $inlineContext->getDelimiterStack();
     $stackBottom = $opener->getPrevious();
     foreach ($this->environment->getInlineProcessors() as $inlineProcessor) {
         $inlineProcessor->processInlines($delimiterStack, $stackBottom);
     }
     if ($delimiterStack instanceof DelimiterStack) {
         $delimiterStack->removeAll($stackBottom);
     }
     // processEmphasis will remove this and later delimiters.
     // Now, for a link, we also remove earlier link openers (no links in links)
     if (!$isImage) {
         $inlineContext->getDelimiterStack()->removeEarlierMatches('[');
     }
     return true;
 }
Exemplo n.º 10
0
 public function testRender()
 {
     $docParser = new DocParser(Environment::createCommonMarkEnvironment());
     $cliRenderer = (new CliRendererFactory())->__invoke();
     $renderer = new MarkdownRenderer($docParser, $cliRenderer);
     $markdown = "### HONEY BADGER DON'T CARE";
     $expected = "\n### HONEY BADGER DON'T CARE\n\n";
     $this->assertSame($expected, $renderer->render($markdown));
 }
Exemplo n.º 11
0
 public function getArticle($uri)
 {
     $environment = Environment::createCommonMarkEnvironment();
     $environment->addExtension(new TableExtension());
     $converter = new Converter(new DocParser($environment), new HtmlRenderer($environment));
     $contents = \Storage::get($uri . '.md');
     preg_match('/^.*$/m', $contents, $matches);
     return view('portal', array('body' => $converter->convertToHtml($contents), 'title' => substr($matches[0], 2)));
 }
Exemplo n.º 12
0
 private function incorporateLine(ContextInterface $context)
 {
     $cursor = new Cursor($context->getLine());
     $context->getBlockCloser()->resetTip();
     $context->setBlocksParsed(false);
     $context->setContainer($context->getDocument());
     while ($context->getContainer()->hasChildren()) {
         $lastChild = $context->getContainer()->getLastChild();
         if (!$lastChild->isOpen()) {
             break;
         }
         $context->setContainer($lastChild);
         if (!$context->getContainer()->matchesNextLine($cursor)) {
             $context->setContainer($context->getContainer()->getParent());
             // back up to the last matching block
             break;
         }
     }
     $context->getBlockCloser()->setLastMatchedContainer($context->getContainer());
     // Check to see if we've hit 2nd blank line; if so break out of list:
     if ($cursor->isBlank() && $context->getContainer()->endsWithBlankLine()) {
         $this->breakOutOfLists($context, $context->getContainer());
     }
     while (!$context->getContainer()->isCode() && !$context->getBlocksParsed()) {
         $parsed = false;
         foreach ($this->environment->getBlockParsers() as $parser) {
             if ($parser->parse($context, $cursor)) {
                 $parsed = true;
                 break;
             }
         }
         if (!$parsed || $context->getContainer()->acceptsLines()) {
             $context->setBlocksParsed(true);
         }
     }
     // What remains at the offset is a text line.  Add the text to the appropriate container.
     // First check for a lazy paragraph continuation:
     if (!$context->getBlockCloser()->areAllClosed() && !$cursor->isBlank() && $context->getTip() instanceof Paragraph && count($context->getTip()->getStrings()) > 0) {
         // lazy paragraph continuation
         $context->getTip()->addLine($cursor->getRemainder());
     } else {
         // not a lazy continuation
         // finalize any blocks not matched
         $context->getBlockCloser()->closeUnmatchedBlocks();
         // Determine whether the last line is blank, updating parents as needed
         $context->getContainer()->setLastLineBlank($cursor, $context->getLineNumber());
         // Handle any remaining cursor contents
         if ($context->getContainer()->isOpen()) {
             $context->getContainer()->handleRemainingContents($context, $cursor);
         } elseif (!$cursor->isBlank()) {
             // Create paragraph container for line
             $context->addBlock(new Paragraph());
             $cursor->advanceToFirstNonSpace();
             $context->getTip()->addLine($cursor->getRemainder());
         }
     }
 }
Exemplo n.º 13
0
 /**
  * Convert body to html
  */
 public function markdown($description)
 {
     $environment = Environment::createCommonMarkEnvironment();
     $parser = new DocParser($environment);
     $htmlRenderer = new HtmlRenderer($environment);
     $markdown = $this->description;
     $documentAST = $parser->parse($markdown);
     return $htmlRenderer->renderBlock($documentAST);
 }
Exemplo n.º 14
0
 private function parseCode($string)
 {
     $environment = Environment::createCommonMarkEnvironment();
     $environment->addInlineParser(new MentionParser());
     $parser = new DocParser($environment);
     $renderer = new HtmlRenderer($environment);
     $this->service = new CommonMarkParser($environment, $parser, $renderer);
     return $this->service->render($string);
 }
Exemplo n.º 15
0
 /**
  * Creates a new article object from its values.
  */
 public function __construct(array $metatdata, string $text, string $slug)
 {
     $this->metatdata = $metatdata;
     $this->date = new Carbon($this->metatdata['date'] ?? 'now');
     $this->slug = $slug;
     // Parse the Markdown document.
     $environment = Environment::createCommonMarkEnvironment();
     $parser = new DocParser($environment);
     $this->renderer = new HtmlRenderer($environment);
     $this->document = $parser->parse($text);
 }
 protected function newCommonMarkConverter(RootConfig $config)
 {
     $environment = Environment::createCommonMarkEnvironment();
     foreach ($config->getCommonMarkExtensions() as $extension) {
         if (!class_exists($extension)) {
             throw new \RuntimeException(sprintf('CommonMark extension class "%s" does not exists. You must use a FCQN!', $extension));
         }
         $environment->addExtension(new $extension());
     }
     return new \League\CommonMark\Converter(new DocParser($environment), new HtmlRenderer($environment));
 }
Exemplo n.º 17
0
 public function toHtml($content)
 {
     $environment = \League\CommonMark\Environment::createCommonMarkEnvironment();
     $environment->mergeConfig([]);
     $environment->addExtension(new \Webuni\CommonMark\TableExtension\TableExtension());
     $converter = new \League\CommonMark\Converter(new \League\CommonMark\DocParser($environment), new \League\CommonMark\HtmlRenderer($environment));
     $content = $converter->convertToHtml($content);
     // strip comment marks
     $markdownContent = preg_replace("/\n\\-\\-[\\ ]*/s", "\n", $content);
     return $markdownContent;
 }
Exemplo n.º 18
0
 public function htmlIntroduction($before = '', $after = '')
 {
     $introduction = trim($this->introduction);
     if (empty($introduction)) {
         return;
     }
     $environment = Environment::createCommonMarkEnvironment();
     $parser = new DocParser($environment);
     $htmlRenderer = new HtmlRenderer($environment);
     $text = $parser->parse($introduction);
     return $before . $htmlRenderer->renderBlock($text) . $after;
 }
Exemplo n.º 19
0
 /**
  * @param string $string
  * @param string $expected
  * @return void
  *
  * @dataProvider dataForIntegrationTest
  */
 public function testStrikethrough($string, $expected)
 {
     $environment = Environment::createCommonMarkEnvironment();
     $environment->addInlineParser(new StrikethroughParser());
     $environment->addInlineRenderer('CommonMarkExt\\Strikethrough\\Strikethrough', new StrikethroughRenderer());
     $parser = new DocParser($environment);
     $renderer = new HtmlRenderer($environment);
     $document = $parser->parse($string);
     $html = $renderer->renderBlock($document);
     //
     //        $converter = new CommonMarkConverter($environment->getConfig());
     //        $html = $converter->convertToHtml($string);
     $this->assertSame($expected, $html);
 }
Exemplo n.º 20
0
 /**
  * Returns rendered view
  *
  * @return string
  */
 public function render()
 {
     if ($this->isMarkdown()) {
         $environment = Environment::createCommonMarkEnvironment();
         $environment->addInlineParser(new TwitterHandleParser());
         $parser = new DocParser($environment);
         $htmlRenderer = new HtmlRenderer($environment);
         $document = $parser->parse(file_get_contents($this->filename));
         return $htmlRenderer->renderBlock($document);
     }
     ob_start();
     extract($this->vars);
     require $this->filename;
     return ob_get_clean();
 }
Exemplo n.º 21
0
 /**
  * Register the environment class.
  *
  * @return void
  */
 protected function registerEnvironment()
 {
     $this->app->singleton('markdown.environment', function (Container $app) {
         $environment = Environment::createCommonMarkEnvironment();
         $environment->addExtension(new TableExtension());
         $environment->addExtension(new AttributesExtension());
         $config = $app->config->get('markdown');
         $environment->mergeConfig(array_except($config, ['extensions', 'views']));
         foreach ((array) array_get($config, 'extensions') as $extension) {
             $environment->addExtension($app->make($extension));
         }
         return $environment;
     });
     $this->app->alias('markdown.environment', Environment::class);
 }
Exemplo n.º 22
0
 /**
  * Parse blocks
  *
  * @param ContextInterface $context
  * @param Cursor           $cursor
  */
 private function parseBlocks(ContextInterface $context, Cursor $cursor)
 {
     while (!$context->getContainer()->isCode() && !$context->getBlocksParsed()) {
         $parsed = false;
         foreach ($this->environment->getBlockParsers() as $parser) {
             if ($parser->parse($context, $cursor)) {
                 $parsed = true;
                 break;
             }
         }
         if (!$parsed || $context->getContainer()->acceptsLines()) {
             $context->setBlocksParsed(true);
         }
     }
 }
Exemplo n.º 23
0
 public function transform($markdownText)
 {
     $environment = Environment::createCommonMarkEnvironment();
     $beforeParseEvent = Croogo::dispatchEvent('Helper.Markdown.beforeMarkdownParse', $this->_View, array('environment' => $environment, 'markdown' => $markdownText));
     $markdownText = $beforeParseEvent->data['markdown'];
     $environment = $beforeParseEvent->data['environment'];
     $parser = new DocParser($environment);
     $htmlRenderer = new HtmlRenderer($environment);
     $documentAST = $parser->parse($markdownText);
     $beforeRenderEvent = Croogo::dispatchEvent('Helper.Markdown.beforeMarkdownRender', $this->_View, array('ast' => $documentAST));
     $documentAST = $beforeRenderEvent->data['ast'];
     $rendered = $htmlRenderer->renderBlock($documentAST);
     $afterRenderEvent = Croogo::dispatchEvent('Helper.Markdown.afterMarkdownRender', $this->_View, array('rendered' => $rendered));
     return $afterRenderEvent->data['rendered'];
 }
 /**
  * Register the CommonMark Environment.
  *
  * @return void
  */
 protected function registerMarkdownEnvironment()
 {
     $app = $this->app;
     $app->singleton('commonmark.environment', function ($app) {
         $config = $app['config']['markdown'];
         $environment = Environment::createCommonMarkEnvironment();
         if ($config['configurations']) {
             $environment->mergeConfig($config['configurations']);
         }
         foreach ($config['extensions'] as $extension) {
             if (class_exists($extension)) {
                 $environment->addExtension(new $extension());
             }
         }
         return $environment;
     });
     $app->alias('commonmark.environment', Environment::class);
 }
Exemplo n.º 25
0
 public function init()
 {
     $this->markdown = new CommonMarkConverter(apply_filters('cws_markdown_config', []), apply_filters('cws_markdown_environment', Environment::createCommonMarkEnvironment()));
     load_plugin_textdomain('markdown-on-save', NULL, basename(dirname(__FILE__)));
     add_filter('wp_insert_post_data', array($this, 'wp_insert_post_data'), 10, 2);
     // add_action( 'do_meta_boxes', array( $this, 'do_meta_boxes' ), 20, 2 );
     add_action('post_submitbox_misc_actions', array($this, 'submitbox_actions'));
     add_filter('edit_post_content', array($this, 'edit_post_content'), 10, 2);
     add_filter('edit_post_content_filtered', array($this, 'edit_post_content_filtered'), 10, 2);
     add_action('load-post.php', array($this, 'load'));
     add_action('load-post.php', array($this, 'enqueue'));
     add_action('load-post-new.php', array($this, 'enqueue'));
     add_action('xmlrpc_call', array($this, 'xmlrpc_actions'));
     add_action('init', array($this, 'maybe_remove_kses'), 99);
     add_action('set_current_user', array($this, 'maybe_remove_kses'), 99);
     add_action('wp_insert_post', array($this, 'wp_insert_post'));
     add_action('wp_restore_post_revision', array($this, 'wp_restore_post_revision'), 10, 2);
     add_filter('_wp_post_revision_fields', array($this, '_wp_post_revision_fields'));
 }
 /**
  * {@inheritdoc}
  */
 public function __construct(array $config = [])
 {
     parent::__construct($config);
     $this->addExtension(new CommonMarkCoreExtension());
     $this->mergeConfig(['renderer' => ['block_separator' => "\n", 'inner_separator' => "\n", 'soft_break' => "\n"]]);
     $filter = $this->config->getConfig('filter');
     // Iterate over each hook defined extension and add it to the environment.
     foreach (commonmark_get_extensions($filter) as $extension) {
         try {
             $class = new \ReflectionClass($extension['class']);
             $args = $extension['class arguments'];
             if ($extension['class arguments callback'] && is_callable($extension['class arguments callback'])) {
                 $args = call_user_func_array($extension['class arguments callback'], [$extension, $this]);
             }
             // Instantiate the extension.
             $extension_instance = $class->newInstanceArgs($args);
             // If this is a Drupal\CommonMark\Extension, load in the settings.
             if (in_array('Drupal\\CommonMark\\ExtensionInterface', class_implements($extension['class']))) {
                 // Set the extension's default settings.
                 $extension_instance->setSettings($extension['default settings']);
                 // Set the extension's current settings.
                 $extension_instance->setSettings($extension['settings']);
             }
             // Replace the placeholder for the extension instance in the method
             // arguments with the real class instance.
             $method_args = $extension['method arguments'];
             $index = array_search(self::EXTENSION_INSTANCE_PLACEHOLDER, $method_args, TRUE);
             if ($index !== FALSE) {
                 $method_args[$index] = $extension_instance;
             } else {
                 $method_args[] = $extension_instance;
             }
             // Actually add the extension to the environment.
             call_user_func_array([$this, $extension['method']], $method_args);
         } catch (\Exception $e) {
             watchdog('commonmark', $e->getMessage());
         }
     }
 }
Exemplo n.º 27
0
 private function createEnvironment()
 {
     $this->environment = Environment::createCommonMarkEnvironment();
     $this->addInlineRenderers();
 }
Exemplo n.º 28
0
 /**
  * Register the environment class.
  *
  * @param \Illuminate\Contracts\Foundation\Application $app
  *
  * @return void
  */
 protected function registerEnvironment(Application $app)
 {
     $app->singleton('markdown.environment', function ($app) {
         return Environment::createCommonMarkEnvironment();
     });
     $app->alias('markdown.environment', Environment::class);
 }
Exemplo n.º 29
0
 public function setEnvironment(Environment $environment)
 {
     $this->config->mergeConfig($environment->getConfig());
 }
Exemplo n.º 30
0
 /**
  * Create a new instance of commonMark with some custom parser rules
  * 
  * @param  string $mediaRoot
  * @return \League\CommonMark\Environment
  */
 protected function initializeCommonMark($mediaRoot)
 {
     $environment = Environment::createCommonMarkEnvironment();
     $environment->addInlineParser(new MediaParser($mediaRoot));
     return $environment;
 }