Skip to content

Instantly share code, notes, and snippets.

@kmader
Last active January 11, 2016 18:34
Show Gist options
  • Save kmader/947c7ed134ccf95bc264 to your computer and use it in GitHub Desktop.
Save kmader/947c7ed134ccf95bc264 to your computer and use it in GitHub Desktop.
Create markdown from nested latex files by following input and include commands using a simple python script

About

The script is to supplement the conversion in pandoc from latex to markdown by following simple commands like include and input since this is common in larger documents which are the ones that benefit most from pandoc's automatic conversion.

Example Command

To convert cv-stylish.tex to cv.md without intermediate files

python latexExpander.py cv-stylish.tex | pandoc --from=latex -o cv.md
import sys
def expandCommand(inText,cmdName,appendSuffix):
"""
takes a text and returns (recurvsively) all of the latex code involved)
"""
spLines = inText.split('\\'+cmdName+'{')
if(len(spLines)>1):
restArgs = map(lambda s: s.partition('}'),spLines[1:])
completeFile = [expandLatex(fName+appendSuffix)+' '+fLines for (fName,junk,fLines) in restArgs]
return ' '.join([spLines[0]]+completeFile)
else:
return inText
def expandLatex(inFileName,debug=False):
"""
takes a file and returns (recurvsively) all of the latex code involved)
"""
if (debug): print 'Parsing latex file:'+inFileName
fullFile = open(inFileName,'r').readlines()
allText=''.join(fullFile)
allText=expandCommand(allText,'input','.tex')
allText=expandCommand(allText,'include','')
return allText
def expandLatexFile(inFile,outFile):
exText = expandLatex(inFile,True)
out=open(outFile,'w')
out.write(exText)
out.flush()
out.close()
if __name__ == "__main__":
latexFile=sys.argv[1]
if(len(sys.argv)>2):
outFile=sys.argv[2]
expandLatexFile(latexFile,outFile)
else:
print expandLatex(latexFile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment