]> git.donarmstrong.com Git - lilypond.git/blobdiff - python/book_latex.py
Release: bump Welcome versions.
[lilypond.git] / python / book_latex.py
index ec4ce93156565a0a7af613d1d295dda2ef2981bf..ec5412b1d8192bee41e292e31bc62a78798cc45d 100644 (file)
@@ -3,9 +3,17 @@
 import re
 import tempfile
 import os
+import sys
+import subprocess
 import book_base as BookBase
 from book_snippets import *
 import lilylib as ly
+global _;_=ly._
+
+progress = ly.progress
+warning = ly.warning
+error = ly.error
+debug = ly.debug_output
 
 # Recognize special sequences in the input.
 #
@@ -63,6 +71,17 @@ Latex_snippet_res = {
            (?P<filename>\S+?)
           })''',
 
+    'musicxml_file':
+         r'''(?smx)
+          ^[^%\n]*?
+          (?P<match>
+          \\musicxmlfile\s*(
+          \[
+           \s*(?P<options>.*?)\s*
+          \])?\s*\{
+           (?P<filename>\S+?)
+          })''',
+
     'singleline_comment':
          r'''(?mx)
           ^.*?
@@ -101,24 +120,26 @@ Latex_output = {
 
     OUTPUT: r'''{%%
 \parindent 0pt
+\noindent
 \ifx\preLilyPondExample \undefined
 \else
   \expandafter\preLilyPondExample
 \fi
 \def\lilypondbook{}%%
-\input %(base)s-systems.tex
+\input{%(base)s-systems.tex}
 \ifx\postLilyPondExample \undefined
 \else
   \expandafter\postLilyPondExample
 \fi
 }''',
 
-    PRINTFILENAME: '''\\texttt{%(filename)s}
+    PRINTFILENAME: r'''\texttt{%(filename)s}
+\linebreak
 ''',
 
-    QUOTE: r'''\begin{quotation}
+    QUOTE: r'''\begin{quote}
 %(str)s
-\end{quotation}''',
+\end{quote}''',
 
     VERBATIM: r'''\noindent
 \begin{verbatim}%(verb)s\end{verbatim}
@@ -145,30 +166,76 @@ LATEX_INSPECTION_DOCUMENT = r'''
 
 # Do we need anything else besides `textwidth'?
 def get_latex_textwidth (source, global_options):
+    # default value
+    textwidth = 550.0
+
     m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
     if m == None:
         warning (_ ("cannot find \\begin{document} in LaTeX document"))
-
-        ## what's a sensible default?
-        return 550.0
+        return textwidth
 
     preamble = source[:m.start (0)]
     latex_document = LATEX_INSPECTION_DOCUMENT % {'preamble': preamble}
 
     (handle, tmpfile) = tempfile.mkstemp('.tex')
-    logfile = os.path.splitext (tmpfile)[0] + '.log'
-    logfile = os.path.split (logfile)[1]
+    tmpfileroot = os.path.splitext (tmpfile)[0]
+    tmpfileroot = os.path.split (tmpfileroot)[1]
+    auxfile = tmpfileroot + '.aux'
+    logfile = tmpfileroot + '.log'
 
     tmp_handle = os.fdopen (handle,'w')
     tmp_handle.write (latex_document)
     tmp_handle.close ()
 
-    ly.system ('%s %s' % (global_options.latex_program, tmpfile),
-               be_verbose=global_options.verbose)
-    parameter_string = file (logfile).read()
-
+    progress (_ ("Running `%s' on file `%s' to detect default page settings.\n")
+              % (global_options.latex_program, tmpfile))
+    cmd = '%s %s' % (global_options.latex_program, tmpfile)
+    debug ("Executing: %s\n" % cmd)
+    run_env = os.environ.copy()
+    run_env['LC_ALL'] = 'C'
+    run_env['TEXINPUTS'] = '%s:%s' % \
+                           (global_options.input_dir, run_env.get('TEXINPUTS',""))
+
+    ### unknown why this is necessary
+    universal_newlines = True
+    if sys.platform == 'mingw32':
+        universal_newlines = False
+        ### use os.system to avoid weird sleep() problems on
+        ### GUB's python 2.4.2 on mingw
+        # make file to write to
+        output_dir = tempfile.mkdtemp()
+        output_filename = os.path.join(output_dir, 'output.txt')
+        # call command
+        cmd += " > %s" % output_filename
+        oldtexinputs = os.environ.get ('TEXINPUTS')
+        os.environ['TEXINPUTS'] = run_env['TEXINPUTS']
+        returncode = os.system(cmd)
+        if oldtexinputs:
+            os.environ['TEXINPUTS'] = oldtexinputs
+        else:
+            del os.environ['TEXINPUTS']
+        parameter_string = open(output_filename).read()
+        if returncode != 0:
+            warning (_ ("Unable to auto-detect default settings:\n"))
+        # clean up
+        os.remove(output_filename)
+        os.rmdir(output_dir)
+    else:
+        proc = subprocess.Popen (cmd,
+            env=run_env,
+            universal_newlines=universal_newlines,
+            shell=True,
+            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+        (parameter_string, error_string) = proc.communicate ()
+        if proc.returncode != 0:
+            warning (_ ("Unable to auto-detect default settings:\n%s")
+                    % error_string)
     os.unlink (tmpfile)
-    os.unlink (logfile)
+    if os.path.exists (auxfile):
+        os.unlink (auxfile)
+    if os.path.exists (logfile):
+        parameter_string = file (logfile).read()
+        os.unlink (logfile)
 
     columns = 0
     m = re.search ('columns=([0-9.]+)', parameter_string)
@@ -180,12 +247,22 @@ def get_latex_textwidth (source, global_options):
     if m:
         columnsep = float (m.group (1))
 
-    textwidth = 0
     m = re.search ('textwidth=([0-9.]+)pt', parameter_string)
     if m:
         textwidth = float (m.group (1))
-        if columns:
-            textwidth = (textwidth - columnsep) / columns
+    else:
+        warning (_ ("cannot detect textwidth from LaTeX"))
+        return textwidth
+
+    debug ('Detected values:')
+    debug ('  columns = %s' % columns)
+    debug ('  columnsep = %s' % columnsep)
+    debug ('  textwidth = %s' % textwidth)
+
+    if m and columns:
+        textwidth = (textwidth - columnsep) / columns
+        debug ('Adjusted value:')
+        debug ('  textwidth = %s' % textwidth)
 
     return textwidth
 
@@ -226,9 +303,10 @@ class BookLatexOutputFormat (BookBase.BookOutputFormat):
     def input_fullname (self, input_filename):
         # Use kpsewhich if available, otherwise fall back to the default:
         if ly.search_exe_path ('kpsewhich'):
-            return os.popen ('kpsewhich ' + input_filename).read()[:-1]
-        else:
-            return BookBase.BookOutputFormat.input_fullname (self, input_filename)
+            trial = os.popen ('kpsewhich ' + input_filename).read()[:-1]
+            if trial:
+                return trial
+        return BookBase.BookOutputFormat.input_fullname (self, input_filename)
 
     def process_chunks (self, chunks):
         for c in chunks:
@@ -241,8 +319,11 @@ class BookLatexOutputFormat (BookBase.BookOutputFormat):
     def snippet_output (self, basename, snippet):
         str = ''
         rep = snippet.get_replacements ();
-        rep['base'] = basename
-        str += self.output_print_filename (basename, snippet)
+        rep['base'] = basename.replace ('\\', '/')
+        rep['filename'] = os.path.basename (snippet.filename).replace ('\\', '/')
+        rep['ext'] = snippet.ext
+        if PRINTFILENAME in snippet.option_dict:
+            str += self.output[PRINTFILENAME] % rep
         if VERBATIM in snippet.option_dict:
             rep['verb'] = snippet.verb_ly ()
             str += self.output[VERBATIM] % rep
@@ -255,8 +336,7 @@ class BookLatexOutputFormat (BookBase.BookOutputFormat):
             str += "".ljust (breaks, "\n").replace ("\n","%\n")
 
         if QUOTE in snippet.option_dict:
-            rep['str'] = str
-            str = self.output[QUOTE] % rep
+            str = self.output[QUOTE] % {'str': str}
         return str