]> git.donarmstrong.com Git - lilypond.git/blobdiff - scripts/mup2ly.py
*** empty log message ***
[lilypond.git] / scripts / mup2ly.py
index f7b7da1effda3defb4d5035c9be2bcb138b191ed..d9154fe079e9a71d8c4d4f0dda95a50e6842a37c 100644 (file)
@@ -34,46 +34,300 @@ import __main__
 import operator
 import tempfile
 
-sys.path.append ('@datadir@/python')
-sys.path.append ('@datadir@/buildscripts/out')
-sys.path.append ('@datadir@/modules/out')
 
+# if set, LILYPONDPREFIX must take prevalence
+# if datadir is not set, we're doing a build and LILYPONDPREFIX 
+datadir = '@local_lilypond_datadir@'
+if os.environ.has_key ('LILYPONDPREFIX') \
+   or '@local_lilypond_datadir@' == '@' + 'local_lilypond_datadir' + '@':
+       datadir = os.environ['LILYPONDPREFIX']
+else:
+       datadir = '@local_lilypond_datadir@'
+
+sys.path.append (os.path.join (datadir, 'python'))
+sys.path.append (os.path.join (datadir, 'python/out'))
+
+program_name = sys.argv[0]
+program_version = '@TOPLEVEL_VERSION@'
+original_dir = os.getcwd ()
+temp_dir = os.path.join (original_dir,  '%s.dir' % program_name)
+errorport = sys.stderr
+keep_temp_dir_p = 0
+verbose_p = 0
+
+localedir = '@localedir@'
 try:
        import gettext
-       gettext.bindtextdomain ('lilypond', '@localedir@')
+       gettext.bindtextdomain ('lilypond', localedir)
        gettext.textdomain ('lilypond')
        _ = gettext.gettext
 except:
        def _ (s):
                return s
 
-# Attempt to fix problems with limited stack size set by Python!
-# Sets unlimited stack size. Note that the resource module only
-# is available on UNIX.
-try:
-       import resource
-       resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
-except:
-       pass
 
 program_name = 'mup2ly'
-package_name = 'lilypond'
-help_summary = _ ("Convert mup to LilyPond source")
+help_summary = _ ("Convert mup to LilyPond source.")
 
 option_definitions = [
        ('', 'd', 'debug', _ ("debug")),
        ('NAME[=EXP]', 'D', 'define', _ ("define macro NAME [optional expansion EXP]")),
-       ('', 'h', 'help', _ ("this help")),
+       ('', 'h', 'help', _ ("print this help")),
        ('FILE', 'o', 'output', _ ("write output to FILE")),
        ('', 'E', 'pre-process', _ ("only pre-process")),
-       ('', 'V', 'verbose', _ ("verbose")),
+       ('', 'V', 'verbose', _ ("be verbose")),
        ('', 'v', 'version', _ ("print version number")),
        ('', 'w', 'warranty', _ ("show warranty and copyright")),
        ]
 
 
-from lilylib import *
+################################################################
+# lilylib.py -- options and stuff
+# 
+# source file of the GNU LilyPond music typesetter
 
+# 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.
+
+# todo: should check Python version first.
+try:
+       import pre
+       re = pre
+       del pre
+except ImportError:
+       import re
+
+# Attempt to fix problems with limited stack size set by Python!
+# Sets unlimited stack size. Note that the resource module only
+# is available on UNIX.
+try:
+       import resource
+       resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
+except:
+       pass
+
+try:
+       import gettext
+       gettext.bindtextdomain ('lilypond', localedir)
+       gettext.textdomain ('lilypond')
+       _ = gettext.gettext
+except:
+       def _ (s):
+               return s
+
+program_version = '@TOPLEVEL_VERSION@'
+if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
+       program_version = '1.5.54'
+
+def identify ():
+       sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
+
+def warranty ():
+       identify ()
+       sys.stdout.write ('\n')
+       sys.stdout.write (_ ('Copyright (c) %s by') % '2001--2005')
+       sys.stdout.write ('\n')
+       sys.stdout.write ('  Han-Wen Nienhuys')
+       sys.stdout.write ('  Jan Nieuwenhuizen')
+       sys.stdout.write ('\n\n')
+       sys.stdout.write (_ ("Distributed under terms of the GNU General Public License."))
+       sys.stdout.write (_ ("It comes with NO WARRANTY."))
+       sys.stdout.write ('\n')
+
+def progress (s):
+       errorport.write (s + '\n')
+
+def warning (s):
+       progress (_ ("warning: ") + s)
+
+def user_error (s, e=1):
+       errorport.write (program_name + ":" + _ ("error: ") + s + '\n')
+       sys.exit (e)
+       
+def error (s):
+       '''Report the error S.  Exit by raising an exception. Please
+       do not abuse by trying to catch this error. If you do not want
+       a stack trace, write to the output directly.
+
+       RETURN VALUE
+
+       None
+       
+       '''
+       
+       progress (_ ("error: ") + s)
+       raise _ ("Exiting ... ")
+
+def getopt_args (opts):
+       '''Construct arguments (LONG, SHORT) for getopt from  list of options.'''
+       short = ''
+       long = []
+       for o in opts:
+               if o[1]:
+                       short = short + o[1]
+                       if o[0]:
+                               short = short + ':'
+               if o[2]:
+                       l = o[2]
+                       if o[0]:
+                               l = l + '='
+                       long.append (l)
+       return (short, long)
+
+def option_help_str (o):
+       '''Transform one option description (4-tuple ) into neatly formatted string'''
+       sh = '  '       
+       if o[1]:
+               sh = '-%s' % o[1]
+
+       sep = '  '
+       if o[1] and o[2]:
+               sep = ', '
+               
+       long = ''
+       if o[2]:
+               long= '--%s' % o[2]
+
+       arg = ''
+       if o[0]:
+               if o[2]:
+                       arg = '='
+               arg = arg + o[0]
+       return '  ' + sh + sep + long + arg
+
+
+def options_help_str (opts):
+       '''Convert a list of options into a neatly formatted string'''
+       w = 0
+       strs =[]
+       helps = []
+
+       for o in opts:
+               s = option_help_str (o)
+               strs.append ((s, o[3]))
+               if len (s) > w:
+                       w = len (s)
+
+       str = ''
+       for s in strs:
+               str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0])  + 3), s[1])
+       return str
+
+def help ():
+       ls = [(_ ("Usage: %s [OPTIONS]... FILE") % program_name),
+               ('\n\n'),
+               (help_summary),
+               ('\n\n'),
+               (_ ("Options:")),
+               ('\n'),
+               (options_help_str (option_definitions)),
+               ('\n\n'),
+               (_ ("Report bugs to %s.") % 'bug-lilypond@gnu.org'),
+               ('\n')]
+       map (sys.stdout.write, ls)
+       
+def setup_temp ():
+       """
+       Create a temporary directory, and return its name. 
+       """
+       global temp_dir
+       if not keep_temp_dir_p:
+               temp_dir = tempfile.mktemp (program_name)
+       try:
+               os.mkdir (temp_dir, 0777)
+       except OSError:
+               pass
+
+       return temp_dir
+
+
+def system (cmd, ignore_error = 0, quiet =0):
+       """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
+
+       RETURN VALUE
+
+       Exit status of CMD
+       """
+       
+       if verbose_p:
+               progress (_ ("Invoking `%s\'") % cmd)
+
+       st = os.system (cmd)
+       if st:
+               name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
+               msg = name + ': ' + _ ("command exited with value %d") % st
+               if ignore_error:
+                       if not quiet:
+                               warning (msg + ' ' + _ ("(ignored)") + ' ')
+               else:
+                       error (msg)
+
+       return st
+
+
+def cleanup_temp ():
+       if not keep_temp_dir_p:
+               if verbose_p:
+                       progress (_ ("Cleaning %s...") % temp_dir)
+               shutil.rmtree (temp_dir)
+
+
+def strip_extension (f, ext):
+       (p, e) = os.path.splitext (f)
+       if e == ext:
+               e = ''
+       return p + e
+
+
+def cp_to_dir (pattern, dir):
+       "Copy files matching re PATTERN from cwd to DIR"
+       # Duh.  Python style portable: cp *.EXT OUTDIR
+       # system ('cp *.%s %s' % (ext, outdir), 1)
+       files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
+       map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
+
+
+# Python < 1.5.2 compatibility
+#
+# On most platforms, this is equivalent to
+#`normpath(join(os.getcwd()), PATH)'.  *Added in Python version 1.5.2*
+if os.path.__dict__.has_key ('abspath'):
+       abspath = os.path.abspath
+else:
+       def abspath (path):
+               return os.path.normpath (os.path.join (os.getcwd (), path))
+
+if os.__dict__.has_key ('makedirs'):
+       makedirs = os.makedirs
+else:
+       def makedirs (dir, mode=0777):
+               system ('mkdir -p %s' % dir)
+
+
+def mkdir_p (dir, mode=0777):
+       if not os.path.isdir (dir):
+               makedirs (dir, mode)
+
+
+# if set, LILYPONDPREFIX must take prevalence
+# if datadir is not set, we're doing a build and LILYPONDPREFIX 
+datadir = '@local_lilypond_datadir@'
+
+if os.environ.has_key ('LILYPONDPREFIX') :
+       datadir = os.environ['LILYPONDPREFIX']
+else:
+       datadir = '@local_lilypond_datadir@'
+
+
+while datadir[-1] == os.sep:
+       datadir= datadir[:-1]
+
+sys.path.insert (0, os.path.join (datadir, 'python'))
+
+################################################################
+# END Library
 
 
 output = 0
@@ -200,8 +454,8 @@ class Slur:
                e= self.end_chord
 
                if e and s:
-                       s.note_suffix = s.note_suffix + '('
-                       e.note_prefix = ')' + e.note_prefix
+                       s.note_suffix = s.note_suffix + '-('
+                       e.note_prefix = e.note_suffix + "-)"
                else:
                        sys.stderr.write ("\nOrphaned slur")
                        
@@ -270,7 +524,7 @@ class Voice:
                str = str  + ln
                id = self.idstring ()
                        
-               str = '''%s = \\context Voice = %s \\notes {
+               str = '''%s = \\context Voice = %s {
 %s
 }
 
@@ -312,9 +566,9 @@ class Key:
                if self.sharps and self.flats:
                        k = '\\keysignature %s ' % 'TODO'
                elif self.sharps:
-                       k = '\\notes\\key %s \major' % key_sharps[self.sharps]
+                       k = '\\key %s \major' % key_sharps[self.sharps]
                elif self.flats:
-                       k = '\\notes\\key %s \major' % key_flats[self.flats]
+                       k = '\\key %s \major' % key_flats[self.flats]
                return k
 
 class Time:
@@ -383,8 +637,8 @@ class Staff:
                                str = str + v.dump()
                                refs = refs + '\n  \\' + v.idstring ()
                str = str + '''
-%s = \context Staff = %s <%s
->
+%s = \context Staff = %s <<%s
+>>
 
 ''' % (self.idstring (), self.idstring (), refs)
                return str
@@ -466,19 +720,21 @@ class Chord:
                for p in self.pitches:
                        if str:
                                str = str + ' ' 
-                       str = str + pitch_to_lily_string (p) + sd
+                       str = str + pitch_to_lily_string (p)
 
-               for s in self.scripts:
-                       str = str + '-' + s
 
                str = self.note_prefix +str  + self.note_suffix
                
                if len (self.pitches) > 1:
                        str = '<%s>' % str
                elif self.multimeasure:
-                       str = 'R' + sd
+                       str = 'R'
                elif len (self.pitches) == 0:
-                       str = 'r' + sd
+                       str = 'r'
+
+               str = str + sd
+               for s in self.scripts:
+                       str = str + '-' + s
 
                str = self.chord_prefix + str + self.chord_suffix
                
@@ -843,9 +1099,9 @@ class Parser:
                str = str + '''
 
 \score {
-  <%s
-  >
-  \paper {}
+  <<%s
+  >>
+  \layout {}
   \midi {}
 }
 ''' % refs 
@@ -1034,12 +1290,13 @@ if not files:
        files = ['-']
        
 for f in files:
-
+       h = None
        if f == '-':
                h = sys.stdin
        elif f and not os.path.isfile (f):
                f = strip_extension (f, '.mup') + '.mup'
-               h = open (f)
+               
+       h = open (f)
        progress ( _("Processing `%s'..." % f))
        raw_lines = h.readlines ()
        p = Pre_processor (raw_lines)