Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active January 27, 2023 21:28
Show Gist options
  • Save westonruter/d35a909df087d90e0100d111eed77faa to your computer and use it in GitHub Desktop.
Save westonruter/d35a909df087d90e0100d111eed77faa to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: Syntax-highlighting Code Comments
* Plugin URI: https://gist.github.com/westonruter/d35a909df087d90e0100d111eed77faa
* Description: Extension plugin for Syntax-highlighting Code Block to also add syntax highlighting to code in comments.
* Version: 0.1.1
* Author: Weston Ruter
* Author URI: https://weston.ruter.net/
* License: GPL2
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: syntax-highlighting-code-block
* Requires PHP: 5.6
* Gist Plugin URI: https://gist.github.com/westonruter/d35a909df087d90e0100d111eed77faa
*
* @package Syntax_Highlighting_Code_Comments
*/
namespace Syntax_Highlighting_Code_Comments;
use WP_Block_Type;
use WP_Block_Type_Registry;
/**
* Make <code>...</code> in (comment) text syntax-highlighted.
*
* The <code> element may be optionally wrapped in a <pre> tags, and then start and end on a line by itself. In other
* words it must be presented as a block/paragraph and not inline; when <code> appears inline in paragraphs, it will
* not be syntax-highlighted.
*
* @param string $comment_text Comment text.
* @return string Syntax-highlighted.
*/
function filter_comment_text( $comment_text ) {
if ( ! function_exists( '\Syntax_Highlighting_Code_Block\render_block' ) ) {
return $comment_text;
}
$registry = WP_Block_Type_Registry::get_instance();
$block_type = $registry->get_registered( 'core/code' );
if ( ! $block_type instanceof WP_Block_Type ) {
return $comment_text;
}
$attributes = [];
foreach ( $block_type->attributes as $name => $schema ) {
if ( isset( $schema['default'] ) ) {
$attributes[ $name ] = $schema['default'];
}
}
$pattern = implode(
'',
[
'(?<=^|\n)',
'(<pre[^>]*?>\s*)?',
'<code[^>]*?>(?P<contents>[^<]*?)</code>',
'(\s*</pre>)?',
'(?=\r?\n|$)',
]
);
return preg_replace_callback(
"#{$pattern}#si",
static function( $matches ) use ( $attributes ) {
$contents = $matches['contents'];
$before = '<pre><code>';
$after = '</code></pre>';
return \Syntax_Highlighting_Code_Block\render_block( $attributes, $before . $contents . $after );
},
$comment_text
);
}
add_filter( 'comment_text', __NAMESPACE__ . '\filter_comment_text', 20 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment