Wednesday, February 17, 2010

Blogging, JavaScript and CSS

I've started posting little bits of code to my blog, and I thought it would be nice to have some sort of a code tag, similar to how blocks of code are set apart on Gentoo Forums. My first thought was that there must certainly already be something like that already for Blogger. Well, no. Then I decided to just start using <pre> tags. That works, but then you lose line wrapping. The then realized that I was going to have to write some CSS. I hate having to delve into CSS because despite the fact that I spend all day, every day coding in Java in Eclipse, I don't have much time for web programming and I find writing HTML or programming in loosely typed languages to be distasteful.

I won't go into all of the details, but even that has turned out to be more involved than I was hoping. At least to do it right. After trying several things, I've finally come up with a little bit of CSS and JavaScript that work together to do a mediocre job of what I want to accomplish. You'll see the results in this blog posting.

First, I created this CSS that I added directly to my Blogger template in Layout -> Edit HTML:

.code {
padding: .5em;
border-right: #d1d7dc 1px solid;
border-top: #d1d7dc 1px solid;
border-left: #d1d7dc 1px solid;
color: #000000;
border-bottom: #d1d7dc 1px solid;
font-family: 'Liberation Mono', Courier, 'Courier New', monospace;
font-style: bold;
background-color: #ffffcc
}

That gives me the block that I want, setting off the code from the article text. But then I noticed that any extra spaces were being lost as happens with HTML. That led to this bit of JavaScript added to the HTML/JavaScript block in Layout -> Page Elements:

<script type="text/javascript">
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++) {
if(divs[i].className == 'code') {
str = divs[i].innerHTML;
str = str.replace(/ /g, '&nbsp;');
divs[i].innerHTML = str;
}
}
</script>

This is very sub-optimal, though, as the regex in replace() is overly simplistic. I tried several expressions, trying to get something better, but had no luck. What needs to happen is that all blocks of multiple spaces at the beginning of a code line need to be replaced with &nbsp;. I simply could not figure out a single expression that would replace a variable number of spaces with a corresponding quantity of &nbsp;, and only do it on the beginning of a line. If you can think of something that might work, let me know. Otherwise, I may just write some code to inspect the line and figure out what spaces need to be replaced.

I'll come back around to this when I have more time. Or, I might just use Alex Gorbatchev's Syntax Highlighter, but that was way more involved than I wanted to deal with today.

1 comment:

  1. very cool & good tip, thank you very much for sharing.

    ReplyDelete