Code in comments

I made some changes to my WordPress install to make it easier to post code in comments. You can now post code by enclosing it in <code> or <pre>. You still have to escape <, >, and & as &lt;, &gt;, and &amp;, but you no longer have to worry about wrapping, indentation, and smart quotes.

Making these changes was harder than I expected.

Allowing <pre> tags

I edited wp-includes/kses.php to allow <pre> tags. I will have to do this again every time I reinstall WordPress.

Preserving spacing and avoiding smart quotes

I installed Preserve code formatting. I edited it to only touch comments (I had already turned off formatting and texturizing for posts using Text Control). I also edited it to not try to escape HTML, because I consider that incorrect and because it was doing so in a way that caused > to be double-escaped.


I edited styles.css to make the rule for code also apply to pre, and added

  text-align: left;
  white-space: pre;

to that rule.

6 Responses to “Code in comments”

  1. Phil Ringnalda Says:

    You might also want to add an overflow rule for pre – I’d guess that the risk of widening is why it’s not allowed by default.

  2. Jesse Ruderman Says:

    I’d rather let the code spill into the margins than make a scrollbar appear on each <pre> that overflows. Hopefully, someday I will have a layout where code overflowing into margins doesn’t look bad.

  3. Jesse Ruderman Says:

    On second thought, I’ll try out scrollbars.

    pre {
      overflow: auto;
      max-height: 40em;
      padding: .5em; 
      border: 1px solid #bbb;
  4. Matt Says:

    You don’t have to edit kses.php every time, just put your own $allowed_tags in your wp-config.php file and define the CUSTOM_TAGS constant as true. Also don’t forget to copy your style changes into your own theme so upgrading is extra-easy.

  5. Alex Says:

    Will you be releasing your modified version of Preserve code formatting as well?

  6. Jesse Ruderman Says:

    Alex, my only edits to the plugin were commenting out two or three lines.