我决定使用Pygments作为我正在制作的网站,但我缺乏终极知识。
我想使用pygmentize
突出显示博文中的语法,但由于它们存储在数据库中,因此我不能只将文件名传递给它。有什么方法可以将字符串传入其中吗?
如果没有,我将不得不将帖子内容保存在临时文件中,对其进行pygmentize并加载到数据库中,但是如果可能的话,这会增加我真正想避免的开销。
我没有看到CLI documentation对此有任何说法。
答案 0 :(得分:2)
man page表示如果省略infile则从stdin读取,如果省略outfile则写入stdout。
因此,在cmdline上键入:
$ pymentize -l php -f html
<?php
echo 'hello world!';
^D // type: Control+D
pymentize会输出:
<div class="highlight"><pre><span class="cp"><?php</span>
<span class="k">echo</span> <span class="s1">'hello world!'</span><span class="p">; </span>
</pre></div>
如果您使用PHP运行它,则必须使用proc_open()
开始pygmentize,因为您必须写入stdin。这里有一个简短的例子:
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;
}
不过,pygmentize是非常酷的东西!我也在用它。)