How to post source code on WordPress

This post is for folks who blog about Python (or any programming language for that matter) on WordPress.
Updated 2011-11-09 to make it easier to copy-and-paste the [sourcecode] template.

My topic today is How to post source code on WordPress.

The trick is to use the WordPress [sourcecode] shortcut tag, as documented at http://en.support.wordpress.com/code/posting-source-code/.

Note that when the WordPress docs tell you to enclose the [sourcecode] shortcut tag in square — not pointy — brackets, they mean it. When you view your post as HTML, what you should see is square brackets around the shortcut tags, not pointy brackets.

Here is the tag I like to use for snippets of Python code.


[sourcecode language="python" wraplines="false" collapse="false"]
your source code goes here
[/sourcecode]


The default for wraplines is true, which causes long lines to be wrapped. That isn’t appropriate for Python, so I specify wraplines=”false”.

The default for collapse is false, which is what I normally want. But I code it explicitly, as a reminder that if I ever want to collapse a long code snippet, I can.


Here are some examples.

Note that

  • WordPress knows how to do syntax highlighting for Python. It uses Alex Gorbatchev’s SyntaxHighlighter.
  • If you hover your mouse pointer over the code, you get a pop-up toolbar that allows you to look at the original source code snippet, copy it to the clipboard, print it, etc.

(1)

First, a normal chunk of relatively short lines of Python code.

indentCount = 0
textChars = []
suffixChars = []

# convert the line into a list of characters
# and feed the list to the ReadAhead generator
chars = ReadAhead(list(line))

c = chars.next() # get first

while c and c == INDENT_CHAR:
    # process indent characters
    indentCount += 1
    c = chars.next()

while c and c != SYMBOL:
    # process text characters
    textChars.append(c)
    c = chars.next()

if c and c == SYMBOL:
    c = chars.next() # read past the SYMBOL
    while c:
        # process suffix characters
        suffixChars.append(c)
        c = chars.next()

(2)

Here is a different code snippet. This one has a line containing a very long comment. Note that the long line is NOT wrapped, and a horizontal scrollbar is available so that you can scroll as far to the right as you need to. That is because we have specified wraplines=”false”.

somePythonVariable = 1
# This is a long, single-line, comment.  I put it here to illustrate the effect of the wraplines argument.  In this code snippet, wraplines="false", so lines are NOT wrapped, but extend indefinitely, and a horizontal scrollbar is available so that you can scroll as far to the right as you need to.

(3)

This is what a similar code snippet would look like if we had specified wraplines=true. Note that line 2 wraps around and there is no horizontal scrollbar.

somePythonVariable = 1
# This is a long, single-line, comment.  I put it here to illustrate the effect of the wraplines argument.  In this code snippet, wraplines="true", so lines are ARE wrapped.  They do NOT extend indefinitely, and a horizontal scrollbar is NOT available so that you can scroll as far to the right as you need to.

(4)

Finally, the same code snippet with collapse=true, so the code snippet initially displays as collapsed. Clicking on the collapsed code snippet will cause it to expand.

somePythonVariable = 1
# This is a long, single-line, comment.  I put it here to illustrate the effect of the wraplines argument.  In this code snippet, wraplines="true", so lines are ARE wrapped.  They do NOT extend indefinitely, and a horizontal scrollbar is NOT available so that you can scroll as far to the right as you need to.

As far as I can tell, once a reader has expanded a snippet that was initially collapsed, there is no way for him to re-collapse it. That would be a nice enhancement for WordPress — to allow a reader to collapse and expand a code snippet.


Here is a final thought about wraplines. If you specify wraplines=”false”, and a reader prints a paper copy of your post, the printed output will not show the scrollbar, and it will show only the portion of long lines that were visible on the screen. In short, the printed output might cut off the right-hand part of long lines.

In most cases, I think, this should not be a problem. The pop-up tools allow a reader to view or print the entire source code snippet if he wants to. Still, I can imagine cases in which I might choose to specify wraplines=”true”, even for a whitespace-sensitive language such as Python. And I can understand that someone else, simply as a matter of personal taste, might prefer to specify wraplines=”true” all of the time.

Now that I think of it, another nice enhancement for WordPress would be to allow a reader to toggle wraplines on and off.


Keep on bloggin’!

About these ads

23 thoughts on “How to post source code on WordPress

  1. Weird. I just tried this and it didn’t work at all. The

    [sourcecode language="python" wraplines="false" collapse="false"]
    [/sourcecode]
    

    line itself was visible and my code turned into plain text. Is there some option that needs to be turned on in WordPress itself?

  2. Note that for this technique to work (or at least, to work reliably), you must be in HTML mode, not Visual mode.

    The following will NOT work.

    • You create you own new WordPress post.
    • You go to this post and copy the code for the [sourcecode] template to your clipboard.
    • Back in your own post — in Visual mode — you paste the contents of the clipboard into your post.

    If you do that, in your post you will see the text of the [sourcecode] template, which of course is not what you want to see.

    The reason is this— When you copied the template code from this post, you got the underlying HTML markup along with the visible text of the template. When you pasted the clipboard into your own post in Visual mode, the underlying HTML markup came into your post along with the visible text of the template. The result is that your post shows the template, not a code snippet.

    The trick is to paste the clipboard containing the template code into your post in HTML mode.

  3. Just for the sake of interest, it might be fun to explain how you can put the template code into a post in such a way that it shows up as template text, and not formatted as a code snippet.

    The trick is to put an empty HTML tag as a separator between the left square bracket and whatever follows it. This will prevent WordPress from treating the left bracket as the beginning of a shortcut tag. If we used an <em> tag as our separator, the text (in HTML mode, of course) looks like this:

    [<em></em>sourcecode language="python" wraplines="false" collapse="false"]
    your source code goes here
    [<em></em>/sourcecode]
    
    • Weird. This doesn’t work on my self-hosted site either. Maybe there’s a difference between hosting your code on WordPress proper and self-hosting. I’m in HTML mode and I tried this with my latest post, but when I preview it, the code is not formatted at all and I see just the [sourcecode language="python" wraplines="false" collapse="false"][/sourcecode] line…not sure why it stripped out the <em> tags. Oh well, I have a plugin that works pretty well, it just doesn’t have line numbering.

      • If you are seeing the [sourcecode...] shortcut tag while you are editing your post in HTML mode, then I have no idea what the problem might be. Unless …

        If you are running a self-hosted WordPress, you might need to download the syntax highlighting plug-in.

      • On thing that you might try doing, as a debugging technique, is to switch back and forth, in the WordPress editor, between Visual mode and HTML mode. That might give you a clue as to what is going on.

        The problem might be as simple as (say) a space after the left square bracket. I get stumped by that kind of thing occasionally. It’s the kind of thing that is easy to miss.

      • You wrote:

        when I preview it, the code is not formatted at all and I see just the [sourcecode language="python" wraplines="false" collapse="false"][/sourcecode] line

        The word “line” seems to me significant.

        Is your source code between the
        [sourcecode language="python" wraplines="false" collapse="false"]
        and
        [/sourcecode]
        shortcut tags?

  4. Yeah, I followed your example exactly, copying and pasting from your example. I just replaced my own custom code field with yours. I’ll check and see if there’s a syntax highlighting plug-in I can install later tonight. Thanks for the help!

  5. Just like driscollis, I had the same issue of the the copy-paste technique failing on my self-hosted WordPress site.
    I fixed it simply by installing the “SyntaxHighlighter Evolved” plugin.

  6. For those that didn’t see correct results in your Visual tab preview (but pasted it correctly to the HTML tab), I didn’t either and thought it wasn’t working. But, when I published and viewed the final piece, it looked great. Thanks for the tip!

  7. these tags work awesome only when i dont put XML code into it….when i put xml code, and update the post, then all the xml code dissappears (only comments remain)…please help….
    thanks in advance… :)

    • In my experience… WordPress will strip out HTML tags that it doesn’t recognize or doesn’t allow. So my guess is that it is seeing your XML tags, failing to recognize them as acceptable HTML code, and stripping them out. My advice is —

      in HTML mode… try replacing the “greater than” and “less than” characters in your XML with &gt; and &lt; and see how it works.

      or

      copy and paste your XML into your post while editing in VISUAL mode.

      • pasting XML in visual mode worked !!!…thank you Mr Ferg…..thanks a lot

  8. Thank you!
    I disregarded sourcecode embeds since they rendered in the ugliest way (the font is tiny and their style is so 1990s), but I just found out that you can make them look way better by styling CSS.

  9. I found this does work on the wordpress site, but only when you publish, all the time the you are in text mode, then switch to visual it still shows the tags, only when you publish then it shows as the nice code nuggets. Is this correct?

  10. Hi, I am new with WordPress but I am very interesting about this. I try in my self-hosted site and in my wordpress blog web based in http://tuwebdetecnologia.wordpress.com/ but not work.

    I only know wirte in visual mode and in text mode but you say and in the web of html mode. How I can go to html mode?

    Thanks in advance.

  11. An aclaration, In preview not but when updated it works, It´s only in the self hosted where not work.

    Any idea?

    Regards

Comments are closed.