1

I decided to use Pygments for a website I'm working on, but my lack of terminal knowledge is amazing.

I want to use pygmentize to highlight syntax in blog posts, but as they are stored in database I can't just pass filename to it. Is there any way I can pass string into it?

If not, I will have to save post contents in a temp file, pygmentize it and load into database but this adds overhead that I would really like to avoid if at all possible.

I don't see CLI documentation saying anything about it.

1 Answers1

2

The man page says it reads from stdin if infile is omitted and it writes to stdout if outfile is omitted.

So on the cmdline you would type:

$ pymentize -l php -f html
<?php

echo 'hello world!';
^D // type: Control+D

pymentize would output:

<div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">echo</span> <span class="s1">&#39;hello world!&#39;</span><span class="p">; </span>
</pre></div>

If you'll run this with from PHP you'll have to start pygmentize using proc_open() as you'll have to write to stdin of it. Here comes a short example how to do it:

echo pygmentize('<?php echo "hello world!\n"; ?>');

/**
 * Highlights a source code string using pygmentize
 */
function pygmentize($string, $lexer = 'php', $format = 'html') {
    // use proc open to start pygmentize
    $descriptorspec = array (
        array("pipe", "r"), // stdin
        array("pipe", "w"), // stdout
        array("pipe", "w"), // stderr
    );  

    $cwd = dirname(__FILE__);
    $env = array();

    $proc = proc_open('/usr/bin/pygmentize -l ' . $lexer . ' -f ' . $format,
        $descriptorspec, $pipes, $cwd, $env);

    if(!is_resource($proc)) {
        return false;
    }   

    // now write $string to pygmentize's input
    fwrite($pipes[0], $string);
    fclose($pipes[0]);

    // the result should be available on stdout
    $result = stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    // we don't care about stderr in this example

    // just checking the return val of the cmd
    $return_val = proc_close($proc);
    if($return_val !== 0) {
        return false;
    }   

    return $result;
}

Btw, pygmentize is pretty cool stuff! I'm using it too :)

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • Yeah, I realized that and figured it would be better to find a way to use it with PHP rather than to settle with JavaScript solutions. Amazing answer if it works, accepting as soon as I test it! –  Jan 24 '13 at 00:47
  • Fine :) Have fun with that. You should read from stderr too, to obtain error messages if pygments fails for any reason – hek2mgl Jan 24 '13 at 00:55
  • 1
    I will for sure. If it does fail, I'll just return clean source as it came in. –  Jan 24 '13 at 00:57