]> git.donarmstrong.com Git - lilypond.git/blobdiff - scripts/ly2dvi.py
release: 1.2.7
[lilypond.git] / scripts / ly2dvi.py
index a36afe58321ed5863d68a758f662d007d1525e61..e0682e5b23ac34f5564cfca6ad623d0e622307e7 100644 (file)
@@ -1,5 +1,8 @@
 #!@PYTHON@
 
+
+# TODO: Rewrite this.  The control structure is too hairy.
+
 """
 =======================================================================
 LilyPond to dvi converter
@@ -14,7 +17,7 @@ Output: DVI file
 """
 
 name = 'ly2dvi'
-version = '0.0.7'
+version = '@TOPLEVEL_VERSION@'
 errorlog = ''
 
 import sys
@@ -24,12 +27,13 @@ import re
 import string
 import time
 import glob
+import tempfile
 
 
 class Input:
     """
     This class handles all ly2dvi.py input file methods
-
+    
     Public methods:
     
     __init__()  Constructor
@@ -54,7 +58,7 @@ class Input:
         open file and set private class variable __fd.  The search
         sequence is: current directory followed by the directories
         found in include property list.  Each directory is searched
-        for file, file.ly, and file.fly.
+        for file, file.ly, file.sly and file.fly.
         
         input:  file   filename
         output: void
@@ -63,7 +67,7 @@ class Input:
 
         for i in [''] + Props.get('include')[0:]:
             ifile = os.path.join(i,file)
-            for j in ['','.ly','.fly']:
+            for j in ['','.ly','.fly', '.sly']:
                 jfile = ifile+j
                 try:
                     this.__fd = open( jfile, 'r' )
@@ -102,7 +106,7 @@ class Input:
 
         firstline = this.__fd.readline()
         this.__fd.seek(0)
-        if  re.match('% Creator: GNU LilyPond [0-9]+[.0-9]+',firstline ):
+        if  re.match('%created by: GNU LilyPond [0-9]+[.0-9]+',firstline ):
             return 'output'
         else:
             return 'source'
@@ -231,7 +235,7 @@ class TeXOutput:
         else:
             pageheight = Props.get('pageheight')
             pagewidth = Props.get('pagewidth')
-                             
+                                
         horizontalMarginArg =  ( (pagewidth - linewidth)/2 )   
         verticalMarginArg =  ( (pageheight - textheight)/2  )
 
@@ -260,9 +264,12 @@ class TeXOutput:
         linewidth, horizontalMarginArg, textheight, verticalMarginArg,
         Props.get('header') )
         
-        pathcomp = os.path.splitext(file)
-        this.__base = pathcomp[0]
-        this.__outfile = '%s.%d%s' % (pathcomp[0], os.getpid(), pathcomp[1])
+        base, ext = os.path.splitext(file)
+        this.__base = base
+        tempfile.template= base + '_ly'
+        this.__outfile = tempfile.mktemp(ext)
+        base, ext = os.path.splitext(this.__outfile)
+        this.__tmpbase = base
         try:
             this.__fd = open(this.__outfile,"w")
         except:
@@ -270,7 +277,6 @@ class TeXOutput:
         this.write(top)
         this.__mudelaDefs('')
         this.write("""\
-\\cmrtwenty% ugh
 \\makelilytitle
 """) 
 
@@ -319,10 +325,12 @@ class TeXOutput:
             outfile = os.path.join(Props.get('output'), outfile )
             
         this.write("""\
-\\vfill\\hfill{\\LilyIdString}
+\\vfill\\hfill{\\mudelatagline}
 \\end{document}
 """)
         this.__fd.close()
+        if os.path.isfile(outfile):
+            os.remove(outfile)
         if ( os.name == 'posix' ):
             stat = os.system('latex \'\\nonstopmode \\input %s\'' %
                              (this.__outfile))
@@ -331,23 +339,27 @@ class TeXOutput:
                              (this.__outfile))
         if stat:
             sys.exit('ExitBadLatex')
-        if os.path.isfile(outfile):
-            os.remove(outfile)
-        os.rename(this.__base + '.' + str(os.getpid()) + '.dvi', outfile)
-        sys.stderr.write( '\n' + program_id() + ': dvi file name is %s\n\n'
-                   % (outfile))
+        if not os.path.isfile(outfile):
+               os.rename(this.__tmpbase + '.dvi', outfile)
+               
+        sys.stderr.write('\n' + program_id() + ': dvi file name is %s\n\n'
+                        % (outfile))
 
         if Props.get('postscript'):
             psoutfile=this.__base + '.ps'
             if Props.get('output') != '':
                 psoutfile = os.path.join(Props.get('output'), psoutfile )
-            stat = os.system('dvips -o %s %s 2>&1' % (psoutfile,outfile))
+            stat = os.system('dvips -o %s %s' % (psoutfile,outfile))
             if stat:
                 sys.exit('ExitBadPostscript')
             
 
 \f
 
+
+# ARG! THIS CODE IS BLOATED:
+# FIXME: Junk all set/get methods.
+
 class Properties:
     """
     This class handles all ly2dvi.py property manipulation
@@ -370,7 +382,7 @@ class Properties:
         # init          Initial default values
         # file          The values found in the lilypond generated TeX files
         # environment   Envrionment variables LILYINCLUDE, LILYPONDPREFIX
-        # rcfile        $LILYPONDPREFIX/share/lilypond/.lilyrc
+        # rcfile        $LILYPONDPREFIX/.lilyrc
         # rcfile        $HOME/.lilyrc
         # rcfile        ./.lilyrc
         # commandline   command line arguments
@@ -393,7 +405,7 @@ class Properties:
             'pageheight'   :  [845, this.__overrideTable['init']],
             'papersize'    :  ['a4paper', this.__overrideTable['init']],
             'textheight'   :  [0, this.__overrideTable['init']],
-            'linewidth'    :  [0, this.__overrideTable['init']],
+            'linewidth'    :  [500, this.__overrideTable['init']],
             'orientation'  :  ['portrait', this.__overrideTable['init']],
             'language'     :  ['%', this.__overrideTable['init']],
             'include'      :  [[], this.__overrideTable['init']],
@@ -424,7 +436,7 @@ class Properties:
             p=os.path.split(p[0])
            # bit silly. for ly2dvi, overrules compiled-in datadir...
            # how to do this better (without running lily, of course?
-            this.setRoot(p[0] + '/share/lilypond', 'init')
+            this.setRoot(os.path.join(p[0],'share','lilypond'), 'init')
 
         if not os.environ.has_key('HOME'):
             if os.environ.has_key('HOMEDRIVE') and \
@@ -443,22 +455,24 @@ class Properties:
             this.__set('include', tmp, 'environment')    
 
 
-        t=''
+        t= os.pathsep
        if os.environ.has_key ('TEXINPUTS'):
-               t = os.pathsep + os.environ['TEXINPUTS']
-        os.environ['TEXINPUTS'] = os.path.join(this.get('root'), 'share',
-                                              'lilypond', 'tex' ) + t
+               t = os.environ['TEXINPUTS'] + os.pathsep
+        os.environ['TEXINPUTS'] = t + \
+       os.path.join(this.get('root'), 'tex' ) + \
+       os.pathsep + os.path.join(this.get('root'), 'ps' )
 
         t=''
        if os.environ.has_key ('MFINPUTS'):
-               t = os.pathsep + os.environ['MFINPUTS']
-        os.environ['MFINPUTS'] = os.path.join(this.get('root'), 'share',
-                                              'lilypond', 'mf' ) + t
+               t = os.environ['MFINPUTS'] 
+        os.environ['MFINPUTS'] = os.pathsep + t + \
+                                 os.path.join(this.get('root'), 'mf')
 
         if os.environ.has_key('TMP'):
             this.__set('tmp',os.environ['TMP'],'environment')
 
-        
+
+    def read_titledefs (this):
        fd=this.get_texfile_path ('titledefs.tex')
         mudefs=[]    
 
@@ -507,8 +521,7 @@ class Properties:
         """
 
         if os.name == 'nt':
-            path = os.path.join(this.get('root'), 'share', 'lilypond',
-                                'tex', var)
+            path = os.path.join(this.get('root'), 'tex', var)
         else:
             path =''
             cmd =('kpsewhich tex %s %s' % (var,errorlog))
@@ -516,8 +529,7 @@ class Properties:
             path = pipe.readline ()[:-1] # chop off \n
             return_status =  pipe.close()
             if return_status and not path:
-                path = os.path.join(this.get('root'), 'share', 'lilypond',
-                                    'tex', var)
+                path = os.path.join(this.get('root'), 'tex', var)
        fd = open(path, 'r')
         return fd
 
@@ -556,7 +568,7 @@ class Properties:
         else: # Windows apps like edit choke on .lilyrc
             dotFilename='_lilyrc'
 
-       for d in [os.path.join(this.get('root'),'share','lilypond','ly'), \
+       for d in [os.path.join(this.get('root'),'ly'), \
                   os.environ['HOME'], os.curdir ]:
            file=os.path.join(d,dotFilename)
            try:
@@ -676,7 +688,7 @@ class Properties:
            else:
                sys.exit('ExitBadWidth', m.group(2))
        else:           
-           sys.exit('ExitBadWidth', size)
+           sys.stderr.write ('ly2dvi: warning: ignoring linewidth: ' + size + '\n')
 
     #
     # setOrientation
@@ -761,9 +773,9 @@ class Properties:
         """
 
         if int(value) == 1:
-            this.__set('pagenumber',1,requester)
+            this.__set('pagenumber','\\pagestyle{empty}',requester)
         else:
-            this.__set('pagenumber',0,requester)
+            this.__set('pagenumber','%',requester)
 
     #
     # setSeparate
@@ -793,7 +805,7 @@ class Properties:
     #
     # Set or Clear Dependencies flag to generate makefile dependencies
     #
-    def setDependencies(this, requester):      
+    def setDependencies(this, value, requester):       
         """
         Set or Clear dependencies flag
         """
@@ -855,7 +867,11 @@ class Properties:
         """
 
         os.environ['LILYPONDPREFIX'] = path
+        if os.name == 'nt' or os.name == 'dos':
+            path = unc2dos(path);
+
        this.__set('root',path,requester)
+        
 
     #
     # printProps
@@ -882,15 +898,17 @@ def getLilyopts():
     else:
 
         if Props.get('dependencies'):
-            dep=' -d'
+            dep=' -M'
         else:
             dep=''
        return inc + dep
     return inc
 
-def writeLilylog(contents):
+def writeLilylog(file,contents):
     if Props.get('keeplilypond'):
-        file='lilylog.' + str(os.getpid())
+        base, ext = os.path.splitext(file)
+        tempfile.template=base + "_li"
+        file=tempfile.mktemp('.log')
         output = Props.get('output')
         if output != '':
             file = os.path.join( output, file )
@@ -913,8 +931,19 @@ def getTeXFile(contents):
     else:
         return texfiles
 
+def unc2dos(path):
+    """
+    Convert a path of format //<drive>/this/that/the/other to
+    <drive>:\this\that\the\other
+    """
+    m=re.match('^//([A-Za-z])(/.*)$',path)
+    if m:
+        return m.group(1) + ':' + os.path.normpath(m.group(2))
+    
+    
+
 def program_id ():
-    return name + ' ' + version;
+    return 'ly2dvi (GNU lilypond) ' + version;
 
 
 def mailaddress():
@@ -927,32 +956,36 @@ def mailaddress():
 def identify ():
     sys.stderr.write (program_id () + '\n')
 
+def print_version ():
+    sys.stdout.write (program_id () + '\n')
+
 def help ():
-    sys.stderr.write (
-        'Generate dvi file from mudela or lilypond output\n'
-        'Usage: ' + name + ' [OPTION]... [FILE]...\n'
-        '\n'
-        'Options:\n'
-        '  -D,--debug           increase verbosity\n'
-        '  -F,--headers=        name of additional LaTeX headers file\n'
-        '  -H,--Height=         set paper height (points) (see manual page)\n'
-        '  -I,--include=DIR     add DIR to LilyPond\'s search path\n'
-        '  -K,--keeplilypond    keep lilypond output files\n'
-        '  -L,--landscape       set landscape orientation\n'
-        '  -N,--nonumber        switch off page numbering\n'
-        '  -O,--orientation=    set orientation (obsolete - use -L instead)\n'
-        '  -P,--postscript      generate postscript file\n'
-        '  -W,--Width=          set paper width (points) (see manual page)\n'
-        '  -d,--dependencies    tell lilypond make a dependencies file\n'
-        '  -h,--help            this help text\n'
-        '  -k,--keeply2dvi      keep ly2dvi output files\n'
-        '  -l,--language=       give LaTeX language (babel)\n'
-        '  -o,--output=         set output directory\n'
-        '  -p,--papersize=      give LaTeX papersize (eg. a4)\n'
-        '  -s,--separate        run all files separately through LaTeX\n'
-        '\n'
-        'files may be (a mix of) input to or output from lilypond(1)\n'
-        )
+    sys.stdout.write (
+"""Usage: %s [OPTION]... [FILE]...
+
+Generate dvi file from mudela or lilypond output
+
+Options:
+  -D,--debug           increase verbosity
+  -F,--headers=        name of additional LaTeX headers file
+  -H,--Height=         set paper height (points) (see manual page)
+  -I,--include=DIR     add DIR to LilyPond\'s search path
+  -K,--keeplilypond    keep lilypond output files
+  -L,--landscape       set landscape orientation
+  -N,--nonumber        switch off page numbering
+  -O,--orientation=    set orientation (obsolete - use -L instead)
+  -P,--postscript      generate postscript file
+  -W,--Width=          set paper width (points) (see manual page)
+  -M,--dependencies    tell lilypond make a dependencies file
+  -h,--help            this help text
+  -k,--keeply2dvi      keep ly2dvi output files
+  -l,--language=       give LaTeX language (babel)
+  -o,--output=         set output directory
+  -p,--papersize=      give LaTeX papersize (eg. a4)
+  -s,--separate        run all files separately through LaTeX
+
+files may be (a mix of) input to or output from lilypond(1)
+""" % name)
 
 \f
 
@@ -966,14 +999,15 @@ def main():
     infile = Input()
     outfile = TeXOutput()
     texInputFiles=[]
+    tempfile.tempdir=""
 
     (options, files) = getopt.getopt (sys.argv[1:],
-                                      'DF:H:I:KLNPW:dhkl:o:p:s',
+                                      'DF:H:I:KLNPW:Mhkl:o:p:s',
                                       ['debug', 'headers=', 'Height=',
                                        'include=', 'keeplilypond', 'landscape',
                                        'nonumber', 'Width=', 'dependencies',
                                        'help', 'keeply2dvi', 'language=',
-                                       'output=', 'papersize=', 'separate',
+                                       'output=', 'version', 'papersize=', 'separate',
                                        'postscript'])
     for opt in options:
         o = opt[0]
@@ -991,14 +1025,14 @@ def main():
         elif o == '--landscape' or o == '-L':
            Props.setOrientation('landscape','commandline')
         elif o == '--nonumber' or o == '-N':
-           Props.setNonumber('commandline')
+           Props.setNonumber(1,'commandline')
         elif o == '--Width' or o == '-W':
            Props.setLineWidth(a,'commandline')
-        elif o == '--dependencies' or o == '-d':
+        elif o == '--dependencies' or o == '-M':
            Props.setDependencies(1,'commandline')
         elif o == '--help' or o == '-h':
             help()
-            return 0
+           return 0
         elif o == '--keeply2dvi' or o == '-k':
            Props.setKeeply2dvi(1,'commandline')
         elif o == '--language' or o == '-l':
@@ -1011,14 +1045,24 @@ def main():
            Props.setSeparate(1,'commandline')
         elif o == '--postscript' or o == '-P':
            Props.setPostscript(1,'commandline')
-
+       elif o == '--version':
+           print_version ()
+           return 0
+           
+    identify()
+    Props.read_titledefs ()
+    
     if len(files):
         for file in files:
             infile.open(file)
             type = infile.type()
             infile.close()
             if type == 'source':
-                cmd = 'lilypond %s %s 2>&1' % (getLilyopts(), file)
+                if os.environ.has_key('OS') and \
+                   os.environ['OS'] == 'Windows_95':
+                    cmd = 'ash -c "lilypond %s %s 2>&1"' %(getLilyopts(), file)
+                else:
+                    cmd = 'lilypond %s %s 2>&1' % (getLilyopts(), file)
                sys.stderr.write ('executing: %s\n'% cmd)
                
                 fd = os.popen(cmd , 'r')
@@ -1041,7 +1085,7 @@ def main():
                 if stat:
                     sys.exit('ExitBadLily', cmd )
                 texFiles=getTeXFile(log)
-                writeLilylog(log)
+                writeLilylog(file,log)
                 Props.addLilyOutputFiles(texFiles,'program')
                 texInputFiles = texInputFiles + texFiles
             else:
@@ -1055,7 +1099,7 @@ def main():
             if Props.get('debug'):
                 Props.printProps()
             if firstfile:
-                outfile.start(file)
+                outfile.start(file)  # allow for specified name
             else:
                 outfile.next()
             outfile.write("""\
@@ -1096,13 +1140,12 @@ def cleanup():
     if not Props.get('keeplilypond'):
         lilyfiles = Props.get('lilyOutputFiles')
     if not Props.get('keeply2dvi'):
-        tmpfiles = glob.glob('*.' + str(os.getpid()) + '.*' )
+        tmpfiles = glob.glob('*_ly[0-9]*.*')
     for file in lilyfiles + tmpfiles:
         if os.path.isfile(file):
             os.remove(file)
 
 
-identify()
 Props = Properties()
 
 try: