Question

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.

Était-ce utile?

La solution

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 :)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top