Anonymous avatar Anonymous committed 258ea8b

First version of desagetex parser scripts

Comments (0)

Files changed (3)

desagetexparser.py

+import sys
+sys.path.append('/home/drake/k/urohome/download/pyparsing-1.4.11')
+
+from pyparsing import *
+
+
+def skipToMatching(opener, closer):
+  nest = nestedExpr(opener, closer)
+  nest.setParseAction(lambda l, s, t: l[s:getTokensEndLoc()])
+  return nest
+
+curlybrackets = skipToMatching('{', '}')
+squarebrackets = skipToMatching('[', ']')
+
+class SoutParser():
+
+  def __init__(self, fn):
+    self.label = {}
+
+    parselabel = '\\newlabel{@sagelabel' + \
+                 Word(nums).setResultsName('num') + \
+                 '}{' + \
+                 curlybrackets.setResultsName('result') + \
+                 '{}{}{}{}}'
+    parselabel.ignore('%' + restOfLine)
+    parselabel.setParseAction(self.newlabel)
+
+    OneOrMore(parselabel).parseFile(fn)
+
+  def newlabel(self, s, l, t):
+    self.label[int(t.num)] = t.result[1:-1]
+
+
+class DeSageTex():
+
+  def __init__(self, fn_):
+    self.fn = fn_
+    self.sagen = 0
+    self.plotn = 0
+
+    self.sout = SoutParser(self.fn + '.sout')
+
+    # \sage{}:
+    smacro = '\\sage' + curlybrackets
+    smacro.setParseAction(self.sage)
+
+    # \usepackage[]{sagetex}:
+    usepackage = '\\usepackage' + \
+                 Optional(squarebrackets) + \
+                 '{sagetex}'
+    usepackage.setParseAction(replaceWith("""\\RequirePackage{verbatim}
+\\RequirePackage{graphicx}"""))
+
+    # \sageplot[][]{}:
+    splot = '\\sageplot' + \
+            Optional(squarebrackets).setResultsName('options') + \
+            Optional(squarebrackets) + \
+            curlybrackets
+    splot.setParseAction(self.plot)
+
+    # the printed environments:
+    beginorend = oneOf('begin end')
+
+    blockorverb = 'sage' + oneOf('block verbatim') 
+    blockorverb.setParseAction(replaceWith('verbatim'))
+    senv = '\\' + beginorend + '{' + blockorverb + '}'
+
+    # the non-printed environment:
+    silent = Literal('sagesilent')
+    silent.setParseAction(replaceWith('comment'))
+
+    ssilent = '\\' + beginorend + '{' + silent + '}'
+
+    # \sagetexindent:
+    stexindent = Suppress('\\setlength{\\sagetexindent}' + curlybrackets)
+
+    doit = smacro | senv | ssilent | usepackage | splot | stexindent
+    doit.ignore('%' + restOfLine)
+    doit.ignore('\\begin{verbatim}' + SkipTo('\\end{verbatim}'))
+    doit.ignore('\\begin{comment}' + SkipTo('\\end{comment}'))
+    
+    f = open(self.fn + '.tex', 'r')
+    str = ''.join(f.readlines())
+    self.result = doit.transformString(str)
+
+  def sage(self, s, l, t):
+    self.sagen += 1
+    return self.sout.label[self.sagen - 1]
+
+  def plot(self, s, l, t):
+    self.plotn += 1
+    if len(t.options) == 0:
+      opts = '[width=.75\\textwidth]'
+    else:
+      opts = t.options[0]
+    return '\\includegraphics%s{sage-plots-for-%s.tex/plot-%s}' % \
+      (opts, self.fn, self.plotn - 1)
+
+
+if __name__ == '__main__':
+  sout = SoutParser('example.sout')
+  print '=' * 50
+  print sout.label
 %
 %    \usepackage[imagemagick]{sagetex}
 
+\setlength{\sagetexindent}{10ex}
+
 \begin{document}
 \maketitle
 
 
 Here's a small plot of $f$ from $-5$ to $5$, which I've centered:
 
-\centerline{\sageplot[scale=.2]{p}}
+\begin{center} \sageplot[scale=.2]{p} \end{center}
 
 On second thought, use the default size of $3/4$ the \verb|\textwidth|
 and don't use axes:
 \sageplot[angle=45, width=.5\textwidth][png]{plot1}
 
 If you use regular \verb|latex| to make a DVI file, you'll see a box,
-beause DVI files can't include PNG files. If you use \verb|pdflatex|
+because DVI files can't include PNG files. If you use \verb|pdflatex|
 that will work. See the documentation for details.
 
 When using \verb|\sageplot|, you can pass in just about anything that
+#!/usr/bin/env python
+
+import sys
+import getopt
+import os.path
+from desagetexparser import DeSageTex
+
+def usage():
+  print("""Usage: %s [-h|--help] [-o|--overwrite] inputfile [outputfile] 
+
+Removes SageTeX macros from `inputfile' and replaces them with the
+Sage-computed results to make a "static" file. You'll need to have run
+Sage on `inputfile' already.
+
+`inputfile' can include the .tex extension or not. If you provide
+`outputfile', the results will be written to a file of that name.
+Specify `-o' or `--overwrite' to overwrite the file if it exists.
+
+See the SageTeX documentation for more details.""" % sys.argv[0])
+
+try:
+  opts, args = getopt.getopt(sys.argv[1:], 'ho', ['help', 'overwrite'])
+except getopt.GetoptError, err:
+  print str(err)
+  usage()
+  sys.exit(1)
+
+overwrite = False
+for o, a in opts:
+  if o in ('-h', '--help'):
+    usage()
+    sys.exit()
+  elif o in ('-o', '--overwrite'):
+    overwrite = True
+
+if len(args) == 0 or len(args) > 2:
+  print('Error: wrong number of arguments. Make sure you specify options first.\n') 
+  usage()
+  sys.exit(1)
+
+if len(args) == 2 and (os.path.exists(args[1]) and not overwrite):
+  print('Error: %s exists and overwrite option not specified.' % args[1])
+  sys.exit(1)
+
+src, ext = os.path.splitext(args[0])
+desagetexed = DeSageTex(src)
+
+if len(args) == 2:
+  dest = open(args[1], 'w')
+  dest.write(desagetexed.result)
+else:
+  print(desagetexed.result)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.