3 # once upon a rainy monday afternoon.
8 # ABC standard v1.6: http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt
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.
39 # Multiple tunes in single file not supported
40 # Blank T: header lines should write score and open a new score
41 # Not all header fields supported
42 # ABC line breaks are ignored
43 # Block comments generate error and are ignored
44 # Postscript commands are ignored
45 # lyrics not resynchronized by line breaks (lyrics must fully match notes)
46 # %%LY slyrics can't be directly before a w: line.
53 # Convert to new chord styles.
59 program_name
= 'abc2ly'
60 version
= '@TOPLEVEL_VERSION@'
61 if version
== '@' + 'TOPLEVEL_VERSION' + '@':
62 version
= '(unknown version)' # uGUHGUHGHGUGH
77 header
['footnotes'] = ''
82 repeat_state
= [0] * 8
83 current_voice_idx
= -1
84 current_lyric_idx
= -1
90 global_key
= [0] * 7 # UGH
91 names
= ["One", "Two", "Three"]
93 alphabet
="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
99 sys
.stderr
.write (msg
)
107 if re
.match('-8va', s
) or re
.match('treble8', s
):
108 # treble8 is used by abctab2ps; -8va is used by barfly,
109 # and by my patch to abc2ps. If there's ever a standard
110 # about this we'll support that.
112 state
.base_octave
= -1
113 voices_append("\\clef \"G_8\"\n")
114 elif re
.match('^treble', s
):
116 if re
.match ('^-8', s
):
118 state
.base_octave
= -2
119 voices_append("\\clef \"G_8\"\n")
121 state
.base_octave
= 0
122 voices_append("\\clef treble\n")
123 elif re
.match('^alto', s
):
125 state
.base_octave
= -1
126 voices_append ("\\clef alto\n" )
127 elif re
.match('^bass',s
):
129 state
.base_octave
= -2
130 voices_append ("\\clef bass\n" )
133 def select_voice (name
, rol
):
134 if not voice_idx_dict
.has_key (name
):
135 state_list
.append(Parser_state())
138 voice_idx_dict
[name
] = len (voices
) -1
139 __main__
.current_voice_idx
= voice_idx_dict
[name
]
140 __main__
.state
= state_list
[current_voice_idx
]
142 m
= re
.match ('^([^ \t=]*)=(.*)$', rol
) # find keywork
146 a
= re
.match ('^("[^"]*"|[^ \t]*) *(.*)$', rol
)
150 if keyword
== 'clef':
152 elif keyword
== "name":
153 value
= re
.sub ('\\\\','\\\\\\\\', value
)
154 voices_append ("\\property Staff.instrument = %s\n" % value
)
155 __main__
.part_names
= 1
156 elif keyword
== "sname" or keyword
== "snm":
157 voices_append ("\\property Staff.instr = %s\n" % value
)
165 def dump_header (outf
,hdr
):
166 outf
.write ('\\header {\n')
170 hdr
[k
] = re
.sub('"', '\\"', hdr
[k
])
171 outf
.write ('\t%s = "%s"\n'% (k
,hdr
[k
]))
174 def dump_lyrics (outf
):
176 outf
.write("\n\\score\n{\n \\context Lyrics\n <<\n")
177 for i
in range (len (lyrics
)):
178 outf
.write ( lyrics
[i
])
180 outf
.write(" >>\n \\paper{}\n}\n")
182 def dump_default_bar (outf
):
184 Nowadays abc2ly outputs explicits barlines (?)
186 outf
.write ("\n\\property Score.defaultBarType=\"empty\"\n")
189 def dump_slyrics (outf
):
190 ks
= voice_idx_dict
.keys()
193 if re
.match('[1-9]', k
):
194 m
= alphabet
[string
.atoi(k
)]
197 for i
in range (len(slyrics
[voice_idx_dict
[k
]])):
199 outf
.write ("\nwords%sV%s = \\lyrics {" % (m
, l
))
200 outf
.write ("\n" + slyrics
[voice_idx_dict
[k
]][i
])
203 def dump_voices (outf
):
204 global doing_alternative
, in_repeat
205 ks
= voice_idx_dict
.keys()
208 if re
.match ('[1-9]', k
):
209 m
= alphabet
[string
.atoi(k
)]
212 outf
.write ("\nvoice%s = \\notes {" % m
)
213 dump_default_bar(outf
)
214 if repeat_state
[voice_idx_dict
[k
]]:
215 outf
.write("\n\\repeat volta 2 {")
216 outf
.write ("\n" + voices
[voice_idx_dict
[k
]])
218 if doing_alternative
[voice_idx_dict
[k
]]:
220 if in_repeat
[voice_idx_dict
[k
]]:
226 #assume that Q takes the form "Q:1/4=120"
227 #There are other possibilities, but they are deprecated
228 if string
.count(a
, '/') == 1:
229 array
=string
.split(a
,'/')
232 sys
.stderr
.write("abc2ly: Warning, unable to translate a Q specification with a numerator of %s: %s\n" % (numerator
, a
))
233 array2
=string
.split(array
[1],'=')
234 denominator
=array2
[0]
236 duration
=str(string
.atoi(denominator
)/string
.atoi(numerator
))
237 midi_specs
=string
.join(["\\tempo", duration
, "=", perminute
])
239 sys
.stderr
.write("abc2ly: Warning, unable to parse Q specification: %s\n" % a
)
241 def dump_score (outf
):
242 outf
.write (r
"""\score{
246 ks
= voice_idx_dict
.keys ();
249 if re
.match('[1-9]', k
):
250 m
= alphabet
[string
.atoi(k
)]
253 if k
== 'default' and len (voice_idx_dict
) > 1:
255 if len ( slyrics
[voice_idx_dict
[k
]] ):
256 outf
.write ("\n \\addlyrics")
257 outf
.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k
)
259 outf
.write ("\t \\voicedefault\n")
260 outf
.write ("\t \\voice%s " % m
)
261 outf
.write ("\n\t}\n")
262 if len ( slyrics
[voice_idx_dict
[k
]] ):
263 outf
.write ("\n\t\\context Lyrics=\"%s\" \n\t<<\t" % k
)
264 if re
.match('[1-9]',k
):
265 m
= alphabet
[string
.atoi(k
)]
268 for i
in range (len(slyrics
[voice_idx_dict
[k
]])):
270 outf
.write("\n\t { \\words%sV%s }" % ( m
, l
) )
271 outf
.write ( "\n\t>>\n" )
273 outf
.write ("\n\t\\paper {\n")
275 outf
.write ("\t \\translator \n\t {\n")
276 outf
.write ("\t\t\\StaffContext\n")
277 # outf.write ("\t\t\\consists Staff_margin_engraver\n")
278 outf
.write ("\t }\n")
279 outf
.write ("\t}\n\t\\midi {%s}\n}\n" % midi_specs
)
283 def set_default_length (s
):
284 global length_specified
285 m
= re
.search ('1/([0-9]+)', s
)
287 __main__
.default_len
= string
.atoi ( m
.group (1))
290 def set_default_len_from_time_sig (s
):
291 m
= re
.search ('([0-9]+)/([0-9]+)', s
)
293 n
= string
.atoi (m
.group (1))
294 d
= string
.atoi (m
.group (2))
295 if (n
* 1.0 )/(d
* 1.0) < 0.75:
296 __main__
.default_len
= 16
298 __main__
.default_len
= 8
307 sys
.stderr
.write ("can't open file: `%s'\n" % f
)
311 sys
.stderr
.write ("gulped empty file: `%s'\n" % f
)
316 # pitch manipulation. Tuples are (name, alteration).
317 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
318 # pitch in semitones.
319 def semitone_pitch (tup
):
329 p
= p
+ t
* 2 + tup
[1]
332 def fifth_above_pitch (tup
):
333 (n
, a
) = (tup
[0] + 4, tup
[1])
335 difference
= 7 - (semitone_pitch ((n
,a
)) - semitone_pitch (tup
))
346 (t
,a
) = fifth_above_pitch (p
)
347 if semitone_pitch((t
,a
)) % 12 == 0:
359 (t
,a
) = quart_above_pitch (p
)
360 if semitone_pitch((t
,a
)) % 12 == 0:
366 def quart_above_pitch (tup
):
367 (n
, a
) = (tup
[0] + 3, tup
[1])
369 difference
= 5 - (semitone_pitch ((n
,a
)) - semitone_pitch (tup
))
374 key_lookup
= { # abc to lilypond key mode names
383 'mix' : 'mixolydian',
384 'mixolydian' : 'mixolydian',
394 if k
and k
[0] == '#':
397 elif k
and k
[0] == 'b':
401 return '%s \\major' % key
404 if key_lookup
.has_key(type):
405 return("%s \\%s" % ( key
, key_lookup
[type]))
406 sys
.stderr
.write("Unknown key type `%s' ignored\n" % type)
409 def shift_key (note
, acc
, shift
):
410 s
= semitone_pitch((note
, acc
))
411 s
= (s
+ shift
+ 12) % 12
423 key_shift
= { # semitone shifts for key mode names
446 intkey
= (ord (k
[0]) - ord('a') + 5) % 7
450 if k
and k
[0] == 'b':
453 elif k
and k
[0] == '#':
457 if k
and key_shift
.has_key(k
):
458 (intkey
, intkeyacc
) = shift_key(intkey
, intkeyacc
, key_shift
[k
])
459 keytup
= (intkey
, intkeyacc
)
461 sharp_key_seq
= sharp_keys ()
462 flat_key_seq
= flat_keys ()
466 if keytup
in sharp_key_seq
:
468 key_count
= sharp_key_seq
.index (keytup
)
469 accseq
= map (lambda x
: (4*x
-1 ) % 7, range (1, key_count
+ 1))
471 elif keytup
in flat_key_seq
:
473 key_count
= flat_key_seq
.index (keytup
)
474 accseq
= map (lambda x
: (3*x
+ 3 ) % 7, range (1, key_count
+ 1))
481 key_table
[a
] = key_table
[a
] + accsign
496 def try_parse_tuplet_begin (str, state
):
497 if re
.match ('\([2-9]', str):
500 prev_tuplet_state
= state
.parsing_tuplet
501 state
.parsing_tuplet
= string
.atoi (dig
[0])
502 if prev_tuplet_state
:
504 voices_append ("\\times %s {" % tup_lookup
[dig
])
507 def try_parse_group_end (str, state
):
508 if str and str[0] in HSPACE
:
512 def header_append (key
, a
):
514 if header
.has_key (key
):
515 s
= header
[key
] + "\n"
519 linelen
= len (v
) - string
.rfind(v
, '\n')
520 if linelen
+ len (a
) > 80:
524 def stuff_append (stuff
, idx
, a
):
528 stuff
[idx
] = wordwrap(a
, stuff
[idx
])
532 def voices_append(a
):
533 if current_voice_idx
< 0:
534 select_voice ('default', '')
535 stuff_append (voices
, current_voice_idx
, a
)
537 def repeat_prepend():
539 if current_voice_idx
< 0:
540 select_voice ('default', '')
542 repeat_state
[current_voice_idx
] = 't'
545 def lyrics_append(a
):
546 a
= re
.sub ( '#', '\\#', a
) # latex does not like naked #'s
547 a
= re
.sub ( '"', '\\"', a
) # latex does not like naked "'s
548 a
= '\t{ \\lyrics "' + a
+ '" }\n'
549 stuff_append (lyrics
, current_lyric_idx
, a
)
551 # break lyrics to words and put "'s around words containing numbers and '"'s
555 m
= re
.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
559 word
= re
.sub('"', '\\"', word
) # escape "
560 if re
.match('.*[0-9"\(]', word
):
561 word
= re
.sub('_', ' ', word
) # _ causes probs inside ""
562 ret
= ret
+ '\"' + word
+ '\" '
564 ret
= ret
+ word
+ ' '
569 def slyrics_append(a
):
570 a
= re
.sub ( '_', ' _ ', a
) # _ to ' _ '
571 a
= re
.sub ( '-', '- ', a
) # split words with -
572 a
= re
.sub ( '\\\\- ', '-', a
) # unless \-
573 a
= re
.sub ( '~', '_', a
) # ~ to space('_')
574 a
= re
.sub ( '\*', '_ ', a
) # * to to space
575 a
= re
.sub ( '#', '\\#', a
) # latex does not like naked #'s
576 if re
.match('.*[0-9"\(]', a
): # put numbers and " and ( into quoted string
578 a
= re
.sub ( '$', ' ', a
) # insure space between lines
579 __main__
.lyric_idx
= lyric_idx
+ 1
580 if len(slyrics
[current_voice_idx
]) <= lyric_idx
:
581 slyrics
[current_voice_idx
].append(a
)
583 v
= slyrics
[current_voice_idx
][lyric_idx
]
584 slyrics
[current_voice_idx
][lyric_idx
] = wordwrap(a
, slyrics
[current_voice_idx
][lyric_idx
])
587 def try_parse_header_line (ln
, state
):
588 global length_specified
589 m
= re
.match ('^([A-Za-z]): *(.*)$', ln
)
595 a
= re
.sub('[ \t]*$','', a
) #strip trailing blanks
596 if header
.has_key('title'):
598 if len(header
['title']):
599 header
['title'] = header
['title'] + '\\\\\\\\' + a
601 header
['subtitle'] = a
606 if not state
.common_time
:
607 state
.common_time
= 1
608 voices_append ("\\property Staff.TimeSignature \\override #\'style = #'C\n")
611 if not state
.common_time
:
612 state
.common_time
= 1
613 voices_append ("\\property Staff.TimeSignature \\override #\'style = #'C\n")
615 if not length_specified
:
616 set_default_len_from_time_sig (a
)
620 voices_append ('\\time %s' % a
)
625 m
= re
.match ('^([^ \t]*) *(.*)$', a
) # seperate clef info
627 # there may or may not be a space
628 # between the key letter and the mode
629 if key_lookup
.has_key(m
.group(2)[0:3]):
630 key_info
= m
.group(1) + m
.group(2)[0:3]
631 clef_info
= m
.group(2)[4:]
633 key_info
= m
.group(1)
634 clef_info
= m
.group(2)
635 __main__
.global_key
= compute_key (key_info
)# ugh.
636 voices_append ('\\key %s' % lily_key(key_info
))
637 check_clef(clef_info
)
639 __main__
.global_key
= compute_key (a
)# ugh.
640 voices_append ('\\key %s \\major' % lily_key(a
))
642 header
['footnotes'] = header
['footnotes'] + '\\\\\\\\' + a
643 if g
== 'O': # Origin
644 header
['origin'] = a
645 if g
== 'X': # Reference Number
646 header
['crossRefNumber'] = a
649 if g
== 'H': # History
650 header_append ('history', a
)
653 if g
== 'C': # Composer
654 if header
.has_key('composer'):
656 header
['composer'] = header
['composer'] + '\\\\\\\\' + a
658 header
['composer'] = a
660 header
['subtitle'] = a
661 if g
== 'L': # Default note length
662 set_default_length (ln
)
664 voice
= re
.sub (' .*$', '', a
)
665 rest
= re
.sub ('^[^ \t]* *', '', a
)
667 voices_append(state
.next_bar
)
669 select_voice (voice
, rest
)
672 if g
== 'w': # vocals
679 # we use in this order specified accidental, active accidental for bar,
680 # active accidental for key
681 def pitch_to_lilypond_name (name
, acc
, bar_acc
, key
):
695 return(chr (name
+ ord('c')) + s
)
698 def octave_to_lilypond_quotes (o
):
711 while str and str[0] in DIGITS
:
712 durstr
= durstr
+ str[0]
717 n
=string
.atoi (durstr
)
721 def duration_to_lilypond_duration (multiply_tup
, defaultlen
, dots
):
723 # (num / den) / defaultlen < 1/base
724 while base
* multiply_tup
[0] < multiply_tup
[1]:
727 if (multiply_tup
[0] / multiply_tup
[1]) == 2:
729 if (multiply_tup
[0] / multiply_tup
[1]) == 3:
732 if (multiply_tup
[0] / multiply_tup
[1]) == 4:
734 return '%s%s' % ( base
, '.'* dots
)
739 self
.next_articulation
= ''
743 self
.parsing_tuplet
= 0
750 # return (str, num,den,dots)
751 def parse_duration (str, parser_state
):
753 den
= parser_state
.next_den
754 parser_state
.next_den
= 1
756 (str, num
) = parse_num (str)
762 while str[:1] == '/':
766 (str, d
) =parse_num (str)
770 den
= den
* default_len
772 current_dots
= parser_state
.next_dots
773 parser_state
.next_dots
= 0
774 if re
.match ('[ \t]*[<>]', str):
775 while str[0] in HSPACE
:
779 current_dots
= current_dots
+ 1
780 parser_state
.next_den
= parser_state
.next_den
* 2
785 parser_state
.next_dots
= parser_state
.next_dots
+ 1
793 if num
% multiplier
== 0 and den
% f
== 0:
794 num
= num
/ multiplier
796 current_dots
= current_dots
+ d
798 return (str, num
,den
,current_dots
)
801 def try_parse_rest (str, parser_state
):
802 if not str or str[0] <> 'z' and str[0] <> 'x':
805 __main__
.lyric_idx
= -1
807 if parser_state
.next_bar
:
808 voices_append(parser_state
.next_bar
)
809 parser_state
.next_bar
= ''
817 (str, num
,den
,d
) = parse_duration (str, parser_state
)
818 voices_append ('%s%s' % (rest
, duration_to_lilypond_duration ((num
,den
), default_len
, d
)))
819 if parser_state
.next_articulation
:
820 voices_append (parser_state
.next_articulation
)
821 parser_state
.next_articulation
= ''
834 'J' : '', # ignore slide
835 'R' : '', # ignore roll
839 def try_parse_articulation (str, state
):
840 while str and artic_tbl
.has_key(str[:1]):
841 state
.next_articulation
= state
.next_articulation
+ artic_tbl
[str[:1]]
842 if not artic_tbl
[str[:1]]:
843 sys
.stderr
.write("Warning: ignoring `%s'\n" % str[:1] )
849 # s7m2 input doesnt care about spaces
850 if re
.match('[ \t]*\(', str):
851 str = string
.lstrip (str)
854 while str[:1] =='(' and str[1] not in DIGITS
:
855 slur_begin
= slur_begin
+ 1
856 state
.next_articulation
= state
.next_articulation
+ '('
862 # remember accidental for rest of bar
864 def set_bar_acc(note
, octave
, acc
, state
):
867 n_oct
= note
+ octave
* 7
868 state
.in_acc
[n_oct
] = acc
870 # get accidental set in this bar or UNDEF if not set
871 def get_bar_acc(note
, octave
, state
):
872 n_oct
= note
+ octave
* 7
873 if state
.in_acc
.has_key(n_oct
):
874 return(state
.in_acc
[n_oct
])
878 def clear_bar_acc(state
):
879 for k
in state
.in_acc
.keys():
884 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
885 def try_parse_note (str, parser_state
):
904 octave
= parser_state
.base_octave
905 if str[0] in "ABCDEFG":
906 str = string
.lower (str[0]) + str[1:]
911 if str[0] in "abcdefg":
912 notename
= (ord(str[0]) - ord('a') + 5)%7
915 return str # failed; not a note!
918 __main__
.lyric_idx
= -1
920 if parser_state
.next_bar
:
921 voices_append(parser_state
.next_bar
)
922 parser_state
.next_bar
= ''
927 while str[0] == '\'':
931 (str, num
,den
,current_dots
) = parse_duration (str, parser_state
)
933 if re
.match('[ \t]*\)', str):
934 str = string
.lstrip (str)
938 slur_end
= slur_end
+ 1
942 bar_acc
= get_bar_acc(notename
, octave
, parser_state
)
943 pit
= pitch_to_lilypond_name(notename
, acc
, bar_acc
, global_key
[notename
])
944 oct = octave_to_lilypond_quotes (octave
)
945 if acc
!= UNDEF
and (acc
== global_key
[notename
] or acc
== bar_acc
):
949 voices_append ("%s%s%s%s" %
951 duration_to_lilypond_duration ((num
,den
), default_len
, current_dots
)))
953 set_bar_acc(notename
, octave
, acc
, parser_state
)
954 if parser_state
.next_articulation
:
955 articulation
= articulation
+ parser_state
.next_articulation
956 parser_state
.next_articulation
= ''
958 voices_append (articulation
)
960 if parser_state
.parsing_tuplet
:
961 parser_state
.parsing_tuplet
= parser_state
.parsing_tuplet
- 1
962 if not parser_state
.parsing_tuplet
:
965 voices_append ('-(' * slur_begin
)
967 voices_append ('-)' *slur_end
)
973 def junk_space (str):
974 while str and str[0] in '\t\n ':
980 def try_parse_guitar_chord (str, state
):
984 if str[0] == '_' or (str[0] == '^'):
989 while str and str[0] != '"':
995 gc
= re
.sub('#', '\\#', gc
) # escape '#'s
996 state
.next_articulation
= ("%c\"%s\"" % (position
,gc
)) + state
.next_articulation
999 def try_parse_escape (str):
1000 if not str or str [0] != '\\':
1005 key_table
= compute_key ()
1009 # |] thin-thick double bar line
1010 # || thin-thin double bar line
1011 # [| thick-thin double bar line
1014 # :: left-right repeat
1030 '|]' : '\\bar "|."',
1031 '||' : '\\bar "||"',
1032 '[|' : '\\bar "||"',
1034 '|:' : '\\repeat volta 2 {',
1035 '::' : '} \\repeat volta 2 {',
1036 '|1' : '} \\alternative{{',
1043 warn_about
= ['|:', '::', ':|', '|1', ':|2', '|2']
1044 alternative_opener
= ['|1', '|2', ':|2']
1045 repeat_ender
= ['::', ':|']
1046 repeat_opener
= ['::', '|:']
1047 in_repeat
= [''] * 8
1048 doing_alternative
= [''] * 8
1051 def try_parse_bar (str,state
):
1052 global in_repeat
, doing_alternative
, using_old
1055 if current_voice_idx
< 0:
1056 select_voice ('default', '')
1057 # first try the longer one
1058 for trylen
in [3,2,1]:
1059 if str[:trylen
] and bar_dict
.has_key (str[:trylen
]):
1062 bs
= "\\bar \"%s\"" % old_bar_dict
[s
]
1064 bs
= "%s" % bar_dict
[s
]
1066 if s
in alternative_opener
:
1067 if not in_repeat
[current_voice_idx
]:
1069 bs
= "\\bar \"%s\"" % old_bar_dict
[s
]
1071 doing_alternative
[current_voice_idx
] = 't'
1073 if s
in repeat_ender
:
1074 if not in_repeat
[current_voice_idx
]:
1075 sys
.stderr
.write("Warning: inserting repeat to beginning of notes.\n")
1077 in_repeat
[current_voice_idx
] = ''
1079 if doing_alternative
[current_voice_idx
]:
1082 bs
= "\\bar \"%s\"" % old_bar_dict
[s
]
1085 doing_alternative
[current_voice_idx
] = ''
1086 in_repeat
[current_voice_idx
] = ''
1087 if s
in repeat_opener
:
1088 in_repeat
[current_voice_idx
] = 't'
1090 bs
= "\\bar \"%s\"" % old_bar_dict
[s
]
1095 state
.next_bar
= '|\n'
1097 clear_bar_acc(state
)
1099 if bs
<> None or state
.next_bar
!= '':
1100 if state
.parsing_tuplet
:
1101 state
.parsing_tuplet
=0
1102 voices_append ('} ')
1105 clear_bar_acc(state
)
1108 voices_append("} }")
1112 def try_parse_tie (str):
1115 voices_append (' ~ ')
1118 def bracket_escape (str, state
):
1119 m
= re
.match ( '^([^\]]*)] *(.*)$', str)
1123 try_parse_header_line (cmd
, state
)
1126 def try_parse_chord_delims (str, state
):
1129 if re
.match('[A-Z]:', str): # bracket escape
1130 return bracket_escape(str, state
)
1132 voices_append(state
.next_bar
)
1138 if state
.plus_chord
:
1140 state
.plus_chord
= 0
1143 voices_append(state
.next_bar
)
1146 state
.plus_chord
= 1
1154 while str[:1] ==')':
1159 voices_append ("\\spanrequest \\stop \"slur\"" * end
)
1163 def try_parse_grace_delims (str, state
):
1166 voices_append(state
.next_bar
)
1169 voices_append ('\\grace { ')
1177 def try_parse_comment (str):
1180 if str[0:5] == '%MIDI':
1181 #the nobarlines option is necessary for an abc to lilypond translator for
1182 #exactly the same reason abc2midi needs it: abc requires the user to enter
1183 #the note that will be printed, and MIDI and lilypond expect entry of the
1184 #pitch that will be played.
1186 #In standard 19th century musical notation, the algorithm for translating
1187 #between printed note and pitch involves using the barlines to determine
1188 #the scope of the accidentals.
1190 #Since ABC is frequently used for music in styles that do not use this
1191 #convention, such as most music written before 1700, or ethnic music in
1192 #non-western scales, it is necessary to be able to tell a translator that
1193 #the barlines should not affect its interpretation of the pitch.
1194 if (string
.find(str,'nobarlines') > 0):
1196 elif str[0:3] == '%LY':
1197 p
= string
.find(str, 'voices')
1199 voices_append(str[p
+7:])
1201 p
= string
.find(str, 'slyrics')
1203 slyrics_append(str[p
+8:])
1205 #write other kinds of appending if we ever need them.
1209 def parse_file (fn
):
1213 select_voice('default', '')
1215 sys
.stderr
.write ("Line ... ")
1217 __main__
.state
= state_list
[current_voice_idx
]
1222 if not (lineno
% happy_count
):
1223 sys
.stderr
.write ('[%d]'% lineno
)
1225 m
= re
.match ('^([^%]*)%(.*)$',ln
) # add comments to current voice
1228 try_parse_comment(m
.group(2))
1229 voices_append ('%% %s\n' % m
.group(2))
1234 ln
= try_parse_header_line (ln
, state
)
1236 # Try nibbling characters off until the line doesn't change.
1238 while ln
!= prev_ln
:
1240 ln
= try_parse_chord_delims (ln
, state
)
1241 ln
= try_parse_rest (ln
, state
)
1242 ln
= try_parse_articulation (ln
,state
)
1243 ln
= try_parse_note (ln
, state
)
1244 ln
= try_parse_bar (ln
, state
)
1245 ln
= try_parse_tie (ln
)
1246 ln
= try_parse_escape (ln
)
1247 ln
= try_parse_guitar_chord (ln
, state
)
1248 ln
= try_parse_tuplet_begin (ln
, state
)
1249 ln
= try_parse_group_end (ln
, state
)
1250 ln
= try_parse_grace_delims (ln
, state
)
1251 ln
= junk_space (ln
)
1254 error ("%s: %d: Huh? Don't understand\n" % (fn
, lineno
))
1255 left
= orig_ln
[0:-len (ln
)]
1256 sys
.stderr
.write (left
+ '\n')
1257 sys
.stderr
.write (' ' * len (left
) + ln
+ '\n')
1261 sys
.stderr
.write ("%s from LilyPond %s\n" % (program_name
, version
))
1265 Convert ABC to lilypond.
1267 Usage: abc2ly [OPTIONS]... ABC-FILE
1270 -h, --help print this help
1271 -o, --output=FILE set output filename to FILE
1272 -v, --version show version information
1273 -s, --strict be strict about succes
1275 This program converts ABC music files (see
1276 http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt) to LilyPond input.
1279 Report bugs to bug-lilypond@gnu.org.
1281 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>, Laura Conrad
1282 <lconrad@laymusic.org>, Roy Rankin <Roy.Rankin@@alcatel.com.au>.
1285 def print_version ():
1286 print r
"""abc2ly (GNU lilypond) %s""" % version
1290 (options
, files
) = getopt
.getopt (sys
.argv
[1:], 'vo:hs', ['help','version', 'output=', 'strict'])
1296 if o
== '--help' or o
== '-h':
1299 elif o
== '--version' or o
== '-v':
1302 elif o
== '--strict' or o
== '-s':
1304 elif o
== '--output' or o
== '-o':
1312 header
['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1317 sys
.stderr
.write ('Parsing `%s\'...\n' % f
)
1320 if not out_filename
:
1321 out_filename
= os
.path
.basename (os
.path
.splitext (f
)[0]) + ".ly"
1322 sys
.stderr
.write ('lilypond output to: `%s\'...' % out_filename
)
1323 outf
= open (out_filename
, 'w')
1325 # dump_global (outf)
1326 dump_header (outf
,header
)
1331 sys
.stderr
.write ('\n')