From 46a390d6759065271b2158537691a53679c58989 Mon Sep 17 00:00:00 2001 From: Martin Fischer Date: Sat, 3 Dec 2022 07:07:55 +0100 Subject: allow code display to be customized via Scribunto --- Code.php | 41 ++++++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 11 deletions(-) (limited to 'Code.php') diff --git a/Code.php b/Code.php index 0243e6f..045448e 100644 --- a/Code.php +++ b/Code.php @@ -4,10 +4,12 @@ namespace MediaWiki\Extension\Code; use Content; use ErrorPageError; use ExtensionRegistry; +use FatalError; use Html; use MediaWiki\Content\Renderer\ContentParseParams; use MediaWiki\MediaWikiServices; use Parser; +use ParserOptions; use ParserOutput; use Sanitizer; use SpecialPage; @@ -70,15 +72,6 @@ function renderCode( string $code, $lang, $outputPage, ?array $tagAttrs = null ) $codeBlock = pre( $code, $tagAttrs ); } - foreach ( $lang['linkifiers'] as $regex => $href ) { - $codeBlock = preg_replace_callback( $regex, fn( $match ) => - Xml::element( 'a', [ - 'href' => str_replace( '$1', $match[0], $href ), - 'tabindex' => -1 - ], $match[0] ), - $codeBlock ); - } - $actions = ''; foreach ( $lang['actions'] as $action => $url ) { @@ -96,7 +89,34 @@ function renderCode( string $code, $lang, $outputPage, ?array $tagAttrs = null ) $actions .= Xml::closeElement( 'a' ) . ' '; } - return $codeBlock . $actions; + $additionalOutput = ''; + + $scribuntoModule = $lang['scribuntoModule'] ?? null; + if ( $scribuntoModule && ExtensionRegistry::getInstance()->isLoaded( 'Scribunto' ) ) { + $callFunction = static function ( Parser $parser, string $function, array $extraArgs = [] ) use ( $scribuntoModule, $code, $lang, $tagAttrs ) { + $args = [ $scribuntoModule, $function, $code, $lang['tag'], $tagAttrs == null ]; + $args = array_merge( $args, $extraArgs ); + if ( $tagAttrs ) { + $args = array_merge( $args, $tagAttrs ); + } + $frame = $parser->getPreprocessor()->newFrame(); + $res = $parser->callParserFunction( $frame, '#invoke', $args ); + if ( !$res['found'] ) { + throw new FatalError( "unexpected condition in Code extension: the Scribunto module is loaded but the #invoke parser function wasn't found" ); + } + return Sanitizer::removeSomeTags( $res['text'], [ 'extraTags' => [ 'a' ], 'extra' ] ); + }; + if ( $tagAttrs ) { + $parser = MediaWikiServices::getInstance()->getParser(); + } else { + $parser = MediaWikiServices::getInstance()->getParserFactory()->create(); + $parser->startExternalParse( null, ParserOptions::newFromAnon(), Parser::OT_HTML ); + } + $codeBlock = $callFunction( $parser, 'formatCode', [ $codeBlock ] ); + $additionalOutput = $callFunction( $parser, 'additionalOutput' ); + } + + return $codeBlock . $actions . $additionalOutput; } class ContentHandler extends TextContentHandler { @@ -118,7 +138,6 @@ class ContentHandler extends TextContentHandler { $lang = [ 'pygmentsLexer' => 'text', 'actions' => [], - 'linkifiers' => [], ]; } $out .= renderCode( $content->getText(), $lang, $output ); -- cgit v1.2.3