Quality Reads

Tuesday, August 07, 2007

Code Highlighting


If you're in the market for a code highlighter, I just ran into a good one that handles PHP, Java, Javascript, Perl, SQL, HTML, and CSS. To rock this on your blog/website, all you need to do is include the javascript source in you page header and add a textarea tag like so:


<textarea id="myCpWindow" class="codepress javascript linenumbers-off">
// your code here
</textarea>

Notice the language to be highlighted is included in the class declaration. There's a couple other useful features (such as copying code to the user's clipboard) that can be found here. To make life even easier, I've written up a quick ColdFusion custom tag to create the textarea declaration and include the appropriate content (sorry, non-CF users). Here's the code:


<CFSETTING enablecfoutputonly="true">
<CFIF ThisTag.ExecutionMode eq "Start">
<cfparam name="attributes.language" type="string"><!--- Language to Highlight --->
<cfparam name="attributes.file" type="string"><!--- relative file path --->
<cfparam name="attributes.readOnly" type="boolean" default="false">
<cfparam name="attributes.lineNumbers" type="boolean" default="true">
<cfparam name="attributes.autoComplete" type="boolean" default="false">

<cfset attriList = "language,file,readOnly,lineNumbers,autoComplete">
<cfset attriKey = StructKeyList(attributes)>

<CFTRY>
<CFFILE action="read"
file="#ExpandPath(attributes.file)#"
variable="fileResult">

<CFCATCH type="any">
<CFTHROW detail="Double check the file location. The error occurred trying reading the specified filed.">
</CFCATCH>
</CFTRY>

<CFOUTPUT><textarea class='codepress</CFOUTPUT>
<CFIF attributes.readOnly><CFOUTPUT> readonly-on </CFOUTPUT></CFIF>
<CFIF NOT attributes.lineNumbers><CFOUTPUT> linenumbers-off </CFOUTPUT></CFIF>
<CFIF NOT attributes.autoComplete><CFOUTPUT> autocomplete-off </CFOUTPUT></CFIF>
<CFOUTPUT>'</CFOUTPUT>
<CFLOOP from="1" to="#ListLen(attriKey)#" index="aIndex">
<CFIF NOT ListFindNoCase(attriList, ListGetAt(attriKey,aIndex))>
<CFOUTPUT> #ListGetAt(attriKey,aIndex)#='#attributes[ListGetAt(attriKey,aIndex)]#' </CFOUTPUT>
</CFIF>
</CFLOOP>
<CFOUTPUT>>#fileResult#</textarea></CFOUTPUT>

</CFIF>
<CFSETTING enablecfoutputonly="false">


You can use the tag like so:


<cf_syntaxify <-- whatever you name the tag -->
language="ColdFusion"
file="test.cfm"
id="testID" />


Any attribute you define in the tag that is not param'ed at the top of the custom tag will be passed onto the <textarea> tag. Note the id attribute in the above example.

There are a couple other code highlighters available, most notably the one released by Google, but the simplicity of CodePress is immediately apparent once you check out the docs. Let me know if you run into any problems w/ the custom tag (I haven't tested it extensively yet).

Cheers,
Todd

No comments: