]> git.donarmstrong.com Git - lilypond.git/blob - scripts/mup2ly.py
* scripts/mup2ly.py: Cut-n-paste include missing lilylib.
[lilypond.git] / scripts / mup2ly.py
1 #!@PYTHON@
2 # mup2ly.py -- mup input converter
3
4 # source file of the GNU LilyPond music typesetter
5 #
6 # (c) 2001
7
8 '''
9 TODO:
10    LOTS: we get all notes out now, rest after 1.4
11
12    * lyrics (partly done)
13    * bars
14    * slurs,ties
15    * staff settings
16    * tuplets
17    * grace
18    * ornaments
19    * midi settings
20    * titling
21    * chords entry mode
22    * repeats, percent repeats
23    
24 '''
25
26 import os
27 import fnmatch
28 import stat
29 import string
30 import re
31 import getopt
32 import sys
33 import __main__
34 import operator
35 import tempfile
36
37
38 # if set, LILYPONDPREFIX must take prevalence
39 # if datadir is not set, we're doing a build and LILYPONDPREFIX 
40 datadir = '@datadir@'
41 if os.environ.has_key ('LILYPONDPREFIX') \
42    or '@datadir@' == '@' + 'datadir' + '@':
43         datadir = os.environ['LILYPONDPREFIX']
44 else:
45         datadir = '@datadir@'
46
47 sys.path.append (os.path.join (datadir, 'python'))
48 sys.path.append (os.path.join (datadir, 'python/out'))
49
50 program_name = 'ly2dvi'
51 program_version = '@TOPLEVEL_VERSION@'
52 original_dir = os.getcwd ()
53 temp_dir = os.path.join (original_dir,  '%s.dir' % program_name)
54 errorport = sys.stderr
55 keep_temp_dir_p = 0
56 verbose_p = 0
57
58 try:
59         import gettext
60         gettext.bindtextdomain ('lilypond', '@localedir@')
61         gettext.textdomain ('lilypond')
62         _ = gettext.gettext
63 except:
64         def _ (s):
65                 return s
66
67
68 program_name = 'mup2ly'
69 help_summary = _ ("Convert mup to LilyPond source")
70
71 option_definitions = [
72         ('', 'd', 'debug', _ ("debug")),
73         ('NAME[=EXP]', 'D', 'define', _ ("define macro NAME [optional expansion EXP]")),
74         ('', 'h', 'help', _ ("this help")),
75         ('FILE', 'o', 'output', _ ("write output to FILE")),
76         ('', 'E', 'pre-process', _ ("only pre-process")),
77         ('', 'V', 'verbose', _ ("verbose")),
78         ('', 'v', 'version', _ ("print version number")),
79         ('', 'w', 'warranty', _ ("show warranty and copyright")),
80         ]
81
82
83 ################################################################
84 # lilylib.py -- options and stuff
85
86 # source file of the GNU LilyPond music typesetter
87
88 # Handle bug in Python 1.6-2.1
89 #
90 # there are recursion limits for some patterns in Python 1.6 til 2.1. 
91 # fix this by importing pre instead. Fix by Mats.
92
93 # todo: should check Python version first.
94 try:
95         import pre
96         re = pre
97         del pre
98 except ImportError:
99         import re
100
101 # Attempt to fix problems with limited stack size set by Python!
102 # Sets unlimited stack size. Note that the resource module only
103 # is available on UNIX.
104 try:
105        import resource
106        resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
107 except:
108        pass
109
110 try:
111         import gettext
112         gettext.bindtextdomain ('lilypond', localedir)
113         gettext.textdomain ('lilypond')
114         _ = gettext.gettext
115 except:
116         def _ (s):
117                 return s
118
119 program_version = '@TOPLEVEL_VERSION@'
120 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
121         program_version = '1.5.54'
122
123 def identify ():
124         sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
125
126 def warranty ():
127         identify ()
128         sys.stdout.write ('\n')
129         sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001--2002'))
130         sys.stdout.write ('\n')
131         sys.stdout.write ('  Han-Wen Nienhuys')
132         sys.stdout.write ('  Jan Nieuwenhuizen')
133         sys.stdout.write ('\n')
134         sys.stdout.write (_ (r'''
135 Distributed under terms of the GNU General Public License. It comes with
136 NO WARRANTY.'''))
137         sys.stdout.write ('\n')
138
139 def progress (s):
140         errorport.write (s + '\n')
141
142 def warning (s):
143         progress (_ ("warning: ") + s)
144
145 def user_error (s, e=1):
146         errorport.write (program_name + ":" + _ ("error: ") + s + '\n')
147         sys.exit (e)
148         
149 def error (s):
150         '''Report the error S.  Exit by raising an exception. Please
151         do not abuse by trying to catch this error. If you do not want
152         a stack trace, write to the output directly.
153
154         RETURN VALUE
155
156         None
157         
158         '''
159         
160         progress (_ ("error: ") + s)
161         raise _ ("Exiting ... ")
162
163 def getopt_args (opts):
164         '''Construct arguments (LONG, SHORT) for getopt from  list of options.'''
165         short = ''
166         long = []
167         for o in opts:
168                 if o[1]:
169                         short = short + o[1]
170                         if o[0]:
171                                 short = short + ':'
172                 if o[2]:
173                         l = o[2]
174                         if o[0]:
175                                 l = l + '='
176                         long.append (l)
177         return (short, long)
178
179 def option_help_str (o):
180         '''Transform one option description (4-tuple ) into neatly formatted string'''
181         sh = '  '       
182         if o[1]:
183                 sh = '-%s' % o[1]
184
185         sep = ' '
186         if o[1] and o[2]:
187                 sep = ','
188                 
189         long = ''
190         if o[2]:
191                 long= '--%s' % o[2]
192
193         arg = ''
194         if o[0]:
195                 if o[2]:
196                         arg = '='
197                 arg = arg + o[0]
198         return '  ' + sh + sep + long + arg
199
200
201 def options_help_str (opts):
202         '''Convert a list of options into a neatly formatted string'''
203         w = 0
204         strs =[]
205         helps = []
206
207         for o in opts:
208                 s = option_help_str (o)
209                 strs.append ((s, o[3]))
210                 if len (s) > w:
211                         w = len (s)
212
213         str = ''
214         for s in strs:
215                 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0])  + 3), s[1])
216         return str
217
218 def help ():
219         ls = [(_ ("Usage: %s [OPTION]... FILE") % program_name),
220                 ('\n\n'),
221                 (help_summary),
222                 ('\n\n'),
223                 (_ ("Options:")),
224                 ('\n'),
225                 (options_help_str (option_definitions)),
226                 ('\n\n'),
227                 (_ ("Report bugs to %s") % 'bug-lilypond@gnu.org'),
228                 ('\n')]
229         map (sys.stdout.write, ls)
230         
231 def setup_temp ():
232         """
233         Create a temporary directory, and return its name. 
234         """
235         global temp_dir
236         if not keep_temp_dir_p:
237                 temp_dir = tempfile.mktemp (program_name)
238         try:
239                 os.mkdir (temp_dir, 0777)
240         except OSError:
241                 pass
242
243         return temp_dir
244
245
246 def system (cmd, ignore_error = 0, quiet =0):
247         """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
248
249         RETURN VALUE
250
251         Exit status of CMD
252         """
253         
254         if verbose_p:
255                 progress (_ ("Invoking `%s\'") % cmd)
256
257         st = os.system (cmd)
258         if st:
259                 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
260                 msg = name + ': ' + _ ("command exited with value %d") % st
261                 if ignore_error:
262                         if not quiet:
263                                 warning (msg + ' ' + _ ("(ignored)") + ' ')
264                 else:
265                         error (msg)
266
267         return st
268
269
270 def cleanup_temp ():
271         if not keep_temp_dir_p:
272                 if verbose_p:
273                         progress (_ ("Cleaning %s...") % temp_dir)
274                 shutil.rmtree (temp_dir)
275
276
277 def strip_extension (f, ext):
278         (p, e) = os.path.splitext (f)
279         if e == ext:
280                 e = ''
281         return p + e
282
283
284 def cp_to_dir (pattern, dir):
285         "Copy files matching re PATTERN from cwd to DIR"
286         # Duh.  Python style portable: cp *.EXT OUTDIR
287         # system ('cp *.%s %s' % (ext, outdir), 1)
288         files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
289         map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
290
291
292 # Python < 1.5.2 compatibility
293 #
294 # On most platforms, this is equivalent to
295 #`normpath(join(os.getcwd()), PATH)'.  *Added in Python version 1.5.2*
296 if os.path.__dict__.has_key ('abspath'):
297         abspath = os.path.abspath
298 else:
299         def abspath (path):
300                 return os.path.normpath (os.path.join (os.getcwd (), path))
301
302 if os.__dict__.has_key ('makedirs'):
303         makedirs = os.makedirs
304 else:
305         def makedirs (dir, mode=0777):
306                 system ('mkdir -p %s' % dir)
307
308
309 def mkdir_p (dir, mode=0777):
310         if not os.path.isdir (dir):
311                 makedirs (dir, mode)
312
313
314 # if set, LILYPONDPREFIX must take prevalence
315 # if datadir is not set, we're doing a build and LILYPONDPREFIX 
316 datadir = '@datadir@'
317
318 if os.environ.has_key ('LILYPONDPREFIX') :
319         datadir = os.environ['LILYPONDPREFIX']
320 else:
321         datadir = '@datadir@'
322
323
324 while datadir[-1] == os.sep:
325         datadir= datadir[:-1]
326
327 sys.path.insert (0, os.path.join (datadir, 'python'))
328
329 ################################################################
330 # END Library
331
332
333 output = 0
334
335 #
336 # PMX cut and paste
337 #
338
339 def encodeint (i):
340         return chr (i  + ord ('A'))
341
342         
343 actab = {-2: 'eses', -1: 'es', 0 : '', 1: 'is', 2:'isis'}
344
345 def pitch_to_lily_string (tup):
346         (o,n,a) = tup
347
348         nm = chr((n + 2) % 7 + ord ('a'))
349         nm = nm + actab[a]
350         if o > 0:
351                 nm = nm + "'" * o
352         elif o < 0:
353                 nm = nm + "," * -o
354         return nm
355
356 def gcd (a,b):
357         if b == 0:
358                 return a
359         c = a
360         while c: 
361                 c = a % b
362                 a = b
363                 b = c
364         return a
365
366 def rat_simplify (r):
367         (n,d) = r
368         if d < 0:
369                 d = -d
370                 n = -n
371         if n == 0:
372                 return (0,1)
373         else:
374                 g = gcd (n, d)
375                 return (n/g, d/g)
376         
377 def rat_multiply (a,b):
378         (x,y) = a
379         (p,q) = b
380
381         return rat_simplify ((x*p, y*q))
382
383 def rat_divide (a,b):
384         (p,q) = b
385         return rat_multiply (a, (q,p))
386
387 tuplet_table = {
388         2: 3,
389         3: 2,
390         5: 4
391 }
392
393
394 def rat_add (a,b):
395         (x,y) = a
396         (p,q) = b
397
398         return rat_simplify ((x*q + p*y, y*q))
399
400 def rat_neg (a):
401         (p,q) = a
402         return (-p,q)
403
404
405 def rat_larger (a,b):
406         return rat_subtract (a, b )[0] > 0
407
408 def rat_subtract (a,b ):
409         return rat_add (a, rat_neg (b))
410
411 def rat_to_duration (frac):
412         log = 1
413         d = (1,1)
414         while rat_larger (d, frac):
415                 d = rat_multiply (d, (1,2))
416                 log = log << 1
417
418         frac = rat_subtract (frac, d)
419         dots = 0
420         if frac == rat_multiply (d, (1,2)):
421                 dots = 1
422         elif frac == rat_multiply (d, (3,4)):
423                 dots = 2
424         return (log, dots)      
425
426
427 class Barcheck :
428         def __init__ (self):
429                 pass
430         def dump (self):
431                 return '|\n'
432
433
434 class Meter :
435         def __init__ (self,nums):
436                 self.nums = nums
437         def dump (self):
438                 return ' %{ FIXME: meter change %} '
439                 
440 class Beam:
441         def __init__ (self, ch):
442                 self.char = ch
443         def dump (self):
444                 return self.char
445
446 class Slur:
447         def __init__ (self,id):
448                 self.id = id
449                 self.start_chord = None
450                 self.end_chord = None
451                 
452         def calculate (self):
453                 s =self.start_chord
454                 e= self.end_chord
455
456                 if e and s:
457                         s.note_suffix = s.note_suffix + '('
458                         e.note_prefix = ')' + e.note_prefix
459                 else:
460                         sys.stderr.write ("\nOrphaned slur")
461                         
462 class Voice:
463         def __init__ (self, n):
464                 self.number = n
465                 self.entries = []
466                 self.chords = []
467                 self.staff = None
468                 self.current_slurs = []
469                 self.slurs = []
470                 
471         def toggle_slur (self, id):
472                 
473                 for s in self.current_slurs:
474                         if s.id == id:
475                                 self.current_slurs.remove (s)
476                                 s.end_chord = self.chords[-1]
477                                 return
478                 s = Slur (id)
479                 s.start_chord = self.chords[-1]
480                 self.current_slurs.append (s)
481                 self.slurs.append (s)
482                 
483         def last_chord (self):
484                 if len (self.chords):
485                         return self.chords[-1]
486                 else:
487                         ch = Chord ()
488                         ch.basic_duration = 4
489                         return ch
490                 
491         def add_chord (self, ch):
492                 self.chords.append (ch)
493                 self.entries.append (ch)
494                 
495         def add_nonchord (self, nch):
496                 self.entries.append (nch)
497
498         def idstring (self):
499                 return 'staff%svoice%s ' % (encodeint (self.staff.number) , encodeint(self.number))
500         
501         def dump (self):
502                 str = ''
503                 #if not self.entries:
504                 #        #return '\n'
505                 #        #ugh ugh
506                 #        return '\n%s = {}\n\n' % self.idstring ()
507                 ln = '  '
508                 one_two = ("One", "Two")
509                 if self.staff.voices [1 - self.number].entries:
510                         ln = ln + '\\voice%s\n  ' % one_two[self.number]
511                 for e in self.entries:
512                         next = e.dump ()
513                         if next[-1] == '\n':
514                                 str  = str + ln + next + ' '
515                                 ln = '  '
516                                 continue
517                         
518                         if len (ln) +len (next) > 72:
519                                 str = str+ ln + '\n'
520                                 ln = '  '
521                         ln = ln + next + ' '
522                         
523                         
524                 str = str  + ln
525                 id = self.idstring ()
526                         
527                 str = '''%s = \\context Voice = %s \\notes {
528 %s
529 }
530
531 '''% (id, id, str)
532                 return str
533         
534         def calculate_graces (self):
535                 lastgr = 0
536                 lastc = None
537                 for c in self.chords:
538                         if c.grace and  not lastgr:
539                                 c.chord_prefix = c.chord_prefix + '\\grace { '
540                         elif not c.grace and lastgr:
541                                 lastc.chord_suffix = lastc.chord_suffix + ' } '
542                         lastgr = c.grace
543                         lastc = c
544                         
545         def calculate (self):
546                 self.calculate_graces ()
547                 for s in self.slurs:
548                         s.calculate ()
549
550 class Clef:
551         def __init__ (self, cl):
552                 self.type = cl
553                 
554         def dump (self):
555                 return '\\clef %s' % self.type
556
557 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
558 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
559
560 class Key:
561         def __init__ (self, sharps, flats):
562                 self.flats = flats
563                 self.sharps = sharps
564                 
565         def dump (self):
566                 if self.sharps and self.flats:
567                         k = '\\keysignature %s ' % 'TODO'
568                 elif self.sharps:
569                         k = '\\notes\\key %s \major' % key_sharps[self.sharps]
570                 elif self.flats:
571                         k = '\\notes\\key %s \major' % key_flats[self.flats]
572                 return k
573
574 class Time:
575         def __init__ (self, frac):
576                 self.frac = frac
577                 
578         def dump (self):
579                 return '\\time %d/%d' % (self.frac[0], self.frac[1])
580         
581
582 clef_table = {
583         'b':'bass'  ,
584         'r':'baritone',
585         'n':'tenor',
586         'a':'alto',
587         'm':'mezzosoprano',
588         's':'soprano',
589         't':'treble',
590         'f':'frenchviolin',
591         }
592
593 class Staff:
594         def __init__ (self, n):
595                 # ugh
596                 self.voices = (Voice (0), Voice (1))
597                 
598                 self.clef = None
599                 self.time = None
600                 self.key = None
601                 self.instrument = 0
602                 self.number = n
603                 
604                 i = 0
605                 for v in self.voices:
606                         v.staff = self
607                         v.number = i
608                         i = i+1
609                         
610         #def set_clef (self, letter):
611         #       clstr = clef_table[letter]
612         #       self.voices[0].add_nonchord (Clef (clstr))
613                 
614         def calculate (self):
615                 for v in self.voices:
616                         v.calculate ()
617                         
618         def idstring (self):
619                 return 'staff%s' % encodeint (self.number)
620
621         def dump (self):
622                 str = ''
623
624                 refs = ''
625                 for v in self.voices:
626                         if v.entries:
627                                 # urg
628                                 if v == self.voices[0]:
629                                         if self.clef:
630                                                 refs = refs + self.clef.dump ()
631                                         if self.time:
632                                                 refs = refs + self.time.dump ()
633                                         if self.key:
634                                                 refs = refs + self.key.dump ()
635                                         if refs:
636                                                 refs = '\n  ' + refs
637                                 str = str + v.dump()
638                                 refs = refs + '\n  \\' + v.idstring ()
639                 str = str + '''
640 %s = \context Staff = %s <%s
641 >
642
643 ''' % (self.idstring (), self.idstring (), refs)
644                 return str
645
646 class Tuplet:
647         def __init__ (self, number, base, dots):
648                 self.chords = []
649                 self.number = number
650                 self.replaces = tuplet_table[number]
651                 self.base = base
652                 self.dots = dots
653                 
654                 length = (1,base)
655                 if dots == 1:
656                         length = rat_multiply (length, (3,2))
657                 elif dots == 2:
658                         length = rat_multiply (length, (7,4))
659
660                 length = rat_multiply (length, (1,self.replaces))
661
662                 (nb,nd) =rat_to_duration (length)
663
664                 self.note_base = nb
665                 self.note_dots = nd
666
667         def add_chord (self, ch):
668                 ch.dots = self.note_dots
669                 ch.basic_duration = self.note_base
670                 self.chords.append (ch)
671
672                 if len (self.chords) == 1:
673                         ch.chord_prefix = '\\times %d/%d { ' % (self.replaces, self.number)
674                 elif len (self.chords) == self.number:
675                         ch.chord_suffix = ' }' 
676                 
677 class Chord:
678         def __init__ (self):
679                 self.pitches = []
680                 self.multimeasure = 0
681                 self.dots = 0
682                 self.basic_duration = 0
683                 self.scripts = []
684                 self.grace = 0
685                 self.chord_prefix = ''
686                 self.chord_suffix = ''
687                 self.note_prefix = ''
688                 self.note_suffix = ''
689
690         # maybe use import copy?
691         def copy (self):
692                 ch = Chord ()
693                 #for i in self.pitches:
694                 #       ch.pitches.append (i)
695                 ch.pitches = self.pitches[:]
696                 ch.multimeasure = self.multimeasure
697                 ch.dots = self.dots
698                 ch.basic_duration = self.basic_duration
699                 #for i in self.scripts:
700                 #       ch.scripts.append (i)
701                 ch.scripts = self.scripts[:]
702                 ch.grace = self.grace
703
704                 ch.chord_prefix = self.chord_prefix
705                 ch.chord_suffix = self.chord_suffix
706                 ch.note_prefix = self.note_prefix
707                 ch.note_suffix = self.note_suffix
708                 return ch
709
710                 
711         def dump (self):
712                 str = ''
713
714                 sd = ''
715                 if self.basic_duration == 0.5:
716                         sd = '\\breve'
717                 else:
718                         sd = '%d' % self.basic_duration
719                 sd = sd + '.' * self.dots 
720                 for p in self.pitches:
721                         if str:
722                                 str = str + ' ' 
723                         str = str + pitch_to_lily_string (p) + sd
724
725                 for s in self.scripts:
726                         str = str + '-' + s
727
728                 str = self.note_prefix +str  + self.note_suffix
729                 
730                 if len (self.pitches) > 1:
731                         str = '<%s>' % str
732                 elif self.multimeasure:
733                         str = 'R' + sd
734                 elif len (self.pitches) == 0:
735                         str = 'r' + sd
736
737                 str = self.chord_prefix + str + self.chord_suffix
738                 
739                 return str
740                 
741 SPACE=' \t\n'
742 DIGITS ='0123456789'
743 basicdur_table = {
744         9: 0.5,
745         0: 0 ,
746         2: 2 ,
747         4: 4 ,
748         8: 8 ,
749         1: 16,
750         3: 32,
751         6: 64
752         }
753
754
755 ornament_table = {
756         't': '\\prall',
757         'm': '\\mordent',
758         'x': '"x"',
759         '+': '+',
760         'u': '"pizz"',
761         'p': '|',
762         '(': '"paren"',
763         ')': '"paren"',
764         'g': '"segno"',
765         '.': '.',
766         'fd': '\\fermata',
767         'f': '\\fermata',
768         '_': '-',
769         'T': '\\trill',
770         '>': '>',
771         '^': '^',
772         }
773
774 # http://www.arkkra.com/doc/uguide/contexts.html
775
776 contexts = (
777         'header', 
778         'footer', 
779         'header2', 
780         'footer2', 
781         'score', 
782         'staff',
783         'voice',
784         'grids', 
785         'music',
786         )
787
788 class Parser:
789         def __init__ (self, lines):
790                 self.parse_function = self.parse_context_music
791                 self.staffs = []
792                 self.current_voices = []
793                 self.forced_duration = None
794                 self.last_name = 0
795                 self.last_oct = 0               
796                 self.tuplets_expected = 0
797                 self.tuplets = []
798                 self.clef = None
799                 self.time = None
800                 self.key = None
801                 
802                 self.parse (lines)
803                 
804         def parse_compound_location (self, line):
805                 colon = string.index (line, ':')
806                 s = line[:colon]
807                 debug (s)
808                 line = line[colon + 1:]
809                 debug (line)
810                 self.current_voices = []
811                 ##self.current_staffs = []
812                 map (self.parse_location, string.split (s, '&'))
813                 return line
814
815         def parse_location (self, line):
816                 m = re.match ('^([-,0-9]+) *([-,0-9]*)', string.lstrip (line))
817                 
818                 def range_list_to_idxs (s):
819                         
820                         # duh
821                         def flatten (l):
822                                 f = []
823                                 for i in l:
824                                         for j in i:
825                                                 f.append (j)
826                                 return f
827                                          
828                         def range_to_list (s):
829                                 if string.find (s, '-') >= 0:
830                                         debug ('s: ' + s)
831                                         l = map (string.lstrip,
832                                                  string.split (s, '-'))
833                                         r = range (string.atoi (l[0]) - 1,
834                                                    string.atoi (l[1]))
835                                 else:
836                                         r = (string.atoi (s) - 1,)
837                                 return r
838                         
839                         ranges = string.split (s, ',')
840                         l = flatten (map (range_to_list, ranges))
841                         l.sort ()
842                         return l
843                 
844                 staff_idxs = range_list_to_idxs (m.group (1))
845                 if m.group (2):
846                         voice_idxs = range_list_to_idxs (m.group (2))
847                 else:
848                         voice_idxs = [0]
849                 for s in staff_idxs:
850                         while s > len (self.staffs) - 1:
851                                 self.staffs.append (Staff (s))
852                         for v in voice_idxs:
853                                 self.current_voices.append (self.staffs[s].voices[v])
854                         
855         def parse_note (self, line):
856                 # FIXME: 1?
857                 oct = 1
858                 name = (ord (line[0]) - ord ('a') + 5) % 7
859                 # FIXME: does key play any role in this?
860                 alteration = 0
861                 debug ('NOTE: ' + `line`)
862                 line = string.lstrip (line[1:])
863                 while line:
864                         if len (line) > 1 and line[:2] == '//':
865                                 line = 0
866                                 break
867                         elif line[0] == '#':
868                                 alteration = alteration + 1
869                         elif line[0] == '&':
870                                 alteration = alteration - 1
871                         elif line[0] == '+':
872                                 oct = oct + 1 
873                         elif line[0] == '-':
874                                 oct = oct - 1
875                         else:
876                                 skipping (line[0])
877                         line = string.lstrip (line[1:])
878                 return (oct, name, alteration)
879                         
880         def parse_chord (self, line):
881                 debug ('CHORD: ' + line)
882                 line = string.lstrip (line)
883                 ch = Chord ()
884                 if not line:
885                         #ch = self.current_voices[0].last_chord ()
886                         ch = self.last_chord.copy ()
887                 else:
888                         m = re.match ('^([0-9]+)([.]*)', line)
889                         if m:
890                                 ch.basic_duration = string.atoi (m.group (1))
891                                 line = line[len (m.group (1)):]
892                                 if m.group (2):
893                                         ch.dots = len (m.group (2))
894                                         line = line[len (m.group (2)):]
895                         else:
896                                 #ch.basic_duration = self.current_voices[0].last_chord ().basic_duration
897                                 ch.basic_duration = self.last_chord.basic_duration
898                                 
899                         line = string.lstrip (line)
900                         if len (line) > 1 and line[:2] == '//':
901                                 line = 0
902                         #ugh
903                         if not line:
904                                 debug ('nline: ' + line)
905                                 #ch = self.current_voices[0].last_chord ()
906                                 n = self.last_chord.copy ()
907                                 n.basic_duration = ch.basic_duration
908                                 n.dots = ch.dots
909                                 ch = n
910                                 debug ('ch.pitsen:' + `ch.pitches`)
911                                 debug ('ch.dur:' + `ch.basic_duration`)
912                         else:
913                                 debug ('eline: ' + line)
914                                 
915                         while line:
916                                 if len (line) > 1 and line[:2] == '//':
917                                         line = 0
918                                         break
919                                 elif line[:1] == 'mr':
920                                         ch.multimeasure = 1
921                                         line = line[2:]
922                                 elif line[:1] == 'ms':
923                                         ch.multimeasure = 1
924                                         line = line[2:]
925                                 elif line[0] in 'rs':
926                                         line = line[1:]
927                                         pass
928                                 elif line[0] in 'abcdefg':
929                                         m = re.match ('([a-g][-#&+]*)', line)
930                                         l = len (m.group (1))
931                                         pitch = self.parse_note (line[:l])
932                                         debug ('PITCH: ' + `pitch`)
933                                         ch.pitches.append (pitch)
934                                         line = line[l:]
935                                         break
936                                 else:
937                                         skipping (line[0])
938                                         line = line[1:]
939                                 line = string.lstrip (line)
940                 debug ('CUR-VOICES: ' + `self.current_voices`)
941                 map (lambda x, ch=ch: x.add_chord (ch), self.current_voices)
942                 self.last_chord = ch
943
944         def parse_lyrics_location (self, line):
945                 line = line.lstrip (line)
946                 addition = 0
947                 m = re.match ('^(between[ \t]+)', line)
948                 if m:
949                         line = line[len (m.group (1)):]
950                         addition = 0.5
951                 else:
952                         m = re.match ('^(above [ \t]+)', line)
953                         if m:
954                                 line = line[len (m.group (1)):]
955                                 addition = -0.5
956                         else:
957                                 addlyrics = 1
958                 
959         def parse_voice (self, line):
960                 line = string.lstrip (line)
961                 # `;' is not a separator, chords end with ';'
962                 chords = string.split (line, ';')[:-1]
963                 # mup resets default duration and pitch each bar
964                 self.last_chord = Chord ()
965                 self.last_chord.basic_duration = 4
966                 map (self.parse_chord, chords)
967
968         def init_context_header (self, line):
969                 self.parse_function = self.parse_context_header
970                                         
971         def parse_context_header (self, line):
972                 debug ('header: ' + line)
973                 skipping (line)
974                 
975         def init_context_footer (self, line):
976                 self.parse_function = self.parse_context_footer
977
978         def parse_context_footer (self, line):
979                 debug ('footer: ' + line)
980                 skipping (line)
981
982         def init_context_header2 (self, line):
983                 self.parse_function = self.parse_context_header2
984
985         def parse_context_header2 (self, line):
986                 debug ('header2: ' + line)
987                 skipping (line)
988
989         def init_context_footer2 (self, line):
990                 self.parse_function = self.parse_context_footer2
991
992         def parse_context_footer2 (self, line):
993                 debug ('footer2: ' + line)
994                 skipping (line)
995
996         def init_context_score (self, line):
997                 self.parse_function = self.parse_context_score
998
999         def parse_context_score (self, line):
1000                 debug ('score: ' + line)
1001                 line = string.lstrip (line)
1002                 # ugh: these (and lots more) should also be parsed in
1003                 # context staff.  we should have a class Staff_properties
1004                 # and parse/set all those.
1005                 m = re.match ('^(time[ \t]*=[ \t]*([0-9]+)[ \t]*/[ \t]*([0-9]+))', line)
1006                 if m:
1007                         line = line[len (m.group (1)):]
1008                         self.time = Time ((string.atoi (m.group (2)),
1009                                            string.atoi (m.group (3))))
1010
1011                 m = re.match ('^(key[ \t]*=[ \t]*([0-9]+)[ \t]*(#|@))', line)
1012                 if m:
1013                         line = line[len (m.group (1)):]
1014                         n = string.atoi (m.group (2))
1015                         if m.group (3) == '#':
1016                                 self.key = Key (n, 0)
1017                         else:
1018                                 self.key = Key (0, n)
1019                 skipping (line)
1020
1021         def init_context_staff (self, line):
1022                 self.parse_function = self.parse_context_staff
1023
1024         def parse_context_staff (self, line):
1025                 debug ('staff: ' + line)
1026                 skipping (line)
1027
1028         def init_context_voice (self, line):
1029                 self.parse_function = self.parse_context_voice
1030
1031         def parse_context_voice (self, line):
1032                 debug ('voice: ' + line)
1033                 skipping (line)
1034
1035         def init_context_grids (self, line):
1036                 self.parse_function = self.parse_context_grids
1037
1038         def parse_context_grids (self, line):
1039                 debug ('grids: ' + line)
1040                 skipping (line)
1041
1042         def init_context_music (self, line):
1043                 self.parse_function = self.parse_context_music
1044
1045         def parse_context_music (self, line):
1046                 debug ('music: ' + line)
1047                 line = string.lstrip (line)
1048                 if line and line[0] in '0123456789':
1049                         line = self.parse_compound_location (line)
1050                         self.parse_voice (line)
1051                 else:
1052                         m = re.match ('^(TODOlyrics[ \t]+)', line)
1053                         if m:
1054                                 line = line[len (m.group (1)):]
1055                                 self.parse_lyrics_location (line[7:])
1056                                 self.parse_lyrics (line)
1057                         else:
1058                                 skipping (line)
1059
1060         def parse (self, lines):
1061                 # shortcut: set to official mup maximum (duh)
1062                 # self.set_staffs (40)
1063                 for line in lines:
1064                         debug ('LINE: ' + `line`)
1065                         m = re.match ('^([a-z]+2?)', line)
1066                         
1067                         if m:
1068                                 word = m.group (1)
1069                                 if word in contexts:
1070                                         eval ('self.init_context_%s (line)' % word)
1071                                         continue
1072                                 else:
1073                                         warning (_ ("no such context: %s") % word)
1074                                         skipping (line)
1075                         else:
1076                                 debug ('FUNC: ' + `self.parse_function`)
1077                                 self.parse_function (line)
1078                                 
1079                 for c in self.staffs:
1080                         # hmm
1081                         if not c.clef and self.clef:
1082                                 c.clef = self.clef
1083                         if not c.time and self.time:
1084                                 c.time = self.time
1085                         if not c.key and self.key:
1086                                 c.key = self.key
1087                         c.calculate ()
1088
1089         def dump (self):
1090                 str = ''
1091
1092                 refs = ''
1093                 for s in self.staffs:
1094                         str = str +  s.dump ()
1095                         refs = refs + '\n    \\' + s.idstring ()
1096
1097                 str = str + '''
1098
1099 \score {
1100   <%s
1101   >
1102   \paper {}
1103   \midi {}
1104 }
1105 ''' % refs 
1106                 return str
1107
1108
1109 class Pre_processor:
1110         def __init__ (self, raw_lines):
1111                 self.lines = []
1112                 self.active = [1]
1113                 self.process_function = self.process_line
1114                 self.macro_name = ''
1115                 self.macro_body = ''
1116                 self.process (raw_lines)
1117
1118         def process_line (self, line):
1119                 global macros
1120                 m = re.match ('^([ \t]*([a-zA-Z]+))', line)
1121                 s = line
1122                 if m:
1123                         word = m.group (2)
1124                         debug ('MACRO?: ' + `word`)
1125                         if word in pre_processor_commands:
1126                                 line = line[len (m.group (1)):]
1127                                 eval ('self.process_macro_%s (line)' % word)
1128                                 s = ''
1129                         else:
1130                                 if macros.has_key (word):
1131                                         s = macros[word] + line[len (m.group (1)):]
1132                 if not self.active [-1]:
1133                         s = ''
1134                 return s
1135
1136         def process_macro_body (self, line):
1137                 global macros
1138                 # dig this: mup allows ifdefs inside macro bodies
1139                 s = self.process_line (line)
1140                 m = re.match ('(.*[^\\\\])(@)(.*)', s)
1141                 if m:
1142                         self.macro_body = self.macro_body + '\n' + m.group (1)
1143                         macros[self.macro_name] = self.macro_body
1144                         debug ('MACROS: ' + `macros`)
1145                         # don't do nested multi-line defines
1146                         self.process_function = self.process_line
1147                         if m.group (3):
1148                                 s = m.group (3)
1149                         else:
1150                                 s = ''
1151                 else:
1152                         self.macro_body = self.macro_body + '\n' + s
1153                         s = ''
1154                 return s
1155
1156         # duh: mup is strictly line-based, except for `define',
1157         # which is `@' terminated and may span several lines
1158         def process_macro_define (self, line):
1159                 global macros
1160                 # don't define new macros in unactive areas
1161                 if not self.active[-1]:
1162                         return
1163                 m = re.match ('^[ \t]*([a-zA-Z][a-zA-Z1-9_]*)(([^@]*)|(\\\\@))(@)?', line)
1164                 n = m.group (1)
1165                 if m.group (5):
1166                         if m.group (2):
1167                                 e = m.group (2)
1168                         else:
1169                                 e = ''
1170                         macros[n] = e
1171                         debug ('MACROS: ' + `macros`)
1172                 else:
1173                         # To support nested multi-line define's
1174                         # process_function and macro_name, macro_body
1175                         # should become lists (stacks)
1176                         # The mup manual is undetermined on this
1177                         # and I haven't seen examples doing it.
1178                         #
1179                         # don't do nested multi-line define's
1180                         if m.group (2):
1181                                 self.macro_body = m.group (2)
1182                         else:
1183                                 self.macro_body = ''
1184                         self.macro_name = n
1185                         self.process_function = self.process_macro_body
1186                 
1187         def process_macro_ifdef (self, line):
1188                 m = re.match ('^[ \t]*([a-zA-Z][a-zA-Z1-9_]*)', line)
1189                 if m:
1190                         
1191                         active = self.active[-1] and macros.has_key (m.group (1))
1192                         debug ('ACTIVE: %d' % active)
1193                         self.active.append (active)
1194
1195         def process_macro_ifndef (self, line):
1196                 m = re.match ('^[ \t]*([a-zA-Z][a-zA-Z1-9_]*)', line)
1197                 if m:
1198                         active = self.active[-1] and not macros.has_key (m.group (1))
1199                         self.active.append (active)
1200
1201         def process_macro_else (self, line):
1202                 debug ('ELSE')
1203                 self.active[-1] = not self.active[-1]
1204                 
1205         def process_macro_endif (self, line):
1206                 self.active = self.active[:-1]
1207                         
1208         def process (self, raw_lines):
1209                 s = ''
1210                 for line in raw_lines:
1211                         ls = string.split (self.process_function (line), '\n')
1212                         for i in ls:
1213                                 if i:
1214                                         s = s + string.rstrip (i)
1215                                         if s and s[-1] == '\\':
1216                                                 s = string.rstrip (s[:-1])
1217                                         elif s:
1218                                                 self.lines.append (s)
1219                                                 s = ''
1220
1221
1222 debug_p = 0
1223 only_pre_process_p = 0
1224 def debug (s):
1225         if debug_p:
1226                 progress ('DEBUG: ' + s)
1227
1228 def skipping (s):
1229         if verbose_p or debug_p:
1230                 progress ('SKIPPING: ' + s)
1231
1232 (sh, long) = getopt_args (__main__.option_definitions)
1233 try:
1234         (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1235 except:
1236         help ()
1237         sys.exit (2)
1238
1239 macros = {}
1240 pre_processor_commands = (
1241         'define',
1242         'else',
1243         'endif',
1244         'ifdef',
1245         'ifndef',
1246         )
1247
1248 for opt in options:
1249         o = opt[0]
1250         a = opt[1]
1251         if 0:
1252                 pass
1253         elif o== '--debug' or o == '-d':
1254                 debug_p = 1
1255         elif o== '--define' or o == '-D':
1256                 if string.find (a, '=') >= 0:
1257                         (n, e) = string.split (a, '=')
1258                 else:
1259                         n = a
1260                         e = ''
1261                 macros[n] = e
1262         elif o== '--pre-process' or o == '-E':
1263                 only_pre_process_p = 1
1264         elif o== '--help' or o == '-h':
1265                 help ()
1266                 sys.exit (0)
1267         elif o== '--verbose' or o == '-V':
1268                 verbose_p = 1
1269         elif o == '--version' or o == '-v':
1270                 identify ()
1271                 sys.exit (0)
1272         elif o == '--output' or o == '-o':
1273                 output = a
1274         else:
1275                 print o
1276                 raise getopt.error
1277
1278 # writes to stdout for help2man
1279 # don't call 
1280 # identify ()
1281 # sys.stdout.flush ()
1282
1283 # handy emacs testing
1284 # if not files:
1285 #       files = ['template.mup']
1286
1287 if not files:
1288         files = ['-']
1289         
1290 for f in files:
1291
1292         if f == '-':
1293                 h = sys.stdin
1294         elif f and not os.path.isfile (f):
1295                 f = strip_extension (f, '.mup') + '.mup'
1296                 h = open (f)
1297         progress ( _("Processing `%s'..." % f))
1298         raw_lines = h.readlines ()
1299         p = Pre_processor (raw_lines)
1300         if only_pre_process_p:
1301                 if not output:
1302                         output = os.path.basename (re.sub ('(?i).mup$', '.mpp', f))
1303         else:
1304                 e = Parser (p.lines)
1305                 if not output:
1306                         output = os.path.basename (re.sub ('(?i).mup$', '.ly', f))
1307                 if output == f:
1308                         output = os.path.basename (f + '.ly')
1309                         
1310         if f == '-':
1311                 output = '-'
1312                 out_h = sys.stdout
1313         else:
1314                 out_h = open (output, 'w')
1315
1316         progress (_ ("Writing `%s'...") % output)
1317
1318         tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, f)
1319         if only_pre_process_p:
1320                 # duh
1321                 ly = string.join (p.lines, '\n')
1322         else:
1323                 ly = tag + '\n\n' + e.dump ()
1324
1325         out_h.write (ly)
1326         out_h.close ()
1327         if debug_p:
1328                 print (ly)
1329