Showing posts with label source. Show all posts
Showing posts with label source. Show all posts

Friday, April 24, 2009

JavaFX Brush for SyntaxHighlighter

I wanted to display well-formatted JavaFX Script source code using Alex Gorbatchev's SyntaxHighlighter. But the current version of SyntaxHighlighter does not include a JavaFX brush. So I wrote one. A sample of highlighted code is below. Note that some of the code is a bit silly. It is written that way to exemplify the highlighting features.
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.scene.transform.Scale;
import javafx.stage.Stage;

/**
 * @author Patrick Webster
 */
var mouseX: Number;
var mouseY: Number;
var scale: Float = (-2.3 - 1.0) * -1.;
var egg: Circle;

Stage {
   title: "Easing Raw Egg"
   scene: Scene {
      fill: Color.BLACK
      height: 0x2EB  width: 0X30C
      content:
         egg = Circle {
            fill: Color.WHITE
            centerX: bind mouseX
            centerY: bind mouseY
            radius: 323.456e-02
            transforms: Scale {
               // Egg eases to moving mouse cursor
               pivotX: bind mouseX
               pivotY: bind mouseY
               x: bind scale * .02298E3
               y: bind scale *  32.56789
            }

            onMouseMoved: function( me: MouseEvent ) {
               updateMousePosition(me);
            }
            onMouseWheelMoved: function( we: MouseEvent ) {
               updateMousePosition(we);
               updateScale(we);
            }
         }
   }
}

function updateMousePosition(me : MouseEvent) : Void {
   mouseX = me.x;
   mouseY = me.y;
}

function updateScale(we: MouseEvent) : Float {
   var newScale = scale + (we.wheelRotation * -0.1);
   if (newScale < 1.0)
      return scale = 1.0000000e+00;
   return scale = newScale;
}

There are others who have written JavaFX brushes for SyntaxHighlighter, but they all lack the functionality that I desire. My implementation differs from others by including these additional features:
  1. Negative signs for constants are highlighted.
  2. Constants with scientific notation are highlighted.
  3. Leading and trailing decimal points are highlighted.
  4. Keywords are up-to-date for JavaFX 1.1.1.
  5. Deprecated keywords are supported.
  6. JavaFX built-in data types are highlighted differently than keywords.


Constants
In order to recognize all number formats for constants in JavaFX Script, I wrote the following horrendous regular expression:
/(-?\.?)(\b(\d*\.?\d+|\d+\.?\d*)(e[+-]?\d+)?|0x[a-f\d]+)\b\.?/gi
I am not going to explain every little detail of the above mess, but I will say that there are basically three parts. The first part matches on regular numbers with an optional leading negative sign and decimal point. The middle part looks for scientific notation. The last part checks for hexadecimal format. The major assumption is that correct JavaFX Script is the input. It is possible for the above expression to match on illegal code, but the hope is that people will not be highlighting incorrect code on their blogs. One small problem is that the above regular expression will match on the binary subtraction operator if there is no space between the operator and the subtrahend:
def b: Double = a-4;
I would prefer if the minus operator were not highlighted. But in general, it is good style to surround binary operators with a space, so this is really not a big problem.


Keywords
As the JavaFX Script language evolves, keywords come and go. The latest JavaFX Script 1.1.1 keywords are listed here. I'm sure this list will need to be updated again after the next language revision. I also include a separate list of deprecated keywords that is easily commented-out if desired.


Built-In Types
There are several built-in data types in JavaFX Script. I chose to highlight the following types in their own distinct color:
Boolean Byte Character Double Duration Float Integer Long Number Short String Void


Blogger Usage
If you followed my instructions on how to install SyntaxHighlighter into Blogger, then getting the JavaFX highlighter working will be a simple task. First you will need to download my brush file here. Expand it and place it somewhere on the internet. Then insert a link to the brush file in your Blogger HTML template. For example, I inserted this line in my template:
<script src='http://patrickwebster.googlepages.com/shBrushJavaFX.js' type='text/javascript'/>
I do not recommend that you link to my file because the file may move or change names at any time. Once the template is edited, new JavaFX code can be highlighted by wrapping it in the <pre class="brush: javafx"> and </pre> tags. The brush aliases 'jfx' or 'javafx' may be used within the <pre> tag.


Update: May 3rd, 2009
The newly released version 2.0.320 of SyntaxHighlighter includes a JavaFX brush! So you do not need to download my script. Simply upgrade to the new release and wrap your JavaFX code in the <pre> tag as explained above. You can link to the hosted version of the brush file by adding the following line to the appropriate section of your Blogger template:
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJavaFX.js' type='text/javascript'/>



Friday, February 27, 2009

SyntaxHighlighter in Blogger

If you want to display well-formatted and easy-to-read source code in your Blogger blog, you may want to used Alex Gorbatchev's SyntaxHighlighter. Here is a sample of formatted Java:
public @interface Politics {}

@Override
public final void liveInAmerica(boolean insane) {
  Party<Fool>    republican = new Party<Fool>(false);
  // Party like it's 1999!
  Party<Dude> nonRepublican = new Party<Dude>(true);
  while(isBush()) {
    suffer(13);
  }
  if(insane) {
    elect(republican);
  }
  else {
    System.out.println("Free at last!");
    elect(nonRepublican);
    beHappy(7);
  }
}
In order to display my Java code, I perform the following three steps:
  1. Add CSS styles and a JavaScript to the Blogger template.
  2. Make source code more HTML friendly.
  3. Wrap code in <pre> tag when posting.


Step 1: Modify Template
In Blogger's Layout tab, select the “Edit HTML” sub-tab. Locate </head> in the text area. Right BEFORE this tag (before the <), paste the following code.
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/> <link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/> <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/> <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/> <script type='text/javascript'> SyntaxHighlighter.config.clipboardSwf = &#39;http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf&#39;; SyntaxHighlighter.config.bloggerMode = true; SyntaxHighlighter.all(); </script>
Click the SAVE TEMPLATE button. If no errors occurred, you may navigate away from the Layout tab. This step only needs to be performed once. For each subsequent blog post, you only need to do the remaining steps to get highlighted source code.


Step 2: Clean the Code
Java code that uses generics contains lots of less-than (<) and greater-than (>) symbols. These symbols confuse HTML renderers. So the generified Java must be converted to a more friendly format. That is, each less-than and greater-than symbol needs to be replaced with “&lt;” and “&gt;” (without the quotation marks,) respectively. I use an online HTML encoder to quickly format the code. There are many other tools that achieve the same result.


Step 3: Wrap Code in <pre> Tag
Precede each block of Java code with the following:
<pre class="brush: java">
Finish the code block with:
</pre>


Blank Lines in IE
In order for Blogger to display blank lines within highlighted source code on Internet Explorer, one additional setting must be adjusted. Under the Settings tab, in the Formatting sub-tab, the option “Convert line breaks” must be changed to “No.” With this setting, hard-returns typed in the WYSIWYG post editor will not be converted to HTML line break tags.

WARNING: changing this option from yes to no will reformat all posts. If you don't want to spend forever re-entering all line breaks in your existing posts, then you may want to live without blank lines in your highlighted source code. But if you only have a few posts, then it is worth the reformatting exercise. Blank lines can make long source code listings much more readable. Keep in mind that the WYSIWYG “Compose” editor will be basically useless after changing this option to “No.” All line breaks will have to be entered as <br /> tags in the “Edit Html” editor, or a third-party blog editor.


Other Languages
The brush option in the <pre> tag tells SyntaxHighlighter which language to use. If you want to post source code in other languages, you would need to change the brush type in the <pre> tag and add the appropriate language script to your Blogger template. I only use Java, so I only added the Java script. It is a good idea to add as few JavaScripts as possible to your template in order to minimize page load times. You may choose from a complete list of supported languages and add the appropriate script line to your template for each desired language. For example, to add C++ support to your blog, add the following line to your template:
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'/>


SyntaxHighlighter Usage
In order for the “copy to clipboard” feature to work, the blog viewer must have the Flash plugin installed. Without the appropriate Flash plugin, a blank area will be displayed where the clipboard button is usually located.

If you wish to host the SyntaxHighlighter scripts on your own site and not rely on the developer's server, you can find more information here. It is preferred that you host SyntaxHighlighter on your own server in order to conserve the developer's hosting bandwidth.