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_prefix
141 sys.stderr.write ("\nOrphaned slur")
148 self.current_slurs = []
150 def toggle_slur (self, id):
152 for s in self.current_slurs:
154 self.current_slurs.remove (s)
155 s.end_chord = self.chords[-1]
158 s.start_chord = self.chords[-1]
159 self.current_slurs.append (s)
160 self.slurs.append (s)
162 def last_chord (self):
163 return self.chords[-1]
164 def add_chord (self, ch):
165 self.chords.append (ch)
166 self.entries.append (ch)
167 def add_nonchord (self, nch):
168 self.entries.append (nch)
171 return 'staff%svoice%s ' % (encodeint (self.staff.number) , encodeint(self.number))
175 for e in self.entries:
176 next = ' ' + e.dump ()
178 str = str + ln + next
182 if len (ln) +len (next) > 72:
189 id = self.idstring ()
191 str = '%s = \\notes { \n %s }\n '% (id, str)
193 def calculate_graces (self):
196 for c in self.chords:
197 if c.grace and not lastgr:
198 c.chord_prefix = c.chord_prefix + '\\grace { '
199 elif not c.grace and lastgr:
200 lastc.chord_suffix = lastc.chord_suffix + ' } '
203 def calculate (self):
204 self.calculate_graces ()
209 def __init__ (self, cl):
212 return '\\clef %s' % self.type
215 def __init__ (self, key):
218 return '\\key %s' % self.type
247 self.voices = (Voice (), Voice())
255 for v in self.voices:
259 def set_clef (self, letter):
260 clstr = clef_table[letter]
261 self.voices[0].add_nonchord (Clef (clstr))
264 def current_voice (self):
265 return self.voices[self.voice_idx]
266 def next_voice (self):
267 self.voice_idx = (self.voice_idx + 1)%len (self.voices)
269 def calculate (self):
270 for v in self.voices:
273 return 'staff%s' % encodeint (self.number)
278 for v in self.voices:
280 refs = refs + '\\' + v.idstring ()+ ' '
282 str = str + '\n\n%s = \\context Staff = %s \n < \n %s >\n\n\n'% (self.idstring (), self.idstring (), refs)
286 def __init__ (self, number, base, dots):
289 self.replaces = tuplet_table[number]
295 length = rat_multiply (length, (3,2))
297 length = rat_multiply (length, (7,4))
299 length = rat_multiply (length, (1,self.replaces))
301 (nb,nd) =rat_to_duration (length)
306 def add_chord (self, ch):
307 ch.dots = self.note_dots
308 ch.basic_duration = self.note_base
309 self.chords.append (ch)
311 if len (self.chords) == 1:
312 ch.chord_prefix = '\\times %d/%d { ' % (self.replaces, self.number)
313 elif len (self.chords) == self.number:
314 ch.chord_suffix = ' }'
320 self.basic_duration = 0
323 self.chord_prefix = ''
324 self.chord_suffix = ''
325 self.note_prefix = ''
326 self.note_suffix = ''
332 if self.basic_duration == 0.5:
335 sd = '%d' % self.basic_duration
336 sd = sd + '.' * self.dots
337 for p in self.pitches:
340 str = str + pitch_to_lily_string (p) + sd
342 for s in self.scripts:
345 str = self.note_prefix +str + self.note_suffix
347 if len (self.pitches) > 1:
349 elif len (self.pitches) == 0:
352 str = self.chord_prefix + str + self.chord_suffix
390 def __init__ (self, filename):
392 self.forced_duration = None
395 self.tuplets_expected = 0
397 self.last_basic_duration = 4
399 self.parse (filename)
401 def set_staffs (self, number):
402 self.staffs = map (lambda x: Staff (), range(0, number))
407 for s in self.staffs:
410 def current_staff (self):
411 return self.staffs[self.staff_idx]
413 def current_voice (self):
414 return self.current_staff ().current_voice ()
416 def next_staff (self):
417 self.staff_idx = (self.staff_idx + 1)% len (self.staffs)
419 def parse_note (self, str):
429 ch = self.current_voice().last_chord()
433 self.current_voice().add_chord (ch)
437 name = (ord (str[0]) - ord('a') + 5) % 7
441 ch.grace = ch.grace or grace
451 while str[0] in 'dsfmnul0123456789.,+-':
455 alteration = alteration -1
461 alteration = alteration +1
464 elif c in DIGITS and durdigit == None and \
465 self.tuplets_expected == 0:
466 durdigit = string.atoi (c)
468 oct = string.atoi (c) - 3
470 extra_oct = extra_oct + 1
472 extra_oct = extra_oct - 1
481 tupnumber = string.atoi (str[0])
483 str=re.sub (r'^n?f?[+-0-9.]+', '' , str)
488 basic_duration = basicdur_table[durdigit]
489 self.last_basic_duration = basic_duration
491 sys.stderr.write ("""
492 Huh? expected duration, found %d Left was `%s'""" % (durdigit, str[:20]))
496 basic_duration = self.last_basic_duration
500 if name <> None and oct == None:
502 if self.last_name < name and name -self.last_name > 3:
504 elif self.last_name > name and self.last_name -name > 3:
507 oct = self.last_oct +e + extra_oct
511 self.last_name = name
514 ch.pitches.append ((oct, name, alteration))
516 # do before adding to tuplet.
517 ch.basic_duration = basic_duration
521 self.forced_duration = ch.basic_duration / forced_duration
524 tup =Tuplet (tupnumber, basic_duration, dots)
525 self.tuplets_expected = tupnumber
526 self.tuplets.append (tup)
528 if self.tuplets_expected > 0:
529 self.tuplets[-1].add_chord (ch)
530 self.tuplets_expected = self.tuplets_expected - 1
533 def parse_basso_continuo (self, str):
534 while str[0] in DIGITS +'#n-':
538 scr = '\\\\textsharp'
540 if len(scr)>1 or scr not in DIGITS:
543 self.current_voice().last_chord ().scripts.append (scr)
546 def parse_beams (self,str):
548 # self.current_voice().add_nonchord (Beam(c))
551 while str[0] in '+-0123456789':
558 def parse_key (self, str):
560 #The key is changed by a string of the form K[+-]<num>[+-]<num>
561 #where the first number is the transposition and the second number is the
562 #new key signature. For now, we won't bother with the transposition.
564 sys.stderr.write("Transposition not implemented yet: ")
565 while str[0] in '+-0123456789':
570 while str[0] in '+-0123456789':
573 keystr = key_table[key]
574 self.current_voice().add_nonchord (Key(keystr))
578 def parse_header (self, ls):
580 if re.search('\\.', a):
581 return string.atof (a)
583 return string.atoi (a)
588 while len (numbers) < number_count:
592 opening = re.sub ('[ \t\n]+', ' ', opening)
593 opening = re.sub ('^ ', '', opening)
594 opening = re.sub (' $', '', opening)
597 opening = string.split (opening, ' ')
599 numbers = numbers + map (atonum, opening)
601 (no_staffs, no_instruments, timesig_num, timesig_den, ptimesig_num,
602 ptimesig_den, pickup_beats,keysig_number) = tuple (numbers[0:8])
603 (no_pages,no_systems, musicsize, fracindent) = tuple (numbers[8:])
606 # opening = map (string.atoi, re.split ('[\t ]+', opening))
609 while len (instruments) < no_instruments:
610 instruments.append (ls[0])
616 self.set_staffs (no_staffs)
618 for s in self.staffs:
628 def parse_ornament (self, left):
630 e = self.current_voice ().last_chord ()
640 orn = ornament_table[id]
642 sys.stderr.write ("unknown ornament `%s'\n" % id)
644 e.scripts.append (orn)
646 def parse_barcheck (self, left):
647 self.current_voice ().add_nonchord (Barcheck ())
651 def parse_slur (self, left):
656 if re.match ('[A-Z0-9]', left[0]):
659 while left[0] in 'uld0123456789+-.':
662 self.current_voice ().toggle_slur (id)
665 def parse_mumbo_jumbo (self,left):
667 while left and left[0] <> '\\':
672 def parsex (self,left):
674 while left[0] in DIGITS:
679 def parse_body (self, left):
685 f = string.find (left, '\n')
691 m = re.match ('([o0-9]/[o0-9]/[o0-9]/[o0-9])', left)
694 left = left[len (nums):]
695 nums = map (string.atoi , nums)
696 self.current_voice ().add_nonchord (Meter (nums))
699 m= re.match ('([0-9o]+)', left)
702 self.current_voice ().add_nonchord (Meter (map (string.atoi (nums))))
705 elif left[0] in 'lh':
706 f = string.find (left, '\n')
712 f = string.find (left, '\n')
715 elif c in 'Gzabcdefgr':
716 left = self.parse_note (left)
717 elif c in DIGITS + 'n#-':
718 left = self.parse_basso_continuo (left)
722 left = self.parse_slur (left)
724 left = self.parse_barcheck (left)
726 left = self.parse_ornament (left)
728 left = self.parsex (left)
730 self.current_staff().set_clef(str(left[1]))
733 left = self.parse_key (left)
735 left = self.parse_beams (left)
736 elif left[:2] == "//":
737 self.current_staff().next_voice ()
743 left = self.parse_mumbo_jumbo(left)
747 sys.stderr.write ("""
748 Huh? Unknown directive `%s', before `%s'""" % (c, left[:20] ))
755 for s in self.staffs:
756 str = str + s.dump ()
757 refs = '\\' + s.idstring() + refs
759 str = str + "\n\n\\score { <\n %s\n > }" % refs
764 ls = open (fn).readlines ()
766 return re.sub ('%.*$', '', s)
768 ls = self.parse_header (ls)
769 left = string.join (ls, ' ')
772 self.parse_body (left)
773 for c in self.staffs:
782 """Usage: pmx2ly [OPTION]... PMX-FILE
784 Convert PMX to LilyPond.
788 -o, --output=FILE set output filename to FILE
789 -v, --version version information
791 PMX is a Musixtex preprocessor written by Don Simons, see
792 http://www.gmd.de/Misc/Music/musixtex/software/pmx/
794 Report bugs to bug-lilypond@gnu.org.
796 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>
800 def print_version ():
801 sys.stdout.write ("""pmx2ly (GNU LilyPond) %s
803 This is free software. It is covered by the GNU General Public License,
804 and you are welcome to change it and/or distribute copies of it under
805 certain conditions. Invoke as `midi2ly --warranty' for more information.
807 Copyright (c) 2000--2002 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
810 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
814 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
819 if o== '--help' or o == '-h':
822 if o == '--version' or o == '-v':
826 if o == '--output' or o == '-o':
838 sys.stderr.write ('Processing `%s\'\n' % f)
841 out_filename = os.path.basename (re.sub ('(?i).pmx$', '.ly', f))
843 if out_filename == f:
844 out_filename = os.path.basename (f + '.ly')
846 sys.stderr.write ('Writing `%s\'' % out_filename)
851 fo = open (out_filename, 'w')
852 fo.write ('%% lily was here -- automatically converted by pmx2ly from %s\n' % f)