Convert source to syntax-hilighted HTML in TextMate

Friday, July 28. 2006
0 comments
0 trackbacks

Here is a TextMate Command to convert JavaScript Source to syntax highlighted HTML. It does work with every language supported by enscript. Just change -Ejavascript to -Eyourlanguage. Below is the source as well as an example. (I used the php extensions for enscript) I have a list of all supported languages in the long version of this article!

Download SyntaxHilight.tmCom

#!/usr/bin/env php
<?
if ($fp=fopen("php://stdin","r")) {
    $text="";
    while (!feof($fp)) {
        $text.= fread($fp,4096);
    }
    fclose($fp);

    $command = '/usr/bin/enscript -q -Ejavascript -p - -Whtml --color=emacs';

    $descriptorspec = array(
       0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
     1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
     2 => array("file", "/dev/null", "a") // stderr is a file to write to
  );

    $process = proc_open($command, $descriptorspec, $pipes);

    fwrite($pipes[0], $text);
    fclose($pipes[0]);

    $result="";
    while (!feof($pipes[1])) {
        $result.= fread($pipes[1],4096);
    }
    fclose($pipes[1]);

    proc_close($process);

    $res = preg_match ('/<PRE>(.+)<\/PRE>/s',$result, $hits);

    $html=$hits[1];

    $clean = preg_replace ('/<font color="([^"]*)">/i','<span style="color:$1;">', $html);
    $clean = preg_replace ('/<b>/i','<span style="font-weight:bold">', $clean);

    $clean = preg_replace ('/<i>/i','<span style="font-style:italic;">', $clean);

    $clean = preg_replace ('/<\/[^>]*>/i','</span>', $clean);

    echo '<pre>'.$clean.'</pre>';
}
?>

Supported Languages:

  • ada
  • asm
  • awk
  • c
  • changelog
  • cpp
  • diff
  • diffu
  • delphi
  • elisp
  • fortran
  • haskell
  • html
  • idl
  • java
  • javascript
  • mail
  • makefile
  • nroff
  • objc
  • pascal
  • perl
  • postscript
  • python
  • scheme
  • sh
  • sql
  • states
  • synopsys
  • tcl
  • verilog
  • vhdl
  • vba
by Stefan LH

Comments
Display comments as (Linear | Threaded)

No comments

Add Comment

You can use [geshi lang=lang_name [,ln={y|n}]][/lang] tags to embed source code snippets
Standard emoticons like :-) and ;-) are converted to images.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Markdown format allowed