Displaying Source Code in a Post

I generally include source code of one kind or another in my postings.  Being used to the <code>, </code> tags commonly available in user forums such as www.unix.com, I was surprised to find that no such facility was available for use on Blogger.  I searched around the Internet and came across similar complaints from other users and various suggestions and means of formating code so that it is attractively and usefully displayed in a post.  After trying a number of methods and formats developed by others and generally being unhappy with the results, I decided that my best approach was to develop and incorporate a custom CSS element for displaying source code into my Blogger layout template.

Here is the CSS element which I am using to display the source code in this post:
 /* Custom styling ----------------------------- */
.displaybox, .displaybox pre
{
font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace;
font-size: 12px;
color: black;
background-color: RGB(245,218,199);
border: 1px dashed #999999;
line-height: 14px;
padding: 5px;
overflow: auto;
width: 100%
}
I added this code to my blog template in the <b:skin> section of the template just about the Comments section.

Here is a sample of the output for a simple C function.  No changes had to be made to the source code except to change the include header angle brackets to &lt; and &gt; respectively.
#include <shell.h>

int
b_hello(int argc, char *argv[], void *extra
{
if (argc != 2) {
printf("Usage: hello arg\n");
return(2);
}

printf("Hello %s\n", argv[1]);

return(0);
}
This custom CSS element in my blog template will not eliminate the need to make any changes to source code before including the code in a post but it does simplify things.   With this CSS element in place, the only parts of the source code that I should have to manually edit in order to display correctly are angle brackets, ampersands and quotation marks.

0 comments:

Post a Comment