]> git.donarmstrong.com Git - lilypond.git/blobdiff - scripts/lilypond-book.py
''
[lilypond.git] / scripts / lilypond-book.py
index 3deb00b92b31c04d5e1079e9bc0fd1ea36019ac8..cbb84e7b84ef6843c0e7f15f564b0a2184771d57 100644 (file)
@@ -40,8 +40,6 @@
 import os
 import stat
 import string
-
-
 import getopt
 import sys
 import __main__
@@ -50,14 +48,16 @@ import operator
 # Handle bug in Python 1.6-2.1
 #
 # there are recursion limits for some patterns in Python 1.6 til 2.1. 
-# fix this by importing pre instead. Fix by Mats.
+# fix this by importing the 1.5.2 implementation pre instead. Fix by Mats.
 
-# todo: should check Python version first.
-try:
-       import pre
-       re = pre
-       del pre
-except ImportError:
+if float (sys.version[0:3]) < 2.2:
+       try:
+               import pre
+               re = pre
+               del pre
+       except ImportError:
+               import re
+else:
        import re
 
 # Attempt to fix problems with limited stack size set by Python!
@@ -72,6 +72,8 @@ except:
 errorport = sys.stderr
 verbose_p = 0
 
+
+
 try:
        import gettext
        gettext.bindtextdomain ('lilypond', localedir)
@@ -101,15 +103,17 @@ else:
 while datadir[-1] == os.sep:
        datadir= datadir[:-1]
 
-# Try to cater for bad installations of LilyPond, that have
-# broken TeX setup.  Just hope this doesn't hurt good TeX
-# setups.  Maybe we should check if kpsewhich can find
-# feta16.{afm,mf,tex,tfm}, and only set env upon failure.
+kpse = os.popen ('kpsexpand \$TEXMF').read()
+kpse = re.sub('[ \t\n]+$','', kpse)
+type1_paths = os.popen ('kpsewhich -expand-path=\$T1FONTS').read ()
+
 environment = {
-       'MFINPUTS' : datadir + '/mf:',
-       'TEXINPUTS': datadir + '/tex:' + datadir + '/ps:.:',
-       'TFMFONTS' : datadir + '/tfm:',
-       'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
+       # TODO: * prevent multiple addition.
+       #       * clean TEXINPUTS, MFINPUTS, TFMFONTS,
+       #         as these take prevalence over $TEXMF
+       #         and thus may break tex run?
+       'TEXMF' : "{%s,%s}" % (datadir, kpse) ,
+       'GS_FONTPATH' : type1_paths,
        'GS_LIB' : datadir + '/ps',
 }
 
@@ -121,6 +125,10 @@ non_path_environment = {
 }
 
 def setup_environment ():
+       # $TEXMF is special, previous value is already taken care of
+       if os.environ.has_key ('TEXMF'):
+               del os.environ['TEXMF']
        for key in environment.keys ():
                val = environment[key]
                if os.environ.has_key (key):
@@ -143,6 +151,7 @@ g_force_lilypond_fontsize = 0
 g_read_lys = 0
 g_do_pictures = 1
 g_num_cols = 1
+g_do_music = 1
 
 format = ''
 g_run_lilypond = 1
@@ -441,6 +450,7 @@ option_definitions = [
        ('PREF', '',  'dep-prefix', 'prepend PREF before each -M dependency'),
        ('', 'n', 'no-lily', 'don\'t run lilypond'),
        ('', '', 'no-pictures', "don\'t generate pictures"),
+       ('', '', 'no-music', "strip all lilypond blocks from output"),  
        ('', '', 'read-lys', "don't write ly files."),
        ('FILE', 'o', 'outname', 'filename main output file'),
        ('FILE', '', 'outdir', "where to place generated files"),
@@ -563,9 +573,11 @@ def output_verbatim (body):
 
 #warning: this uses extended regular expressions. Tread with care.
 
-# legenda (?P  name parameter
-# *? match non-greedily.
+# legenda
 
+# (?P  -- name parameter
+# *? -- match non-greedily.
+# (?m)  -- ?  
 re_dict = {
        'html': {
                 'include':  no_match,
@@ -575,9 +587,9 @@ re_dict = {
                 'landscape': no_match,
                 'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
                 'verb': r'''(?P<code><pre>.*?</pre>)''',
-                'lilypond-file': '(?m)(?P<match><lilypondfile(?P<options>[^>]*)?>\s*(?P<filename>.*?)\s*</lilypondfile>)',
+                'lilypond-file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
                 'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
-                'lilypond-block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]*)?>(?P<code>.*?)</lilypond>)''',
+                'lilypond-block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
                  'option-sep' : '\s*',
                  'intertext': r',?\s*intertext=\".*?\"',
                  'multiline-comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
@@ -619,7 +631,7 @@ re_dict = {
                 'verb': r'''(?P<code>@code{.*?})''',
                 'lilypond-file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
                 'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
-                'lilypond-block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
+                'lilypond-block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end +lilypond)\s''',
                 'option-sep' : ',\s*',
                 'intertext': r',?\s*intertext=\".*?\"',
                 'multiline-comment': r"(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end ignore)\s",
@@ -825,7 +837,7 @@ def scan_latex_preamble(chunks):
                                        paperguru.m_fontsize = int(m.group(1))
                break
        
-       while chunks[idx][0] != 'preamble-end':
+       while idx < len(chunks) and chunks[idx][0] != 'preamble-end':
                if chunks[idx] == 'ignore':
                        idx = idx + 1
                        continue
@@ -871,19 +883,25 @@ def completize_preamble (chunks):
                        m = get_re('def-post-re').search(chunk[1])
                        if m:
                                post_b = 1
+                               
                if chunk[0] == 'input':
                        m = get_re('usepackage-graphics').search(chunk[1])
                        if m:
                                graphics_b = 1
        x = 0
-       while chunks[x][0] != 'preamble-end':
+       while x < len (chunks) and   chunks[x][0] != 'preamble-end':
                x = x + 1
+
+       if x == len(chunks):
+               return chunks
+       
        if not pre_b:
                chunks.insert(x, ('input', get_output ('output-default-pre')))
        if not post_b:
                chunks.insert(x, ('input', get_output ('output-default-post')))
        if not graphics_b:
                chunks.insert(x, ('input', get_output ('usepackage-graphics')))
+
        return chunks
 
 
@@ -959,6 +977,9 @@ def make_lilypond_file(m):
                        (options, content))]
 
 def make_lilypond_block(m):
+       if not g_do_music:
+               return []
+       
        if m.group('options'):
                options = get_re('option-sep').split (m.group('options'))
        else:
@@ -1001,7 +1022,7 @@ def determine_format (str):
        if __main__.format == '':
                
                html = re.search ('(?i)<[dh]tml', str[:200])
-               latex = re.search ('''\\document''', str[:200])
+               latex = re.search (r'''\\document''', str[:200])
                texi = re.search ('@node|@setfilename', str[:200])
 
                f = ''
@@ -1131,7 +1152,7 @@ def schedule_lilypond_block (chunk):
        newbody = newbody + get_output (s) % {'fn': basename }
        return ('lilypond', newbody, opts, todo, basename)
 
-def process_lilypond_blocks(outname, chunks):#ugh rename
+def process_lilypond_blocks(chunks):#ugh rename
        newchunks = []
        # Count sections/chapters.
        for c in chunks:
@@ -1151,6 +1172,12 @@ def system (cmd):
                error ('Error command exited with value %d\n' % st)
        return st
 
+def quiet_system (cmd, name):
+       if not verbose_p:
+               progress ( _("Running %s...") % name)
+               cmd = cmd + ' 1> /dev/null 2> /dev/null'
+
+       return system (cmd)
 
 def get_bbox (filename):
        system ('gs -sDEVICE=bbox -q  -sOutputFile=- -dNOPAUSE %s -c quit > %s.bbox 2>&1 ' % (filename, filename))
@@ -1175,13 +1202,11 @@ def make_pixmap (name):
        x = (2* margin + bbox[2] - bbox[0]) * res / 72.
        y = (2* margin + bbox[3] - bbox[1]) * res / 72.
 
-       cmd = r'''gs -g%dx%d -sDEVICE=pgm  -dTextAlphaBits=4 -dGraphicsAlphaBits=4  -q -sOutputFile=- -r%d -dNOPAUSE %s %s -c quit | pnmtopng > %s'''
+       cmd = r'''gs -g%dx%d -sDEVICE=pnggray  -dTextAlphaBits=4 -dGraphicsAlphaBits=4  -q -sOutputFile=- -r%d -dNOPAUSE %s %s -c quit  > %s'''
        
        cmd = cmd % (x, y, res, name + '.trans.eps', name + '.eps',name + '.png')
-       if not verbose_p:
-               progress ( _("Running %s...") % 'gs')
-               cmd = cmd + ' 1> /dev/null 2> /dev/null'
-               
+       quiet_system (cmd, 'gs')
+
        try:
                status = system (cmd)
        except:
@@ -1227,9 +1252,7 @@ def compile_all_files (chunks):
                texfiles = string.join (tex, ' ')
                cmd = 'lilypond --header=texidoc %s %s %s' \
                      % (lilyopts, g_extra_opts, texfiles)
-               if not verbose_p:
-                       progress ( _("Running %s...") % 'LilyPond')
-                       cmd = cmd + ' 1> /dev/null 2> /dev/null'
+
                system (cmd)
 
                #
@@ -1247,17 +1270,11 @@ def compile_all_files (chunks):
                                f.close ()
 
        for e in eps:
-               cmd = r"tex '\nonstopmode \input %s'" % e
-               if not verbose_p:
-                       progress ( _("Running %s...") % 'TeX')
-                       cmd = cmd + ' 1> /dev/null 2> /dev/null'
-               system (cmd)
+               cmd = r"echo $TEXMF; tex '\nonstopmode \input %s'" % e
+               quiet_system (cmd, 'TeX')
                
                cmd = r"dvips -E -o %s %s" % (e + '.eps', e)
-               if not verbose_p:
-                       progress ( _("Running %s...") % 'dvips')
-                       cmd = cmd + ' 1> /dev/null 2> /dev/null'
-               system (cmd) 
+               quiet_system (cmd, 'dvips')
                
        for g in png:
                make_pixmap (g)
@@ -1439,17 +1456,9 @@ def fix_epswidth (chunks):
        return newchunks
 
 
+##docme: why global?
 foutn=""
 def do_file(input_filename):
-       global foutn
-       file_settings = {}
-       if outname:
-               my_outname = outname
-       elif input_filename == '-' or input_filename == "/dev/stdin":
-               my_outname = '-'
-       else:
-               my_outname = os.path.basename (os.path.splitext(input_filename)[0])
-       my_depname = my_outname + '.dep'                
 
        chunks = read_doc_file(input_filename)
        chunks = chop_chunks(chunks, 'lilypond', make_lilypond, 1)
@@ -1462,7 +1471,7 @@ def do_file(input_filename):
        #for c in chunks: print "c:", c;
        #sys.exit()
        scan_preamble(chunks)
-       chunks = process_lilypond_blocks(my_outname, chunks)
+       chunks = process_lilypond_blocks(chunks)
 
        # Do It.
        if __main__.g_run_lilypond:
@@ -1474,14 +1483,24 @@ def do_file(input_filename):
 
        x = 0
        chunks = completize_preamble (chunks)
+
+
+       global foutn
+
+       if outname:
+               my_outname = outname
+       elif input_filename == '-' or input_filename == "/dev/stdin":
+               my_outname = '-'
+       else:
+               my_outname = os.path.basename (os.path.splitext(input_filename)[0]) + '.' + format
+       my_depname = my_outname + '.dep'                
+       
        if my_outname == '-' or my_outname == '/dev/stdout':
                fout = sys.stdout
                foutn = "<stdout>"
                __main__.do_deps = 0
        else:
-               ## ugh, ugh.
-               foutn = os.path.join (g_outdir, my_outname + '.' + format)
-               ## foutn = os.path.join (g_outdir, my_outname)
+               foutn = os.path.join (g_outdir, my_outname)
                sys.stderr.write ("Writing `%s'\n" % foutn)
                fout = open (foutn, 'w')
        for c in chunks:
@@ -1543,6 +1562,8 @@ for opt in options:
                g_dep_prefix = a
        elif o == '--no-pictures':
                g_do_pictures = 0
+       elif o == '--no-music':
+               g_do_music = 0
        elif o == '--read-lys':
                g_read_lys = 1
        elif o == '--outdir':