strapyourself.in and flouri.sh

Syntax highlighting Mephistro admin side

November 4th, 2007

Using CodePress to make writing blog entries easier

After I got Metphisto working with Ultraviolet syntax highlighting, I decided to make writing blog entries easier! I already had some experience with my TicTacToe project using CodePress for real-time syntax highlighting. From there, I was able to modify Mephisto to use syntax highlighting while I was writing my articles... the goal being to make the HTML easier to read and easier to write:

screenshot

The first step was to install CodePress from codepress.org into the mephistro public directory. I ended up putting the css in /stylesheets, and the javascript in /javascripts... big mistake! Codepress likes to be kept all together (probably best in /public), and you shouldn't have to rewrite any of the paths in codepress.html or codepress.js, like I did.

The second step was to include codepress.js in your layout.

Then I made the following modifications to /app/views/admin/articles/_form.rhtml replacing only the dd tag that defines the "body" textarea:

<dd><%= form.text_area :body, :class => 'fat codepress html linenumbers-off', :rows => 25  %>
  <br/><%= check_box_tag "enable_codepress", "1", true, :onchange => "article_body.toggleEditor();" %>
&nbsp;  Use codepress for syntax highlighting 
  <%= hidden_field_tag "article[body_hidden]", @article.body, :id => "article_body_hidden" %>
</dd>

Just changing the class of the text_area is enough to active codepress... pretty cool huh? The checkbox is cool too, allowing you to turn codepress on/off on the fly. Unfortunately, I had to do some craziness with a hidden field. Codepress does not submit the edited data with the form, like you'd expect. Because it creates an design-mode iframe, the browser does not submit your code the way you want it to. However, it provides an object on which you can call a method to get the unformatted code. We can copy the code into the hidden field with an onsubmit in /app/views/admin/articles/new.rhtml and /app/views/admin/articles/edit.rhtml by adding an :onsubmit option to the form like so:

{:id => 'article-form', :multipart => true, 
  :onsubmit => "document.getElementById('article_body_hidden').value = article_body.getCode();"}

Of course, we've now got a hidden field named article[body_hidden] which contains the actual body, rather than the regular field article[body], so we need to deal with that somewhere. I chose /app/models/article.rb, adding the following public method:

def body_hidden=(newval)
  self.body = newval
end

This is still mostly untested, but I'm really enjoying it so far. Uploading an asset inline might not submit the body of the article anymore, so you'll have to a similar piece of javascript to copy the value from the codepress object or lose your changes when you upload an image.

Sorry, comments are closed for this article.

original design by gorotron ported by railsgrunt powered by mephisto