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.") %
206 "http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs"),
208 map (sys.stdout.write, ls)
212 Create a temporary directory, and return its name.
216 if not keep_temp_dir_p:
217 temp_dir = tempfile.mktemp (program_name)
219 os.mkdir (temp_dir, 0777)
226 def system (cmd, ignore_error = 0, quiet =0):
227 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
235 progress (_ ("Invoking `%s\'") % cmd)
239 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
240 msg = name + ': ' + _ ("command exited with value %d") % st
243 warning (msg + ' ' + _ ("(ignored)") + ' ')
251 if not keep_temp_dir_p:
253 progress (_ ("Cleaning %s...") % temp_dir)
254 shutil.rmtree (temp_dir)
257 def strip_extension (f, ext):
258 (p, e) = os.path.splitext (f)
264 def cp_to_dir (pattern, dir):
265 "Copy files matching re PATTERN from cwd to DIR"
266 # Duh. Python style portable: cp *.EXT OUTDIR
267 # system ('cp *.%s %s' % (ext, outdir), 1)
268 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
269 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
272 def mkdir_p (dir, mode=0777):
273 if not os.path.isdir (dir):
277 # if set, LILYPONDPREFIX must take prevalence
278 # if datadir is not set, we're doing a build and LILYPONDPREFIX
279 datadir = '@local_lilypond_datadir@'
281 if os.environ.has_key ('LILYPONDPREFIX') :
282 datadir = os.environ['LILYPONDPREFIX']
284 datadir = '@local_lilypond_datadir@'
287 while datadir[-1] == os.sep:
288 datadir= datadir[:-1]
290 sys.path.insert (0, os.path.join (datadir, 'python'))
292 ################################################################
303 return chr (i + ord ('A'))
306 actab = {-2: 'eses', -1: 'es', 0 : '', 1: 'is', 2:'isis'}
308 def pitch_to_lily_string (tup):
311 nm = chr((n + 2) % 7 + ord ('a'))
329 def rat_simplify (r):
340 def rat_multiply (a,b):
344 return rat_simplify ((x*p, y*q))
346 def rat_divide (a,b):
348 return rat_multiply (a, (q,p))
361 return rat_simplify ((x*q + p*y, y*q))
368 def rat_larger (a,b):
369 return rat_subtract (a, b )[0] > 0
371 def rat_subtract (a,b ):
372 return rat_add (a, rat_neg (b))
374 def rat_to_duration (frac):
377 while rat_larger (d, frac):
378 d = rat_multiply (d, (1,2))
381 frac = rat_subtract (frac, d)
383 if frac == rat_multiply (d, (1,2)):
385 elif frac == rat_multiply (d, (3,4)):
398 def __init__ (self,nums):
401 return ' %{ FIXME: meter change %} '
404 def __init__ (self, ch):
410 def __init__ (self,id):
412 self.start_chord = None
413 self.end_chord = None
415 def calculate (self):
420 s.note_suffix = s.note_suffix + '-('
421 e.note_prefix = e.note_suffix + "-)"
423 sys.stderr.write ("\nOrphaned slur")
426 def __init__ (self, n):
431 self.current_slurs = []
434 def toggle_slur (self, id):
436 for s in self.current_slurs:
438 self.current_slurs.remove (s)
439 s.end_chord = self.chords[-1]
442 s.start_chord = self.chords[-1]
443 self.current_slurs.append (s)
444 self.slurs.append (s)
446 def last_chord (self):
447 if len (self.chords):
448 return self.chords[-1]
451 ch.basic_duration = 4
454 def add_chord (self, ch):
455 self.chords.append (ch)
456 self.entries.append (ch)
458 def add_nonchord (self, nch):
459 self.entries.append (nch)
462 return 'staff%svoice%s ' % (encodeint (self.staff.number) , encodeint(self.number))
466 #if not self.entries:
469 # return '\n%s = {}\n\n' % self.idstring ()
471 one_two = ("One", "Two")
472 if self.staff.voices [1 - self.number].entries:
473 ln = ln + '\\voice%s\n ' % one_two[self.number]
474 for e in self.entries:
477 str = str + ln + next + ' '
481 if len (ln) +len (next) > 72:
488 id = self.idstring ()
490 str = '''%s = \\context Voice = %s {
497 def calculate_graces (self):
500 for c in self.chords:
501 if c.grace and not lastgr:
502 c.chord_prefix = c.chord_prefix + '\\grace { '
503 elif not c.grace and lastgr:
504 lastc.chord_suffix = lastc.chord_suffix + ' } '
508 def calculate (self):
509 self.calculate_graces ()
514 def __init__ (self, cl):
518 return '\\clef %s' % self.type
520 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
521 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
524 def __init__ (self, sharps, flats):
529 if self.sharps and self.flats:
530 k = '\\keysignature %s ' % 'TODO'
532 k = '\\key %s \major' % key_sharps[self.sharps]
534 k = '\\key %s \major' % key_flats[self.flats]
538 def __init__ (self, frac):
542 return '\\time %d/%d' % (self.frac[0], self.frac[1])
557 def __init__ (self, n):
559 self.voices = (Voice (0), Voice (1))
568 for v in self.voices:
573 #def set_clef (self, letter):
574 # clstr = clef_table[letter]
575 # self.voices[0].add_nonchord (Clef (clstr))
577 def calculate (self):
578 for v in self.voices:
582 return 'staff%s' % encodeint (self.number)
588 for v in self.voices:
591 if v == self.voices[0]:
593 refs = refs + self.clef.dump ()
595 refs = refs + self.time.dump ()
597 refs = refs + self.key.dump ()
601 refs = refs + '\n \\' + v.idstring ()
603 %s = \context Staff = %s <<%s
606 ''' % (self.idstring (), self.idstring (), refs)
610 def __init__ (self, number, base, dots):
613 self.replaces = tuplet_table[number]
619 length = rat_multiply (length, (3,2))
621 length = rat_multiply (length, (7,4))
623 length = rat_multiply (length, (1,self.replaces))
625 (nb,nd) =rat_to_duration (length)
630 def add_chord (self, ch):
631 ch.dots = self.note_dots
632 ch.basic_duration = self.note_base
633 self.chords.append (ch)
635 if len (self.chords) == 1:
636 ch.chord_prefix = '\\times %d/%d { ' % (self.replaces, self.number)
637 elif len (self.chords) == self.number:
638 ch.chord_suffix = ' }'
643 self.multimeasure = 0
645 self.basic_duration = 0
648 self.chord_prefix = ''
649 self.chord_suffix = ''
650 self.note_prefix = ''
651 self.note_suffix = ''
653 # maybe use import copy?
656 #for i in self.pitches:
657 # ch.pitches.append (i)
658 ch.pitches = self.pitches[:]
659 ch.multimeasure = self.multimeasure
661 ch.basic_duration = self.basic_duration
662 #for i in self.scripts:
663 # ch.scripts.append (i)
664 ch.scripts = self.scripts[:]
665 ch.grace = self.grace
667 ch.chord_prefix = self.chord_prefix
668 ch.chord_suffix = self.chord_suffix
669 ch.note_prefix = self.note_prefix
670 ch.note_suffix = self.note_suffix
678 if self.basic_duration == 0.5:
681 sd = '%d' % self.basic_duration
682 sd = sd + '.' * self.dots
683 for p in self.pitches:
686 str = str + pitch_to_lily_string (p)
689 str = self.note_prefix +str + self.note_suffix
691 if len (self.pitches) > 1:
693 elif self.multimeasure:
695 elif len (self.pitches) == 0:
699 for s in self.scripts:
702 str = self.chord_prefix + str + self.chord_suffix
739 # http://www.arkkra.com/doc/uguide/contexts.html
754 def __init__ (self, lines):
755 self.parse_function = self.parse_context_music
757 self.current_voices = []
758 self.forced_duration = None
761 self.tuplets_expected = 0
769 def parse_compound_location (self, line):
770 colon = string.index (line, ':')
773 line = line[colon + 1:]
775 self.current_voices = []
776 ##self.current_staffs = []
777 map (self.parse_location, string.split (s, '&'))
780 def parse_location (self, line):
781 m = re.match ('^([-,0-9]+) *([-,0-9]*)', string.lstrip (line))
783 def range_list_to_idxs (s):
793 def range_to_list (s):
794 if string.find (s, '-') >= 0:
796 l = map (string.lstrip,
797 string.split (s, '-'))
798 r = range (string.atoi (l[0]) - 1,
801 r = (string.atoi (s) - 1,)
804 ranges = string.split (s, ',')
805 l = flatten (map (range_to_list, ranges))
809 staff_idxs = range_list_to_idxs (m.group (1))
811 voice_idxs = range_list_to_idxs (m.group (2))
815 while s > len (self.staffs) - 1:
816 self.staffs.append (Staff (s))
818 self.current_voices.append (self.staffs[s].voices[v])
820 def parse_note (self, line):
823 name = (ord (line[0]) - ord ('a') + 5) % 7
824 # FIXME: does key play any role in this?
826 debug ('NOTE: ' + `line`)
827 line = string.lstrip (line[1:])
829 if len (line) > 1 and line[:2] == '//':
833 alteration = alteration + 1
835 alteration = alteration - 1
842 line = string.lstrip (line[1:])
843 return (oct, name, alteration)
845 def parse_chord (self, line):
846 debug ('CHORD: ' + line)
847 line = string.lstrip (line)
850 #ch = self.current_voices[0].last_chord ()
851 ch = self.last_chord.copy ()
853 m = re.match ('^([0-9]+)([.]*)', line)
855 ch.basic_duration = string.atoi (m.group (1))
856 line = line[len (m.group (1)):]
858 ch.dots = len (m.group (2))
859 line = line[len (m.group (2)):]
861 #ch.basic_duration = self.current_voices[0].last_chord ().basic_duration
862 ch.basic_duration = self.last_chord.basic_duration
864 line = string.lstrip (line)
865 if len (line) > 1 and line[:2] == '//':
869 debug ('nline: ' + line)
870 #ch = self.current_voices[0].last_chord ()
871 n = self.last_chord.copy ()
872 n.basic_duration = ch.basic_duration
875 debug ('ch.pitsen:' + `ch.pitches`)
876 debug ('ch.dur:' + `ch.basic_duration`)
878 debug ('eline: ' + line)
881 if len (line) > 1 and line[:2] == '//':
884 elif line[:1] == 'mr':
887 elif line[:1] == 'ms':
890 elif line[0] in 'rs':
893 elif line[0] in 'abcdefg':
894 m = re.match ('([a-g][-#&+]*)', line)
895 l = len (m.group (1))
896 pitch = self.parse_note (line[:l])
897 debug ('PITCH: ' + `pitch`)
898 ch.pitches.append (pitch)
904 line = string.lstrip (line)
905 debug ('CUR-VOICES: ' + `self.current_voices`)
906 map (lambda x, ch=ch: x.add_chord (ch), self.current_voices)
909 def parse_lyrics_location (self, line):
910 line = line.lstrip (line)
912 m = re.match ('^(between[ \t]+)', line)
914 line = line[len (m.group (1)):]
917 m = re.match ('^(above [ \t]+)', line)
919 line = line[len (m.group (1)):]
924 def parse_voice (self, line):
925 line = string.lstrip (line)
926 # `;' is not a separator, chords end with ';'
927 chords = string.split (line, ';')[:-1]
928 # mup resets default duration and pitch each bar
929 self.last_chord = Chord ()
930 self.last_chord.basic_duration = 4
931 map (self.parse_chord, chords)
933 def init_context_header (self, line):
934 self.parse_function = self.parse_context_header
936 def parse_context_header (self, line):
937 debug ('header: ' + line)
940 def init_context_footer (self, line):
941 self.parse_function = self.parse_context_footer
943 def parse_context_footer (self, line):
944 debug ('footer: ' + line)
947 def init_context_header2 (self, line):
948 self.parse_function = self.parse_context_header2
950 def parse_context_header2 (self, line):
951 debug ('header2: ' + line)
954 def init_context_footer2 (self, line):
955 self.parse_function = self.parse_context_footer2
957 def parse_context_footer2 (self, line):
958 debug ('footer2: ' + line)
961 def init_context_score (self, line):
962 self.parse_function = self.parse_context_score
964 def parse_context_score (self, line):
965 debug ('score: ' + line)
966 line = string.lstrip (line)
967 # ugh: these (and lots more) should also be parsed in
968 # context staff. we should have a class Staff_properties
969 # and parse/set all those.
970 m = re.match ('^(time[ \t]*=[ \t]*([0-9]+)[ \t]*/[ \t]*([0-9]+))', line)
972 line = line[len (m.group (1)):]
973 self.time = Time ((string.atoi (m.group (2)),
974 string.atoi (m.group (3))))
976 m = re.match ('^(key[ \t]*=[ \t]*([0-9]+)[ \t]*(#|@))', line)
978 line = line[len (m.group (1)):]
979 n = string.atoi (m.group (2))
980 if m.group (3) == '#':
981 self.key = Key (n, 0)
983 self.key = Key (0, n)
986 def init_context_staff (self, line):
987 self.parse_function = self.parse_context_staff
989 def parse_context_staff (self, line):
990 debug ('staff: ' + line)
993 def init_context_voice (self, line):
994 self.parse_function = self.parse_context_voice
996 def parse_context_voice (self, line):
997 debug ('voice: ' + line)
1000 def init_context_grids (self, line):
1001 self.parse_function = self.parse_context_grids
1003 def parse_context_grids (self, line):
1004 debug ('grids: ' + line)
1007 def init_context_music (self, line):
1008 self.parse_function = self.parse_context_music
1010 def parse_context_music (self, line):
1011 debug ('music: ' + line)
1012 line = string.lstrip (line)
1013 if line and line[0] in '0123456789':
1014 line = self.parse_compound_location (line)
1015 self.parse_voice (line)
1017 m = re.match ('^(TODOlyrics[ \t]+)', line)
1019 line = line[len (m.group (1)):]
1020 self.parse_lyrics_location (line[7:])
1021 self.parse_lyrics (line)
1025 def parse (self, lines):
1026 # shortcut: set to official mup maximum (duh)
1027 # self.set_staffs (40)
1029 debug ('LINE: ' + `line`)
1030 m = re.match ('^([a-z]+2?)', line)
1034 if word in contexts:
1035 eval ('self.init_context_%s (line)' % word)
1038 warning (_ ("no such context: %s") % word)
1041 debug ('FUNC: ' + `self.parse_function`)
1042 self.parse_function (line)
1044 for c in self.staffs:
1046 if not c.clef and self.clef:
1048 if not c.time and self.time:
1050 if not c.key and self.key:
1058 for s in self.staffs:
1059 str = str + s.dump ()
1060 refs = refs + '\n \\' + s.idstring ()
1074 class Pre_processor:
1075 def __init__ (self, raw_lines):
1078 self.process_function = self.process_line
1079 self.macro_name = ''
1080 self.macro_body = ''
1081 self.process (raw_lines)
1083 def process_line (self, line):
1085 m = re.match ('^([ \t]*([a-zA-Z]+))', line)
1089 debug ('MACRO?: ' + `word`)
1090 if word in pre_processor_commands:
1091 line = line[len (m.group (1)):]
1092 eval ('self.process_macro_%s (line)' % word)
1095 if macros.has_key (word):
1096 s = macros[word] + line[len (m.group (1)):]
1097 if not self.active [-1]:
1101 def process_macro_body (self, line):
1103 # dig this: mup allows ifdefs inside macro bodies
1104 s = self.process_line (line)
1105 m = re.match ('(.*[^\\\\])(@)(.*)', s)
1107 self.macro_body = self.macro_body + '\n' + m.group (1)
1108 macros[self.macro_name] = self.macro_body
1109 debug ('MACROS: ' + `macros`)
1110 # don't do nested multi-line defines
1111 self.process_function = self.process_line
1117 self.macro_body = self.macro_body + '\n' + s
1121 # duh: mup is strictly line-based, except for `define',
1122 # which is `@' terminated and may span several lines
1123 def process_macro_define (self, line):
1125 # don't define new macros in unactive areas
1126 if not self.active[-1]:
1128 m = re.match ('^[ \t]*([a-zA-Z][a-zA-Z1-9_]*)(([^@]*)|(\\\\@))(@)?', line)
1136 debug ('MACROS: ' + `macros`)
1138 # To support nested multi-line define's
1139 # process_function and macro_name, macro_body
1140 # should become lists (stacks)
1141 # The mup manual is undetermined on this
1142 # and I haven't seen examples doing it.
1144 # don't do nested multi-line define's
1146 self.macro_body = m.group (2)
1148 self.macro_body = ''
1150 self.process_function = self.process_macro_body
1152 def process_macro_ifdef (self, line):
1153 m = re.match ('^[ \t]*([a-zA-Z][a-zA-Z1-9_]*)', line)
1156 active = self.active[-1] and macros.has_key (m.group (1))
1157 debug ('ACTIVE: %d' % active)
1158 self.active.append (active)
1160 def process_macro_ifndef (self, line):
1161 m = re.match ('^[ \t]*([a-zA-Z][a-zA-Z1-9_]*)', line)
1163 active = self.active[-1] and not macros.has_key (m.group (1))
1164 self.active.append (active)
1166 def process_macro_else (self, line):
1168 self.active[-1] = not self.active[-1]
1170 def process_macro_endif (self, line):
1171 self.active = self.active[:-1]
1173 def process (self, raw_lines):
1175 for line in raw_lines:
1176 ls = string.split (self.process_function (line), '\n')
1179 s = s + string.rstrip (i)
1180 if s and s[-1] == '\\':
1181 s = string.rstrip (s[:-1])
1183 self.lines.append (s)
1188 only_pre_process_p = 0
1191 progress ('DEBUG: ' + s)
1194 if verbose_p or debug_p:
1195 progress ('SKIPPING: ' + s)
1197 (sh, long) = getopt_args (__main__.option_definitions)
1199 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1205 pre_processor_commands = (
1218 elif o== '--debug' or o == '-d':
1220 elif o== '--define' or o == '-D':
1221 if string.find (a, '=') >= 0:
1222 (n, e) = string.split (a, '=')
1227 elif o== '--pre-process' or o == '-E':
1228 only_pre_process_p = 1
1229 elif o== '--help' or o == '-h':
1232 elif o== '--verbose' or o == '-V':
1234 elif o == '--version' or o == '-v':
1237 elif o == '--output' or o == '-o':
1243 # writes to stdout for help2man
1246 # sys.stdout.flush ()
1248 # handy emacs testing
1250 # files = ['template.mup']
1259 elif f and not os.path.isfile (f):
1260 f = strip_extension (f, '.mup') + '.mup'
1263 progress ( _("Processing `%s'..." % f))
1264 raw_lines = h.readlines ()
1265 p = Pre_processor (raw_lines)
1266 if only_pre_process_p:
1268 output = os.path.basename (re.sub ('(?i).mup$', '.mpp', f))
1270 e = Parser (p.lines)
1272 output = os.path.basename (re.sub ('(?i).mup$', '.ly', f))
1274 output = os.path.basename (f + '.ly')
1280 out_h = open (output, 'w')
1282 progress (_ ("Writing `%s'...") % output)
1284 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, f)
1285 if only_pre_process_p:
1287 ly = string.join (p.lines, '\n')
1289 ly = tag + '\n\n' + e.dump ()