2 # -*- coding: utf-8 -*-
3 # once upon a rainy monday afternoon.
8 # ABC standard v1.6: http://www.walshaw.plus.com/abc/
10 # Enhancements (Roy R. Rankin)
12 # Header section moved to top of lilypond file
13 # handle treble, treble-8, alto, and bass clef
14 # Handle voices (V: headers) with clef and part names, multiple voices
15 # Handle w: lyrics with multiple verses
16 # Handle key mode names for minor, major, phrygian, ionian, locrian, aeolian,
17 # mixolydian, lydian, dorian
18 # Handle part names from V: header
19 # Tuplets handling fixed up
20 # Lines starting with |: not discarded as header lines
21 # Multiple T: and C: header entries handled
22 # Accidental maintained until next bar check
23 # Silent rests supported
24 # articulations fermata, upbow, downbow, ltoe, accent, tenuto supported
25 # Chord strings([-^]"string") can contain a '#'
26 # Header fields enclosed by [] in notes string processed
27 # W: words output after tune as abc2ps does it (they failed before)
29 # Enhancements (Laura Conrad)
31 # Barring now preserved between ABC and lilypond
32 # the default placement for text in abc is above the staff.
34 # \breve and \longa supported.
35 # M:none doesn't crash lily.
36 # lilypond '--' supported.
38 # Enhancements (Guy Gascoigne-Piggford)
40 # Add support for maintaining ABC's notion of beaming, this is selectable
41 # from the command line with a -b or --beam option.
42 # Fixd a problem where on cygwin empty lines weren't being correctly identifed
43 # and so were complaining, but still generating the correct output.
47 # Multiple tunes in single file not supported
48 # Blank T: header lines should write score and open a new score
49 # Not all header fields supported
50 # ABC line breaks are ignored
51 # Block comments generate error and are ignored
52 # Postscript commands are ignored
53 # lyrics not resynchronized by line breaks (lyrics must fully match notes)
54 # %%LY slyrics can't be directly before a w: line.
63 # * GNU style messages: warning:FILE:LINE:
66 # Convert to new chord styles.
78 program_name = sys.argv[0]
88 version = '@TOPLEVEL_VERSION@'
89 if version == '@' + 'TOPLEVEL_VERSION' + '@':
90 version = '(unknown version)' # uGUHGUHGHGUGH
96 header['footnotes'] = ''
101 repeat_state = [0] * 8
102 current_voice_idx = -1
103 current_lyric_idx = -1
109 global_key = [0] * 7 # UGH
110 names = ["One", "Two", "Three"]
117 sys.stderr.write (msg)
118 if global_options.strict:
123 return chr (i + ord('A'))
126 # the number gives the base_octave
127 clefs = [("treble", "treble", 0),
128 ("treble1", "french", 0),
129 ("bass3", "varbaritone", 0),
131 ("alto4", "tenor", 0),
132 ("alto2", "mezzosoprano", 0),
133 ("alto1", "soprano", 0),
135 ("perc", "percussion", 0)]
136 modifier = [("-8va", "_8", -1),
146 m = re.match('^'+c[0], s)
148 (clef, octave) = (c[1], c[2])
156 m = re.match('^'+md[0], s)
163 state.base_octave = octave
164 voices_append ("\\clef \""+clef+mod+"\"\n")
167 def select_voice (name, rol):
168 if not voice_idx_dict.has_key (name):
169 state_list.append(Parser_state())
172 voice_idx_dict[name] = len (voices) -1
173 __main__.current_voice_idx = voice_idx_dict[name]
174 __main__.state = state_list[current_voice_idx]
176 m = re.match ('^([^ \t=]*)=(.*)$', rol) # find keywork
180 a = re.match ('^("[^"]*"|[^ \t]*) *(.*)$', rol)
184 if keyword == 'clef':
186 elif keyword == "name":
187 value = re.sub ('\\\\','\\\\\\\\', value)
189 voices_append ("\\set Staff.instrument = %s\n" % value )
191 __main__.part_names = 1
192 elif keyword == "sname" or keyword == "snm":
193 voices_append ("\\set Staff.instr = %s\n" % value )
197 def dump_header (outf,hdr):
198 outf.write ('\\header {\n')
202 hdr[k] = re.sub('"', '\\"', hdr[k])
203 outf.write ('\t%s = "%s"\n'% (k,hdr[k]))
206 def dump_lyrics (outf):
208 outf.write("\n\\score\n{\n \\lyrics\n <<\n")
209 for i in range (len (lyrics)):
210 outf.write ( lyrics [i])
212 outf.write(" >>\n \\layout{}\n}\n")
214 def dump_default_bar (outf):
216 Nowadays abc2ly outputs explicits barlines (?)
219 outf.write ("\n\\set Score.defaultBarType = \"empty\"\n")
222 def dump_slyrics (outf):
223 ks = voice_idx_dict.keys()
226 if re.match('[1-9]', k):
227 m = alphabet (int (k))
230 for i in range (len(slyrics[voice_idx_dict[k]])):
232 outf.write ("\nwords%sV%s = \\lyricmode {" % (m, l))
233 outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
236 def dump_voices (outf):
237 global doing_alternative, in_repeat
238 ks = voice_idx_dict.keys()
241 if re.match ('[1-9]', k):
242 m = alphabet (int (k))
245 outf.write ("\nvoice%s = {" % m)
246 dump_default_bar(outf)
247 if repeat_state[voice_idx_dict[k]]:
248 outf.write("\n\\repeat volta 2 {")
249 outf.write ("\n" + voices [voice_idx_dict[k]])
251 if doing_alternative[voice_idx_dict[k]]:
253 if in_repeat[voice_idx_dict[k]]:
259 #assume that Q takes the form "Q:1/4=120"
260 #There are other possibilities, but they are deprecated
261 if a.count ('/') == 1:
264 if int(numerator) != 1:
265 sys.stderr.write("abc2ly: Warning, unable to translate a Q specification with a numerator of %s: %s\n" % (numerator, a))
266 array2 = array[1].split ('=')
267 denominator=array2[0]
269 duration = str (int (denominator) / int (numerator))
270 midi_specs = ' '.join(["\n\t\t\\context {\n\t\t \\Score tempoWholesPerMinute = #(ly:make-moment ", perminute, " ", duration, ")\n\t\t }\n"])
272 sys.stderr.write("abc2ly: Warning, unable to parse Q specification: %s\n" % a)
274 def dump_score (outf):
281 ks = voice_idx_dict.keys ();
284 if re.match('[1-9]', k):
285 m = alphabet (int (k))
288 if k == 'default' and len (voice_idx_dict) > 1:
290 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k )
292 outf.write ("\t \\voicedefault\n")
293 outf.write ("\t \\voice%s " % m)
294 outf.write ("\n\t}\n")
297 for lyrics in slyrics [voice_idx_dict[k]]:
298 outf.write ("\n\t\\addlyrics {\n")
299 if re.match('[1-9]',k):
300 m = alphabet (int (k))
304 outf.write ( " \\words%sV%s } " % ( m, chr (l)) )
308 outf.write ("\n\t\\layout {\n")
309 outf.write ("\t}\n\t\\midi {%s}\n}\n" % midi_specs)
313 def set_default_length (s):
314 global length_specified
315 m = re.search ('1/([0-9]+)', s)
317 __main__.default_len = int ( m.group (1))
320 def set_default_len_from_time_sig (s):
321 m = re.search ('([0-9]+)/([0-9]+)', s)
323 n = int (m.group (1))
324 d = int (m.group (2))
325 if (n * 1.0 )/(d * 1.0) < 0.75:
326 __main__.default_len = 16
328 __main__.default_len = 8
337 sys.stderr.write ("cannot open file: `%s'\n" % f)
341 sys.stderr.write ("gulped empty file: `%s'\n" % f)
346 # pitch manipulation. Tuples are (name, alteration).
347 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
348 # pitch in semitones.
349 def semitone_pitch (tup):
359 p = p + t* 2 + tup[1]
362 def fifth_above_pitch (tup):
363 (n, a) = (tup[0] + 4, tup[1])
365 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
376 (t,a) = fifth_above_pitch (p)
377 if semitone_pitch((t,a)) % 12 == 0:
389 (t,a) = quart_above_pitch (p)
390 if semitone_pitch((t,a)) % 12 == 0:
396 def quart_above_pitch (tup):
397 (n, a) = (tup[0] + 3, tup[1])
399 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
404 key_lookup = { # abc to lilypond key mode names
413 'mix' : 'mixolydian',
414 'mixolydian' : 'mixolydian',
427 if k and k[0] == '#':
430 elif k and k[0] == 'b':
434 return '%s \\major' % key
437 if not key_lookup.has_key (type):
438 #ugh, use lilylib, say WARNING:FILE:LINE:
439 sys.stderr.write ("abc2ly:warning:")
440 sys.stderr.write ("ignoring unknown key: `%s'" % orig)
441 sys.stderr.write ('\n')
443 return ("%s \\%s" % ( key, key_lookup[type]))
445 def shift_key (note, acc, shift):
446 s = semitone_pitch((note, acc))
447 s = (s + shift + 12) % 12
459 key_shift = { # semitone shifts for key mode names
482 intkey = (ord (k[0]) - ord('a') + 5) % 7
486 if k and k[0] == 'b':
489 elif k and k[0] == '#':
493 if k and key_shift.has_key(k):
494 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
495 keytup = (intkey, intkeyacc)
497 sharp_key_seq = sharp_keys ()
498 flat_key_seq = flat_keys ()
502 if keytup in sharp_key_seq:
504 key_count = sharp_key_seq.index (keytup)
505 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
507 elif keytup in flat_key_seq:
509 key_count = flat_key_seq.index (keytup)
510 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
513 raise Exception ("Huh")
517 key_table[a] = key_table[a] + accsign
532 def try_parse_tuplet_begin (str, state):
533 if re.match ('\([2-9]', str):
536 prev_tuplet_state = state.parsing_tuplet
537 state.parsing_tuplet = int (dig[0])
538 if prev_tuplet_state:
540 voices_append ("\\times %s {" % tup_lookup[dig])
543 def try_parse_group_end (str, state):
544 if str and str[0] in HSPACE:
546 close_beam_state(state)
549 def header_append (key, a):
551 if header.has_key (key):
552 s = header[key] + "\n"
556 linelen = len (v) - v.rfind ('\n')
557 if linelen + len (a) > 80:
561 def stuff_append (stuff, idx, a):
565 stuff [idx] = wordwrap(a, stuff[idx])
567 # ignore wordwrap since we are adding to the previous word
568 def stuff_append_back(stuff, idx, a):
572 point = len(stuff[idx])-1
573 while stuff[idx][point] is ' ':
576 stuff[idx] = stuff[idx][:point] + a + stuff[idx][point:]
578 def voices_append(a):
579 if current_voice_idx < 0:
580 select_voice ('default', '')
581 stuff_append (voices, current_voice_idx, a)
583 # word wrap really makes it hard to bind beams to the end of notes since it
584 # pushes out whitespace on every call. The _back functions do an append
585 # prior to the last space, effectively tagging whatever they are given
587 def voices_append_back(a):
588 if current_voice_idx < 0:
589 select_voice ('default', '')
590 stuff_append_back(voices, current_voice_idx, a)
592 def repeat_prepend():
594 if current_voice_idx < 0:
595 select_voice ('default', '')
597 repeat_state[current_voice_idx] = 't'
600 def lyrics_append(a):
601 a = re.sub ('#', '\\#', a) # latex does not like naked #'s
602 a = re.sub ('"', '\\"', a) # latex does not like naked "'s
603 a = '\t{ "' + a + '" }\n'
604 stuff_append (lyrics, current_lyric_idx, a)
606 # break lyrics to words and put "'s around words containing numbers and '"'s
610 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
614 word = re.sub('"', '\\"', word) # escape "
615 if re.match('.*[0-9"\(]', word):
616 word = re.sub('_', ' ', word) # _ causes probs inside ""
617 ret = ret + '\"' + word + '\" '
619 ret = ret + word + ' '
624 def slyrics_append(a):
625 a = re.sub ( '_', ' _ ', a) # _ to ' _ '
626 a = re.sub ( '([^-])-([^-])', '\\1- \\2', a) # split words with "-" unless was originally "--"
627 a = re.sub ( '\\\\- ', '-', a) # unless \-
628 a = re.sub ( '~', '_', a) # ~ to space('_')
629 a = re.sub ( '\*', '_ ', a) # * to to space
630 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
631 if re.match('.*[0-9"\(]', a): # put numbers and " and ( into quoted string
633 a = re.sub ( '$', ' ', a) # insure space between lines
634 __main__.lyric_idx = lyric_idx + 1
635 if len(slyrics[current_voice_idx]) <= lyric_idx:
636 slyrics[current_voice_idx].append(a)
638 v = slyrics[current_voice_idx][lyric_idx]
639 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
642 def try_parse_header_line (ln, state):
643 global length_specified
644 m = re.match ('^([A-Za-z]): *(.*)$', ln)
650 a = re.sub('[ \t]*$','', a) #strip trailing blanks
651 if header.has_key('title'):
653 if len(header['title']):
654 # the non-ascii character
655 # in the string below is a
656 # punctuation dash. (TeX ---)
657 header['title'] = header['title'] + ' — ' + a
659 header['subtitle'] = a
664 if not state.common_time:
665 state.common_time = 1
666 voices_append (" \\override Staff.TimeSignature #'style = #'C\n")
669 if not state.common_time:
670 state.common_time = 1
671 voices_append ("\\override Staff.TimeSignature #'style = #'C\n")
673 if not length_specified:
674 set_default_len_from_time_sig (a)
678 voices_append ('\\time %s' % a)
683 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
685 # there may or may not be a space
686 # between the key letter and the mode
687 if key_lookup.has_key(m.group(2)[0:3]):
688 key_info = m.group(1) + m.group(2)[0:3]
689 clef_info = m.group(2)[4:]
691 key_info = m.group(1)
692 clef_info = m.group(2)
693 __main__.global_key = compute_key (key_info)
694 k = lily_key (key_info)
696 voices_append ('\\key %s' % k)
697 check_clef(clef_info)
699 __main__.global_key = compute_key (a)
702 voices_append ('\\key %s \\major' % k)
704 header ['footnotes'] = header['footnotes'] + '\\\\\\\\' + a
705 if g == 'O': # Origin
706 header ['origin'] = a
707 if g == 'X': # Reference Number
708 header ['crossRefNumber'] = a
711 if g == 'H': # History
712 header_append ('history', a)
715 if g == 'C': # Composer
716 if header.has_key('composer'):
718 header['composer'] = header['composer'] + '\\\\\\\\' + a
720 header['composer'] = a
722 header ['subtitle'] = a
723 if g == 'L': # Default note length
724 set_default_length (ln)
726 voice = re.sub (' .*$', '', a)
727 rest = re.sub ('^[^ \t]* *', '', a)
729 voices_append(state.next_bar)
731 select_voice (voice, rest)
734 if g == 'w': # vocals
741 # we use in this order specified accidental, active accidental for bar,
742 # active accidental for key
743 def pitch_to_lilypond_name (name, acc, bar_acc, key):
757 return(chr (name + ord('c')) + s)
760 def octave_to_lilypond_quotes (o):
773 while str and str[0] in DIGITS:
774 durstr = durstr + str[0]
783 def duration_to_lilypond_duration (multiply_tup, defaultlen, dots):
785 # (num / den) / defaultlen < 1/base
786 while base * multiply_tup[0] < multiply_tup[1]:
789 if (multiply_tup[0] / multiply_tup[1]) == 2:
791 if (multiply_tup[0] / multiply_tup[1]) == 3:
794 if (multiply_tup[0] / multiply_tup[1]) == 4:
796 return '%s%s' % ( base, '.'* dots)
801 self.next_articulation = ''
805 self.parsing_tuplet = 0
809 self.parsing_beam = 0
813 # return (str, num,den,dots)
814 def parse_duration (str, parser_state):
816 den = parser_state.next_den
817 parser_state.next_den = 1
819 (str, num) = parse_num (str)
825 while str[:1] == '/':
829 (str, d) =parse_num (str)
833 den = den * default_len
835 current_dots = parser_state.next_dots
836 parser_state.next_dots = 0
837 if re.match ('[ \t]*[<>]', str):
838 while str[0] in HSPACE:
842 current_dots = current_dots + 1
843 parser_state.next_den = parser_state.next_den * 2
848 parser_state.next_dots = parser_state.next_dots + 1
856 if num % multiplier == 0 and den % f == 0:
857 num = num / multiplier
859 current_dots = current_dots + d
861 return (str, num,den,current_dots)
864 def try_parse_rest (str, parser_state):
865 if not str or str[0] <> 'z' and str[0] <> 'x':
868 __main__.lyric_idx = -1
870 if parser_state.next_bar:
871 voices_append(parser_state.next_bar)
872 parser_state.next_bar = ''
880 (str, num,den,d) = parse_duration (str, parser_state)
881 voices_append ('%s%s' % (rest, duration_to_lilypond_duration ((num,den), default_len, d)))
882 if parser_state.next_articulation:
883 voices_append (parser_state.next_articulation)
884 parser_state.next_articulation = ''
897 'J' : '', # ignore slide
898 'R' : '', # ignore roll
904 def try_parse_articulation (str, state):
905 while str and artic_tbl.has_key(str[:1]):
906 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
907 if not artic_tbl[str[:1]]:
908 sys.stderr.write("Warning: ignoring `%s'\n" % str[:1] )
914 # s7m2 input doesnt care about spaces
915 if re.match('[ \t]*\(', str):
919 while str[:1] =='(' and str[1] not in DIGITS:
920 slur_begin = slur_begin + 1
921 state.next_articulation = state.next_articulation + '('
927 # remember accidental for rest of bar
929 def set_bar_acc(note, octave, acc, state):
932 n_oct = note + octave * 7
933 state.in_acc[n_oct] = acc
935 # get accidental set in this bar or UNDEF if not set
936 def get_bar_acc(note, octave, state):
937 n_oct = note + octave * 7
938 if state.in_acc.has_key(n_oct):
939 return(state.in_acc[n_oct])
943 def clear_bar_acc(state):
947 # if we are parsing a beam, close it off
948 def close_beam_state(state):
949 if state.parsing_beam and global_options.beams:
950 state.parsing_beam = 0
951 voices_append_back( ']' )
954 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
955 def try_parse_note (str, parser_state):
974 octave = parser_state.base_octave
975 if str[0] in "ABCDEFG":
976 str = str[0].lower () + str[1:]
981 if str[0] in "abcdefg":
982 notename = (ord(str[0]) - ord('a') + 5)%7
985 return str # failed; not a note!
988 __main__.lyric_idx = -1
990 if parser_state.next_bar:
991 voices_append(parser_state.next_bar)
992 parser_state.next_bar = ''
997 while str[0] == '\'':
1001 (str, num,den,current_dots) = parse_duration (str, parser_state)
1003 if re.match('[ \t]*\)', str):
1007 while str[:1] ==')':
1008 slur_end = slur_end + 1
1012 bar_acc = get_bar_acc(notename, octave, parser_state)
1013 pit = pitch_to_lilypond_name(notename, acc, bar_acc, global_key[notename])
1014 oct = octave_to_lilypond_quotes (octave)
1015 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
1019 voices_append ("%s%s%s%s" %
1021 duration_to_lilypond_duration ((num,den), default_len, current_dots)))
1023 set_bar_acc(notename, octave, acc, parser_state)
1024 if parser_state.next_articulation:
1025 articulation = articulation + parser_state.next_articulation
1026 parser_state.next_articulation = ''
1028 voices_append (articulation)
1030 if parser_state.parsing_tuplet:
1031 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
1032 if not parser_state.parsing_tuplet:
1035 voices_append ('-(' * slur_begin )
1037 voices_append ('-)' *slur_end )
1039 if global_options.beams and \
1040 str[0] in '^=_ABCDEFGabcdefg' and \
1041 not parser_state.parsing_beam and \
1042 not parser_state.parsing_tuplet:
1043 parser_state.parsing_beam = 1
1044 voices_append_back( '[' )
1048 def junk_space (str,state):
1049 while str and str[0] in '\t\n\r ':
1051 close_beam_state(state)
1056 def try_parse_guitar_chord (str, state):
1060 if str[0] == '_' or (str[0] == '^'):
1065 while str and str[0] != '"':
1071 gc = re.sub('#', '\\#', gc) # escape '#'s
1072 state.next_articulation = ("%c\"%s\"" % (position, gc)) \
1073 + state.next_articulation
1076 def try_parse_escape (str):
1077 if not str or str [0] != '\\':
1082 key_table = compute_key ()
1086 # |] thin-thick double bar line
1087 # || thin-thin double bar line
1088 # [| thick-thin double bar line
1091 # :: left-right repeat
1107 '|]' : '\\bar "|."',
1108 '||' : '\\bar "||"',
1109 '[|' : '\\bar "||"',
1111 '|:' : '\\repeat volta 2 {',
1112 '::' : '} \\repeat volta 2 {',
1113 '|1' : '} \\alternative{{',
1120 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
1121 alternative_opener = ['|1', '|2', ':|2']
1122 repeat_ender = ['::', ':|']
1123 repeat_opener = ['::', '|:']
1124 in_repeat = [''] * 8
1125 doing_alternative = [''] * 8
1128 def try_parse_bar (str,state):
1129 global in_repeat, doing_alternative, using_old
1132 if current_voice_idx < 0:
1133 select_voice ('default', '')
1134 # first try the longer one
1135 for trylen in [3,2,1]:
1136 if str[:trylen] and bar_dict.has_key (str[:trylen]):
1139 bs = "\\bar \"%s\"" % old_bar_dict[s]
1141 bs = "%s" % bar_dict[s]
1143 if s in alternative_opener:
1144 if not in_repeat[current_voice_idx]:
1146 bs = "\\bar \"%s\"" % old_bar_dict[s]
1148 doing_alternative[current_voice_idx] = 't'
1150 if s in repeat_ender:
1151 if not in_repeat[current_voice_idx]:
1152 sys.stderr.write("Warning: inserting repeat to beginning of notes.\n")
1154 in_repeat[current_voice_idx] = ''
1156 if doing_alternative[current_voice_idx]:
1159 bs = "\\bar \"%s\"" % old_bar_dict[s]
1162 doing_alternative[current_voice_idx] = ''
1163 in_repeat[current_voice_idx] = ''
1164 if s in repeat_opener:
1165 in_repeat[current_voice_idx] = 't'
1167 bs = "\\bar \"%s\"" % old_bar_dict[s]
1172 state.next_bar = '|\n'
1174 clear_bar_acc(state)
1175 close_beam_state(state)
1177 if bs <> None or state.next_bar != '':
1178 if state.parsing_tuplet:
1179 state.parsing_tuplet =0
1180 voices_append ('} ')
1183 clear_bar_acc(state)
1184 close_beam_state(state)
1191 def try_parse_tie (str):
1194 voices_append (' ~ ')
1197 def bracket_escape (str, state):
1198 m = re.match ( '^([^\]]*)] *(.*)$', str)
1202 try_parse_header_line (cmd, state)
1205 def try_parse_chord_delims (str, state):
1208 if re.match('[A-Z]:', str): # bracket escape
1209 return bracket_escape(str, state)
1211 voices_append(state.next_bar)
1213 voices_append ('<<')
1217 if state.plus_chord:
1218 voices_append ('>>')
1219 state.plus_chord = 0
1222 voices_append(state.next_bar)
1224 voices_append ('<<')
1225 state.plus_chord = 1
1233 while str[:1] ==')':
1238 voices_append ("\\spanrequest \\stop \"slur\"" * end)
1242 def try_parse_grace_delims (str, state):
1245 voices_append(state.next_bar)
1248 voices_append ('\\grace { ')
1256 def try_parse_comment (str):
1259 if str[0:5] == '%MIDI':
1260 #the nobarlines option is necessary for an abc to lilypond translator for
1261 #exactly the same reason abc2midi needs it: abc requires the user to enter
1262 #the note that will be printed, and MIDI and lilypond expect entry of the
1263 #pitch that will be played.
1265 #In standard 19th century musical notation, the algorithm for translating
1266 #between printed note and pitch involves using the barlines to determine
1267 #the scope of the accidentals.
1269 #Since ABC is frequently used for music in styles that do not use this
1270 #convention, such as most music written before 1700, or ethnic music in
1271 #non-western scales, it is necessary to be able to tell a translator that
1272 #the barlines should not affect its interpretation of the pitch.
1273 if 'nobarlines' in str:
1275 elif str[0:3] == '%LY':
1276 p = str.find ('voices')
1278 voices_append(str[p+7:])
1280 p = str.find ('slyrics')
1282 slyrics_append(str[p+8:])
1284 #write other kinds of appending if we ever need them.
1289 def parse_file (fn):
1292 ls = map (lambda x: re.sub ("\r$", '', x), ls)
1294 select_voice('default', '')
1297 sys.stderr.write ("Line ... ")
1299 __main__.state = state_list[current_voice_idx]
1304 if not (lineno % happy_count):
1305 sys.stderr.write ('[%d]'% lineno)
1307 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1310 try_parse_comment(m.group(2))
1311 voices_append ('%% %s\n' % m.group(2))
1316 ln = try_parse_header_line (ln, state)
1318 # Try nibbling characters off until the line doesn't change.
1320 while ln != prev_ln:
1322 ln = try_parse_chord_delims (ln, state)
1323 ln = try_parse_rest (ln, state)
1324 ln = try_parse_articulation (ln,state)
1325 ln = try_parse_note (ln, state)
1326 ln = try_parse_bar (ln, state)
1327 ln = try_parse_tie (ln)
1328 ln = try_parse_escape (ln)
1329 ln = try_parse_guitar_chord (ln, state)
1330 ln = try_parse_tuplet_begin (ln, state)
1331 ln = try_parse_group_end (ln, state)
1332 ln = try_parse_grace_delims (ln, state)
1333 ln = junk_space (ln, state)
1336 error ("%s: %d: Huh? Don't understand\n" % (fn, lineno))
1337 left = orig_ln[0:-len (ln)]
1338 sys.stderr.write (left + '\n')
1339 sys.stderr.write (' ' * len (left) + ln + '\n')
1343 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1346 Written by Han-Wen Nienhuys <hanwen@xs4all.nl>, Laura Conrad
1347 <lconrad@laymusic.org>, Roy Rankin <Roy.Rankin@@alcatel.com.au>.
1350 def print_version ():
1351 print r"""abc2ly (GNU lilypond) %s""" % version
1353 def get_option_parser ():
1354 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'abc2ly',
1355 description=_ ('''abc2ly converts ABC music files (see
1356 %s) to LilyPond input.
1357 ''') % 'http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt',
1358 add_help_option=False)
1360 p.version = "abc2ly (LilyPond) @TOPLEVEL_VERSION@"
1361 p.add_option("--version",
1363 help=_ ("show version number and exit"))
1365 p.add_option("-h", "--help",
1367 help=_ ("show this help and exit"))
1368 p.add_option ('-o', '--output', metavar='FILE',
1369 help=_ ("write output to FILE"),
1371 p.add_option ('-s', '--strict', help=_ ("be strict about success"),
1372 action='store_true')
1373 p.add_option ('-b', '--beams', help=_ ("preserve ABC's notion of beams"))
1374 p.add_option_group ('',
1376 _ ('Report bugs via %s')
1377 % 'http://post.gmane.org/post.php'
1378 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
1382 option_parser = get_option_parser ()
1383 (global_options, files) = option_parser.parse_args ()
1388 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1393 sys.stderr.write ('Parsing `%s\'...\n' % f)
1396 if not global_options.output:
1397 global_options.output = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1398 sys.stderr.write ('lilypond output to: `%s\'...' % global_options.output)
1399 outf = open (global_options.output, 'w')
1401 # don't substitute @VERSION@. We want this to reflect
1402 # the last version that was verified to work.
1403 outf.write ('\\version "2.7.40"\n')
1405 # dump_global (outf)
1406 dump_header (outf, header)
1411 sys.stderr.write ('\n')