Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve styled markup in Code #698

Draft
wants to merge 1 commit into
base: develop
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion syntax-highlighting-code-block.php
Original file line number Diff line number Diff line change
Expand Up @@ -622,9 +622,47 @@ function render_block( $attributes, $content ) {

$language = $attributes['language'];

$content = $matches['content'];
// @todo We need to remove all tags but remember the byte positions, and also we need to do the same for entities.

$token_offets = [];

$token_regexps = [
'(?P<start_tag><\w[^<]*?>)',
'(?P<end_tag><\\/\w[^<]*?>)',
'(?P<entity>&(?:\w+|#(?:\d+|x[0-9a-fA-F]+));)',
//'(?P<named_entity>&\w+;)',
//'(?P<decimal_entity>&#\d+;)',
//'(?P<hex_entity>&#x[0-9a-fA-F]+;)',
];

$offset_diff = 0;

$pattern = '/' . implode( '|', $token_regexps ) . '/s';

$content = preg_replace_callback(
$pattern,
static function ( $matches ) use ( $token_offets, $offset_diff ) {
$original = $matches[0][0];

if ( $matches['start_tag'][1] !== -1 ) {
$replacement = '';
} elseif ( $matches['end_tag'][1] !== -1 ) {
$replacement = '';
} elseif ( $matches['entity'][1] !== -1 ) {
$replacement = html_entity_decode( $matches['entity'][0], ENT_QUOTES | ENT_HTML5, 'utf-8' );
}

return $replacement;
},
$content,
-1,
$count,
PREG_OFFSET_CAPTURE
);

// Note that the decoding here is reversed later in the escape() function.
// @todo Now that Code blocks may have markup (e.g. bolding, italics, and hyperlinks), these need to be removed and then restored after highlighting is completed.
$content = html_entity_decode( $matches['content'], ENT_QUOTES );

// Convert from Prism.js languages names.
if ( 'clike' === $language ) {
Expand Down Expand Up @@ -662,6 +700,8 @@ function render_block( $attributes, $content ) {
set_transient( $transient_key, compact( 'content', 'attributes' ), MONTH_IN_SECONDS );
}

// @todo The tags and entities extracted from $content need to be restored now.

return inject_markup( $matches['pre_start_tag'], $matches['code_start_tag'], $attributes, $content );
} catch ( Exception $e ) {
return sprintf(
Expand Down