Wednesday, October 14, 2015

Sharing code with the world

The main reason I started writing this blog was to share snippets of things I find interesting or as a way to document any solutions I come up with that I would like to share. The problem with the web though, is formatting. When you copy and paste code from your code editor into a web form, things don't go as expected. Some pages will try to interpret the code blocks and in some cases can even cause the page to break. Most of the time, indentation is ignored and sometimes line breaks too.

I started doing the formatting by hand at first and quickly found that while possible, my posts will spend more time being edited than written. The biggest issue I had was that the output was just bland. Blocks of code were getting lost in the rest of the page.

That's when I found SyntaxHighlighter. This CSS/JS library can be used to not only format blocks of code very nicely, it adds line numbers and syntax highlighting for all of the main languages I use, mainly ColdFusion. It also has theme support, which I use Sublime Text 3 as my main editor with the Monoki color scheme and the theme I found, RDark, matches it pretty well. I may end up writing a Monoki theme for SyntaxHighlighter, but that may have to come a bit later.

So now, code blocks just need to be surrounded with a <pre> tag and a brush set to the language it is and SyntaxHighlighter will do the rest for me:

<pre class="brush: java">
 int test=7;
 int y = 5;
</pre>

 int test=7;
 int y = 5;


This makes the code easier to read, but as for writing, I needed to find a way to make that easier. I'll go into details about how I did that in an upcoming post.

3 comments:

  1. Funny how even though we're apart, we still manage to stumble across like problems/issues. My problem was more towards sharing code in an email to a client and I didn't want the code all ugly black so did a quick search on a tool to make my code pretty. I stumbled across this online free tool.

    Ref: http://tohtml.com/

    It served me well and even though it may not fit your blog posting strategies, you can still manually spit out your code, copy & paste it with pretty colors! :-D

    My example (hopefully it works or it'll really look nasty in this comment box) is a Google Map API plugin I did for a client that will end up being part of all the bank branch websites in the San Diego area.

    Ref: https://jsfiddle.net/oukzjd8r/

    ReplyDelete
  2. Bah! Nevermind, it won't let me post the HTML. Thanks Google Blogger #GoogleBloggerFail

    ReplyDelete
    Replies
    1. Yeah, you can't post any code in comments, but I'm able to post HTML directly to the blog. When all else fails, you can always post to something like pastebin and then just put the link in the comments. That's what I tend to use when chatting on IRC or IM.

      Delete