2 # mup2ly.py -- mup input converter
4 # source file of the GNU LilyPond music typesetter
10 LOTS: we get all notes out now, rest after 1.4
12 * lyrics (partly done)
22 * repeats, percent repeats
38 # if set, LILYPONDPREFIX must take prevalence
39 # if datadir is not set, we're doing a build and LILYPONDPREFIX
40 datadir = '@local_lilypond_datadir@'
41 if os.environ.has_key ('LILYPONDPREFIX') \
42 or '@local_lilypond_datadir@' == '@' + 'local_lilypond_datadir' + '@':
43 datadir = os.environ['LILYPONDPREFIX']
45 datadir = '@local_lilypond_datadir@'
47 sys.path.append (os.path.join (datadir, 'python'))
48 sys.path.append (os.path.join (datadir, 'python/out'))
50 program_name = sys.argv[0]
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
58 localedir = '@localedir@'
61 gettext.bindtextdomain ('lilypond', localedir)
62 gettext.textdomain ('lilypond')
69 program_name = 'mup2ly'
70 help_summary = _ ("Convert mup to LilyPond source.")
72 option_definitions = [
73 ('', 'd', 'debug', _ ("debug")),
74 ('NAME[=EXP]', 'D', 'define', _ ("define macro NAME [optional expansion EXP]")),
75 ('', 'h', 'help', _ ("print this help")),
76 ('FILE', 'o', 'output', _ ("write output to FILE")),
77 ('', 'E', 'pre-process', _ ("only pre-process")),
78 ('', 'V', 'verbose', _ ("be verbose")),
79 ('', 'v', 'version', _ ("print version number")),
80 ('', 'w', 'warranty', _ ("show warranty and copyright")),
84 ################################################################
85 # lilylib.py -- options and stuff
87 # source file of the GNU LilyPond music typesetter
91 gettext.bindtextdomain ('lilypond', localedir)
92 gettext.textdomain ('lilypond')
98 program_version = '@TOPLEVEL_VERSION@'
99 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
100 program_version = '1.5.54'
103 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
107 sys.stdout.write ('\n')
108 sys.stdout.write (_ ('Copyright (c) %s by') % '2001--2005')
109 sys.stdout.write ('\n')
110 sys.stdout.write (' Han-Wen Nienhuys')
111 sys.stdout.write (' Jan Nieuwenhuizen')
112 sys.stdout.write ('\n\n')
113 sys.stdout.write (_ ("Distributed under terms of the GNU General Public License."))
114 sys.stdout.write (_ ("It comes with NO WARRANTY."))
115 sys.stdout.write ('\n')
118 errorport.write (s + '\n')
121 progress (_ ("warning: ") + s)
123 def user_error (s, e=1):
124 errorport.write (program_name + ":" + _ ("error: ") + s + '\n')
128 '''Report the error S. Exit by raising an exception. Please
129 do not abuse by trying to catch this error. If you do not want
130 a stack trace, write to the output directly.
138 progress (_ ("error: ") + s)
139 raise _ ("Exiting ... ")
141 def getopt_args (opts):
142 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
157 def option_help_str (o):
158 '''Transform one option description (4-tuple ) into neatly formatted string'''
176 return ' ' + sh + sep + long + arg
179 def options_help_str (opts):
180 '''Convert a list of options into a neatly formatted string'''
186 s = option_help_str (o)
187 strs.append ((s, o[3]))
193 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
197 ls = [(_ ("Usage: %s [OPTIONS]... FILE") % program_name),
203 (options_help_str (option_definitions)),
205 (_ ("Report bugs to %s.") % 'bug-lilypond@gnu.org'),
207 map (sys.stdout.write, ls)
211 Create a temporary directory, and return its name.
214 if not keep_temp_dir_p:
215 temp_dir = tempfile.mktemp (program_name)
217 os.mkdir (temp_dir, 0777)
224 def system (cmd, ignore_error = 0, quiet =0):
225 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
233 progress (_ ("Invoking `%s\'") % cmd)
237 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
238 msg = name + ': ' + _ ("command exited with value %d") % st
241 warning (msg + ' ' + _ ("(ignored)") + ' ')
249 if not keep_temp_dir_p:
251 progress (_ ("Cleaning %s...") % temp_dir)
252 shutil.rmtree (temp_dir)
255 def strip_extension (f, ext):
256 (p, e) = os.path.splitext (f)
262 def cp_to_dir (pattern, dir):
263 "Copy files matching re PATTERN from cwd to DIR"
264 # Duh. Python style portable: cp *.EXT OUTDIR
265 # system ('cp *.%s %s' % (ext, outdir), 1)
266 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
267 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
270 def mkdir_p (dir, mode=0777):
271 if not os.path.isdir (dir):
275 # if set, LILYPONDPREFIX must take prevalence
276 # if datadir is not set, we're doing a build and LILYPONDPREFIX
277 datadir = '@local_lilypond_datadir@'
279 if os.environ.has_key ('LILYPONDPREFIX') :
280 datadir = os.environ['LILYPONDPREFIX']
282 datadir = '@local_lilypond_datadir@'
285 while datadir[-1] == os.sep:
286 datadir= datadir[:-1]
288 sys.path.insert (0, os.path.join (datadir, 'python'))
290 ################################################################
301 return chr (i + ord ('A'))
304 actab = {-2: 'eses', -1: 'es', 0 : '', 1: 'is', 2:'isis'}
306 def pitch_to_lily_string (tup):
309 nm = chr((n + 2) % 7 + ord ('a'))
327 def rat_simplify (r):
338 def rat_multiply (a,b):
342 return rat_simplify ((x*p, y*q))
344 def rat_divide (a,b):
346 return rat_multiply (a, (q,p))
359 return rat_simplify ((x*q + p*y, y*q))
366 def rat_larger (a,b):
367 return rat_subtract (a, b )[0] > 0
369 def rat_subtract (a,b ):
370 return rat_add (a, rat_neg (b))
372 def rat_to_duration (frac):
375 while rat_larger (d, frac):
376 d = rat_multiply (d, (1,2))
379 frac = rat_subtract (frac, d)
381 if frac == rat_multiply (d, (1,2)):
383 elif frac == rat_multiply (d, (3,4)):
396 def __init__ (self,nums):
399 return ' %{ FIXME: meter change %} '
402 def __init__ (self, ch):
408 def __init__ (self,id):
410 self.start_chord = None
411 self.end_chord = None
413 def calculate (self):
418 s.note_suffix = s.note_suffix + '-('
419 e.note_prefix = e.note_suffix + "-)"
421 sys.stderr.write ("\nOrphaned slur")
424 def __init__ (self, n):
429 self.current_slurs = []
432 def toggle_slur (self, id):
434 for s in self.current_slurs:
436 self.current_slurs.remove (s)
437 s.end_chord = self.chords[-1]
440 s.start_chord = self.chords[-1]
441 self.current_slurs.append (s)
442 self.slurs.append (s)
444 def last_chord (self):
445 if len (self.chords):
446 return self.chords[-1]
449 ch.basic_duration = 4
452 def add_chord (self, ch):
453 self.chords.append (ch)
454 self.entries.append (ch)
456 def add_nonchord (self, nch):
457 self.entries.append (nch)
460 return 'staff%svoice%s ' % (encodeint (self.staff.number) , encodeint(self.number))
464 #if not self.entries:
467 # return '\n%s = {}\n\n' % self.idstring ()
469 one_two = ("One", "Two")
470 if self.staff.voices [1 - self.number].entries:
471 ln = ln + '\\voice%s\n ' % one_two[self.number]
472 for e in self.entries:
475 str = str + ln + next + ' '
479 if len (ln) +len (next) > 72:
486 id = self.idstring ()
488 str = '''%s = \\context Voice = %s {
495 def calculate_graces (self):
498 for c in self.chords:
499 if c.grace and not lastgr:
500 c.chord_prefix = c.chord_prefix + '\\grace { '
501 elif not c.grace and lastgr:
502 lastc.chord_suffix = lastc.chord_suffix + ' } '
506 def calculate (self):
507 self.calculate_graces ()
512 def __init__ (self, cl):
516 return '\\clef %s' % self.type
518 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
519 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
522 def __init__ (self, sharps, flats):
527 if self.sharps and self.flats:
528 k = '\\keysignature %s ' % 'TODO'
530 k = '\\key %s \major' % key_sharps[self.sharps]
532 k = '\\key %s \major' % key_flats[self.flats]
536 def __init__ (self, frac):
540 return '\\time %d/%d' % (self.frac[0], self.frac[1])
555 def __init__ (self, n):
557 self.voices = (Voice (0), Voice (1))
566 for v in self.voices:
571 #def set_clef (self, letter):
572 # clstr = clef_table[letter]
573 # self.voices[0].add_nonchord (Clef (clstr))
575 def calculate (self):
576 for v in self.voices:
580 return 'staff%s' % encodeint (self.number)
586 for v in self.voices:
589 if v == self.voices[0]:
591 refs = refs + self.clef.dump ()
593 refs = refs + self.time.dump ()
595 refs = refs + self.key.dump ()
599 refs = refs + '\n \\' + v.idstring ()
601 %s = \context Staff = %s <<%s
604 ''' % (self.idstring (), self.idstring (), refs)
608 def __init__ (self, number, base, dots):
611 self.replaces = tuplet_table[number]
617 length = rat_multiply (length, (3,2))
619 length = rat_multiply (length, (7,4))
621 length = rat_multiply (length, (1,self.replaces))
623 (nb,nd) =rat_to_duration (length)
628 def add_chord (self, ch):
629 ch.dots = self.note_dots
630 ch.basic_duration = self.note_base
631 self.chords.append (ch)
633 if len (self.chords) == 1:
634 ch.chord_prefix = '\\times %d/%d { ' % (self.replaces, self.number)
635 elif len (self.chords) == self.number:
636 ch.chord_suffix = ' }'
641 self.multimeasure = 0
643 self.basic_duration = 0
646 self.chord_prefix = ''
647 self.chord_suffix = ''
648 self.note_prefix = ''
649 self.note_suffix = ''
651 # maybe use import copy?
654 #for i in self.pitches:
655 # ch.pitches.append (i)
656 ch.pitches = self.pitches[:]
657 ch.multimeasure = self.multimeasure
659 ch.basic_duration = self.basic_duration
660 #for i in self.scripts:
661 # ch.scripts.append (i)
662 ch.scripts = self.scripts[:]
663 ch.grace = self.grace
665 ch.chord_prefix = self.chord_prefix
666 ch.chord_suffix = self.chord_suffix
667 ch.note_prefix = self.note_prefix
668 ch.note_suffix = self.note_suffix
676 if self.basic_duration == 0.5:
679 sd = '%d' % self.basic_duration
680 sd = sd + '.' * self.dots
681 for p in self.pitches:
684 str = str + pitch_to_lily_string (p)
687 str = self.note_prefix +str + self.note_suffix
689 if len (self.pitches) > 1:
691 elif self.multimeasure:
693 elif len (self.pitches) == 0:
697 for s in self.scripts:
700 str = self.chord_prefix + str + self.chord_suffix
737 # http://www.arkkra.com/doc/uguide/contexts.html
752 def __init__ (self, lines):
753 self.parse_function = self.parse_context_music
755 self.current_voices = []
756 self.forced_duration = None
759 self.tuplets_expected = 0
767 def parse_compound_location (self, line):
768 colon = string.index (line, ':')
771 line = line[colon + 1:]
773 self.current_voices = []
774 ##self.current_staffs = []
775 map (self.parse_location, string.split (s, '&'))
778 def parse_location (self, line):
779 m = re.match ('^([-,0-9]+) *([-,0-9]*)', string.lstrip (line))
781 def range_list_to_idxs (s):
791 def range_to_list (s):
792 if string.find (s, '-') >= 0:
794 l = map (string.lstrip,
795 string.split (s, '-'))
796 r = range (string.atoi (l[0]) - 1,
799 r = (string.atoi (s) - 1,)
802 ranges = string.split (s, ',')
803 l = flatten (map (range_to_list, ranges))
807 staff_idxs = range_list_to_idxs (m.group (1))
809 voice_idxs = range_list_to_idxs (m.group (2))
813 while s > len (self.staffs) - 1:
814 self.staffs.append (Staff (s))
816 self.current_voices.append (self.staffs[s].voices[v])
818 def parse_note (self, line):
821 name = (ord (line[0]) - ord ('a') + 5) % 7
822 # FIXME: does key play any role in this?
824 debug ('NOTE: ' + `line`)
825 line = string.lstrip (line[1:])
827 if len (line) > 1 and line[:2] == '//':
831 alteration = alteration + 1
833 alteration = alteration - 1
840 line = string.lstrip (line[1:])
841 return (oct, name, alteration)
843 def parse_chord (self, line):
844 debug ('CHORD: ' + line)
845 line = string.lstrip (line)
848 #ch = self.current_voices[0].last_chord ()
849 ch = self.last_chord.copy ()
851 m = re.match ('^([0-9]+)([.]*)', line)
853 ch.basic_duration = string.atoi (m.group (1))
854 line = line[len (m.group (1)):]
856 ch.dots = len (m.group (2))
857 line = line[len (m.group (2)):]
859 #ch.basic_duration = self.current_voices[0].last_chord ().basic_duration
860 ch.basic_duration = self.last_chord.basic_duration
862 line = string.lstrip (line)
863 if len (line) > 1 and line[:2] == '//':
867 debug ('nline: ' + line)
868 #ch = self.current_voices[0].last_chord ()
869 n = self.last_chord.copy ()
870 n.basic_duration = ch.basic_duration
873 debug ('ch.pitsen:' + `ch.pitches`)
874 debug ('ch.dur:' + `ch.basic_duration`)
876 debug ('eline: ' + line)
879 if len (line) > 1 and line[:2] == '//':
882 elif line[:1] == 'mr':
885 elif line[:1] == 'ms':
888 elif line[0] in 'rs':
891 elif line[0] in 'abcdefg':
892 m = re.match ('([a-g][-#&+]*)', line)
893 l = len (m.group (1))
894 pitch = self.parse_note (line[:l])
895 debug ('PITCH: ' + `pitch`)
896 ch.pitches.append (pitch)
902 line = string.lstrip (line)
903 debug ('CUR-VOICES: ' + `self.current_voices`)
904 map (lambda x, ch=ch: x.add_chord (ch), self.current_voices)
907 def parse_lyrics_location (self, line):
908 line = line.lstrip (line)
910 m = re.match ('^(between[ \t]+)', line)
912 line = line[len (m.group (1)):]
915 m = re.match ('^(above [ \t]+)', line)
917 line = line[len (m.group (1)):]
922 def parse_voice (self, line):
923 line = string.lstrip (line)
924 # `;' is not a separator, chords end with ';'
925 chords = string.split (line, ';')[:-1]
926 # mup resets default duration and pitch each bar
927 self.last_chord = Chord ()
928 self.last_chord.basic_duration = 4
929 map (self.parse_chord, chords)
931 def init_context_header (self, line):
932 self.parse_function = self.parse_context_header
934 def parse_context_header (self, line):
935 debug ('header: ' + line)
938 def init_context_footer (self, line):
939 self.parse_function = self.parse_context_footer
941 def parse_context_footer (self, line):
942 debug ('footer: ' + line)
945 def init_context_header2 (self, line):
946 self.parse_function = self.parse_context_header2
948 def parse_context_header2 (self, line):
949 debug ('header2: ' + line)
952 def init_context_footer2 (self, line):
953 self.parse_function = self.parse_context_footer2
955 def parse_context_footer2 (self, line):
956 debug ('footer2: ' + line)
959 def init_context_score (self, line):
960 self.parse_function = self.parse_context_score
962 def parse_context_score (self, line):
963 debug ('score: ' + line)
964 line = string.lstrip (line)
965 # ugh: these (and lots more) should also be parsed in
966 # context staff. we should have a class Staff_properties
967 # and parse/set all those.
968 m = re.match ('^(time[ \t]*=[ \t]*([0-9]+)[ \t]*/[ \t]*([0-9]+))', line)
970 line = line[len (m.group (1)):]
971 self.time = Time ((string.atoi (m.group (2)),
972 string.atoi (m.group (3))))
974 m = re.match ('^(key[ \t]*=[ \t]*([0-9]+)[ \t]*(#|@))', line)
976 line = line[len (m.group (1)):]
977 n = string.atoi (m.group (2))
978 if m.group (3) == '#':
979 self.key = Key (n, 0)
981 self.key = Key (0, n)
984 def init_context_staff (self, line):
985 self.parse_function = self.parse_context_staff
987 def parse_context_staff (self, line):
988 debug ('staff: ' + line)
991 def init_context_voice (self, line):
992 self.parse_function = self.parse_context_voice
994 def parse_context_voice (self, line):
995 debug ('voice: ' + line)
998 def init_context_grids (self, line):
999 self.parse_function = self.parse_context_grids
1001 def parse_context_grids (self, line):
1002 debug ('grids: ' + line)
1005 def init_context_music (self, line):
1006 self.parse_function = self.parse_context_music
1008 def parse_context_music (self, line):
1009 debug ('music: ' + line)
1010 line = string.lstrip (line)
1011 if line and line[0] in '0123456789':
1012 line = self.parse_compound_location (line)
1013 self.parse_voice (line)
1015 m = re.match ('^(TODOlyrics[ \t]+)', line)
1017 line = line[len (m.group (1)):]
1018 self.parse_lyrics_location (line[7:])
1019 self.parse_lyrics (line)
1023 def parse (self, lines):
1024 # shortcut: set to official mup maximum (duh)
1025 # self.set_staffs (40)
1027 debug ('LINE: ' + `line`)
1028 m = re.match ('^([a-z]+2?)', line)
1032 if word in contexts:
1033 eval ('self.init_context_%s (line)' % word)
1036 warning (_ ("no such context: %s") % word)
1039 debug ('FUNC: ' + `self.parse_function`)
1040 self.parse_function (line)
1042 for c in self.staffs:
1044 if not c.clef and self.clef:
1046 if not c.time and self.time:
1048 if not c.key and self.key:
1056 for s in self.staffs:
1057 str = str + s.dump ()
1058 refs = refs + '\n \\' + s.idstring ()
1072 class Pre_processor:
1073 def __init__ (self, raw_lines):
1076 self.process_function = self.process_line
1077 self.macro_name = ''
1078 self.macro_body = ''
1079 self.process (raw_lines)
1081 def process_line (self, line):
1083 m = re.match ('^([ \t]*([a-zA-Z]+))', line)
1087 debug ('MACRO?: ' + `word`)
1088 if word in pre_processor_commands:
1089 line = line[len (m.group (1)):]
1090 eval ('self.process_macro_%s (line)' % word)
1093 if macros.has_key (word):
1094 s = macros[word] + line[len (m.group (1)):]
1095 if not self.active [-1]:
1099 def process_macro_body (self, line):
1101 # dig this: mup allows ifdefs inside macro bodies
1102 s = self.process_line (line)
1103 m = re.match ('(.*[^\\\\])(@)(.*)', s)
1105 self.macro_body = self.macro_body + '\n' + m.group (1)
1106 macros[self.macro_name] = self.macro_body
1107 debug ('MACROS: ' + `macros`)
1108 # don't do nested multi-line defines
1109 self.process_function = self.process_line
1115 self.macro_body = self.macro_body + '\n' + s
1119 # duh: mup is strictly line-based, except for `define',
1120 # which is `@' terminated and may span several lines
1121 def process_macro_define (self, line):
1123 # don't define new macros in unactive areas
1124 if not self.active[-1]:
1126 m = re.match ('^[ \t]*([a-zA-Z][a-zA-Z1-9_]*)(([^@]*)|(\\\\@))(@)?', line)
1134 debug ('MACROS: ' + `macros`)
1136 # To support nested multi-line define's
1137 # process_function and macro_name, macro_body
1138 # should become lists (stacks)
1139 # The mup manual is undetermined on this
1140 # and I haven't seen examples doing it.
1142 # don't do nested multi-line define's
1144 self.macro_body = m.group (2)
1146 self.macro_body = ''
1148 self.process_function = self.process_macro_body
1150 def process_macro_ifdef (self, line):
1151 m = re.match ('^[ \t]*([a-zA-Z][a-zA-Z1-9_]*)', line)
1154 active = self.active[-1] and macros.has_key (m.group (1))
1155 debug ('ACTIVE: %d' % active)
1156 self.active.append (active)
1158 def process_macro_ifndef (self, line):
1159 m = re.match ('^[ \t]*([a-zA-Z][a-zA-Z1-9_]*)', line)
1161 active = self.active[-1] and not macros.has_key (m.group (1))
1162 self.active.append (active)
1164 def process_macro_else (self, line):
1166 self.active[-1] = not self.active[-1]
1168 def process_macro_endif (self, line):
1169 self.active = self.active[:-1]
1171 def process (self, raw_lines):
1173 for line in raw_lines:
1174 ls = string.split (self.process_function (line), '\n')
1177 s = s + string.rstrip (i)
1178 if s and s[-1] == '\\':
1179 s = string.rstrip (s[:-1])
1181 self.lines.append (s)
1186 only_pre_process_p = 0
1189 progress ('DEBUG: ' + s)
1192 if verbose_p or debug_p:
1193 progress ('SKIPPING: ' + s)
1195 (sh, long) = getopt_args (__main__.option_definitions)
1197 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1203 pre_processor_commands = (
1216 elif o== '--debug' or o == '-d':
1218 elif o== '--define' or o == '-D':
1219 if string.find (a, '=') >= 0:
1220 (n, e) = string.split (a, '=')
1225 elif o== '--pre-process' or o == '-E':
1226 only_pre_process_p = 1
1227 elif o== '--help' or o == '-h':
1230 elif o== '--verbose' or o == '-V':
1232 elif o == '--version' or o == '-v':
1235 elif o == '--output' or o == '-o':
1241 # writes to stdout for help2man
1244 # sys.stdout.flush ()
1246 # handy emacs testing
1248 # files = ['template.mup']
1257 elif f and not os.path.isfile (f):
1258 f = strip_extension (f, '.mup') + '.mup'
1261 progress ( _("Processing `%s'..." % f))
1262 raw_lines = h.readlines ()
1263 p = Pre_processor (raw_lines)
1264 if only_pre_process_p:
1266 output = os.path.basename (re.sub ('(?i).mup$', '.mpp', f))
1268 e = Parser (p.lines)
1270 output = os.path.basename (re.sub ('(?i).mup$', '.ly', f))
1272 output = os.path.basename (f + '.ly')
1278 out_h = open (output, 'w')
1280 progress (_ ("Writing `%s'...") % output)
1282 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, f)
1283 if only_pre_process_p:
1285 ly = string.join (p.lines, '\n')
1287 ly = tag + '\n\n' + e.dump ()