Python Conquers The Universe

2011/11/06

How to post source code on WordPress

Filed under: Miscellaneous — Steve Ferg @ 12:46 pm

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’!

Advertisement

11 Comments »

  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?

    Comment by driscollis — 2011/11/09 @ 2:57 pm | Reply

    • Note: I almost never use Visual mode and create all my posts in HTML mode.

      Comment by driscollis — 2011/11/09 @ 4:34 pm | Reply

  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.

    Comment by Steve Ferg — 2011/11/09 @ 3:31 pm | Reply

  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]
    

    Comment by Steve Ferg — 2011/11/09 @ 4:10 pm | Reply

    • 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.

      Comment by driscollis — 2011/11/09 @ 4:39 pm | Reply

      • 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.

        Comment by Steve Ferg — 2011/11/09 @ 4:55 pm | Reply

      • 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.

        Comment by Steve Ferg — 2011/11/09 @ 5:09 pm | Reply

      • 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?

        Comment by Steve Ferg — 2011/11/09 @ 5:15 pm | Reply

  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!

    Comment by driscollis — 2011/11/09 @ 6:02 pm | Reply

  5. I get the exact same issue on my self hosted site.

    Comment by ki113d — 2011/12/28 @ 12:54 pm | Reply

  6. Works like a charm! thank you

    Comment by pc repair tucson — 2012/01/25 @ 1:07 am | Reply


RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 39 other followers