3 # PMX is a Musixtex preprocessor written by Don Simons, see
4 # http://www.gmd.de/Misc/Music/musixtex/software/pmx/
7 # * block openings aren't parsed.
15 program_name = 'pmx2ly'
16 version = '@TOPLEVEL_VERSION@'
17 if version == '@' + 'TOPLEVEL_VERSION' + '@':
18 version = '(unknown version)' # uGUHGUHGHGUGH
22 return chr ( i + ord ('A'))
25 actab = {-2: 'eses', -1: 'es', 0 : '', 1: 'is', 2:'isis'}
27 def pitch_to_lily_string (tup):
30 nm = chr((n + 2) % 7 + ord ('a'))
59 def rat_multiply (a,b):
63 return rat_simplify ((x*p, y*q))
67 return rat_multiply (a, (q,p))
80 return rat_simplify ((x*q + p*y, y*q))
88 return rat_subtract (a, b )[0] > 0
90 def rat_subtract (a,b ):
91 return rat_add (a, rat_neg (b))
93 def rat_to_duration (frac):
96 while rat_larger (d, frac):
97 d = rat_multiply (d, (1,2))
100 frac = rat_subtract (frac, d)
102 if frac == rat_multiply (d, (1,2)):
104 elif frac == rat_multiply (d, (3,4)):
117 def __init__ (self,nums):
120 return ' %{ FIXME: meter change %} '
123 def __init__ (self, ch):
129 def __init__ (self,id):
131 self.start_chord = None
132 self.end_chord = None
133 def calculate (self):
138 s.note_suffix = s.note_suffix + '-('
139 e.note_prefix = e.note_suffix + '-)'
141 sys.stderr.write ("\nOrphaned slur")
149 self.current_slurs = []
151 def toggle_slur (self, id):
153 for s in self.current_slurs:
155 self.current_slurs.remove (s)
156 s.end_chord = self.chords[-1]
159 s.start_chord = self.chords[-1]
160 self.current_slurs.append (s)
161 self.slurs.append (s)
163 def last_chord (self):
164 return self.chords[-1]
165 def add_chord (self, ch):
166 self.chords.append (ch)
167 self.entries.append (ch)
168 def add_nonchord (self, nch):
169 self.entries.append (nch)
172 return 'staff%svoice%s ' % (encodeint (self.staff.number) , encodeint(self.number))
176 for e in self.entries:
177 next = ' ' + e.dump ()
179 str = str + ln + next
183 if len (ln) +len (next) > 72:
190 id = self.idstring ()
192 str = '%s = \\notes { \n %s }\n '% (id, str)
194 def calculate_graces (self):
197 for c in self.chords:
198 if c.grace and not lastgr:
199 c.chord_prefix = c.chord_prefix + '\\grace { '
200 elif not c.grace and lastgr:
201 lastc.chord_suffix = lastc.chord_suffix + ' } '
204 def calculate (self):
205 self.calculate_graces ()
210 def __init__ (self, cl):
213 return '\\clef %s' % self.type
216 def __init__ (self, key):
219 return '\\key %s' % self.type
248 self.voices = (Voice (), Voice())
256 for v in self.voices:
260 def set_clef (self, letter):
261 clstr = clef_table[letter]
262 self.voices[0].add_nonchord (Clef (clstr))
265 def current_voice (self):
266 return self.voices[self.voice_idx]
267 def next_voice (self):
268 self.voice_idx = (self.voice_idx + 1)%len (self.voices)
270 def calculate (self):
271 for v in self.voices:
274 return 'staff%s' % encodeint (self.number)
279 for v in self.voices:
281 refs = refs + '\\' + v.idstring ()+ ' '
283 str = str + '\n\n%s = \\context Staff = %s \n < \n %s >\n\n\n'% (self.idstring (), self.idstring (), refs)
287 def __init__ (self, number, base, dots):
290 self.replaces = tuplet_table[number]
296 length = rat_multiply (length, (3,2))
298 length = rat_multiply (length, (7,4))
300 length = rat_multiply (length, (1,self.replaces))
302 (nb,nd) =rat_to_duration (length)
307 def add_chord (self, ch):
308 ch.dots = self.note_dots
309 ch.basic_duration = self.note_base
310 self.chords.append (ch)
312 if len (self.chords) == 1:
313 ch.chord_prefix = '\\times %d/%d { ' % (self.replaces, self.number)
314 elif len (self.chords) == self.number:
315 ch.chord_suffix = ' }'
321 self.basic_duration = 0
324 self.chord_prefix = ''
325 self.chord_suffix = ''
326 self.note_prefix = ''
327 self.note_suffix = ''
333 if self.basic_duration == 0.5:
336 sd = '%d' % self.basic_duration
337 sd = sd + '.' * self.dots
338 for p in self.pitches:
341 str = str + pitch_to_lily_string (p)
343 if len (self.pitches) > 1:
345 elif len (self.pitches) == 0:
349 for s in self.scripts:
352 str = self.note_prefix + str + self.note_suffix
353 str = self.chord_prefix + str + self.chord_suffix
391 def __init__ (self, filename):
393 self.forced_duration = None
396 self.tuplets_expected = 0
398 self.last_basic_duration = 4
400 self.parse (filename)
402 def set_staffs (self, number):
403 self.staffs = map (lambda x: Staff (), range(0, number))
408 for s in self.staffs:
411 def current_staff (self):
412 return self.staffs[self.staff_idx]
414 def current_voice (self):
415 return self.current_staff ().current_voice ()
417 def next_staff (self):
418 self.staff_idx = (self.staff_idx + 1)% len (self.staffs)
420 def parse_note (self, str):
430 ch = self.current_voice().last_chord()
434 self.current_voice().add_chord (ch)
438 name = (ord (str[0]) - ord('a') + 5) % 7
442 ch.grace = ch.grace or grace
452 while str[0] in 'dsfmnul0123456789.,+-':
456 alteration = alteration -1
462 alteration = alteration +1
465 elif c in DIGITS and durdigit == None and \
466 self.tuplets_expected == 0:
467 durdigit = string.atoi (c)
469 oct = string.atoi (c) - 3
471 extra_oct = extra_oct + 1
473 extra_oct = extra_oct - 1
482 tupnumber = string.atoi (str[0])
484 str=re.sub (r'^n?f?[+-0-9.]+', '' , str)
489 basic_duration = basicdur_table[durdigit]
490 self.last_basic_duration = basic_duration
492 sys.stderr.write ("""
493 Huh? expected duration, found %d Left was `%s'""" % (durdigit, str[:20]))
497 basic_duration = self.last_basic_duration
501 if name <> None and oct == None:
503 if self.last_name < name and name -self.last_name > 3:
505 elif self.last_name > name and self.last_name -name > 3:
508 oct = self.last_oct +e + extra_oct
512 self.last_name = name
515 ch.pitches.append ((oct, name, alteration))
517 # do before adding to tuplet.
518 ch.basic_duration = basic_duration
522 self.forced_duration = ch.basic_duration / forced_duration
525 tup =Tuplet (tupnumber, basic_duration, dots)
526 self.tuplets_expected = tupnumber
527 self.tuplets.append (tup)
529 if self.tuplets_expected > 0:
530 self.tuplets[-1].add_chord (ch)
531 self.tuplets_expected = self.tuplets_expected - 1
534 def parse_basso_continuo (self, str):
535 while str[0] in DIGITS +'#n-':
539 scr = '\\\\textsharp'
541 if len(scr)>1 or scr not in DIGITS:
544 self.current_voice().last_chord ().scripts.append (scr)
547 def parse_beams (self,str):
549 # self.current_voice().add_nonchord (Beam(c))
552 while str[0] in '+-0123456789':
559 def parse_key (self, str):
561 #The key is changed by a string of the form K[+-]<num>[+-]<num>
562 #where the first number is the transposition and the second number is the
563 #new key signature. For now, we won't bother with the transposition.
565 sys.stderr.write("Transposition not implemented yet: ")
566 while str[0] in '+-0123456789':
571 while str[0] in '+-0123456789':
574 keystr = key_table[key]
575 self.current_voice().add_nonchord (Key(keystr))
579 def parse_header (self, ls):
581 if re.search('\\.', a):
582 return string.atof (a)
584 return string.atoi (a)
589 while len (numbers) < number_count:
593 opening = re.sub ('[ \t\n]+', ' ', opening)
594 opening = re.sub ('^ ', '', opening)
595 opening = re.sub (' $', '', opening)
598 opening = string.split (opening, ' ')
600 numbers = numbers + map (atonum, opening)
602 (no_staffs, no_instruments, timesig_num, timesig_den, ptimesig_num,
603 ptimesig_den, pickup_beats,keysig_number) = tuple (numbers[0:8])
604 (no_pages,no_systems, musicsize, fracindent) = tuple (numbers[8:])
607 # opening = map (string.atoi, re.split ('[\t ]+', opening))
610 while len (instruments) < no_instruments:
611 instruments.append (ls[0])
617 self.set_staffs (no_staffs)
619 for s in self.staffs:
629 def parse_ornament (self, left):
631 e = self.current_voice ().last_chord ()
641 orn = ornament_table[id]
643 sys.stderr.write ("unknown ornament `%s'\n" % id)
645 e.scripts.append (orn)
647 def parse_barcheck (self, left):
648 self.current_voice ().add_nonchord (Barcheck ())
652 def parse_slur (self, left):
657 if re.match ('[A-Z0-9]', left[0]):
660 while left[0] in 'uld0123456789+-.':
663 self.current_voice ().toggle_slur (id)
666 def parse_mumbo_jumbo (self,left):
668 while left and left[0] <> '\\':
673 def parsex (self,left):
675 while left[0] in DIGITS:
680 def parse_body (self, left):
686 f = string.find (left, '\n')
692 m = re.match ('([o0-9]/[o0-9]/[o0-9]/[o0-9])', left)
695 left = left[len (nums):]
696 nums = map (string.atoi , nums)
697 self.current_voice ().add_nonchord (Meter (nums))
700 m= re.match ('([0-9o]+)', left)
703 self.current_voice ().add_nonchord (Meter (map (string.atoi (nums))))
706 elif left[0] in 'lh':
707 f = string.find (left, '\n')
713 f = string.find (left, '\n')
716 elif c in 'Gzabcdefgr':
717 left = self.parse_note (left)
718 elif c in DIGITS + 'n#-':
719 left = self.parse_basso_continuo (left)
723 left = self.parse_slur (left)
725 left = self.parse_barcheck (left)
727 left = self.parse_ornament (left)
729 left = self.parsex (left)
731 self.current_staff().set_clef(str(left[1]))
734 left = self.parse_key (left)
736 left = self.parse_beams (left)
737 elif left[:2] == "//":
738 self.current_staff().next_voice ()
744 left = self.parse_mumbo_jumbo(left)
748 sys.stderr.write ("""
749 Huh? Unknown directive `%s', before `%s'""" % (c, left[:20] ))
756 for s in self.staffs:
757 str = str + s.dump ()
758 refs = '\\' + s.idstring() + refs
760 str = str + "\n\n\\score { <\n %s\n > }" % refs
765 ls = open (fn).readlines ()
767 return re.sub ('%.*$', '', s)
769 ls = self.parse_header (ls)
770 left = string.join (ls, ' ')
773 self.parse_body (left)
774 for c in self.staffs:
783 """Usage: pmx2ly [OPTION]... PMX-FILE
785 Convert PMX to LilyPond.
789 -o, --output=FILE set output filename to FILE
790 -v, --version version information
792 PMX is a Musixtex preprocessor written by Don Simons, see
793 http://www.gmd.de/Misc/Music/musixtex/software/pmx/
795 Report bugs to bug-lilypond@gnu.org.
797 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>
801 def print_version ():
802 sys.stdout.write ("""pmx2ly (GNU LilyPond) %s
804 This is free software. It is covered by the GNU General Public License,
805 and you are welcome to change it and/or distribute copies of it under
806 certain conditions. Invoke as `midi2ly --warranty' for more information.
808 Copyright (c) 2000--2002 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
811 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
815 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
820 if o== '--help' or o == '-h':
823 if o == '--version' or o == '-v':
827 if o == '--output' or o == '-o':
839 sys.stderr.write ('Processing `%s\'\n' % f)
842 out_filename = os.path.basename (re.sub ('(?i).pmx$', '.ly', f))
844 if out_filename == f:
845 out_filename = os.path.basename (f + '.ly')
847 sys.stderr.write ('Writing `%s\'' % out_filename)
852 fo = open (out_filename, 'w')
853 fo.write ('%% lily was here -- automatically converted by pmx2ly from %s\n' % f)