我决定将Pygments用于我正在开发的网站,但我缺乏终端知识是惊人的。
我想用来pygmentize
突出博客文章中的语法,但由于它们存储在数据库中,我不能只将文件名传递给它。有什么办法可以将字符串传递给它吗?
如果没有,我将不得不将帖子内容保存在临时文件中,对其进行 pygmentize 并加载到数据库中,但这会增加开销,如果可能的话,我真的很想避免。
我没有看到CLI 文档对此有任何说明。
手册页说,如果省略 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 运行它,则必须使用 pygmentize 开始,proc_open()
因为您必须写入它的标准输入。这里有一个简短的例子如何做到这一点:
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 是很酷的东西!我也在用它:)