WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] Put tagged-snippet in <pre></pre> tag

[Resolved] Put tagged-snippet in <pre></pre> tag

  • Hi,

    I am trying to put my WPF code snippet in a HTML “pre” tag pair
    with a syntax-highlighter, but there are two problems (see the screenshot):

    1. All the tags are turned into lower case.
    For example, “Window” in <Window></Window> shoud keep its capitalized form; but obviously it was lowered.

    2. Error-prone tag closing.
    As you can see in the screenshot, the “Grid.RowDefinitions” tag was closed in line 6; so the marked tag in line 24 is redundant, as well as some tags in the same line.

    I’m quite sure that the formatting option “WordPress should correct invalidly nested XHTML automatically” in the “Settings->Writing” was unchecked.
    And I reviewed my saved post, the content wasn’t changed, so I guess the snippet was reformed after read from the DB.

    Any idea?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Don’t remember where I got this, but it will format code nearly the same as in this forum. Just add it to the end of your functions.php, and use [raw] ... [/raw] shortcodes to wrap your code.

    <?php
    function raw_formatter($content) {
      // Shortcode [raw] ... {/raw] to preserve code formatting
    	$new_content = '';
    	$pattern_full = '{(\[raw\].*?\[/raw\])}is';
    	$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
    	$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
    
    	foreach ($pieces as $piece) {
    		if (preg_match($pattern_contents, $piece, $matches)) {
            $newstr = htmlspecialchars($matches[1], ENT_NOQUOTES);
            $new_content .= '<pre>' . preg_replace('/\n/is','<br />',$newstr) . '</pre>';
    		} else {
    			$new_content .= wptexturize(wpautop($piece));
    		}
    	}
    
    	return $new_content;
    }
    remove_filter('the_content', 'wpautop');
    remove_filter('the_content', 'wptexturize');
    
    add_filter('the_content', 'raw_formatter', 99);
    ?>

    @vtxyzzy:

    Thanks for you reply, it brought me a new thought.

    I found the plug-in “SyntaxHighlighter Plus” use similar technique to solve this problem; plus, a decent decoration. 🙂

    Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘[Resolved] Put tagged-snippet in <pre></pre> tag’ is closed to new replies.