2015-06-07 4 views
9

Sto provando ad usare un filtro Pandoc per convertire un file markdown con un'immagine tikz in html. Sono su Win 8.1 (e ho tutte le dipendenze - pdflatex, Python 2.7, ImageMagick e il pacchetto Python pandocfilters). Sto usando lo script tikz.py fornito da John MacFarlane su github.Come usare il filtro Python con Pandoc per convertire md con tikz in html su Windows 8.1

Ho trovato un simile question sul gruppo Google Pandoc e John MacFarlane suggerisce di avvolgere il filtro in uno script batch di Windows (il filtro deve essere un eseguibile). Ecco il mio input da riga di comando (fornirò il contenuto del file di seguito).

pandoc -o temp.html --filter .\tikz.bat -s temp.md 

Ma continuo a ricevere il seguente errore.

pandoc: Failed reading: satisfyElem 

Lo script genera la sottocartella "TikZ-immagini", ma è vuota, così come la risultante temp.html file di output.

Come posso farlo funzionare? FWIW, l'obiettivo più grande è che i file di input siano R Markdown, ma voglio prima comprendere il processo di Pandoc Markdown in HTML.

Ecco i contenuti del file.

tikz.bat

python tikz.py %* 

temp.md

\begin{tikzpicture} 

\draw [<->](-3,0)--(3,0); 
\draw (-2,-.2)--(-2,.2); 
\draw (-1,-.2)--(-1,.2); 
\draw(0,-.2)--(0,.2); 
\draw (1,-.2)--(1,.2); 
\draw (2,-.2)--(2,.2); 
\node[align=left,below] at (-4.5,-0.2) {Cash flow}; 
\node[align=left,above] at (-4.5,0.2) {Time period}; 
\node[align=left,above] at (-2,0.2) {-2}; 
\node[align=left,above] at (-1,0.2) {-1}; 
\node[align=left,above] at (0,0.2) {0}; 
\node[align=left,above] at (1,0.2) {+1}; 
\node[align=left,above] at (2,0.2) {+2}; 
\node[align=left,below] at (1,-0.2) {\$100}; 
\node[align=left,below] at (2,-0.2) {\$100}; 

\end{tikzpicture} 

Can this work? 

tikz.py

#!/usr/bin/env python 

""" 
Pandoc filter to process raw latex tikz environments into images. 
Assumes that pdflatex is in the path, and that the standalone 
package is available. Also assumes that ImageMagick's convert 
is in the path. Images are put in the tikz-images directory. 
""" 

import hashlib 
import re 
import os 
import sys 
import shutil 
from pandocfilters import toJSONFilter, Para, Image 
from subprocess import Popen, PIPE, call 
from tempfile import mkdtemp 

imagedir = "tikz-images" 


def sha1(x): 
    return hashlib.sha1(x.encode(sys.getfilesystemencoding())).hexdigest() 


def tikz2image(tikz, filetype, outfile): 
    tmpdir = mkdtemp() 
    olddir = os.getcwd() 
    os.chdir(tmpdir) 
    f = open('tikz.tex', 'w') 
    f.write("""\\documentclass{standalone} 
      \\usepackage{tikz} 
      \\begin{document} 
      """) 
    f.write(tikz) 
    f.write("\n\\end{document}\n") 
    f.close() 
    p = call(["pdflatex", 'tikz.tex'], stdout=sys.stderr) 
    os.chdir(olddir) 
    if filetype == 'pdf': 
     shutil.copyfile(tmpdir + '/tikz.pdf', outfile + '.pdf') 
    else: 
     call(["convert", tmpdir + '/tikz.pdf', outfile + '.' + filetype]) 
    shutil.rmtree(tmpdir) 


def tikz(key, value, format, meta): 
    if key == 'RawBlock': 
     [fmt, code] = value 
     if fmt == "latex" and re.match("\\\\begin{tikzpicture}", code): 
      outfile = imagedir + '/' + sha1(code) 
      if format == "html": 
       filetype = "png" 
      elif format == "latex": 
       filetype = "pdf" 
      else: 
       filetype = "png" 
      src = outfile + '.' + filetype 
      if not os.path.isfile(src): 
       try: 
        os.mkdir(imagedir) 
        sys.stderr.write('Created directory ' + imagedir + '\n') 
       except OSError: 
        pass 
       tikz2image(code, filetype, outfile) 
       sys.stderr.write('Created image ' + src + '\n') 
      return Para([Image([], [src, ""])]) 

if __name__ == "__main__": 
    toJSONFilter(tikz) 

Aggiornamento ho citato nei commenti che il caps.pyil filtro fallisce anche con gli stessi sintomi. Forse dovrei aggiungere anche i sintomi da python caps.py temp.md, che sta invocando il filtro al di fuori di pandoc. La mia comprensione è che questo dovrebbe stampare il file caps.py sullo schermo in maiuscolo.

Tuttavia, quando eseguo python caps.py temp.md dal prompt dei comandi di Windows, si blocca. Ho ucciso il comando con CTRL-C, quindi ho ottenuto quanto segue.

C:\Users\Richard\Desktop\temp>python caps.py temp.md 
Traceback (most recent call last): 
    File "caps.py", line 15, in <module> 
    toJSONFilter(caps) 

Lo stesso accade con python tikz.py temp.md. Un blocco, seguito da:

C:\Users\Richard\Desktop\temp>python tikz.py temp.md 
Traceback (most recent call last): 
    File "tikz.py", line 70, in <module> 
    toJSONFilter(tikz) 

Update 2 ho cercato di eseguire il debugger di Windows sul prompt dei comandi, ma non sono sicuro che ha funzionato. A volte il prompt dei comandi si bloccava. E sembra che anche il debugger si blocchi. Ecco l'output dal debugger.

*** wait with pending attach 
Symbol search path is: *** Invalid *** 
**************************************************************************** 
* Symbol loading may be unreliable without a symbol search path.   * 
* Use .symfix to have the debugger choose a symbol path.     * 
* After setting your symbol path, use .reload to refresh symbol locations. * 
**************************************************************************** 
Executable search path is: 
ModLoad: 00007ff7`0d920000 00007ff7`0d97d000 C:\windows\system32\cmd.exe 
ModLoad: 00007fff`b7c20000 00007fff`b7dcc000 C:\windows\SYSTEM32\ntdll.dll 
ModLoad: 00007fff`b5c90000 00007fff`b5dce000 C:\windows\system32\KERNEL32.DLL 
ModLoad: 00007fff`b4e40000 00007fff`b4f55000 C:\windows\system32\KERNELBASE.dll 
ModLoad: 00007fff`b7b70000 00007fff`b7c1a000 C:\windows\system32\msvcrt.dll 
ModLoad: 00007fff`b3070000 00007fff`b307e000 C:\windows\SYSTEM32\winbrand.dll 
(1c7c.29a0): Break instruction exception - code 80000003 (first chance) 
*** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\windows\SYSTEM32\ntdll.dll - 
ntdll!DbgBreakPoint: 
00007fff`b7cb2cf0 cc    int  3 

Update 3 Qui ci sono i file in una Dropbox folder. Questa cartella ha gli stessi file che ho incollato sopra, più il file caps.py che è diretto dal repository github dei filtri Pandoc.

+1

Hai provato un filtro di esempio semplice, come la capitalizzazione filtro? – mb21

+0

@ mb21 - Sì, ho provato 'caps.py' con la stessa identica configurazione (cioè, in un file batch con' python caps.py% * '), ma ottengo lo stesso errore:' pandoc: lettura non riuscita: satisfyElem'. Grazie, avrei dovuto includerlo nella mia domanda. Penso che l'errore abbia a che fare con l'essere in grado di passare argomenti a 'tikz.py', ma il mio Python non è abbastanza buono da capirlo. –

+0

Potrebbe forse eseguire lo stesso comando con [questo strumento di debug di Windows] (https://msdn.microsoft.com/en-us/library/windows/hardware/ff552060 (v = vs.85) .aspx) e pubblicare il produzione ? . – Schopenhauer

risposta

0

L'opzione -t viene utilizzata seguita da un formato non un file con l'estensione per esempio pandoc -f json -t markdown emetterà tale markdown, -t html produrrà html eccetera per acquisire l'output utilizzare un operatore di reindirizzamento operazione> file.some_extension. Ma il tuo output andrà alla console. Quindi la sintassi corretta è letteralmente pandoc -f json -t markdown.

Also the pandoc documentation. Se si verificano problemi, provare a modificare la propria lima da: pandoc -o temp.html --filter .\tikz.bat -s temp.md ==> pandoc -t json | ./caps.py latex | pandoc -f json -t html.

Ecco come funziona.

    source format = input_file.html 
         ↓ 
        (pandoc) = pandoc -t json input_file.html 
         ↓ 
       JSON-formatted AST 
         ↓ 
        (filter) = python $HOME/Downloads/pandocfilters-1.2.4/examples/caps.py 
         ↓ 
       JSON-formatted AST 
         ↓ 
        (pandoc) = pandoc -f json -t markdown 
         ↓ 
       target format = output_file.md 

separare i comandi per esaminare uscita e utilizzare un tubo | per reindirizzare l'output:

pandoc -t json ~/testing/testing.html | python examples/caps.py | pandoc -f json -t markdown > output_file.md 

Non è necessario installare pandocfilters scaricare il file tar, tar -xvf eseguire file.xyz o utilizzare qualsiasi altra applicazione di scelta e fare riferimento agli esempi di chiamare python dir/a/script.py poi reindirizzare nuovamente l'output a pandoc e redirezionare l'output nel formato di file desiderato. Ecco riga per riga:

$pandoc -t json ~/testing/testing.html 
[{"unMeta":{"viewport":{"t":"MetaInlines","c":[{"t":"Str","c":"width=device-width,"},{"t":"Space","c":[]},{"t":"Str","c":"initial-scale=1"}]},"title":{"t":"MetaInlines","c":[]},"description":{"t":"MetaInlines","c":[]}}},[{"t":"Para","c":[{"t":"Str","c":"Hello"},{"t":"Space","c":[]},{"t":"Str","c":"world!"},{"t":"Space","c":[]},{"t":"Str","c":"This"},{"t":"Space","c":[]},{"t":"Str","c":"is"},{"t":"Space","c":[]},{"t":"Str","c":"HTML5"},{"t":"Space","c":[]},{"t":"Str","c":"Boilerplate."}]},{"t":"Para","c":[{"t":"Str","c":"l"}]}]] 

poi:

$pandoc -t json ~/testing/testing.html | python examples/caps.py 
[{"unMeta": {"description": {"c": [], "t": "MetaInlines"}, "viewport": {"c": [{"c": "WIDTH=DEVICE-WIDTH,", "t": "Str"}, {"c": [], "t": "Space"}, {"c": "INITIAL-SCALE=1", "t": "Str"}], "t": "MetaInlines"}, "title": {"c": [], "t": "MetaInlines"}}}, [{"c": [{"c": "HELLO", "t": "Str"}, {"c": [], "t": "Space"}, {"c": "WORLD!", "t": "Str"}, {"c": [], "t": "Space"}, {"c": "THIS", "t": "Str"}, {"c": [], "t": "Space"}, {"c": "IS", "t": "Str"}, {"c": [], "t": "Space"}, {"c": "HTML5", "t": "Str"}, {"c": [], "t": "Space"}, {"c": "BOILERPLATE.", "t": "Str"}], "t": "Para"}, {"c": [{"c": "L", "t": "Str"}], "t": "Para"}]] 

infine:

pandoc -t json ~/testing/testing.html | python examples/caps.py | pandoc -f json -t markdown 
HELLO WORLD! THIS IS HTML5 BOILERPLATE. 

note:

diff -y pandoc_json.txt caps_json.txt 
[{"unMeta":{"viewport":{"t":"MetaInlines","c":[{"t":"Str","c"/[{"unMeta": {"description": {"c": [], "t": "MetaInlines"}, "v 
+0

Il mio script batch chiama questo script, sebbene io usi 'easy_install pandocfilters' per installarlo dal repository. Il wrapper di script batch è la soluzione proposta da John MacFarlane (e il poster afferma che funziona, sebbene non fornisca la soluzione di lavoro) nel link che ho fornito nella domanda. –

+0

Puoi provare 'pandoc -t json | ./caps.py latex | pandoc -f json -t temp.md'? – Schopenhauer

+0

Errore stesso 'satisfElem', anche se dovevo rimuovere l'ultimo' -t'. –