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 # convert the mode to lower-case before comparing
688 mode = m.group(2)[0:3].lower();
689 if key_lookup.has_key(mode):
690 # use the full mode, not only the first three letters
691 key_info = m.group(1) + m.group(2).lower()
692 clef_info = a[m.start(4):]
694 key_info = m.group(1)
695 clef_info = a[m.start(2):]
696 __main__.global_key = compute_key (key_info)
697 k = lily_key (key_info)
699 voices_append ('\\key %s' % k)
700 check_clef(clef_info)
702 __main__.global_key = compute_key (a)
705 voices_append ('\\key %s \\major' % k)
707 header ['footnotes'] = header['footnotes'] + '\\\\\\\\' + a
708 if g == 'O': # Origin
709 header ['origin'] = a
710 if g == 'X': # Reference Number
711 header ['crossRefNumber'] = a
714 if g == 'H': # History
715 header_append ('history', a)
718 if g == 'C': # Composer
719 if header.has_key('composer'):
721 header['composer'] = header['composer'] + '\\\\\\\\' + a
723 header['composer'] = a
725 header ['subtitle'] = a
726 if g == 'L': # Default note length
727 set_default_length (ln)
729 voice = re.sub (' .*$', '', a)
730 rest = re.sub ('^[^ \t]* *', '', a)
732 voices_append(state.next_bar)
734 select_voice (voice, rest)
737 if g == 'w': # vocals
744 # we use in this order specified accidental, active accidental for bar,
745 # active accidental for key
746 def pitch_to_lilypond_name (name, acc, bar_acc, key):
760 return(chr (name + ord('c')) + s)
763 def octave_to_lilypond_quotes (o):
776 while str and str[0] in DIGITS:
777 durstr = durstr + str[0]
786 def duration_to_lilypond_duration (multiply_tup, defaultlen, dots):
788 # (num / den) / defaultlen < 1/base
789 while base * multiply_tup[0] < multiply_tup[1]:
792 if (multiply_tup[0] / multiply_tup[1]) == 2:
794 if (multiply_tup[0] / multiply_tup[1]) == 3:
797 if (multiply_tup[0] / multiply_tup[1]) == 4:
799 return '%s%s' % ( base, '.'* dots)
804 self.next_articulation = ''
808 self.parsing_tuplet = 0
812 self.parsing_beam = 0
816 # return (str, num,den,dots)
817 def parse_duration (str, parser_state):
819 den = parser_state.next_den
820 parser_state.next_den = 1
822 (str, num) = parse_num (str)
828 while str[:1] == '/':
832 (str, d) =parse_num (str)
836 den = den * default_len
838 current_dots = parser_state.next_dots
839 parser_state.next_dots = 0
840 if re.match ('[ \t]*[<>]', str):
841 while str[0] in HSPACE:
845 current_dots = current_dots + 1
846 parser_state.next_den = parser_state.next_den * 2
851 parser_state.next_dots = parser_state.next_dots + 1
859 if num % multiplier == 0 and den % f == 0:
860 num = num / multiplier
862 current_dots = current_dots + d
864 return (str, num,den,current_dots)
867 def try_parse_rest (str, parser_state):
868 if not str or str[0] <> 'z' and str[0] <> 'x':
871 __main__.lyric_idx = -1
873 if parser_state.next_bar:
874 voices_append(parser_state.next_bar)
875 parser_state.next_bar = ''
883 (str, num,den,d) = parse_duration (str, parser_state)
884 voices_append ('%s%s' % (rest, duration_to_lilypond_duration ((num,den), default_len, d)))
885 if parser_state.next_articulation:
886 voices_append (parser_state.next_articulation)
887 parser_state.next_articulation = ''
900 'J' : '', # ignore slide
901 'R' : '', # ignore roll
907 def try_parse_articulation (str, state):
908 while str and artic_tbl.has_key(str[:1]):
909 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
910 if not artic_tbl[str[:1]]:
911 sys.stderr.write("Warning: ignoring `%s'\n" % str[:1] )
917 # s7m2 input doesnt care about spaces
918 if re.match('[ \t]*\(', str):
922 while str[:1] =='(' and str[1] not in DIGITS:
923 slur_begin = slur_begin + 1
924 state.next_articulation = state.next_articulation + '('
930 # remember accidental for rest of bar
932 def set_bar_acc(note, octave, acc, state):
935 n_oct = note + octave * 7
936 state.in_acc[n_oct] = acc
938 # get accidental set in this bar or UNDEF if not set
939 def get_bar_acc(note, octave, state):
940 n_oct = note + octave * 7
941 if state.in_acc.has_key(n_oct):
942 return(state.in_acc[n_oct])
946 def clear_bar_acc(state):
950 # if we are parsing a beam, close it off
951 def close_beam_state(state):
952 if state.parsing_beam and global_options.beams:
953 state.parsing_beam = 0
954 voices_append_back( ']' )
957 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
958 def try_parse_note (str, parser_state):
977 octave = parser_state.base_octave
978 if str[0] in "ABCDEFG":
979 str = str[0].lower () + str[1:]
984 if str[0] in "abcdefg":
985 notename = (ord(str[0]) - ord('a') + 5)%7
988 return str # failed; not a note!
991 __main__.lyric_idx = -1
993 if parser_state.next_bar:
994 voices_append(parser_state.next_bar)
995 parser_state.next_bar = ''
1000 while str[0] == '\'':
1004 (str, num,den,current_dots) = parse_duration (str, parser_state)
1006 if re.match('[ \t]*\)', str):
1010 while str[:1] ==')':
1011 slur_end = slur_end + 1
1015 bar_acc = get_bar_acc(notename, octave, parser_state)
1016 pit = pitch_to_lilypond_name(notename, acc, bar_acc, global_key[notename])
1017 oct = octave_to_lilypond_quotes (octave)
1018 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
1022 voices_append ("%s%s%s%s" %
1024 duration_to_lilypond_duration ((num,den), default_len, current_dots)))
1026 set_bar_acc(notename, octave, acc, parser_state)
1027 if parser_state.next_articulation:
1028 articulation = articulation + parser_state.next_articulation
1029 parser_state.next_articulation = ''
1031 voices_append (articulation)
1033 if parser_state.parsing_tuplet:
1034 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
1035 if not parser_state.parsing_tuplet:
1038 voices_append ('-(' * slur_begin )
1040 voices_append ('-)' *slur_end )
1042 if global_options.beams and \
1043 str[0] in '^=_ABCDEFGabcdefg' and \
1044 not parser_state.parsing_beam and \
1045 not parser_state.parsing_tuplet:
1046 parser_state.parsing_beam = 1
1047 voices_append_back( '[' )
1051 def junk_space (str,state):
1052 while str and str[0] in '\t\n\r ':
1054 close_beam_state(state)
1059 def try_parse_guitar_chord (str, state):
1063 if str[0] == '_' or (str[0] == '^'):
1068 while str and str[0] != '"':
1074 gc = re.sub('#', '\\#', gc) # escape '#'s
1075 state.next_articulation = ("%c\"%s\"" % (position, gc)) \
1076 + state.next_articulation
1079 def try_parse_escape (str):
1080 if not str or str [0] != '\\':
1085 key_table = compute_key ()
1089 # |] thin-thick double bar line
1090 # || thin-thin double bar line
1091 # [| thick-thin double bar line
1094 # :: left-right repeat
1110 '|]' : '\\bar "|."',
1111 '||' : '\\bar "||"',
1112 '[|' : '\\bar "||"',
1114 '|:' : '\\repeat volta 2 {',
1115 '::' : '} \\repeat volta 2 {',
1116 '|1' : '} \\alternative{{',
1123 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
1124 alternative_opener = ['|1', '|2', ':|2']
1125 repeat_ender = ['::', ':|']
1126 repeat_opener = ['::', '|:']
1127 in_repeat = [''] * 8
1128 doing_alternative = [''] * 8
1131 def try_parse_bar (str,state):
1132 global in_repeat, doing_alternative, using_old
1135 if current_voice_idx < 0:
1136 select_voice ('default', '')
1137 # first try the longer one
1138 for trylen in [3,2,1]:
1139 if str[:trylen] and bar_dict.has_key (str[:trylen]):
1142 bs = "\\bar \"%s\"" % old_bar_dict[s]
1144 bs = "%s" % bar_dict[s]
1146 if s in alternative_opener:
1147 if not in_repeat[current_voice_idx]:
1149 bs = "\\bar \"%s\"" % old_bar_dict[s]
1151 doing_alternative[current_voice_idx] = 't'
1153 if s in repeat_ender:
1154 if not in_repeat[current_voice_idx]:
1155 sys.stderr.write("Warning: inserting repeat to beginning of notes.\n")
1157 in_repeat[current_voice_idx] = ''
1159 if doing_alternative[current_voice_idx]:
1162 bs = "\\bar \"%s\"" % old_bar_dict[s]
1165 doing_alternative[current_voice_idx] = ''
1166 in_repeat[current_voice_idx] = ''
1167 if s in repeat_opener:
1168 in_repeat[current_voice_idx] = 't'
1170 bs = "\\bar \"%s\"" % old_bar_dict[s]
1175 state.next_bar = '|\n'
1177 clear_bar_acc(state)
1178 close_beam_state(state)
1180 if bs <> None or state.next_bar != '':
1181 if state.parsing_tuplet:
1182 state.parsing_tuplet =0
1183 voices_append ('} ')
1186 clear_bar_acc(state)
1187 close_beam_state(state)
1194 def try_parse_tie (str):
1197 voices_append (' ~ ')
1200 def bracket_escape (str, state):
1201 m = re.match ( '^([^\]]*)] *(.*)$', str)
1205 try_parse_header_line (cmd, state)
1208 def try_parse_chord_delims (str, state):
1211 if re.match('[A-Z]:', str): # bracket escape
1212 return bracket_escape(str, state)
1214 voices_append(state.next_bar)
1216 voices_append ('<<')
1220 if state.plus_chord:
1221 voices_append ('>>')
1222 state.plus_chord = 0
1225 voices_append(state.next_bar)
1227 voices_append ('<<')
1228 state.plus_chord = 1
1236 while str[:1] ==')':
1241 voices_append ("\\spanrequest \\stop \"slur\"" * end)
1245 def try_parse_grace_delims (str, state):
1248 voices_append(state.next_bar)
1251 voices_append ('\\grace { ')
1259 def try_parse_comment (str):
1262 if str[0:5] == '%MIDI':
1263 #the nobarlines option is necessary for an abc to lilypond translator for
1264 #exactly the same reason abc2midi needs it: abc requires the user to enter
1265 #the note that will be printed, and MIDI and lilypond expect entry of the
1266 #pitch that will be played.
1268 #In standard 19th century musical notation, the algorithm for translating
1269 #between printed note and pitch involves using the barlines to determine
1270 #the scope of the accidentals.
1272 #Since ABC is frequently used for music in styles that do not use this
1273 #convention, such as most music written before 1700, or ethnic music in
1274 #non-western scales, it is necessary to be able to tell a translator that
1275 #the barlines should not affect its interpretation of the pitch.
1276 if 'nobarlines' in str:
1278 elif str[0:3] == '%LY':
1279 p = str.find ('voices')
1281 voices_append(str[p+7:])
1283 p = str.find ('slyrics')
1285 slyrics_append(str[p+8:])
1287 #write other kinds of appending if we ever need them.
1292 def parse_file (fn):
1295 ls = map (lambda x: re.sub ("\r$", '', x), ls)
1297 select_voice('default', '')
1300 sys.stderr.write ("Line ... ")
1302 __main__.state = state_list[current_voice_idx]
1307 if not (lineno % happy_count):
1308 sys.stderr.write ('[%d]'% lineno)
1310 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1313 try_parse_comment(m.group(2))
1314 voices_append ('%% %s\n' % m.group(2))
1319 ln = try_parse_header_line (ln, state)
1321 # Try nibbling characters off until the line doesn't change.
1323 while ln != prev_ln:
1325 ln = try_parse_chord_delims (ln, state)
1326 ln = try_parse_rest (ln, state)
1327 ln = try_parse_articulation (ln,state)
1328 ln = try_parse_note (ln, state)
1329 ln = try_parse_bar (ln, state)
1330 ln = try_parse_tie (ln)
1331 ln = try_parse_escape (ln)
1332 ln = try_parse_guitar_chord (ln, state)
1333 ln = try_parse_tuplet_begin (ln, state)
1334 ln = try_parse_group_end (ln, state)
1335 ln = try_parse_grace_delims (ln, state)
1336 ln = junk_space (ln, state)
1339 error ("%s: %d: Huh? Don't understand\n" % (fn, lineno))
1340 left = orig_ln[0:-len (ln)]
1341 sys.stderr.write (left + '\n')
1342 sys.stderr.write (' ' * len (left) + ln + '\n')
1346 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1349 Written by Han-Wen Nienhuys <hanwen@xs4all.nl>, Laura Conrad
1350 <lconrad@laymusic.org>, Roy Rankin <Roy.Rankin@@alcatel.com.au>.
1353 def print_version ():
1354 print r"""abc2ly (GNU lilypond) %s""" % version
1356 def get_option_parser ():
1357 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'abc2ly',
1358 description=_ ('''abc2ly converts ABC music files (see
1359 %s) to LilyPond input.
1360 ''') % 'http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt',
1361 add_help_option=False)
1363 p.version = "abc2ly (LilyPond) @TOPLEVEL_VERSION@"
1364 p.add_option("--version",
1366 help=_ ("show version number and exit"))
1368 p.add_option("-h", "--help",
1370 help=_ ("show this help and exit"))
1371 p.add_option ('-o', '--output', metavar='FILE',
1372 help=_ ("write output to FILE"),
1374 p.add_option ('-s', '--strict', help=_ ("be strict about success"),
1375 action='store_true')
1376 p.add_option ('-b', '--beams', help=_ ("preserve ABC's notion of beams"))
1377 p.add_option_group ('',
1379 _ ('Report bugs via %s')
1380 % 'http://post.gmane.org/post.php'
1381 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
1385 option_parser = get_option_parser ()
1386 (global_options, files) = option_parser.parse_args ()
1391 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1396 sys.stderr.write ('Parsing `%s\'...\n' % f)
1399 if not global_options.output:
1400 global_options.output = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1401 sys.stderr.write ('lilypond output to: `%s\'...' % global_options.output)
1402 outf = open (global_options.output, 'w')
1404 # don't substitute @VERSION@. We want this to reflect
1405 # the last version that was verified to work.
1406 outf.write ('\\version "2.7.40"\n')
1408 # dump_global (outf)
1409 dump_header (outf, header)
1414 sys.stderr.write ('\n')