2013-01-23 2 views
1

나는 작업하고있는 웹 사이트에 Pygments을 사용하기로 결정했으나, 터미널 지식에 대한 나의 부족은 놀랍습니다.Pygments는 패스 문자열을 열거합니다.

블로그 게시물의 구문을 강조하기 위해 pygmentize을 사용하고 싶지만 데이터베이스에 저장되므로 파일 이름을 전달할 수는 없습니다. 문자열을 전달할 수있는 방법이 있습니까?

그렇지 않은 경우 임시 파일에 게시물 내용을 저장하고 파일을 조각화하고 데이터베이스에로드해야하지만 이로 인해 가능한 경우 오버 헤드가 발생합니다.

그것에 대해 아무 것도 말하지 않는 CLI documentation이 표시되지 않습니다.

답변

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">&lt;?php</span> 

<span class="k">echo</span> <span class="s1">&#39;hello world!&#39;</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; 
} 

Btw, pygentize는 매우 멋지다. 나는 그것을 사용하고있다 :)

+0

그래, 나는 깨달았고, JavaScript 솔루션으로 정착하기보다 PHP로 그것을 사용하는 방법을 찾는 것이 더 나을 것이라고 생각했다. 그것은 작동하는 경우 놀라운 대답은, 내가 그것을 테스트하자마자 수용! –

+0

네, 완벽하게 작동합니다! 엄청 고마워! –

+0

좋아 :) 그걸로 즐겁게 보내십시오. 어떤 이유로 든 화일이 실패하면 오류 메시지를 얻기 위해 stderr에서도 읽어야합니다. – hek2mgl