+ QUOTE: r'''
%(str)s
''',
- VERBATIM: r'''
+ VERBATIM: r'''
%(verb)s
''',
- },
+ },
- ##
- LATEX: {
- OUTPUT: r'''{%%
+ ##
+ LATEX: {
+ OUTPUT: r'''{%%
\parindent 0pt%%
\catcode`\@=12%%
\ifx\preLilyPondExample \undefined%%
- \relax%%
+ \relax%%
\else%%
- \preLilyPondExample%%
+ \preLilyPondExample%%
\fi%%
\def\lilypondbook{}%%
\input %(base)s-systems.tex%%
\ifx\postLilyPondExample \undefined%%
- \relax%%
+ \relax%%
\else%%
- \postLilyPondExample%%
+ \postLilyPondExample%%
\fi%%
}''',
- PRINTFILENAME: '''\\texttt{%(filename)s}
- ''',
+ PRINTFILENAME: '''\\texttt{%(filename)s}
+ ''',
- QUOTE: r'''\begin{quotation}%(str)s
+ QUOTE: r'''\begin{quotation}%(str)s
\end{quotation}''',
- VERBATIM: r'''\noindent
+ VERBATIM: r'''\noindent
\begin{verbatim}%(verb)s\end{verbatim}''',
- FILTER: r'''\begin{lilypond}[%(options)s]
+ FILTER: r'''\begin{lilypond}[%(options)s]
%(code)s
\end{lilypond}''',
- },
+ },
- ##
- TEXINFO: {
- FILTER: r'''@lilypond[%(options)s]
+ ##
+ TEXINFO: {
+ FILTER: r'''@lilypond[%(options)s]
%(code)s
@lilypond''',
- OUTPUT: r'''
+ OUTPUT: r'''
@iftex
@include %(base)s-systems.texi
@end iftex
''',
- OUTPUTIMAGE: r'''@noindent
+ OUTPUTIMAGE: r'''@noindent
@ifinfo
@image{%(base)s,,,%(alt)s,%(ext)s}
@end ifinfo
@html
-
-
-
+
+
+
@end html
''',
- PRINTFILENAME: '''
+ PRINTFILENAME: '''
@html
@end html
@@ -611,21 +611,21 @@ output = {
@html
@end html
- ''',
+ ''',
- QUOTE: r'''@quotation
+ QUOTE: r'''@quotation
%(str)s@end quotation
''',
- NOQUOTE: r'''@format
+ NOQUOTE: r'''@format
%(str)s@end format
''',
- VERBATIM: r'''@exampleindent 0
+ VERBATIM: r'''@exampleindent 0
@verbatim
%(verb)s@end verbatim
''',
- },
+ },
}
#
@@ -634,9 +634,9 @@ output = {
## TODO
if 0:
- for f in [HTML, LATEX]:
- for s in (QUOTE, VERBATIM):
- output[f][s] = output[f][s].replace("\n"," ")
+ for f in [HTML, LATEX]:
+ for s in (QUOTE, VERBATIM):
+ output[f][s] = output[f][s].replace("\n"," ")
PREAMBLE_LY = '''%%%% Generated by %(program_name)s
@@ -644,10 +644,10 @@ PREAMBLE_LY = '''%%%% Generated by %(program_name)s
#(set! toplevel-score-handler print-score-with-defaults)
#(set! toplevel-music-handler
- (lambda (p m)
- (if (not (eq? (ly:music-property m \'void) #t))
- (print-score-with-defaults
- p (scorify-music m p)))))
+ (lambda (p m)
+ (if (not (eq? (ly:music-property m \'void) #t))
+ (print-score-with-defaults
+ p (scorify-music m p)))))
#(ly:set-option (quote no-point-and-click))
#(define inside-lilypond-book #t)
@@ -664,13 +664,13 @@ PREAMBLE_LY = '''%%%% Generated by %(program_name)s
%% ****************************************************************
\paper {
- #(define dump-extents #t)
- %(font_dump_setting)s
- %(paper_string)s
+ #(define dump-extents #t)
+ %(font_dump_setting)s
+ %(paper_string)s
}
\layout {
- %(layout_string)s
+ %(layout_string)s
}
'''
@@ -706,696 +706,696 @@ FULL_LY = '''
'''
texinfo_line_widths = {
- '@afourpaper': '160\\mm',
- '@afourwide': '6.5\\in',
- '@afourlatex': '150\\mm',
- '@smallbook': '5\\in',
- '@letterpaper': '6\\in',
+ '@afourpaper': '160\\mm',
+ '@afourwide': '6.5\\in',
+ '@afourlatex': '150\\mm',
+ '@smallbook': '5\\in',
+ '@letterpaper': '6\\in',
}
def classic_lilypond_book_compatibility (key, value):
- if key == 'singleline' and value == None:
- return (RAGGED_RIGHT, None)
+ if key == 'singleline' and value == None:
+ return (RAGGED_RIGHT, None)
- m = re.search ('relative\s*([-0-9])', key)
- if m:
- return ('relative', m.group (1))
+ m = re.search ('relative\s*([-0-9])', key)
+ if m:
+ return ('relative', m.group (1))
- m = re.match ('([0-9]+)pt', key)
- if m:
- return ('staffsize', m.group (1))
+ m = re.match ('([0-9]+)pt', key)
+ if m:
+ return ('staffsize', m.group (1))
- if key == 'indent' or key == 'line-width':
- m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
- if m:
- f = float (m.group (1))
- return (key, '%f\\%s' % (f, m.group (2)))
+ if key == 'indent' or key == 'line-width':
+ m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
+ if m:
+ f = float (m.group (1))
+ return (key, '%f\\%s' % (f, m.group (2)))
- return (None, None)
+ return (None, None)
def find_file (name):
- for i in global_options.include_path:
- full = os.path.join (i, name)
- if os.path.exists (full):
- return full
-
- error (_ ("file not found: %s") % name + '\n')
- exit (1)
- return ''
+ for i in global_options.include_path:
+ full = os.path.join (i, name)
+ if os.path.exists (full):
+ return full
+
+ error (_ ("file not found: %s") % name + '\n')
+ exit (1)
+ return ''
def verbatim_html (s):
- return re.sub ('>', '>',
- re.sub ('<', '<',
- re.sub ('&', '&', s)))
+ return re.sub ('>', '>',
+ re.sub ('<', '<',
+ re.sub ('&', '&', s)))
def split_options (option_string):
- if option_string:
- if global_options.format == HTML:
- options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
- for i in range(len(options)):
- options[i] = re.sub('^([^=]+=\s*)(?P["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
- return options
- else:
- return re.split (format_res[global_options.format]['option_sep'],
- option_string)
- return []
+ if option_string:
+ if global_options.format == HTML:
+ options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
+ for i in range(len(options)):
+ options[i] = re.sub('^([^=]+=\s*)(?P["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
+ return options
+ else:
+ return re.split (format_res[global_options.format]['option_sep'],
+ option_string)
+ return []
def set_default_options (source):
- global default_ly_options
- if not default_ly_options.has_key (LINE_WIDTH):
- if global_options.format == LATEX:
- textwidth = get_latex_textwidth (source)
- default_ly_options[LINE_WIDTH] = \
- '''%.0f\\pt''' % textwidth
- elif global_options.format == TEXINFO:
- for (k, v) in texinfo_line_widths.items ():
- # FIXME: @layout is usually not in
- # chunk #0:
- #
- # \input texinfo @c -*-texinfo-*-
- #
- # Bluntly search first K items of
- # source.
- # s = chunks[0].replacement_text ()
- if re.search (k, source[:1024]):
- default_ly_options[LINE_WIDTH] = v
- break
+ global default_ly_options
+ if not default_ly_options.has_key (LINE_WIDTH):
+ if global_options.format == LATEX:
+ textwidth = get_latex_textwidth (source)
+ default_ly_options[LINE_WIDTH] = \
+ '''%.0f\\pt''' % textwidth
+ elif global_options.format == TEXINFO:
+ for (k, v) in texinfo_line_widths.items ():
+ # FIXME: @layout is usually not in
+ # chunk #0:
+ #
+ # \input texinfo @c -*-texinfo-*-
+ #
+ # Bluntly search first K items of
+ # source.
+ # s = chunks[0].replacement_text ()
+ if re.search (k, source[:1024]):
+ default_ly_options[LINE_WIDTH] = v
+ break
class Chunk:
- def replacement_text (self):
- return ''
+ def replacement_text (self):
+ return ''
- def filter_text (self):
- return self.replacement_text ()
+ def filter_text (self):
+ return self.replacement_text ()
- def ly_is_outdated (self):
- return 0
+ def ly_is_outdated (self):
+ return 0
- def png_is_outdated (self):
- return 0
+ def png_is_outdated (self):
+ return 0
- def is_plain (self):
- return False
-
+ def is_plain (self):
+ return False
+
class Substring (Chunk):
- def __init__ (self, source, start, end, line_number):
- self.source = source
- self.start = start
- self.end = end
- self.line_number = line_number
- self.override_text = None
-
- def is_plain (self):
- return True
-
- def replacement_text (self):
- if self.override_text:
- return self.override_text
- else:
- return self.source[self.start:self.end]
+ def __init__ (self, source, start, end, line_number):
+ self.source = source
+ self.start = start
+ self.end = end
+ self.line_number = line_number
+ self.override_text = None
+
+ def is_plain (self):
+ return True
+
+ def replacement_text (self):
+ if self.override_text:
+ return self.override_text
+ else:
+ return self.source[self.start:self.end]
class Snippet (Chunk):
- def __init__ (self, type, match, format, line_number):
- self.type = type
- self.match = match
- self.hash = 0
- self.option_dict = {}
- self.format = format
- self.line_number = line_number
+ def __init__ (self, type, match, format, line_number):
+ self.type = type
+ self.match = match
+ self.hash = 0
+ self.option_dict = {}
+ self.format = format
+ self.line_number = line_number
- def replacement_text (self):
- return self.match.group ('match')
+ def replacement_text (self):
+ return self.match.group ('match')
- def substring (self, s):
- return self.match.group (s)
+ def substring (self, s):
+ return self.match.group (s)
- def __repr__ (self):
- return `self.__class__` + ' type = ' + self.type
+ def __repr__ (self):
+ return `self.__class__` + ' type = ' + self.type
class Include_snippet (Snippet):
- def processed_filename (self):
- f = self.substring ('filename')
- return os.path.splitext (f)[0] + format2ext[global_options.format]
+ def processed_filename (self):
+ f = self.substring ('filename')
+ return os.path.splitext (f)[0] + format2ext[global_options.format]
- def replacement_text (self):
- s = self.match.group ('match')
- f = self.substring ('filename')
+ def replacement_text (self):
+ s = self.match.group ('match')
+ f = self.substring ('filename')
- return re.sub (f, self.processed_filename (), s)
+ return re.sub (f, self.processed_filename (), s)
class Lilypond_snippet (Snippet):
- def __init__ (self, type, match, format, line_number):
- Snippet.__init__ (self, type, match, format, line_number)
- os = match.group ('options')
- self.do_options (os, self.type)
-
- def ly (self):
- return self.substring ('code')
-
- def full_ly (self):
- s = self.ly ()
- if s:
- return self.compose_ly (s)
- return ''
-
- def do_options (self, option_string, type):
- self.option_dict = {}
-
- options = split_options (option_string)
-
- for i in options:
- if string.find (i, '=') > 0:
- (key, value) = re.split ('\s*=\s*', i)
- self.option_dict[key] = value
- else:
- if i in no_options.keys ():
- if no_options[i] in self.option_dict.keys ():
- del self.option_dict[no_options[i]]
- else:
- self.option_dict[i] = None
-
- has_line_width = self.option_dict.has_key (LINE_WIDTH)
- no_line_width_value = 0
-
- # If LINE_WIDTH is used without parameter, set it to default.
- if has_line_width and self.option_dict[LINE_WIDTH] == None:
- no_line_width_value = 1
- del self.option_dict[LINE_WIDTH]
-
- for i in default_ly_options.keys ():
- if i not in self.option_dict.keys ():
- self.option_dict[i] = default_ly_options[i]
-
- if not has_line_width:
- if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
- self.option_dict[RAGGED_RIGHT] = None
-
- if type == 'lilypond':
- if LINE_WIDTH in self.option_dict.keys ():
- del self.option_dict[LINE_WIDTH]
- else:
- if RAGGED_RIGHT in self.option_dict.keys ():
- if LINE_WIDTH in self.option_dict.keys ():
- del self.option_dict[LINE_WIDTH]
-
- if QUOTE in self.option_dict.keys () or type == 'lilypond':
- if LINE_WIDTH in self.option_dict.keys ():
- del self.option_dict[LINE_WIDTH]
-
- if not INDENT in self.option_dict.keys ():
- self.option_dict[INDENT] = '0\\mm'
-
- # The QUOTE pattern from ly_options only emits the `line-width'
- # keyword.
- if has_line_width and QUOTE in self.option_dict.keys ():
- if no_line_width_value:
- del self.option_dict[LINE_WIDTH]
- else:
- del self.option_dict[QUOTE]
-
- def compose_ly (self, code):
- if FRAGMENT in self.option_dict.keys ():
- body = FRAGMENT_LY
- else:
- body = FULL_LY
-
- # Defaults.
- relative = 1
- override = {}
- # The original concept of the `exampleindent' option is broken.
- # It is not possible to get a sane value for @exampleindent at all
- # without processing the document itself. Saying
- #
- # @exampleindent 0
- # @example
- # ...
- # @end example
- # @exampleindent 5
- #
- # causes ugly results with the DVI backend of texinfo since the
- # default value for @exampleindent isn't 5em but 0.4in (or a smaller
- # value). Executing the above code changes the environment
- # indentation to an unknown value because we don't know the amount
- # of 1em in advance since it is font-dependent. Modifying
- # @exampleindent in the middle of a document is simply not
- # supported within texinfo.
- #
- # As a consequence, the only function of @exampleindent is now to
- # specify the amount of indentation for the `quote' option.
- #
- # To set @exampleindent locally to zero, we use the @format
- # environment for non-quoted snippets.
- override[EXAMPLEINDENT] = r'0.4\in'
- override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
- override.update (default_ly_options)
-
- option_list = []
- for (key, value) in self.option_dict.items ():
- if value == None:
- option_list.append (key)
- else:
- option_list.append (key + '=' + value)
- option_string = string.join (option_list, ',')
-
- compose_dict = {}
- compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
- for a in compose_types:
- compose_dict[a] = []
-
- for (key, value) in self.option_dict.items ():
- (c_key, c_value) = \
- classic_lilypond_book_compatibility (key, value)
- if c_key:
- if c_value:
- warning \
- (_ ("deprecated ly-option used: %s=%s" \
- % (key, value)))
- warning \
- (_ ("compatibility mode translation: %s=%s" \
- % (c_key, c_value)))
- else:
- warning \
- (_ ("deprecated ly-option used: %s" \
- % key))
- warning \
- (_ ("compatibility mode translation: %s" \
- % c_key))
-
- (key, value) = (c_key, c_value)
-
- if value:
- override[key] = value
- else:
- if not override.has_key (key):
- override[key] = None
-
- found = 0
- for type in compose_types:
- if ly_options[type].has_key (key):
- compose_dict[type].append (ly_options[type][key])
- found = 1
- break
-
- if not found and key not in simple_options:
- warning (_ ("ignoring unknown ly option: %s") % key)
-
- # URGS
- if RELATIVE in override.keys () and override[RELATIVE]:
- relative = int (override[RELATIVE])
-
- relative_quotes = ''
-
- # 1 = central C
- if relative < 0:
- relative_quotes += ',' * (- relative)
- elif relative > 0:
- relative_quotes += "'" * relative
-
- paper_string = string.join (compose_dict[PAPER],
- '\n ') % override
- layout_string = string.join (compose_dict[LAYOUT],
- '\n ') % override
- notes_string = string.join (compose_dict[NOTES],
- '\n ') % vars ()
- preamble_string = string.join (compose_dict[PREAMBLE],
- '\n ') % override
-
- font_dump_setting = ''
- if FONTLOAD in self.option_dict:
- font_dump_setting = '#(define-public force-eps-font-include #t)\n'
-
- d = globals().copy()
- d.update (locals())
- return (PREAMBLE_LY + body) % d
-
- # TODO: Use md5?
- def get_hash (self):
- if not self.hash:
- self.hash = abs (hash (self.full_ly ()))
- return self.hash
-
- def basename (self):
- if FILENAME in self.option_dict:
- return self.option_dict[FILENAME]
- if global_options.use_hash:
- return 'lily-%d' % self.get_hash ()
- raise 'to be done'
-
- def write_ly (self):
- outf = open (self.basename () + '.ly', 'w')
- outf.write (self.full_ly ())
-
- open (self.basename () + '.txt', 'w').write ('image of music')
-
- def ly_is_outdated (self):
- base = self.basename ()
-
- tex_file = '%s.tex' % base
- eps_file = '%s.eps' % base
- system_file = '%s-systems.tex' % base
- ly_file = '%s.ly' % base
- ok = os.path.exists (ly_file) \
- and os.path.exists (system_file)\
- and os.stat (system_file)[stat.ST_SIZE] \
- and re.match ('% eof', open (system_file).readlines ()[-1])
- if ok and (not global_options.use_hash or FILENAME in self.option_dict):
- ok = (self.full_ly () == open (ly_file).read ())
- if ok:
- # TODO: Do something smart with target formats
- # (ps, png) and m/ctimes.
- return None
- return self
-
- def png_is_outdated (self):
- base = self.basename ()
- ok = self.ly_is_outdated ()
- if global_options.format in (HTML, TEXINFO):
- ok = ok and os.path.exists (base + '.eps')
-
- page_count = 0
- if ok:
- page_count = ps_page_count (base + '.eps')
-
- if page_count == 1:
- ok = ok and os.path.exists (base + '.png')
- elif page_count > 1:
- for a in range (1, page_count + 1):
- ok = ok and os.path.exists (base + '-page%d.png' % a)
-
- return not ok
-
- def texstr_is_outdated (self):
- if backend == 'ps':
- return 0
-
- base = self.basename ()
- ok = self.ly_is_outdated ()
- ok = ok and (os.path.exists (base + '.texstr'))
- return not ok
-
- def filter_text (self):
- code = self.substring ('code')
- s = run_filter (code)
- d = {
- 'code': s,
- 'options': self.match.group ('options')
- }
- # TODO
- return output[self.format][FILTER] % d
-
- def replacement_text (self):
- func = Lilypond_snippet.__dict__['output_' + self.format]
- return func (self)
-
- def get_images (self):
- base = self.basename ()
- # URGUGHUGHUGUGH
- single = '%(base)s.png' % vars ()
- multiple = '%(base)s-page1.png' % vars ()
- images = (single,)
- if os.path.exists (multiple) \
- and (not os.path.exists (single) \
- or (os.stat (multiple)[stat.ST_MTIME] \
- > os.stat (single)[stat.ST_MTIME])):
- count = ps_page_count ('%(base)s.eps' % vars ())
- images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
- images = tuple (images)
- return images
-
- def output_html (self):
- str = ''
- base = self.basename ()
- if global_options.format == HTML:
- str += self.output_print_filename (HTML)
- if VERBATIM in self.option_dict:
- verb = verbatim_html (self.substring ('code'))
- str += output[HTML][VERBATIM] % vars ()
- if QUOTE in self.option_dict:
- str = output[HTML][QUOTE] % vars ()
-
- str += output[HTML][BEFORE] % vars ()
- for image in self.get_images ():
- (base, ext) = os.path.splitext (image)
- alt = self.option_dict[ALT]
- str += output[HTML][OUTPUT] % vars ()
- str += output[HTML][AFTER] % vars ()
- return str
-
- def output_info (self):
- str = ''
- for image in self.get_images ():
- (base, ext) = os.path.splitext (image)
-
- # URG, makeinfo implicitly prepends dot to extension.
- # Specifying no extension is most robust.
- ext = ''
- alt = self.option_dict[ALT]
- str += output[TEXINFO][OUTPUTIMAGE] % vars ()
-
- base = self.basename ()
- str += output[global_options.format][OUTPUT] % vars ()
- return str
-
- def output_latex (self):
- str = ''
- base = self.basename ()
- if global_options.format == LATEX:
- str += self.output_print_filename (LATEX)
- if VERBATIM in self.option_dict:
- verb = self.substring ('code')
- str += (output[LATEX][VERBATIM] % vars ())
-
- str += (output[LATEX][OUTPUT] % vars ())
-
- ## todo: maintain breaks
- if 0:
- breaks = self.ly ().count ("\n")
- str += "".ljust (breaks, "\n").replace ("\n","%\n")
-
- if QUOTE in self.option_dict:
- str = output[LATEX][QUOTE] % vars ()
- return str
-
- def output_print_filename (self, format):
- str = ''
- if PRINTFILENAME in self.option_dict:
- base = self.basename ()
- filename = self.substring ('filename')
- str = output[global_options.format][PRINTFILENAME] % vars ()
-
- return str
-
- def output_texinfo (self):
- str = ''
- if self.output_print_filename (TEXINFO):
- str += ('@html\n'
- + self.output_print_filename (HTML)
- + '\n@end html\n')
- str += ('@tex\n'
- + self.output_print_filename (LATEX)
- + '\n@end tex\n')
- base = self.basename ()
- if TEXIDOC in self.option_dict:
- texidoc = base + '.texidoc'
- if os.path.exists (texidoc):
- str += '@include %(texidoc)s\n\n' % vars ()
-
- if VERBATIM in self.option_dict:
- verb = self.substring ('code')
- str += (output[TEXINFO][VERBATIM] % vars ())
- if not QUOTE in self.option_dict:
- str = output[TEXINFO][NOQUOTE] % vars ()
-
- str += self.output_info ()
-
-# str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
-# str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
-# str += ('@html\n' + self.output_html () + '\n@end html\n')
-
- if QUOTE in self.option_dict:
- str = output[TEXINFO][QUOTE] % vars ()
-
- # need par after image
- str += '\n'
-
- return str
+ def __init__ (self, type, match, format, line_number):
+ Snippet.__init__ (self, type, match, format, line_number)
+ os = match.group ('options')
+ self.do_options (os, self.type)
+
+ def ly (self):
+ return self.substring ('code')
+
+ def full_ly (self):
+ s = self.ly ()
+ if s:
+ return self.compose_ly (s)
+ return ''
+
+ def do_options (self, option_string, type):
+ self.option_dict = {}
+
+ options = split_options (option_string)
+
+ for i in options:
+ if string.find (i, '=') > 0:
+ (key, value) = re.split ('\s*=\s*', i)
+ self.option_dict[key] = value
+ else:
+ if i in no_options.keys ():
+ if no_options[i] in self.option_dict.keys ():
+ del self.option_dict[no_options[i]]
+ else:
+ self.option_dict[i] = None
+
+ has_line_width = self.option_dict.has_key (LINE_WIDTH)
+ no_line_width_value = 0
+
+ # If LINE_WIDTH is used without parameter, set it to default.
+ if has_line_width and self.option_dict[LINE_WIDTH] == None:
+ no_line_width_value = 1
+ del self.option_dict[LINE_WIDTH]
+
+ for i in default_ly_options.keys ():
+ if i not in self.option_dict.keys ():
+ self.option_dict[i] = default_ly_options[i]
+
+ if not has_line_width:
+ if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
+ self.option_dict[RAGGED_RIGHT] = None
+
+ if type == 'lilypond':
+ if LINE_WIDTH in self.option_dict.keys ():
+ del self.option_dict[LINE_WIDTH]
+ else:
+ if RAGGED_RIGHT in self.option_dict.keys ():
+ if LINE_WIDTH in self.option_dict.keys ():
+ del self.option_dict[LINE_WIDTH]
+
+ if QUOTE in self.option_dict.keys () or type == 'lilypond':
+ if LINE_WIDTH in self.option_dict.keys ():
+ del self.option_dict[LINE_WIDTH]
+
+ if not INDENT in self.option_dict.keys ():
+ self.option_dict[INDENT] = '0\\mm'
+
+ # The QUOTE pattern from ly_options only emits the `line-width'
+ # keyword.
+ if has_line_width and QUOTE in self.option_dict.keys ():
+ if no_line_width_value:
+ del self.option_dict[LINE_WIDTH]
+ else:
+ del self.option_dict[QUOTE]
+
+ def compose_ly (self, code):
+ if FRAGMENT in self.option_dict.keys ():
+ body = FRAGMENT_LY
+ else:
+ body = FULL_LY
+
+ # Defaults.
+ relative = 1
+ override = {}
+ # The original concept of the `exampleindent' option is broken.
+ # It is not possible to get a sane value for @exampleindent at all
+ # without processing the document itself. Saying
+ #
+ # @exampleindent 0
+ # @example
+ # ...
+ # @end example
+ # @exampleindent 5
+ #
+ # causes ugly results with the DVI backend of texinfo since the
+ # default value for @exampleindent isn't 5em but 0.4in (or a smaller
+ # value). Executing the above code changes the environment
+ # indentation to an unknown value because we don't know the amount
+ # of 1em in advance since it is font-dependent. Modifying
+ # @exampleindent in the middle of a document is simply not
+ # supported within texinfo.
+ #
+ # As a consequence, the only function of @exampleindent is now to
+ # specify the amount of indentation for the `quote' option.
+ #
+ # To set @exampleindent locally to zero, we use the @format
+ # environment for non-quoted snippets.
+ override[EXAMPLEINDENT] = r'0.4\in'
+ override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
+ override.update (default_ly_options)
+
+ option_list = []
+ for (key, value) in self.option_dict.items ():
+ if value == None:
+ option_list.append (key)
+ else:
+ option_list.append (key + '=' + value)
+ option_string = string.join (option_list, ',')
+
+ compose_dict = {}
+ compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
+ for a in compose_types:
+ compose_dict[a] = []
+
+ for (key, value) in self.option_dict.items ():
+ (c_key, c_value) = \
+ classic_lilypond_book_compatibility (key, value)
+ if c_key:
+ if c_value:
+ warning \
+ (_ ("deprecated ly-option used: %s=%s" \
+ % (key, value)))
+ warning \
+ (_ ("compatibility mode translation: %s=%s" \
+ % (c_key, c_value)))
+ else:
+ warning \
+ (_ ("deprecated ly-option used: %s" \
+ % key))
+ warning \
+ (_ ("compatibility mode translation: %s" \
+ % c_key))
+
+ (key, value) = (c_key, c_value)
+
+ if value:
+ override[key] = value
+ else:
+ if not override.has_key (key):
+ override[key] = None
+
+ found = 0
+ for type in compose_types:
+ if ly_options[type].has_key (key):
+ compose_dict[type].append (ly_options[type][key])
+ found = 1
+ break
+
+ if not found and key not in simple_options:
+ warning (_ ("ignoring unknown ly option: %s") % key)
+
+ # URGS
+ if RELATIVE in override.keys () and override[RELATIVE]:
+ relative = int (override[RELATIVE])
+
+ relative_quotes = ''
+
+ # 1 = central C
+ if relative < 0:
+ relative_quotes += ',' * (- relative)
+ elif relative > 0:
+ relative_quotes += "'" * relative
+
+ paper_string = string.join (compose_dict[PAPER],
+ '\n ') % override
+ layout_string = string.join (compose_dict[LAYOUT],
+ '\n ') % override
+ notes_string = string.join (compose_dict[NOTES],
+ '\n ') % vars ()
+ preamble_string = string.join (compose_dict[PREAMBLE],
+ '\n ') % override
+
+ font_dump_setting = ''
+ if FONTLOAD in self.option_dict:
+ font_dump_setting = '#(define-public force-eps-font-include #t)\n'
+
+ d = globals().copy()
+ d.update (locals())
+ return (PREAMBLE_LY + body) % d
+
+ # TODO: Use md5?
+ def get_hash (self):
+ if not self.hash:
+ self.hash = abs (hash (self.full_ly ()))
+ return self.hash
+
+ def basename (self):
+ if FILENAME in self.option_dict:
+ return self.option_dict[FILENAME]
+ if global_options.use_hash:
+ return 'lily-%d' % self.get_hash ()
+ raise 'to be done'
+
+ def write_ly (self):
+ outf = open (self.basename () + '.ly', 'w')
+ outf.write (self.full_ly ())
+
+ open (self.basename () + '.txt', 'w').write ('image of music')
+
+ def ly_is_outdated (self):
+ base = self.basename ()
+
+ tex_file = '%s.tex' % base
+ eps_file = '%s.eps' % base
+ system_file = '%s-systems.tex' % base
+ ly_file = '%s.ly' % base
+ ok = os.path.exists (ly_file) \
+ and os.path.exists (system_file)\
+ and os.stat (system_file)[stat.ST_SIZE] \
+ and re.match ('% eof', open (system_file).readlines ()[-1])
+ if ok and (not global_options.use_hash or FILENAME in self.option_dict):
+ ok = (self.full_ly () == open (ly_file).read ())
+ if ok:
+ # TODO: Do something smart with target formats
+ # (ps, png) and m/ctimes.
+ return None
+ return self
+
+ def png_is_outdated (self):
+ base = self.basename ()
+ ok = self.ly_is_outdated ()
+ if global_options.format in (HTML, TEXINFO):
+ ok = ok and os.path.exists (base + '.eps')
+
+ page_count = 0
+ if ok:
+ page_count = ps_page_count (base + '.eps')
+
+ if page_count == 1:
+ ok = ok and os.path.exists (base + '.png')
+ elif page_count > 1:
+ for a in range (1, page_count + 1):
+ ok = ok and os.path.exists (base + '-page%d.png' % a)
+
+ return not ok
+
+ def texstr_is_outdated (self):
+ if backend == 'ps':
+ return 0
+
+ base = self.basename ()
+ ok = self.ly_is_outdated ()
+ ok = ok and (os.path.exists (base + '.texstr'))
+ return not ok
+
+ def filter_text (self):
+ code = self.substring ('code')
+ s = run_filter (code)
+ d = {
+ 'code': s,
+ 'options': self.match.group ('options')
+ }
+ # TODO
+ return output[self.format][FILTER] % d
+
+ def replacement_text (self):
+ func = Lilypond_snippet.__dict__['output_' + self.format]
+ return func (self)
+
+ def get_images (self):
+ base = self.basename ()
+ # URGUGHUGHUGUGH
+ single = '%(base)s.png' % vars ()
+ multiple = '%(base)s-page1.png' % vars ()
+ images = (single,)
+ if os.path.exists (multiple) \
+ and (not os.path.exists (single) \
+ or (os.stat (multiple)[stat.ST_MTIME] \
+ > os.stat (single)[stat.ST_MTIME])):
+ count = ps_page_count ('%(base)s.eps' % vars ())
+ images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
+ images = tuple (images)
+ return images
+
+ def output_html (self):
+ str = ''
+ base = self.basename ()
+ if global_options.format == HTML:
+ str += self.output_print_filename (HTML)
+ if VERBATIM in self.option_dict:
+ verb = verbatim_html (self.substring ('code'))
+ str += output[HTML][VERBATIM] % vars ()
+ if QUOTE in self.option_dict:
+ str = output[HTML][QUOTE] % vars ()
+
+ str += output[HTML][BEFORE] % vars ()
+ for image in self.get_images ():
+ (base, ext) = os.path.splitext (image)
+ alt = self.option_dict[ALT]
+ str += output[HTML][OUTPUT] % vars ()
+ str += output[HTML][AFTER] % vars ()
+ return str
+
+ def output_info (self):
+ str = ''
+ for image in self.get_images ():
+ (base, ext) = os.path.splitext (image)
+
+ # URG, makeinfo implicitly prepends dot to extension.
+ # Specifying no extension is most robust.
+ ext = ''
+ alt = self.option_dict[ALT]
+ str += output[TEXINFO][OUTPUTIMAGE] % vars ()
+
+ base = self.basename ()
+ str += output[global_options.format][OUTPUT] % vars ()
+ return str
+
+ def output_latex (self):
+ str = ''
+ base = self.basename ()
+ if global_options.format == LATEX:
+ str += self.output_print_filename (LATEX)
+ if VERBATIM in self.option_dict:
+ verb = self.substring ('code')
+ str += (output[LATEX][VERBATIM] % vars ())
+
+ str += (output[LATEX][OUTPUT] % vars ())
+
+ ## todo: maintain breaks
+ if 0:
+ breaks = self.ly ().count ("\n")
+ str += "".ljust (breaks, "\n").replace ("\n","%\n")
+
+ if QUOTE in self.option_dict:
+ str = output[LATEX][QUOTE] % vars ()
+ return str
+
+ def output_print_filename (self, format):
+ str = ''
+ if PRINTFILENAME in self.option_dict:
+ base = self.basename ()
+ filename = self.substring ('filename')
+ str = output[global_options.format][PRINTFILENAME] % vars ()
+
+ return str
+
+ def output_texinfo (self):
+ str = ''
+ if self.output_print_filename (TEXINFO):
+ str += ('@html\n'
+ + self.output_print_filename (HTML)
+ + '\n@end html\n')
+ str += ('@tex\n'
+ + self.output_print_filename (LATEX)
+ + '\n@end tex\n')
+ base = self.basename ()
+ if TEXIDOC in self.option_dict:
+ texidoc = base + '.texidoc'
+ if os.path.exists (texidoc):
+ str += '@include %(texidoc)s\n\n' % vars ()
+
+ if VERBATIM in self.option_dict:
+ verb = self.substring ('code')
+ str += (output[TEXINFO][VERBATIM] % vars ())
+ if not QUOTE in self.option_dict:
+ str = output[TEXINFO][NOQUOTE] % vars ()
+
+ str += self.output_info ()
+
+# str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
+# str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
+# str += ('@html\n' + self.output_html () + '\n@end html\n')
+
+ if QUOTE in self.option_dict:
+ str = output[TEXINFO][QUOTE] % vars ()
+
+ # need par after image
+ str += '\n'
+
+ return str
class Lilypond_file_snippet (Lilypond_snippet):
- def ly (self):
- name = self.substring ('filename')
- return '\\sourcefilename \"%s\"\n%s' \
- % (name, open (find_file (name)).read ())
+ def ly (self):
+ name = self.substring ('filename')
+ return '\\sourcefilename \"%s\"\n%s' \
+ % (name, open (find_file (name)).read ())
snippet_type_to_class = {
- 'lilypond_file': Lilypond_file_snippet,
- 'lilypond_block': Lilypond_snippet,
- 'lilypond': Lilypond_snippet,
- 'include': Include_snippet,
+ 'lilypond_file': Lilypond_file_snippet,
+ 'lilypond_block': Lilypond_snippet,
+ 'lilypond': Lilypond_snippet,
+ 'include': Include_snippet,
}
def find_linestarts (s):
- nls = [0]
- start = 0
- end = len (s)
- while 1:
- i = s.find ('\n', start)
- if i < 0:
- break
+ nls = [0]
+ start = 0
+ end = len (s)
+ while 1:
+ i = s.find ('\n', start)
+ if i < 0:
+ break
- i = i + 1
- nls.append (i)
- start = i
+ i = i + 1
+ nls.append (i)
+ start = i
- nls.append (len (s))
- return nls
+ nls.append (len (s))
+ return nls
def find_toplevel_snippets (s, types):
- res = {}
- for i in types:
- res[i] = ly.re.compile (snippet_res[global_options.format][i])
-
- snippets = []
- index = 0
- ## found = dict (map (lambda x: (x, None),
- ## types))
- ## urg python2.1
- found = {}
- map (lambda x, f = found: f.setdefault (x, None),
- types)
-
- line_starts = find_linestarts (s)
- line_start_idx = 0
- # We want to search for multiple regexes, without searching
- # the string multiple times for one regex.
- # Hence, we use earlier results to limit the string portion
- # where we search.
- # Since every part of the string is traversed at most once for
- # every type of snippet, this is linear.
-
- while 1:
- first = None
- endex = 1 << 30
- for type in types:
- if not found[type] or found[type][0] < index:
- found[type] = None
-
- m = res[type].search (s[index:endex])
- if not m:
- continue
-
- cl = Snippet
- if snippet_type_to_class.has_key (type):
- cl = snippet_type_to_class[type]
-
-
- start = index + m.start ('match')
- line_number = line_start_idx
- while (line_starts[line_number] < start):
- line_number += 1
-
- line_number += 1
- snip = cl (type, m, global_options.format, line_number)
-
- found[type] = (start, snip)
-
- if found[type] \
- and (not first \
- or found[type][0] < found[first][0]):
- first = type
-
- # FIXME.
-
- # Limiting the search space is a cute
- # idea, but this *requires* to search
- # for possible containing blocks
- # first, at least as long as we do not
- # search for the start of blocks, but
- # always/directly for the entire
- # @block ... @end block.
-
- endex = found[first][0]
-
- if not first:
- snippets.append (Substring (s, index, len (s), line_start_idx))
- break
-
- while (start > line_starts[line_start_idx+1]):
- line_start_idx += 1
-
- (start, snip) = found[first]
- snippets.append (Substring (s, index, start, line_start_idx + 1))
- snippets.append (snip)
- found[first] = None
- index = start + len (snip.match.group ('match'))
-
- return snippets
+ res = {}
+ for i in types:
+ res[i] = ly.re.compile (snippet_res[global_options.format][i])
+
+ snippets = []
+ index = 0
+ ## found = dict (map (lambda x: (x, None),
+ ## types))
+ ## urg python2.1
+ found = {}
+ map (lambda x, f = found: f.setdefault (x, None),
+ types)
+
+ line_starts = find_linestarts (s)
+ line_start_idx = 0
+ # We want to search for multiple regexes, without searching
+ # the string multiple times for one regex.
+ # Hence, we use earlier results to limit the string portion
+ # where we search.
+ # Since every part of the string is traversed at most once for
+ # every type of snippet, this is linear.
+
+ while 1:
+ first = None
+ endex = 1 << 30
+ for type in types:
+ if not found[type] or found[type][0] < index:
+ found[type] = None
+
+ m = res[type].search (s[index:endex])
+ if not m:
+ continue
+
+ cl = Snippet
+ if snippet_type_to_class.has_key (type):
+ cl = snippet_type_to_class[type]
+
+
+ start = index + m.start ('match')
+ line_number = line_start_idx
+ while (line_starts[line_number] < start):
+ line_number += 1
+
+ line_number += 1
+ snip = cl (type, m, global_options.format, line_number)
+
+ found[type] = (start, snip)
+
+ if found[type] \
+ and (not first \
+ or found[type][0] < found[first][0]):
+ first = type
+
+ # FIXME.
+
+ # Limiting the search space is a cute
+ # idea, but this *requires* to search
+ # for possible containing blocks
+ # first, at least as long as we do not
+ # search for the start of blocks, but
+ # always/directly for the entire
+ # @block ... @end block.
+
+ endex = found[first][0]
+
+ if not first:
+ snippets.append (Substring (s, index, len (s), line_start_idx))
+ break
+
+ while (start > line_starts[line_start_idx+1]):
+ line_start_idx += 1
+
+ (start, snip) = found[first]
+ snippets.append (Substring (s, index, start, line_start_idx + 1))
+ snippets.append (snip)
+ found[first] = None
+ index = start + len (snip.match.group ('match'))
+
+ return snippets
def filter_pipe (input, cmd):
- if global_options.verbose:
- progress (_ ("Opening filter `%s'") % cmd)
-
- (stdin, stdout, stderr) = os.popen3 (cmd)
- stdin.write (input)
- status = stdin.close ()
-
- if not status:
- status = 0
- output = stdout.read ()
- status = stdout.close ()
- error = stderr.read ()
-
- if not status:
- status = 0
- signal = 0x0f & status
- if status or (not output and error):
- exit_status = status >> 8
- error (_ ("`%s' failed (%d)") % (cmd, exit_status))
- error (_ ("The error log is as follows:"))
- sys.stderr.write (error)
- sys.stderr.write (stderr.read ())
- exit (status)
-
- if global_options.verbose:
- progress ('\n')
-
- return output
+ if global_options.verbose:
+ progress (_ ("Opening filter `%s'") % cmd)
+
+ (stdin, stdout, stderr) = os.popen3 (cmd)
+ stdin.write (input)
+ status = stdin.close ()
+
+ if not status:
+ status = 0
+ output = stdout.read ()
+ status = stdout.close ()
+ error = stderr.read ()
+
+ if not status:
+ status = 0
+ signal = 0x0f & status
+ if status or (not output and error):
+ exit_status = status >> 8
+ error (_ ("`%s' failed (%d)") % (cmd, exit_status))
+ error (_ ("The error log is as follows:"))
+ sys.stderr.write (error)
+ sys.stderr.write (stderr.read ())
+ exit (status)
+
+ if global_options.verbose:
+ progress ('\n')
+
+ return output
def run_filter (s):
- return filter_pipe (s, global_options.filter_cmd)
+ return filter_pipe (s, global_options.filter_cmd)
def is_derived_class (cl, baseclass):
- if cl == baseclass:
- return 1
- for b in cl.__bases__:
- if is_derived_class (b, baseclass):
- return 1
- return 0
+ if cl == baseclass:
+ return 1
+ for b in cl.__bases__:
+ if is_derived_class (b, baseclass):
+ return 1
+ return 0
def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
- ly_names = filter (lambda x: x,
- map (Lilypond_snippet.basename, ly_snippets))
- texstr_names = filter (lambda x: x,
- map (Lilypond_snippet.basename, texstr_snippets))
- png_names = filter (lambda x: x,
- map (Lilypond_snippet.basename, png_snippets))
-
- status = 0
- def my_system (cmd):
- status = ly.system (cmd,
- be_verbose=global_options.verbose,
- progress_p= 1)
-
- # UGH
- # the --process=CMD switch is a bad idea
- # it is too generic for lilypond-book.
- if texstr_names:
- my_system (string.join ([cmd, '--backend texstr',
- 'snippet-map.ly'] + texstr_names))
- for l in texstr_names:
- my_system ('latex %s.texstr' % l)
-
- if ly_names:
- my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
+ ly_names = filter (lambda x: x,
+ map (Lilypond_snippet.basename, ly_snippets))
+ texstr_names = filter (lambda x: x,
+ map (Lilypond_snippet.basename, texstr_snippets))
+ png_names = filter (lambda x: x,
+ map (Lilypond_snippet.basename, png_snippets))
+
+ status = 0
+ def my_system (cmd):
+ status = ly.system (cmd,
+ be_verbose=global_options.verbose,
+ progress_p= 1)
+
+ # UGH
+ # the --process=CMD switch is a bad idea
+ # it is too generic for lilypond-book.
+ if texstr_names:
+ my_system (string.join ([cmd, '--backend texstr',
+ 'snippet-map.ly'] + texstr_names))
+ for l in texstr_names:
+ my_system ('latex %s.texstr' % l)
+
+ if ly_names:
+ my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
LATEX_INSPECTION_DOCUMENT = r'''
\nonstopmode
@@ -1409,368 +1409,368 @@ LATEX_INSPECTION_DOCUMENT = r'''
# Do we need anything else besides `textwidth'?
def get_latex_textwidth (source):
- m = re.search (r'''(?P\\begin\s*{document})''', source)
- if m == None:
- warning (_ ("Can't find \\begin{document} in LaTeX document"))
-
- ## what's a sensible default?
- return 550.0
-
- preamble = source[:m.start (0)]
- latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
-
- (handle, tmpfile) = tempfile.mkstemp('.tex')
- logfile = os.path.splitext (tmpfile)[0] + '.log'
- logfile = os.path.split (logfile)[1]
-
- tmp_handle = os.fdopen (handle,'w')
- tmp_handle.write (latex_document)
- tmp_handle.close ()
-
- ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
- parameter_string = open (logfile).read()
-
- os.unlink (tmpfile)
- os.unlink (logfile)
-
- columns = 0
- m = re.search ('columns=([0-9.]*)', parameter_string)
- if m:
- columns = int (m.group (1))
-
- columnsep = 0
- m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
- if m:
- columnsep = float (m.group (1))
-
- textwidth = 0
- m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
- if m:
- textwidth = float (m.group (1))
- if columns:
- textwidth = (textwidth - columnsep) / columns
-
- return textwidth
+ m = re.search (r'''(?P\\begin\s*{document})''', source)
+ if m == None:
+ warning (_ ("Can't find \\begin{document} in LaTeX document"))
+
+ ## what's a sensible default?
+ return 550.0
+
+ preamble = source[:m.start (0)]
+ latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
+
+ (handle, tmpfile) = tempfile.mkstemp('.tex')
+ logfile = os.path.splitext (tmpfile)[0] + '.log'
+ logfile = os.path.split (logfile)[1]
+
+ tmp_handle = os.fdopen (handle,'w')
+ tmp_handle.write (latex_document)
+ tmp_handle.close ()
+
+ ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
+ parameter_string = open (logfile).read()
+
+ os.unlink (tmpfile)
+ os.unlink (logfile)
+
+ columns = 0
+ m = re.search ('columns=([0-9.]*)', parameter_string)
+ if m:
+ columns = int (m.group (1))
+
+ columnsep = 0
+ m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
+ if m:
+ columnsep = float (m.group (1))
+
+ textwidth = 0
+ m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
+ if m:
+ textwidth = float (m.group (1))
+ if columns:
+ textwidth = (textwidth - columnsep) / columns
+
+ return textwidth
def modify_preamble (chunk):
- str = chunk.replacement_text ()
- if (re.search (r"\\begin *{document}", str)
- and not re.search ("{graphic[sx]", str)):
- str = re.sub (r"\\begin{document}",
- r"\\usepackage{graphics}" + '\n'
- + r"\\begin{document}",
- str)
- chunk.override_text = str
-
-
+ str = chunk.replacement_text ()
+ if (re.search (r"\\begin *{document}", str)
+ and not re.search ("{graphic[sx]", str)):
+ str = re.sub (r"\\begin{document}",
+ r"\\usepackage{graphics}" + '\n'
+ + r"\\begin{document}",
+ str)
+ chunk.override_text = str
+
+
ext2format = {
- '.html': HTML,
- '.itely': TEXINFO,
- '.latex': LATEX,
- '.lytex': LATEX,
- '.tely': TEXINFO,
- '.tex': LATEX,
- '.texi': TEXINFO,
- '.texinfo': TEXINFO,
- '.xml': HTML,
+ '.html': HTML,
+ '.itely': TEXINFO,
+ '.latex': LATEX,
+ '.lytex': LATEX,
+ '.tely': TEXINFO,
+ '.tex': LATEX,
+ '.texi': TEXINFO,
+ '.texinfo': TEXINFO,
+ '.xml': HTML,
}
format2ext = {
- HTML: '.html',
- # TEXINFO: '.texinfo',
- TEXINFO: '.texi',
- LATEX: '.tex',
+ HTML: '.html',
+ # TEXINFO: '.texinfo',
+ TEXINFO: '.texi',
+ LATEX: '.tex',
}
class Compile_error:
- pass
+ pass
def write_file_map (lys, name):
- snippet_map = open ('snippet-map.ly', 'w')
- snippet_map.write ("""
+ snippet_map = open ('snippet-map.ly', 'w')
+ snippet_map.write ("""
#(define version-seen? #t)
#(ly:add-file-name-alist '(
""")
- for ly in lys:
- snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
- % (ly.basename (),
- name,
- ly.line_number,
- ly.basename ()))
+ for ly in lys:
+ snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
+ % (ly.basename (),
+ name,
+ ly.line_number,
+ ly.basename ()))
- snippet_map.write ('))\n')
+ snippet_map.write ('))\n')
def do_process_cmd (chunks, input_name):
- all_lys = filter (lambda x: is_derived_class (x.__class__,
- Lilypond_snippet),
- chunks)
-
- write_file_map (all_lys, input_name)
- ly_outdated = \
- filter (lambda x: is_derived_class (x.__class__,
- Lilypond_snippet)
- and x.ly_is_outdated (),
- chunks)
- texstr_outdated = \
- filter (lambda x: is_derived_class (x.__class__,
- Lilypond_snippet)
- and x.texstr_is_outdated (),
- chunks)
- png_outdated = \
- filter (lambda x: is_derived_class (x.__class__,
- Lilypond_snippet)
- and x.png_is_outdated (),
- chunks)
-
- progress (_ ("Writing snippets..."))
- map (Lilypond_snippet.write_ly, ly_outdated)
- progress ('\n')
-
- if ly_outdated:
- progress (_ ("Processing..."))
- progress ('\n')
- process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
- else:
- progress (_ ("All snippets are up to date..."))
- progress ('\n')
+ all_lys = filter (lambda x: is_derived_class (x.__class__,
+ Lilypond_snippet),
+ chunks)
+
+ write_file_map (all_lys, input_name)
+ ly_outdated = \
+ filter (lambda x: is_derived_class (x.__class__,
+ Lilypond_snippet)
+ and x.ly_is_outdated (),
+ chunks)
+ texstr_outdated = \
+ filter (lambda x: is_derived_class (x.__class__,
+ Lilypond_snippet)
+ and x.texstr_is_outdated (),
+ chunks)
+ png_outdated = \
+ filter (lambda x: is_derived_class (x.__class__,
+ Lilypond_snippet)
+ and x.png_is_outdated (),
+ chunks)
+
+ progress (_ ("Writing snippets..."))
+ map (Lilypond_snippet.write_ly, ly_outdated)
+ progress ('\n')
+
+ if ly_outdated:
+ progress (_ ("Processing..."))
+ progress ('\n')
+ process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
+ else:
+ progress (_ ("All snippets are up to date..."))
+ progress ('\n')
def guess_format (input_filename):
- format = None
- e = os.path.splitext (input_filename)[1]
- if e in ext2format.keys ():
- # FIXME
- format = ext2format[e]
- else:
- error (_ ("can't determine format for: %s" \
- % input_filename))
- exit (1)
- return format
+ format = None
+ e = os.path.splitext (input_filename)[1]
+ if e in ext2format.keys ():
+ # FIXME
+ format = ext2format[e]
+ else:
+ error (_ ("can't determine format for: %s" \
+ % input_filename))
+ exit (1)
+ return format
def write_if_updated (file_name, lines):
- try:
- f = open (file_name)
- oldstr = f.read ()
- new_str = string.join (lines, '')
- if oldstr == new_str:
- progress (_ ("%s is up to date.") % file_name)
- progress ('\n')
- return
- except:
- pass
-
- progress (_ ("Writing `%s'...") % file_name)
- open (file_name, 'w').writelines (lines)
- progress ('\n')
+ try:
+ f = open (file_name)
+ oldstr = f.read ()
+ new_str = string.join (lines, '')
+ if oldstr == new_str:
+ progress (_ ("%s is up to date.") % file_name)
+ progress ('\n')
+ return
+ except:
+ pass
+
+ progress (_ ("Writing `%s'...") % file_name)
+ open (file_name, 'w').writelines (lines)
+ progress ('\n')
def note_input_file (name, inputs=[]):
- ## hack: inputs is mutable!
- inputs.append (name)
- return inputs
+ ## hack: inputs is mutable!
+ inputs.append (name)
+ return inputs
def samefile (f1, f2):
- try:
- return os.path.samefile (f1, f2)
- except AttributeError: # Windoze
- f1 = re.sub ("//*", "/", f1)
- f2 = re.sub ("//*", "/", f2)
- return f1 == f2
+ try:
+ return os.path.samefile (f1, f2)
+ except AttributeError: # Windoze
+ f1 = re.sub ("//*", "/", f1)
+ f2 = re.sub ("//*", "/", f2)
+ return f1 == f2
def do_file (input_filename):
- # Ugh.
- if not input_filename or input_filename == '-':
- in_handle = sys.stdin
- input_fullname = ''
- else:
- if os.path.exists (input_filename):
- input_fullname = input_filename
- elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
- input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
- else:
- input_fullname = find_file (input_filename)
-
- note_input_file (input_fullname)
- in_handle = open (input_fullname)
-
- if input_filename == '-':
- input_base = 'stdin'
- else:
- input_base = os.path.basename \
- (os.path.splitext (input_filename)[0])
-
- # Only default to stdout when filtering.
- if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
- output_filename = '-'
- output_file = sys.stdout
- else:
- # don't complain when global_options.output_name is existing
- output_filename = input_base + format2ext[global_options.format]
- if global_options.output_name:
- if not os.path.isdir (global_options.output_name):
- os.mkdir (global_options.output_name, 0777)
- os.chdir (global_options.output_name)
- else:
- if os.path.exists (input_filename) \
- and os.path.exists (output_filename) \
- and samefile (output_filename, input_fullname):
- error (
- _ ("Output would overwrite input file; use --output."))
- exit (2)
-
- try:
- progress (_ ("Reading %s...") % input_fullname)
- source = in_handle.read ()
- progress ('\n')
-
- set_default_options (source)
-
-
- # FIXME: Containing blocks must be first, see
- # find_toplevel_snippets.
- snippet_types = (
- 'multiline_comment',
- 'verbatim',
- 'lilypond_block',
- # 'verb',
- 'singleline_comment',
- 'lilypond_file',
- 'include',
- 'lilypond',
- )
- progress (_ ("Dissecting..."))
- chunks = find_toplevel_snippets (source, snippet_types)
-
- if global_options.format == LATEX:
- for c in chunks:
- if (c.is_plain () and
- re.search (r"\\begin *{document}", c.replacement_text())):
- modify_preamble (c)
- break
- progress ('\n')
-
- if global_options.filter_cmd:
- write_if_updated (output_filename,
- [c.filter_text () for c in chunks])
- elif global_options.process_cmd:
- do_process_cmd (chunks, input_fullname)
- progress (_ ("Compiling %s...") % output_filename)
- progress ('\n')
- write_if_updated (output_filename,
- [s.replacement_text ()
- for s in chunks])
-
- def process_include (snippet):
- os.chdir (original_dir)
- name = snippet.substring ('filename')
- progress (_ ("Processing include: %s") % name)
- progress ('\n')
- return do_file (name)
-
- include_chunks = map (process_include,
- filter (lambda x: is_derived_class (x.__class__,
- Include_snippet),
- chunks))
-
-
- return chunks + reduce (lambda x,y: x + y, include_chunks, [])
-
- except Compile_error:
- os.chdir (original_dir)
- progress (_ ("Removing `%s'") % output_filename)
- progress ('\n')
- raise Compile_error
+ # Ugh.
+ if not input_filename or input_filename == '-':
+ in_handle = sys.stdin
+ input_fullname = ''
+ else:
+ if os.path.exists (input_filename):
+ input_fullname = input_filename
+ elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
+ input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
+ else:
+ input_fullname = find_file (input_filename)
+
+ note_input_file (input_fullname)
+ in_handle = open (input_fullname)
+
+ if input_filename == '-':
+ input_base = 'stdin'
+ else:
+ input_base = os.path.basename \
+ (os.path.splitext (input_filename)[0])
+
+ # Only default to stdout when filtering.
+ if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
+ output_filename = '-'
+ output_file = sys.stdout
+ else:
+ # don't complain when global_options.output_name is existing
+ output_filename = input_base + format2ext[global_options.format]
+ if global_options.output_name:
+ if not os.path.isdir (global_options.output_name):
+ os.mkdir (global_options.output_name, 0777)
+ os.chdir (global_options.output_name)
+ else:
+ if os.path.exists (input_filename) \
+ and os.path.exists (output_filename) \
+ and samefile (output_filename, input_fullname):
+ error (
+ _ ("Output would overwrite input file; use --output."))
+ exit (2)
+
+ try:
+ progress (_ ("Reading %s...") % input_fullname)
+ source = in_handle.read ()
+ progress ('\n')
+
+ set_default_options (source)
+
+
+ # FIXME: Containing blocks must be first, see
+ # find_toplevel_snippets.
+ snippet_types = (
+ 'multiline_comment',
+ 'verbatim',
+ 'lilypond_block',
+ # 'verb',
+ 'singleline_comment',
+ 'lilypond_file',
+ 'include',
+ 'lilypond',
+ )
+ progress (_ ("Dissecting..."))
+ chunks = find_toplevel_snippets (source, snippet_types)
+
+ if global_options.format == LATEX:
+ for c in chunks:
+ if (c.is_plain () and
+ re.search (r"\\begin *{document}", c.replacement_text())):
+ modify_preamble (c)
+ break
+ progress ('\n')
+
+ if global_options.filter_cmd:
+ write_if_updated (output_filename,
+ [c.filter_text () for c in chunks])
+ elif global_options.process_cmd:
+ do_process_cmd (chunks, input_fullname)
+ progress (_ ("Compiling %s...") % output_filename)
+ progress ('\n')
+ write_if_updated (output_filename,
+ [s.replacement_text ()
+ for s in chunks])
+
+ def process_include (snippet):
+ os.chdir (original_dir)
+ name = snippet.substring ('filename')
+ progress (_ ("Processing include: %s") % name)
+ progress ('\n')
+ return do_file (name)
+
+ include_chunks = map (process_include,
+ filter (lambda x: is_derived_class (x.__class__,
+ Include_snippet),
+ chunks))
+
+
+ return chunks + reduce (lambda x,y: x + y, include_chunks, [])
+
+ except Compile_error:
+ os.chdir (original_dir)
+ progress (_ ("Removing `%s'") % output_filename)
+ progress ('\n')
+ raise Compile_error
def do_options ():
- global global_options
+ global global_options
- opt_parser = get_option_parser()
- (global_options, args) = opt_parser.parse_args ()
+ opt_parser = get_option_parser()
+ (global_options, args) = opt_parser.parse_args ()
- if global_options.format in ('texi-html', 'texi'):
- global_options.format = TEXINFO
- global_options.use_hash = True
+ if global_options.format in ('texi-html', 'texi'):
+ global_options.format = TEXINFO
+ global_options.use_hash = True
- global_options.include_path = map (os.path.abspath, global_options.include_path)
-
- if global_options.warranty:
- warranty ()
- exit (0)
- if not args or len (args) > 1:
- opt_parser.print_help ()
- exit (2)
-
- return args
+ global_options.include_path = map (os.path.abspath, global_options.include_path)
+
+ if global_options.warranty:
+ warranty ()
+ exit (0)
+ if not args or len (args) > 1:
+ opt_parser.print_help ()
+ exit (2)
+
+ return args
def main ():
- files = do_options ()
-
- file = files[0]
-
- basename = os.path.splitext (file)[0]
- basename = os.path.split (basename)[1]
-
- if not global_options.format:
- global_options.format = guess_format (files[0])
-
- formats = 'ps'
- if global_options.format in (TEXINFO, HTML):
- formats += ',png'
- if global_options.process_cmd == '':
- global_options.process_cmd = lilypond_binary \
- + ' --formats=%s --backend eps ' % formats
-
- if global_options.process_cmd:
- global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
- for p in global_options.include_path])
-
- identify ()
-
- try:
- chunks = do_file (file)
- if global_options.psfonts:
- fontextract.verbose = global_options.verbose
- snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
- Lilypond_snippet),
- chunks)
-
- psfonts_file = basename + '.psfonts'
- if not global_options.verbose:
- progress (_ ("Writing fonts to %s...") % psfonts_file)
- fontextract.extract_fonts (psfonts_file,
- [x.basename() + '.eps'
- for x in snippet_chunks])
- if not global_options.verbose:
- progress ('\n')
-
- except Compile_error:
- exit (1)
-
- if global_options.format in (TEXINFO, LATEX):
- if not global_options.psfonts:
- warning (_ ("option --psfonts not used"))
- warning (_ ("processing with dvips will have no fonts"))
-
- psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
- output = os.path.join (global_options.output_name, basename + '.dvi' )
-
- progress ('\n')
- progress (_ ("DVIPS usage:"))
- progress ('\n')
- progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
- progress ('\n')
-
- inputs = note_input_file ('')
- inputs.pop ()
-
- base_file_name = os.path.splitext (os.path.basename (file))[0]
- dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
- final_output_file = os.path.join (global_options.output_name,
- base_file_name
- + '.%s' % global_options.format)
-
- os.chdir (original_dir)
- open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
+ files = do_options ()
+
+ file = files[0]
+
+ basename = os.path.splitext (file)[0]
+ basename = os.path.split (basename)[1]
+
+ if not global_options.format:
+ global_options.format = guess_format (files[0])
+
+ formats = 'ps'
+ if global_options.format in (TEXINFO, HTML):
+ formats += ',png'
+ if global_options.process_cmd == '':
+ global_options.process_cmd = lilypond_binary \
+ + ' --formats=%s --backend eps ' % formats
+
+ if global_options.process_cmd:
+ global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
+ for p in global_options.include_path])
+
+ identify ()
+
+ try:
+ chunks = do_file (file)
+ if global_options.psfonts:
+ fontextract.verbose = global_options.verbose
+ snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
+ Lilypond_snippet),
+ chunks)
+
+ psfonts_file = basename + '.psfonts'
+ if not global_options.verbose:
+ progress (_ ("Writing fonts to %s...") % psfonts_file)
+ fontextract.extract_fonts (psfonts_file,
+ [x.basename() + '.eps'
+ for x in snippet_chunks])
+ if not global_options.verbose:
+ progress ('\n')
+
+ except Compile_error:
+ exit (1)
+
+ if global_options.format in (TEXINFO, LATEX):
+ if not global_options.psfonts:
+ warning (_ ("option --psfonts not used"))
+ warning (_ ("processing with dvips will have no fonts"))
+
+ psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
+ output = os.path.join (global_options.output_name, basename + '.dvi' )
+
+ progress ('\n')
+ progress (_ ("DVIPS usage:"))
+ progress ('\n')
+ progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
+ progress ('\n')
+
+ inputs = note_input_file ('')
+ inputs.pop ()
+
+ base_file_name = os.path.splitext (os.path.basename (file))[0]
+ dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
+ final_output_file = os.path.join (global_options.output_name,
+ base_file_name
+ + '.%s' % global_options.format)
+
+ os.chdir (original_dir)
+ open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
if __name__ == '__main__':
- main ()
+ main ()
diff --git a/scripts/midi2ly.py b/scripts/midi2ly.py
index c61cce84ed..a3b53d8fa2 100644
--- a/scripts/midi2ly.py
+++ b/scripts/midi2ly.py
@@ -10,15 +10,15 @@
'''
TODO:
- * test on weird and unquantised midi input (lily-devel)
- * update doc and manpage
-
- * simply insert clef changes whenever too many ledger lines
- [to avoid tex capacity exceeded]
- * do not ever quant skips
- * better lyrics handling
- * [see if it is feasible to] move ly-classes to library for use in
- other converters, while leaving midi specific stuff here
+ * test on weird and unquantised midi input (lily-devel)
+ * update doc and manpage
+
+ * simply insert clef changes whenever too many ledger lines
+ [to avoid tex capacity exceeded]
+ * do not ever quant skips
+ * better lyrics handling
+ * [see if it is feasible to] move ly-classes to library for use in
+ other converters, while leaving midi specific stuff here
'''
import os
@@ -31,21 +31,21 @@ import sys
#
libdir = '@local_lilypond_libdir@'
if not os.path.isdir (libdir):
- libdir = '@lilypond_libdir@'
+ libdir = '@lilypond_libdir@'
# ugh
datadir = '@local_lilypond_datadir@'
if os.environ.has_key ('LILYPONDPREFIX'):
- datadir = os.environ['LILYPONDPREFIX']
- while datadir[-1] == os.sep:
- datadir= datadir[:-1]
- libdir = datadir.replace ('/share/', '/lib/')
+ datadir = os.environ['LILYPONDPREFIX']
+ while datadir[-1] == os.sep:
+ datadir= datadir[:-1]
+ libdir = datadir.replace ('/share/', '/lib/')
if os.path.exists (os.path.join (datadir, 'lib/lilypond/@TOPLEVEL_VERSION@/')):
- libdir = os.path.join (libdir, 'lib/lilypond/@TOPLEVEL_VERSION@/')
+ libdir = os.path.join (libdir, 'lib/lilypond/@TOPLEVEL_VERSION@/')
if os.path.exists (os.path.join (datadir, 'lib/lilypond/current/')):
- libdir = os.path.join (libdir, 'lib/lilypond/current/')
+ libdir = os.path.join (libdir, 'lib/lilypond/current/')
sys.path.insert (0, os.path.join (libdir, 'python'))
@@ -53,8 +53,8 @@ sys.path.insert (0, os.path.join (libdir, 'python'))
bindir = os.path.split (sys.argv[0])[0]
for prefix_component in ['share', 'lib']:
- datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % prefix_component)
- sys.path.insert (0, datadir)
+ datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % prefix_component)
+ sys.path.insert (0, datadir)
import midi
import lilylib as ly
@@ -84,13 +84,13 @@ allowed_tuplet_clocks = []
localedir = '@localedir@'
try:
- import gettext
- gettext.bindtextdomain ('lilypond', localedir)
- gettext.textdomain ('lilypond')
- _ = gettext.gettext
+ import gettext
+ gettext.bindtextdomain ('lilypond', localedir)
+ gettext.textdomain ('lilypond')
+ _ = gettext.gettext
except:
- def _ (s):
- return s
+ def _ (s):
+ return s
program_name = sys.argv[0]
program_version = '@TOPLEVEL_VERSION@'
@@ -98,907 +98,907 @@ program_version = '@TOPLEVEL_VERSION@'
errorport = sys.stderr
def identify ():
- sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
+ sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
def warranty ():
- identify ()
- sys.stdout.write ('''
+ identify ()
+ sys.stdout.write ('''
Copyright (c) %s by
- Han-Wen Nienhuys
- Jan Nieuwenhuizen
+ Han-Wen Nienhuys
+ Jan Nieuwenhuizen
%s
%s
''' ( '2001--2006',
- _('Distributed under terms of the GNU General Public License.'),
- _('It comes with NO WARRANTY.')))
+ _('Distributed under terms of the GNU General Public License.'),
+ _('It comes with NO WARRANTY.')))
def progress (s):
- errorport.write (s + '\n')
+ errorport.write (s + '\n')
def warning (s):
- progress (_ ("warning: ") + s)
-
+ progress (_ ("warning: ") + s)
+
def error (s):
- progress (_ ("error: ") + s)
- raise _ ("Exiting ... ")
+ progress (_ ("error: ") + s)
+ raise _ ("Exiting ... ")
def system (cmd, ignore_error = 0):
- return ly.system (cmd, ignore_error=ignore_error)
+ return ly.system (cmd, ignore_error=ignore_error)
def strip_extension (f, ext):
- (p, e) = os.path.splitext (f)
- if e == ext:
- e = ''
- return p + e
+ (p, e) = os.path.splitext (f)
+ if e == ext:
+ e = ''
+ return p + e
class Duration:
- allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
- def __init__ (self, clocks):
- self.clocks = clocks
- if clocks <= 0:
- self.clocks = duration_quant_clocks
- (self.dur, self.num, self.den) = self.dur_num_den (clocks)
-
- def dur_num_den (self, clocks):
- for i in range (len (allowed_tuplet_clocks)):
- if clocks == allowed_tuplet_clocks[i]:
- return global_options.allowed_tuplets[i]
-
- dur = 0; num = 1; den = 1;
- g = gcd (clocks, clocks_per_1)
- if g:
- (dur, num) = (clocks_per_1 / g, clocks / g)
- if not dur in self.allowed_durs:
- dur = 4; num = clocks; den = clocks_per_4
- return (dur, num, den)
-
- def dump (self):
- if self.den == 1:
- if self.num == 1:
- s = '%d' % self.dur
- elif self.num == 3 and self.dur != 1:
- s = '%d.' % (self.dur / 2)
- else:
- s = '%d*%d' % (self.dur, self.num)
- else:
- s = '%d*%d/%d' % (self.dur, self.num, self.den)
-
- global reference_note
- reference_note.duration = self
-
- return s
-
- def compare (self, other):
- return self.clocks - other.clocks
+ allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
+ def __init__ (self, clocks):
+ self.clocks = clocks
+ if clocks <= 0:
+ self.clocks = duration_quant_clocks
+ (self.dur, self.num, self.den) = self.dur_num_den (clocks)
+
+ def dur_num_den (self, clocks):
+ for i in range (len (allowed_tuplet_clocks)):
+ if clocks == allowed_tuplet_clocks[i]:
+ return global_options.allowed_tuplets[i]
+
+ dur = 0; num = 1; den = 1;
+ g = gcd (clocks, clocks_per_1)
+ if g:
+ (dur, num) = (clocks_per_1 / g, clocks / g)
+ if not dur in self.allowed_durs:
+ dur = 4; num = clocks; den = clocks_per_4
+ return (dur, num, den)
+
+ def dump (self):
+ if self.den == 1:
+ if self.num == 1:
+ s = '%d' % self.dur
+ elif self.num == 3 and self.dur != 1:
+ s = '%d.' % (self.dur / 2)
+ else:
+ s = '%d*%d' % (self.dur, self.num)
+ else:
+ s = '%d*%d/%d' % (self.dur, self.num, self.den)
+
+ global reference_note
+ reference_note.duration = self
+
+ return s
+
+ def compare (self, other):
+ return self.clocks - other.clocks
def sign (x):
- if x >= 0:
- return 1
- else:
- return -1
+ if x >= 0:
+ return 1
+ else:
+ return -1
class Note:
- names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
- alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
- alteration_names = ('eses', 'es', '', 'is' , 'isis')
- def __init__ (self, clocks, pitch, velocity):
- self.pitch = pitch
- self.velocity = velocity
- # hmm
- self.clocks = clocks
- self.duration = Duration (clocks)
- (self.octave, self.notename, self.alteration) = self.o_n_a ()
-
- def o_n_a (self):
- # major scale: do-do
- # minor scale: la-la (= + 5) '''
-
- n = self.names[(self.pitch) % 12]
- a = self.alterations[(self.pitch) % 12]
-
- if a and global_options.key.flats:
- a = - self.alterations[(self.pitch) % 12]
- n = (n - a) % 7
-
- # By tradition, all scales now consist of a sequence
- # of 7 notes each with a distinct name, from amongst
- # a b c d e f g. But, minor scales have a wide
- # second interval at the top - the 'leading note' is
- # sharped. (Why? it just works that way! Anything
- # else doesn't sound as good and isn't as flexible at
- # saying things. In medieval times, scales only had 6
- # notes to avoid this problem - the hexachords.)
-
- # So, the d minor scale is d e f g a b-flat c-sharp d
- # - using d-flat for the leading note would skip the
- # name c and duplicate the name d. Why isn't c-sharp
- # put in the key signature? Tradition. (It's also
- # supposedly based on the Pythagorean theory of the
- # cycle of fifths, but that really only applies to
- # major scales...) Anyway, g minor is g a b-flat c d
- # e-flat f-sharp g, and all the other flat minor keys
- # end up with a natural leading note. And there you
- # have it.
-
- # John Sankey
- #
- # Let's also do a-minor: a b c d e f gis a
- #
- # --jcn
-
- o = self.pitch / 12 - 4
-
- key = global_options.key
- if key.minor:
- # as -> gis
- if key.sharps == 0 and key.flats == 0 \
- and n == 5 and a == -1:
- n = 4; a = 1
- # des -> cis
- elif key.flats == 1 and n == 1 and a == -1:
- n = 0; a = 1
- # ges -> fis
- elif key.flats == 2 and n == 4 and a == -1:
- n = 3; a = 1
- # g -> fisis
- elif key.sharps == 5 and n == 4 and a == 0:
- n = 3; a = 2
- # d -> cisis
- elif key.sharps == 6 and n == 1 and a == 0:
- n = 0; a = 2
- # a -> gisis
- elif key.sharps == 7 and n == 5 and a == 0:
- n = 4; a = 2
-
- # b -> ces
- if key.flats >= 6 and n == 6 and a == 0:
- n = 0; a = -1; o = o + 1
- # e -> fes
- if key.flats >= 7 and n == 2 and a == 0:
- n = 3; a = -1
-
- # f -> eis
- if key.sharps >= 3 and n == 3 and a == 0:
- n = 2; a = 1
- # c -> bis
- if key.sharps >= 4 and n == 0 and a == 0:
- n = 6; a = 1; o = o - 1
-
- return (o, n, a)
-
- def __repr__ (self):
- s = chr ((self.notename + 2) % 7 + ord ('a'))
- return 'Note(%s %s)' % (s, self.duration.dump())
-
- def dump (self, dump_dur = 1):
- global reference_note
- s = chr ((self.notename + 2) % 7 + ord ('a'))
- s = s + self.alteration_names[self.alteration + 2]
- if global_options.absolute_pitches:
- commas = self.octave
- else:
- delta = self.pitch - reference_note.pitch
- commas = sign (delta) * (abs (delta) / 12)
- if ((sign (delta) \
- * (self.notename - reference_note.notename) + 7) \
- % 7 >= 4) \
- or ((self.notename == reference_note.notename) \
- and (abs (delta) > 4) and (abs (delta) < 12)):
- commas = commas + sign (delta)
-
- if commas > 0:
- s = s + "'" * commas
- elif commas < 0:
- s = s + "," * -commas
-
- ## FIXME: compile fix --jcn
- if dump_dur and (global_options.explicit_durations \
- or self.duration.compare (reference_note.duration)):
- s = s + self.duration.dump ()
-
- reference_note = self
-
- # TODO: move space
- return s + ' '
+ names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
+ alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
+ alteration_names = ('eses', 'es', '', 'is' , 'isis')
+ def __init__ (self, clocks, pitch, velocity):
+ self.pitch = pitch
+ self.velocity = velocity
+ # hmm
+ self.clocks = clocks
+ self.duration = Duration (clocks)
+ (self.octave, self.notename, self.alteration) = self.o_n_a ()
+
+ def o_n_a (self):
+ # major scale: do-do
+ # minor scale: la-la (= + 5) '''
+
+ n = self.names[(self.pitch) % 12]
+ a = self.alterations[(self.pitch) % 12]
+
+ if a and global_options.key.flats:
+ a = - self.alterations[(self.pitch) % 12]
+ n = (n - a) % 7
+
+ # By tradition, all scales now consist of a sequence
+ # of 7 notes each with a distinct name, from amongst
+ # a b c d e f g. But, minor scales have a wide
+ # second interval at the top - the 'leading note' is
+ # sharped. (Why? it just works that way! Anything
+ # else doesn't sound as good and isn't as flexible at
+ # saying things. In medieval times, scales only had 6
+ # notes to avoid this problem - the hexachords.)
+
+ # So, the d minor scale is d e f g a b-flat c-sharp d
+ # - using d-flat for the leading note would skip the
+ # name c and duplicate the name d. Why isn't c-sharp
+ # put in the key signature? Tradition. (It's also
+ # supposedly based on the Pythagorean theory of the
+ # cycle of fifths, but that really only applies to
+ # major scales...) Anyway, g minor is g a b-flat c d
+ # e-flat f-sharp g, and all the other flat minor keys
+ # end up with a natural leading note. And there you
+ # have it.
+
+ # John Sankey
+ #
+ # Let's also do a-minor: a b c d e f gis a
+ #
+ # --jcn
+
+ o = self.pitch / 12 - 4
+
+ key = global_options.key
+ if key.minor:
+ # as -> gis
+ if key.sharps == 0 and key.flats == 0 \
+ and n == 5 and a == -1:
+ n = 4; a = 1
+ # des -> cis
+ elif key.flats == 1 and n == 1 and a == -1:
+ n = 0; a = 1
+ # ges -> fis
+ elif key.flats == 2 and n == 4 and a == -1:
+ n = 3; a = 1
+ # g -> fisis
+ elif key.sharps == 5 and n == 4 and a == 0:
+ n = 3; a = 2
+ # d -> cisis
+ elif key.sharps == 6 and n == 1 and a == 0:
+ n = 0; a = 2
+ # a -> gisis
+ elif key.sharps == 7 and n == 5 and a == 0:
+ n = 4; a = 2
+
+ # b -> ces
+ if key.flats >= 6 and n == 6 and a == 0:
+ n = 0; a = -1; o = o + 1
+ # e -> fes
+ if key.flats >= 7 and n == 2 and a == 0:
+ n = 3; a = -1
+
+ # f -> eis
+ if key.sharps >= 3 and n == 3 and a == 0:
+ n = 2; a = 1
+ # c -> bis
+ if key.sharps >= 4 and n == 0 and a == 0:
+ n = 6; a = 1; o = o - 1
+
+ return (o, n, a)
+
+ def __repr__ (self):
+ s = chr ((self.notename + 2) % 7 + ord ('a'))
+ return 'Note(%s %s)' % (s, self.duration.dump())
+
+ def dump (self, dump_dur = 1):
+ global reference_note
+ s = chr ((self.notename + 2) % 7 + ord ('a'))
+ s = s + self.alteration_names[self.alteration + 2]
+ if global_options.absolute_pitches:
+ commas = self.octave
+ else:
+ delta = self.pitch - reference_note.pitch
+ commas = sign (delta) * (abs (delta) / 12)
+ if ((sign (delta) \
+ * (self.notename - reference_note.notename) + 7) \
+ % 7 >= 4) \
+ or ((self.notename == reference_note.notename) \
+ and (abs (delta) > 4) and (abs (delta) < 12)):
+ commas = commas + sign (delta)
+
+ if commas > 0:
+ s = s + "'" * commas
+ elif commas < 0:
+ s = s + "," * -commas
+
+ ## FIXME: compile fix --jcn
+ if dump_dur and (global_options.explicit_durations \
+ or self.duration.compare (reference_note.duration)):
+ s = s + self.duration.dump ()
+
+ reference_note = self
+
+ # TODO: move space
+ return s + ' '
class Time:
- def __init__ (self, num, den):
- self.clocks = 0
- self.num = num
- self.den = den
-
- def bar_clocks (self):
- return clocks_per_1 * self.num / self.den
-
- def __repr__ (self):
- return 'Time(%d/%d)' % (self.num, self.den)
-
- def dump (self):
- global time
- time = self
- return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
+ def __init__ (self, num, den):
+ self.clocks = 0
+ self.num = num
+ self.den = den
+
+ def bar_clocks (self):
+ return clocks_per_1 * self.num / self.den
+
+ def __repr__ (self):
+ return 'Time(%d/%d)' % (self.num, self.den)
+
+ def dump (self):
+ global time
+ time = self
+ return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
class Tempo:
- def __init__ (self, seconds_per_1):
- self.clocks = 0
- self.seconds_per_1 = seconds_per_1
-
- def __repr__ (self):
- return 'Tempo(%d)' % self.bpm ()
-
- def bpm (self):
- return 4 * 60 / self.seconds_per_1
-
- def dump (self):
- return '\n ' + '\\tempo 4 = %d ' % (self.bpm()) + '\n '
+ def __init__ (self, seconds_per_1):
+ self.clocks = 0
+ self.seconds_per_1 = seconds_per_1
+
+ def __repr__ (self):
+ return 'Tempo(%d)' % self.bpm ()
+
+ def bpm (self):
+ return 4 * 60 / self.seconds_per_1
+
+ def dump (self):
+ return '\n ' + '\\tempo 4 = %d ' % (self.bpm()) + '\n '
class Clef:
- clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
- def __init__ (self, type):
- self.type = type
+ clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
+ def __init__ (self, type):
+ self.type = type
- def __repr__ (self):
- return 'Clef(%s)' % self.clefs[self.type]
-
- def dump (self):
- return '\n \\clef %s\n ' % self.clefs[self.type]
+ def __repr__ (self):
+ return 'Clef(%s)' % self.clefs[self.type]
+
+ def dump (self):
+ return '\n \\clef %s\n ' % self.clefs[self.type]
class Key:
- key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
- key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
-
- def __init__ (self, sharps, flats, minor):
- self.clocks = 0
- self.flats = flats
- self.sharps = sharps
- self.minor = minor
-
- def dump (self):
- global_options.key = self
-
- s = ''
- if self.sharps and self.flats:
- pass
- else:
- if self.flats:
- k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
- else:
- k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
-
- if not self.minor:
- name = chr ((k + 2) % 7 + ord ('a'))
- else:
- name = chr ((k + 2) % 7 + ord ('a'))
-
- # fis cis gis dis ais eis bis
- sharps = (2, 4, 6, 1, 3, 5, 7)
- # bes es as des ges ces fes
- flats = (6, 4, 2, 7, 5, 3, 1)
- a = 0
- if self.flats:
- if flats[k] <= self.flats:
- a = -1
- else:
- if sharps[k] <= self.sharps:
- a = 1
-
- if a:
- name = name + Note.alteration_names[a + 2]
-
- s = '\\key ' + name
- if self.minor:
- s = s + ' \\minor'
- else:
- s = s + ' \\major'
-
- return '\n\n ' + s + '\n '
+ key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
+ key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
+
+ def __init__ (self, sharps, flats, minor):
+ self.clocks = 0
+ self.flats = flats
+ self.sharps = sharps
+ self.minor = minor
+
+ def dump (self):
+ global_options.key = self
+
+ s = ''
+ if self.sharps and self.flats:
+ pass
+ else:
+ if self.flats:
+ k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
+ else:
+ k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
+
+ if not self.minor:
+ name = chr ((k + 2) % 7 + ord ('a'))
+ else:
+ name = chr ((k + 2) % 7 + ord ('a'))
+
+ # fis cis gis dis ais eis bis
+ sharps = (2, 4, 6, 1, 3, 5, 7)
+ # bes es as des ges ces fes
+ flats = (6, 4, 2, 7, 5, 3, 1)
+ a = 0
+ if self.flats:
+ if flats[k] <= self.flats:
+ a = -1
+ else:
+ if sharps[k] <= self.sharps:
+ a = 1
+
+ if a:
+ name = name + Note.alteration_names[a + 2]
+
+ s = '\\key ' + name
+ if self.minor:
+ s = s + ' \\minor'
+ else:
+ s = s + ' \\major'
+
+ return '\n\n ' + s + '\n '
class Text:
- text_types = (
- 'SEQUENCE_NUMBER',
- 'TEXT_EVENT',
- 'COPYRIGHT_NOTICE',
- 'SEQUENCE_TRACK_NAME',
- 'INSTRUMENT_NAME',
- 'LYRIC',
- 'MARKER',
- 'CUE_POINT',)
-
- def __init__ (self, type, text):
- self.clocks = 0
- self.type = type
- self.text = text
-
- def dump (self):
- # urg, we should be sure that we're in a lyrics staff
- if self.type == midi.LYRIC:
- s = '"%s"' % self.text
- d = Duration (self.clocks)
- if global_options.explicit_durations \
- or d.compare (reference_note.duration):
- s = s + Duration (self.clocks).dump ()
- s = s + ' '
- else:
- s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
- return s
-
- def __repr__ (self):
- return 'Text(%d=%s)' % (self.type, self.text)
+ text_types = (
+ 'SEQUENCE_NUMBER',
+ 'TEXT_EVENT',
+ 'COPYRIGHT_NOTICE',
+ 'SEQUENCE_TRACK_NAME',
+ 'INSTRUMENT_NAME',
+ 'LYRIC',
+ 'MARKER',
+ 'CUE_POINT',)
+
+ def __init__ (self, type, text):
+ self.clocks = 0
+ self.type = type
+ self.text = text
+
+ def dump (self):
+ # urg, we should be sure that we're in a lyrics staff
+ if self.type == midi.LYRIC:
+ s = '"%s"' % self.text
+ d = Duration (self.clocks)
+ if global_options.explicit_durations \
+ or d.compare (reference_note.duration):
+ s = s + Duration (self.clocks).dump ()
+ s = s + ' '
+ else:
+ s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
+ return s
+
+ def __repr__ (self):
+ return 'Text(%d=%s)' % (self.type, self.text)
def split_track (track):
- chs = {}
- for i in range(16):
- chs[i] = []
-
- for e in track:
- data = list (e[1])
- if data[0] > 0x7f and data[0] < 0xf0:
- c = data[0] & 0x0f
- e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
- chs[c].append (e)
- else:
- chs[0].append (e)
-
- for i in range (16):
- if chs[i] == []:
- del chs[i]
-
- threads = []
- for v in chs.values ():
- events = events_on_channel (v)
- thread = unthread_notes (events)
- if len (thread):
- threads.append (thread)
- return threads
+ chs = {}
+ for i in range(16):
+ chs[i] = []
+
+ for e in track:
+ data = list (e[1])
+ if data[0] > 0x7f and data[0] < 0xf0:
+ c = data[0] & 0x0f
+ e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
+ chs[c].append (e)
+ else:
+ chs[0].append (e)
+
+ for i in range (16):
+ if chs[i] == []:
+ del chs[i]
+
+ threads = []
+ for v in chs.values ():
+ events = events_on_channel (v)
+ thread = unthread_notes (events)
+ if len (thread):
+ threads.append (thread)
+ return threads
def quantise_clocks (clocks, quant):
- q = int (clocks / quant) * quant
- if q != clocks:
- for tquant in allowed_tuplet_clocks:
- if int (clocks / tquant) * tquant == clocks:
- return clocks
- if 2 * (clocks - q) > quant:
- q = q + quant
- return q
+ q = int (clocks / quant) * quant
+ if q != clocks:
+ for tquant in allowed_tuplet_clocks:
+ if int (clocks / tquant) * tquant == clocks:
+ return clocks
+ if 2 * (clocks - q) > quant:
+ q = q + quant
+ return q
def end_note (pitches, notes, t, e):
- try:
- (lt, vel) = pitches[e]
- del pitches[e]
-
- i = len (notes) - 1
- while i > 0:
- if notes[i][0] > lt:
- i = i -1
- else:
- break
- d = t - lt
- if duration_quant_clocks:
- d = quantise_clocks (d, duration_quant_clocks)
- if not d:
- d = duration_quant_clocks
-
- notes.insert (i + 1,
- (lt, Note (d, e, vel)))
-
- except KeyError:
- pass
+ try:
+ (lt, vel) = pitches[e]
+ del pitches[e]
+
+ i = len (notes) - 1
+ while i > 0:
+ if notes[i][0] > lt:
+ i = i -1
+ else:
+ break
+ d = t - lt
+ if duration_quant_clocks:
+ d = quantise_clocks (d, duration_quant_clocks)
+ if not d:
+ d = duration_quant_clocks
+
+ notes.insert (i + 1,
+ (lt, Note (d, e, vel)))
+
+ except KeyError:
+ pass
def events_on_channel (channel):
- pitches = {}
-
- notes = []
- events = []
- last_lyric = 0
- last_time = 0
- for e in channel:
- t = e[0]
-
- if start_quant_clocks:
- t = quantise_clocks (t, start_quant_clocks)
-
-
- if e[1][0] == midi.NOTE_OFF \
- or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
- end_note (pitches, notes, t, e[1][1])
-
- elif e[1][0] == midi.NOTE_ON:
- if not pitches.has_key (e[1][1]):
- pitches[e[1][1]] = (t, e[1][2])
-
- # all include ALL_NOTES_OFF
- elif e[1][0] >= midi.ALL_SOUND_OFF \
- and e[1][0] <= midi.POLY_MODE_ON:
- for i in pitches.keys ():
- end_note (pitches, notes, t, i)
-
- elif e[1][0] == midi.META_EVENT:
- if e[1][1] == midi.END_OF_TRACK:
- for i in pitches.keys ():
- end_note (pitches, notes, t, i)
- break
-
- elif e[1][1] == midi.SET_TEMPO:
- (u0, u1, u2) = map (ord, e[1][2])
- us_per_4 = u2 + 256 * (u1 + 256 * u0)
- seconds_per_1 = us_per_4 * 4 / 1e6
- events.append ((t, Tempo (seconds_per_1)))
- elif e[1][1] == midi.TIME_SIGNATURE:
- (num, dur, clocks4, count32) = map (ord, e[1][2])
- den = 2 ** dur
- events.append ((t, Time (num, den)))
- elif e[1][1] == midi.KEY_SIGNATURE:
- (alterations, minor) = map (ord, e[1][2])
- sharps = 0
- flats = 0
- if alterations < 127:
- sharps = alterations
- else:
- flats = 256 - alterations
-
- k = Key (sharps, flats, minor)
- events.append ((t, k))
-
- # ugh, must set key while parsing
- # because Note init uses key
- # Better do Note.calc () at dump time?
- global_options.key = k
-
- elif e[1][1] == midi.LYRIC \
- or (global_options.text_lyrics and e[1][1] == midi.TEXT_EVENT):
- if last_lyric:
- last_lyric.clocks = t - last_time
- events.append ((last_time, last_lyric))
- last_time = t
- last_lyric = Text (midi.LYRIC, e[1][2])
-
- elif e[1][1] >= midi.SEQUENCE_NUMBER \
- and e[1][1] <= midi.CUE_POINT:
- events.append ((t, Text (e[1][1], e[1][2])))
- else:
- if global_options.verbose:
- sys.stderr.write ("SKIP: %s\n" % `e`)
- pass
- else:
- if global_options.verbose:
- sys.stderr.write ("SKIP: %s\n" % `e`)
- pass
-
- if last_lyric:
- # last_lyric.clocks = t - last_time
- # hmm
- last_lyric.clocks = clocks_per_4
- events.append ((last_time, last_lyric))
- last_lyric = 0
-
- i = 0
- while len (notes):
- if i < len (events) and notes[0][0] >= events[i][0]:
- i = i + 1
- else:
- events.insert (i, notes[0])
- del notes[0]
- return events
+ pitches = {}
+
+ notes = []
+ events = []
+ last_lyric = 0
+ last_time = 0
+ for e in channel:
+ t = e[0]
+
+ if start_quant_clocks:
+ t = quantise_clocks (t, start_quant_clocks)
+
+
+ if e[1][0] == midi.NOTE_OFF \
+ or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
+ end_note (pitches, notes, t, e[1][1])
+
+ elif e[1][0] == midi.NOTE_ON:
+ if not pitches.has_key (e[1][1]):
+ pitches[e[1][1]] = (t, e[1][2])
+
+ # all include ALL_NOTES_OFF
+ elif e[1][0] >= midi.ALL_SOUND_OFF \
+ and e[1][0] <= midi.POLY_MODE_ON:
+ for i in pitches.keys ():
+ end_note (pitches, notes, t, i)
+
+ elif e[1][0] == midi.META_EVENT:
+ if e[1][1] == midi.END_OF_TRACK:
+ for i in pitches.keys ():
+ end_note (pitches, notes, t, i)
+ break
+
+ elif e[1][1] == midi.SET_TEMPO:
+ (u0, u1, u2) = map (ord, e[1][2])
+ us_per_4 = u2 + 256 * (u1 + 256 * u0)
+ seconds_per_1 = us_per_4 * 4 / 1e6
+ events.append ((t, Tempo (seconds_per_1)))
+ elif e[1][1] == midi.TIME_SIGNATURE:
+ (num, dur, clocks4, count32) = map (ord, e[1][2])
+ den = 2 ** dur
+ events.append ((t, Time (num, den)))
+ elif e[1][1] == midi.KEY_SIGNATURE:
+ (alterations, minor) = map (ord, e[1][2])
+ sharps = 0
+ flats = 0
+ if alterations < 127:
+ sharps = alterations
+ else:
+ flats = 256 - alterations
+
+ k = Key (sharps, flats, minor)
+ events.append ((t, k))
+
+ # ugh, must set key while parsing
+ # because Note init uses key
+ # Better do Note.calc () at dump time?
+ global_options.key = k
+
+ elif e[1][1] == midi.LYRIC \
+ or (global_options.text_lyrics and e[1][1] == midi.TEXT_EVENT):
+ if last_lyric:
+ last_lyric.clocks = t - last_time
+ events.append ((last_time, last_lyric))
+ last_time = t
+ last_lyric = Text (midi.LYRIC, e[1][2])
+
+ elif e[1][1] >= midi.SEQUENCE_NUMBER \
+ and e[1][1] <= midi.CUE_POINT:
+ events.append ((t, Text (e[1][1], e[1][2])))
+ else:
+ if global_options.verbose:
+ sys.stderr.write ("SKIP: %s\n" % `e`)
+ pass
+ else:
+ if global_options.verbose:
+ sys.stderr.write ("SKIP: %s\n" % `e`)
+ pass
+
+ if last_lyric:
+ # last_lyric.clocks = t - last_time
+ # hmm
+ last_lyric.clocks = clocks_per_4
+ events.append ((last_time, last_lyric))
+ last_lyric = 0
+
+ i = 0
+ while len (notes):
+ if i < len (events) and notes[0][0] >= events[i][0]:
+ i = i + 1
+ else:
+ events.insert (i, notes[0])
+ del notes[0]
+ return events
def unthread_notes (channel):
- threads = []
- while channel:
- thread = []
- end_busy_t = 0
- start_busy_t = 0
- todo = []
- for e in channel:
- t = e[0]
- if e[1].__class__ == Note \
- and ((t == start_busy_t \
- and e[1].clocks + t == end_busy_t) \
- or t >= end_busy_t):
- thread.append (e)
- start_busy_t = t
- end_busy_t = t + e[1].clocks
- elif e[1].__class__ == Time \
- or e[1].__class__ == Key \
- or e[1].__class__ == Text \
- or e[1].__class__ == Tempo:
- thread.append (e)
- else:
- todo.append (e)
- threads.append (thread)
- channel = todo
-
- return threads
+ threads = []
+ while channel:
+ thread = []
+ end_busy_t = 0
+ start_busy_t = 0
+ todo = []
+ for e in channel:
+ t = e[0]
+ if e[1].__class__ == Note \
+ and ((t == start_busy_t \
+ and e[1].clocks + t == end_busy_t) \
+ or t >= end_busy_t):
+ thread.append (e)
+ start_busy_t = t
+ end_busy_t = t + e[1].clocks
+ elif e[1].__class__ == Time \
+ or e[1].__class__ == Key \
+ or e[1].__class__ == Text \
+ or e[1].__class__ == Tempo:
+ thread.append (e)
+ else:
+ todo.append (e)
+ threads.append (thread)
+ channel = todo
+
+ return threads
def gcd (a,b):
- if b == 0:
- return a
- c = a
- while c:
- c = a % b
- a = b
- b = c
- return a
-
+ if b == 0:
+ return a
+ c = a
+ while c:
+ c = a % b
+ a = b
+ b = c
+ return a
+
def dump_skip (skip, clocks):
- return skip + Duration (clocks).dump () + ' '
+ return skip + Duration (clocks).dump () + ' '
def dump (d):
- return d.dump ()
+ return d.dump ()
def dump_chord (ch):
- s = ''
- notes = []
- for i in ch:
- if i.__class__ == Note:
- notes.append (i)
- else:
- s = s + i.dump ()
- if len (notes) == 1:
- s = s + dump (notes[0])
- elif len (notes) > 1:
- global reference_note
- s = s + '<'
- s = s + notes[0].dump (dump_dur = 0)
- r = reference_note
- for i in notes[1:]:
- s = s + i.dump (dump_dur = 0 )
- s = s + '>'
-
- s = s + notes[0].duration.dump() + ' '
- reference_note = r
- return s
+ s = ''
+ notes = []
+ for i in ch:
+ if i.__class__ == Note:
+ notes.append (i)
+ else:
+ s = s + i.dump ()
+ if len (notes) == 1:
+ s = s + dump (notes[0])
+ elif len (notes) > 1:
+ global reference_note
+ s = s + '<'
+ s = s + notes[0].dump (dump_dur = 0)
+ r = reference_note
+ for i in notes[1:]:
+ s = s + i.dump (dump_dur = 0 )
+ s = s + '>'
+
+ s = s + notes[0].duration.dump() + ' '
+ reference_note = r
+ return s
def dump_bar_line (last_bar_t, t, bar_count):
- s = ''
- bar_t = time.bar_clocks ()
- if t - last_bar_t >= bar_t:
- bar_count = bar_count + (t - last_bar_t) / bar_t
-
- if t - last_bar_t == bar_t:
- s = '|\n %% %d\n ' % bar_count
- last_bar_t = t
- else:
- # urg, this will barf at meter changes
- last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
-
- return (s, last_bar_t, bar_count)
-
-
+ s = ''
+ bar_t = time.bar_clocks ()
+ if t - last_bar_t >= bar_t:
+ bar_count = bar_count + (t - last_bar_t) / bar_t
+
+ if t - last_bar_t == bar_t:
+ s = '|\n %% %d\n ' % bar_count
+ last_bar_t = t
+ else:
+ # urg, this will barf at meter changes
+ last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
+
+ return (s, last_bar_t, bar_count)
+
+
def dump_channel (thread, skip):
- global reference_note, time
-
- global_options.key = Key (0, 0, 0)
- time = Time (4, 4)
- # urg LilyPond doesn't start at c4, but
- # remembers from previous tracks!
- # reference_note = Note (clocks_per_4, 4*12, 0)
- reference_note = Note (0, 4*12, 0)
- last_e = None
- chs = []
- ch = []
-
- for e in thread:
- if last_e and last_e[0] == e[0]:
- ch.append (e[1])
- else:
- if ch:
- chs.append ((last_e[0], ch))
-
- ch = [e[1]]
-
- last_e = e
-
- if ch:
- chs.append ((last_e[0], ch))
- t = 0
- last_t = 0
- last_bar_t = 0
- bar_count = 1
-
- lines = ['']
- for ch in chs:
- t = ch[0]
-
- i = string.rfind (lines[-1], '\n') + 1
- if len (lines[-1][i:]) > LINE_BELL:
- lines.append ('')
-
- if t - last_t > 0:
- lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
- elif t - last_t < 0:
- errorport.write ('BUG: time skew')
-
- (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
- t, bar_count)
- lines[-1] = lines[-1] + s
-
- lines[-1] = lines[-1] + dump_chord (ch[1])
-
- clocks = 0
- for i in ch[1]:
- if i.clocks > clocks:
- clocks = i.clocks
-
- last_t = t + clocks
-
- (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
- last_t, bar_count)
- lines[-1] = lines[-1] + s
-
- return string.join (lines, '\n ') + '\n'
+ global reference_note, time
+
+ global_options.key = Key (0, 0, 0)
+ time = Time (4, 4)
+ # urg LilyPond doesn't start at c4, but
+ # remembers from previous tracks!
+ # reference_note = Note (clocks_per_4, 4*12, 0)
+ reference_note = Note (0, 4*12, 0)
+ last_e = None
+ chs = []
+ ch = []
+
+ for e in thread:
+ if last_e and last_e[0] == e[0]:
+ ch.append (e[1])
+ else:
+ if ch:
+ chs.append ((last_e[0], ch))
+
+ ch = [e[1]]
+
+ last_e = e
+
+ if ch:
+ chs.append ((last_e[0], ch))
+ t = 0
+ last_t = 0
+ last_bar_t = 0
+ bar_count = 1
+
+ lines = ['']
+ for ch in chs:
+ t = ch[0]
+
+ i = string.rfind (lines[-1], '\n') + 1
+ if len (lines[-1][i:]) > LINE_BELL:
+ lines.append ('')
+
+ if t - last_t > 0:
+ lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
+ elif t - last_t < 0:
+ errorport.write ('BUG: time skew')
+
+ (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
+ t, bar_count)
+ lines[-1] = lines[-1] + s
+
+ lines[-1] = lines[-1] + dump_chord (ch[1])
+
+ clocks = 0
+ for i in ch[1]:
+ if i.clocks > clocks:
+ clocks = i.clocks
+
+ last_t = t + clocks
+
+ (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
+ last_t, bar_count)
+ lines[-1] = lines[-1] + s
+
+ return string.join (lines, '\n ') + '\n'
def track_name (i):
- return 'track%c' % (i + ord ('A'))
+ return 'track%c' % (i + ord ('A'))
def channel_name (i):
- return 'channel%c' % (i + ord ('A'))
+ return 'channel%c' % (i + ord ('A'))
def dump_track (channels, n):
- s = '\n'
- track = track_name (n)
- clef = guess_clef (channels)
-
- for i in range (len (channels)):
- channel = channel_name (i)
- item = thread_first_item (channels[i])
-
- if item and item.__class__ == Note:
- skip = 's'
- s = s + '%s = ' % (track + channel)
- if not global_options.absolute_pitches:
- s = s + '\\relative c '
- elif item and item.__class__ == Text:
- skip = '" "'
- s = s + '%s = \\lyricmode ' % (track + channel)
- else:
- skip = '\\skip '
- s = s + '%s = ' % (track + channel)
- s = s + '{\n'
- s = s + ' ' + dump_channel (channels[i][0], skip)
- s = s + '}\n\n'
-
- s = s + '%s = <<\n' % track
-
- if clef.type != 2:
- s = s + clef.dump () + '\n'
-
- for i in range (len (channels)):
- channel = channel_name (i)
- item = thread_first_item (channels[i])
- if item and item.__class__ == Text:
- s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
- track + channel)
- else:
- s = s + ' \\context Voice = %s \\%s\n' % (channel,
- track + channel)
- s = s + '>>\n\n'
- return s
+ s = '\n'
+ track = track_name (n)
+ clef = guess_clef (channels)
+
+ for i in range (len (channels)):
+ channel = channel_name (i)
+ item = thread_first_item (channels[i])
+
+ if item and item.__class__ == Note:
+ skip = 's'
+ s = s + '%s = ' % (track + channel)
+ if not global_options.absolute_pitches:
+ s = s + '\\relative c '
+ elif item and item.__class__ == Text:
+ skip = '" "'
+ s = s + '%s = \\lyricmode ' % (track + channel)
+ else:
+ skip = '\\skip '
+ s = s + '%s = ' % (track + channel)
+ s = s + '{\n'
+ s = s + ' ' + dump_channel (channels[i][0], skip)
+ s = s + '}\n\n'
+
+ s = s + '%s = <<\n' % track
+
+ if clef.type != 2:
+ s = s + clef.dump () + '\n'
+
+ for i in range (len (channels)):
+ channel = channel_name (i)
+ item = thread_first_item (channels[i])
+ if item and item.__class__ == Text:
+ s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
+ track + channel)
+ else:
+ s = s + ' \\context Voice = %s \\%s\n' % (channel,
+ track + channel)
+ s = s + '>>\n\n'
+ return s
def thread_first_item (thread):
- for chord in thread:
- for event in chord:
- if (event[1].__class__ == Note
- or (event[1].__class__ == Text
- and event[1].type == midi.LYRIC)):
-
- return event[1]
- return None
+ for chord in thread:
+ for event in chord:
+ if (event[1].__class__ == Note
+ or (event[1].__class__ == Text
+ and event[1].type == midi.LYRIC)):
+
+ return event[1]
+ return None
def track_first_item (track):
- for thread in track:
- first = thread_first_item (thread)
- if first:
- return first
- return None
+ for thread in track:
+ first = thread_first_item (thread)
+ if first:
+ return first
+ return None
def guess_clef (track):
- i = 0
- p = 0
- for thread in track:
- for chord in thread:
- for event in chord:
- if event[1].__class__ == Note:
- i = i + 1
- p = p + event[1].pitch
- if i and p / i <= 3*12:
- return Clef (0)
- elif i and p / i <= 5*12:
- return Clef (1)
- elif i and p / i >= 7*12:
- return Clef (3)
- else:
- return Clef (2)
-
+ i = 0
+ p = 0
+ for thread in track:
+ for chord in thread:
+ for event in chord:
+ if event[1].__class__ == Note:
+ i = i + 1
+ p = p + event[1].pitch
+ if i and p / i <= 3*12:
+ return Clef (0)
+ elif i and p / i <= 5*12:
+ return Clef (1)
+ elif i and p / i >= 7*12:
+ return Clef (3)
+ else:
+ return Clef (2)
+
def convert_midi (in_file, out_file):
- global clocks_per_1, clocks_per_4, key
- global start_quant_clocks
- global duration_quant_clocks
- global allowed_tuplet_clocks
-
- str = open (in_file).read ()
- midi_dump = midi.parse (str)
-
- clocks_per_1 = midi_dump[0][1]
- clocks_per_4 = clocks_per_1 / 4
-
- if global_options.start_quant:
- start_quant_clocks = clocks_per_1 / global_options.start_quant
-
- if global_options.duration_quant:
- duration_quant_clocks = clocks_per_1 / global_options.duration_quant
-
- allowed_tuplet_clocks = []
- for (dur, num, den) in global_options.allowed_tuplets:
- allowed_tuplet_clocks.append (clocks_per_1 / den)
-
- tracks = []
- for t in midi_dump[1]:
- global_options.key = Key (0, 0, 0)
- tracks.append (split_track (t))
-
- tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
-
+ global clocks_per_1, clocks_per_4, key
+ global start_quant_clocks
+ global duration_quant_clocks
+ global allowed_tuplet_clocks
+
+ str = open (in_file).read ()
+ midi_dump = midi.parse (str)
+
+ clocks_per_1 = midi_dump[0][1]
+ clocks_per_4 = clocks_per_1 / 4
+
+ if global_options.start_quant:
+ start_quant_clocks = clocks_per_1 / global_options.start_quant
+
+ if global_options.duration_quant:
+ duration_quant_clocks = clocks_per_1 / global_options.duration_quant
+
+ allowed_tuplet_clocks = []
+ for (dur, num, den) in global_options.allowed_tuplets:
+ allowed_tuplet_clocks.append (clocks_per_1 / den)
+
+ tracks = []
+ for t in midi_dump[1]:
+ global_options.key = Key (0, 0, 0)
+ tracks.append (split_track (t))
+
+ tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
+
+
+ s = ''
+ s = tag + '\n\\version "2.7.18"\n\n'
+ for i in range (len (tracks)):
+ s = s + dump_track (tracks[i], i)
+
+ s = s + '\n\\score {\n <<\n'
+
+ i = 0
+ for t in tracks:
+ track = track_name (i)
+ item = track_first_item (t)
- s = ''
- s = tag + '\n\\version "2.7.18"\n\n'
- for i in range (len (tracks)):
- s = s + dump_track (tracks[i], i)
-
- s = s + '\n\\score {\n <<\n'
-
- i = 0
- for t in tracks:
- track = track_name (i)
- item = track_first_item (t)
-
- if item and item.__class__ == Note:
- s = s + ' \\context Staff=%s \\%s\n' % (track, track)
- elif item and item.__class__ == Text:
- s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
+ if item and item.__class__ == Note:
+ s = s + ' \\context Staff=%s \\%s\n' % (track, track)
+ elif item and item.__class__ == Text:
+ s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
- i += 1
- s = s + ' >>\n}\n'
+ i += 1
+ s = s + ' >>\n}\n'
- progress (_ ("%s output to `%s'...") % ('LY', out_file))
+ progress (_ ("%s output to `%s'...") % ('LY', out_file))
- if out_file == '-':
- handle = sys.stdout
- else:
- handle = open (out_file, 'w')
+ if out_file == '-':
+ handle = sys.stdout
+ else:
+ handle = open (out_file, 'w')
- handle.write (s)
- handle.close ()
+ handle.write (s)
+ handle.close ()
def get_option_parser ():
- p = ly.get_option_parser (usage='midi2ly [OPTIONS] FILE',
- version="midi2ly (LilyPond) @TOPLEVEL_VERSION@",
- description=_('''Convert MIDI to LilyPond source.'''))
-
- p.add_option ('-a', '--absolute-pitches',
- action='store_true',
- help=_ ("print absolute pitches"))
- p.add_option ('-d', '--duration-quant',
- metavar= _("DUR"),
- help=_("quantise note durations on DUR"))
- p.add_option ('-e', '--explicit-durations',
- action='store_true',
- help=_ ("print explicit durations"))
- p.add_option('-k', '--key', help=_ ("set key: ALT=+sharps|-flats; MINOR=1"),
- metavar=_ ("ALT[:MINOR]"),
- default='0'),
- p.add_option ('-o', '--output', help=_("write output to FILE"),
- metavar=_("FILE"),
- action='store')
- p.add_option ('-s', '--start-quant',help= _ ("quantise note starts on DUR"),
- metavar=_ ("DUR"))
- p.add_option ('-t', '--allow-tuplet',
- metavar=_ ("DUR*NUM/DEN"),
- action = "append",
- dest="allowed_tuplets",
- help=_ ("allow tuplet durations DUR*NUM/DEN"),
- default=[])
- p.add_option ('-V', '--verbose', help=_("be verbose"),
- action='store_true'
- ),
- p.add_option ('-w', '--warranty', help=_("show warranty"),
- action='store_true',
- ),
- p.add_option ('-x', '--text-lyrics', help=_("treat every text as a lyric"),
- action='store_true')
-
- p.add_option_group (_ ("example"),
- description = r'''
- midi2ly --key=-2:1 --duration-quant=32 \
- --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
+ p = ly.get_option_parser (usage='midi2ly [OPTIONS] FILE',
+ version="midi2ly (LilyPond) @TOPLEVEL_VERSION@",
+ description=_('''Convert MIDI to LilyPond source.'''))
+
+ p.add_option ('-a', '--absolute-pitches',
+ action='store_true',
+ help=_ ("print absolute pitches"))
+ p.add_option ('-d', '--duration-quant',
+ metavar= _("DUR"),
+ help=_("quantise note durations on DUR"))
+ p.add_option ('-e', '--explicit-durations',
+ action='store_true',
+ help=_ ("print explicit durations"))
+ p.add_option('-k', '--key', help=_ ("set key: ALT=+sharps|-flats; MINOR=1"),
+ metavar=_ ("ALT[:MINOR]"),
+ default='0'),
+ p.add_option ('-o', '--output', help=_("write output to FILE"),
+ metavar=_("FILE"),
+ action='store')
+ p.add_option ('-s', '--start-quant',help= _ ("quantise note starts on DUR"),
+ metavar=_ ("DUR"))
+ p.add_option ('-t', '--allow-tuplet',
+ metavar=_ ("DUR*NUM/DEN"),
+ action = "append",
+ dest="allowed_tuplets",
+ help=_ ("allow tuplet durations DUR*NUM/DEN"),
+ default=[])
+ p.add_option ('-V', '--verbose', help=_("be verbose"),
+ action='store_true'
+ ),
+ p.add_option ('-w', '--warranty', help=_("show warranty"),
+ action='store_true',
+ ),
+ p.add_option ('-x', '--text-lyrics', help=_("treat every text as a lyric"),
+ action='store_true')
+
+ p.add_option_group (_ ("example"),
+ description = r'''
+ midi2ly --key=-2:1 --duration-quant=32 \
+ --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
''')
-
- p.add_option_group ('bugs',
- description='''Report bugs via http://post.gmane.org/post.php'''
- '''?group=gmane.comp.gnu.lilypond.bugs\n''')
-
- return p
+
+ p.add_option_group ('bugs',
+ description='''Report bugs via http://post.gmane.org/post.php'''
+ '''?group=gmane.comp.gnu.lilypond.bugs\n''')
+
+ return p
def do_options ():
- opt_parser = get_option_parser()
- (options, args) = opt_parser.parse_args ()
-
- if not args or args[0] == '-':
- opt_parser.print_help ()
- sys.stderr.write ('\n%s: %s %s\n' % (program_name, _ ("error: "),
- _ ("no files specified on command line.")))
- sys.exit (2)
-
- if options.duration_quant:
- options.duration_quant = int (options.duration_quant)
-
- if options.warranty:
- warranty ()
- sys.exit (0)
- if 1:
- (alterations, minor) = map (int, string.split (options.key + ':0', ':'))[0:2]
- sharps = 0
- flats = 0
- if alterations >= 0:
- sharps = alterations
- else:
- flats = - alterations
-
- options.key = Key (sharps, flats, minor)
-
-
- if options.start_quant:
- options.start_quant = int (options.start_quant)
-
- options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
- for a in options.allowed_tuplets]
-
- global global_options
- global_options = options
-
- return args
+ opt_parser = get_option_parser()
+ (options, args) = opt_parser.parse_args ()
+
+ if not args or args[0] == '-':
+ opt_parser.print_help ()
+ sys.stderr.write ('\n%s: %s %s\n' % (program_name, _ ("error: "),
+ _ ("no files specified on command line.")))
+ sys.exit (2)
+
+ if options.duration_quant:
+ options.duration_quant = int (options.duration_quant)
+
+ if options.warranty:
+ warranty ()
+ sys.exit (0)
+ if 1:
+ (alterations, minor) = map (int, string.split (options.key + ':0', ':'))[0:2]
+ sharps = 0
+ flats = 0
+ if alterations >= 0:
+ sharps = alterations
+ else:
+ flats = - alterations
+
+ options.key = Key (sharps, flats, minor)
+
+
+ if options.start_quant:
+ options.start_quant = int (options.start_quant)
+
+ options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
+ for a in options.allowed_tuplets]
+
+ global global_options
+ global_options = options
+
+ return args
def main():
- files = do_options()
-
- for f in files:
- g = f
- g = strip_extension (g, '.midi')
- g = strip_extension (g, '.mid')
- g = strip_extension (g, '.MID')
- (outdir, outbase) = ('','')
-
- if not output_name:
- outdir = '.'
- outbase = os.path.basename (g)
- o = os.path.join (outdir, outbase + '-midi.ly')
- elif output_name[-1] == os.sep:
- outdir = output_name
- outbase = os.path.basename (g)
- os.path.join (outdir, outbase + '-gen.ly')
- else:
- o = output_name
- (outdir, outbase) = os.path.split (o)
-
- if outdir != '.' and outdir != '':
- try:
- os.mkdir (outdir, 0777)
- except OSError:
- pass
-
- convert_midi (f, o)
+ files = do_options()
+
+ for f in files:
+ g = f
+ g = strip_extension (g, '.midi')
+ g = strip_extension (g, '.mid')
+ g = strip_extension (g, '.MID')
+ (outdir, outbase) = ('','')
+
+ if not output_name:
+ outdir = '.'
+ outbase = os.path.basename (g)
+ o = os.path.join (outdir, outbase + '-midi.ly')
+ elif output_name[-1] == os.sep:
+ outdir = output_name
+ outbase = os.path.basename (g)
+ os.path.join (outdir, outbase + '-gen.ly')
+ else:
+ o = output_name
+ (outdir, outbase) = os.path.split (o)
+
+ if outdir != '.' and outdir != '':
+ try:
+ os.mkdir (outdir, 0777)
+ except OSError:
+ pass
+
+ convert_midi (f, o)
if __name__ == '__main__':
- main()
+ main()
diff --git a/scripts/musicxml2ly.py b/scripts/musicxml2ly.py
index 15bbb2ba65..71b41d9dc3 100644
--- a/scripts/musicxml2ly.py
+++ b/scripts/musicxml2ly.py
@@ -10,16 +10,16 @@ from gettext import gettext as _
datadir = '@local_lilypond_datadir@'
if not os.path.isdir (datadir):
- datadir = '@lilypond_datadir@'
+ datadir = '@lilypond_datadir@'
if os.environ.has_key ('LILYPONDPREFIX'):
- datadir = os.environ['LILYPONDPREFIX']
- while datadir[-1] == os.sep:
- datadir = datadir[:-1]
+ datadir = os.environ['LILYPONDPREFIX']
+ while datadir[-1] == os.sep:
+ datadir = datadir[:-1]
if os.path.exists (os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')):
- datadir = os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')
+ datadir = os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')
elif os.path.exists (os.path.join (datadir, 'share/lilypond/current/')):
- datadir = os.path.join (datadir, 'share/lilypond/current/')
+ datadir = os.path.join (datadir, 'share/lilypond/current/')
sys.path.insert (0, os.path.join (datadir, 'python'))
@@ -27,8 +27,8 @@ sys.path.insert (0, os.path.join (datadir, 'python'))
bindir = os.path.split (sys.argv[0])[0]
for prefix_component in ['share', 'lib']:
- datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % prefix_component)
- sys.path.insert (0, datadir)
+ datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % prefix_component)
+ sys.path.insert (0, datadir)
@@ -40,349 +40,349 @@ from rational import Rational
def progress (str):
- sys.stderr.write (str + '\n')
- sys.stderr.flush ()
-
+ sys.stderr.write (str + '\n')
+ sys.stderr.flush ()
+
def musicxml_duration_to_lily (mxl_note):
- d = musicexp.Duration ()
- if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
- d.duration_log = mxl_note.get_duration_log ()
- else:
- d.duration_log = 0
+ d = musicexp.Duration ()
+ if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
+ d.duration_log = mxl_note.get_duration_log ()
+ else:
+ d.duration_log = 0
- d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
- d.factor = mxl_note._duration / d.get_length ()
+ d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
+ d.factor = mxl_note._duration / d.get_length ()
- return d
+ return d
def group_tuplets (music_list, events):
- """Collect Musics from
- MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
- """
+ """Collect Musics from
+ MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
+ """
-
- indices = []
+
+ indices = []
- j = 0
- for (ev_chord, tuplet_elt, fraction) in events:
- while (j < len (music_list)):
- if music_list[j]== ev_chord:
- break
- j += 1
- if tuplet_elt.type == 'start':
- indices.append ((j, None, fraction))
- elif tuplet_elt.type == 'stop':
- indices[-1] = (indices[-1][0], j, indices[-1][2])
+ j = 0
+ for (ev_chord, tuplet_elt, fraction) in events:
+ while (j < len (music_list)):
+ if music_list[j]== ev_chord:
+ break
+ j += 1
+ if tuplet_elt.type == 'start':
+ indices.append ((j, None, fraction))
+ elif tuplet_elt.type == 'stop':
+ indices[-1] = (indices[-1][0], j, indices[-1][2])
- new_list = []
- last = 0
- for (i1, i2, frac) in indices:
- if i1 >= i2:
- continue
+ new_list = []
+ last = 0
+ for (i1, i2, frac) in indices:
+ if i1 >= i2:
+ continue
- new_list.extend (music_list[last:i1])
- seq = musicexp.SequentialMusic ()
- last = i2 + 1
- seq.elements = music_list[i1:last]
+ new_list.extend (music_list[last:i1])
+ seq = musicexp.SequentialMusic ()
+ last = i2 + 1
+ seq.elements = music_list[i1:last]
- tsm = musicexp.TimeScaledMusic ()
- tsm.element = seq
+ tsm = musicexp.TimeScaledMusic ()
+ tsm.element = seq
- tsm.numerator = frac[0]
- tsm.denominator = frac[1]
+ tsm.numerator = frac[0]
+ tsm.denominator = frac[1]
- new_list.append (tsm)
+ new_list.append (tsm)
- new_list.extend (music_list[last:])
- return new_list
+ new_list.extend (music_list[last:])
+ return new_list
def musicxml_clef_to_lily (mxl):
- sign = mxl.get_maybe_exist_named_child ('sign')
- change = musicexp.ClefChange ()
- if sign:
- change.type = sign.get_text ()
- return change
+ sign = mxl.get_maybe_exist_named_child ('sign')
+ change = musicexp.ClefChange ()
+ if sign:
+ change.type = sign.get_text ()
+ return change
-
+
def musicxml_time_to_lily (mxl):
- beats = mxl.get_maybe_exist_named_child ('beats')
- type = mxl.get_maybe_exist_named_child ('beat-type')
- change = musicexp.TimeSignatureChange()
- change.fraction = (string.atoi(beats.get_text ()),
- string.atoi(type.get_text ()))
-
- return change
+ beats = mxl.get_maybe_exist_named_child ('beats')
+ type = mxl.get_maybe_exist_named_child ('beat-type')
+ change = musicexp.TimeSignatureChange()
+ change.fraction = (string.atoi(beats.get_text ()),
+ string.atoi(type.get_text ()))
+
+ return change
def musicxml_key_to_lily (mxl):
- start_pitch = musicexp.Pitch ()
- try:
- mode = mxl.get_maybe_exist_named_child ('mode')
- if mode:
- mode = mode.get_text ()
- else:
- mode = 'major'
-
- (n,a) = { 'major' : (0,0),
- 'minor' : (6,0),
- }[mode]
- start_pitch.step = n
- start_pitch.alteration = a
- except KeyError:
- print 'unknown mode', mode
-
- fifths = string.atoi (mxl.get_maybe_exist_named_child ('fifths').get_text ())
-
- fifth = musicexp.Pitch()
- fifth.step = 4
- if fifths < 0:
- fifths *= -1
- fifth.step *= -1
- fifth.normalize ()
-
- start_pitch = musicexp.Pitch()
- for x in range (fifths):
- start_pitch = start_pitch.transposed (fifth)
-
- start_pitch.octave = 0
-
- change = musicexp.KeySignatureChange()
- change.mode = mode
- change.tonic = start_pitch
- return change
-
+ start_pitch = musicexp.Pitch ()
+ try:
+ mode = mxl.get_maybe_exist_named_child ('mode')
+ if mode:
+ mode = mode.get_text ()
+ else:
+ mode = 'major'
+
+ (n,a) = { 'major' : (0,0),
+ 'minor' : (6,0),
+ }[mode]
+ start_pitch.step = n
+ start_pitch.alteration = a
+ except KeyError:
+ print 'unknown mode', mode
+
+ fifths = string.atoi (mxl.get_maybe_exist_named_child ('fifths').get_text ())
+
+ fifth = musicexp.Pitch()
+ fifth.step = 4
+ if fifths < 0:
+ fifths *= -1
+ fifth.step *= -1
+ fifth.normalize ()
+
+ start_pitch = musicexp.Pitch()
+ for x in range (fifths):
+ start_pitch = start_pitch.transposed (fifth)
+
+ start_pitch.octave = 0
+
+ change = musicexp.KeySignatureChange()
+ change.mode = mode
+ change.tonic = start_pitch
+ return change
+
def musicxml_attributes_to_lily (attrs):
- elts = []
- attr_dispatch = {
- 'clef': musicxml_clef_to_lily,
- 'time': musicxml_time_to_lily,
- 'key': musicxml_key_to_lily
- }
- for (k, func) in attr_dispatch.items ():
- childs = attrs.get_named_children (k)
-
- ## ugh: you get clefs spread over staves for piano
- if childs:
- elts.append (func (childs[0]))
-
- return elts
+ elts = []
+ attr_dispatch = {
+ 'clef': musicxml_clef_to_lily,
+ 'time': musicxml_time_to_lily,
+ 'key': musicxml_key_to_lily
+ }
+ for (k, func) in attr_dispatch.items ():
+ childs = attrs.get_named_children (k)
+
+ ## ugh: you get clefs spread over staves for piano
+ if childs:
+ elts.append (func (childs[0]))
+
+ return elts
def create_skip_music (duration):
- skip = musicexp.SkipEvent()
- skip.duration.duration_log = 0
- skip.duration.factor = duration
+ skip = musicexp.SkipEvent()
+ skip.duration.duration_log = 0
+ skip.duration.factor = duration
- evc = musicexp.EventChord ()
- evc.append (skip)
- return evc
+ evc = musicexp.EventChord ()
+ evc.append (skip)
+ return evc
spanner_event_dict = {
- 'slur' : musicexp.SlurEvent,
- 'beam' : musicexp.BeamEvent,
-}
+ 'slur' : musicexp.SlurEvent,
+ 'beam' : musicexp.BeamEvent,
+}
spanner_type_dict = {
- 'start': -1,
- 'begin': -1,
- 'stop': 1,
- 'end' : 1
+ 'start': -1,
+ 'begin': -1,
+ 'stop': 1,
+ 'end' : 1
}
def musicxml_spanner_to_lily_event (mxl_event):
- ev = None
-
- name = mxl_event.get_name()
- try:
- func = spanner_event_dict[name]
- ev = func()
- except KeyError:
- print 'unknown span event ', mxl_event
-
- try:
- key = mxl_event.get_type ()
- ev.span_direction = spanner_type_dict[key]
- except KeyError:
- print 'unknown span type', key, 'for', name
-
- return ev
+ ev = None
+
+ name = mxl_event.get_name()
+ try:
+ func = spanner_event_dict[name]
+ ev = func()
+ except KeyError:
+ print 'unknown span event ', mxl_event
+
+ try:
+ key = mxl_event.get_type ()
+ ev.span_direction = spanner_type_dict[key]
+ except KeyError:
+ print 'unknown span type', key, 'for', name
+
+ return ev
def musicxml_note_to_lily_main_event (n):
- pitch = None
- duration = None
-
- mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
- event = None
- if mxl_pitch:
- pitch = musicxml_pitch_to_lily (mxl_pitch)
- event = musicexp.NoteEvent()
- event.pitch = pitch
-
- acc = n.get_maybe_exist_named_child ('accidental')
- if acc:
- # let's not force accs everywhere.
- event.cautionary = acc.editorial
-
- elif n.get_maybe_exist_typed_child (musicxml.Rest):
- event = musicexp.RestEvent()
-
- event.duration = musicxml_duration_to_lily (n)
- return event
+ pitch = None
+ duration = None
+
+ mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
+ event = None
+ if mxl_pitch:
+ pitch = musicxml_pitch_to_lily (mxl_pitch)
+ event = musicexp.NoteEvent()
+ event.pitch = pitch
+
+ acc = n.get_maybe_exist_named_child ('accidental')
+ if acc:
+ # let's not force accs everywhere.
+ event.cautionary = acc.editorial
+
+ elif n.get_maybe_exist_typed_child (musicxml.Rest):
+ event = musicexp.RestEvent()
+
+ event.duration = musicxml_duration_to_lily (n)
+ return event
def musicxml_voice_to_lily_voice (voice):
- ly_voice = []
- ly_now = Rational (0)
- pending_skip = Rational (0)
-
- tuplet_events = []
-
- for n in voice._elements:
- if n.get_name () == 'forward':
- continue
-
- if isinstance (n, musicxml.Attributes):
- ly_now += pending_skip
- pending_skip = Rational (0)
-
- ly_voice.extend (musicxml_attributes_to_lily (n))
- continue
-
- if not n.__class__.__name__ == 'Note':
- print 'not a Note or Attributes?', n
- continue
-
- if n.is_first () and ly_voice:
- ly_voice[-1].comment += '\n'
-
-
- main_event = musicxml_note_to_lily_main_event (n)
-
- ev_chord = None
- if None == n.get_maybe_exist_typed_child (musicxml.Chord):
- ly_now += pending_skip
- pending_skip = main_event.get_length ()
-
- if ly_now <> n._when:
- diff = n._when - ly_now
-
- if diff < Rational (0):
- print 'huh: negative skip', n._when, ly_now, n._duration
- diff = Rational (1,314159265)
-
- ly_voice.append (create_skip_music (diff))
- ly_now = n._when
-
- ly_voice.append (musicexp.EventChord())
- else:
- pass
-
- ev_chord = ly_voice[-1]
- ev_chord.append (main_event)
-
- notations = n.get_maybe_exist_typed_child (musicxml.Notations)
- tuplet_event = None
- span_events = []
- if notations:
- if notations.get_tuplet():
- tuplet_event = notations.get_tuplet()
- mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
- frac = (1,1)
- if mod:
- frac = mod.get_fraction ()
-
- tuplet_events.append ((ev_chord, tuplet_event, frac))
-
- slurs = [s for s in notations.get_named_children ('slur')
- if s.get_type () in ('start','stop')]
- if slurs:
- if len (slurs) > 1:
- print 'more than 1 slur?'
-
- lily_ev = musicxml_spanner_to_lily_event (slurs[0])
- ev_chord.append (lily_ev)
-
- mxl_tie = notations.get_tie ()
- if mxl_tie and mxl_tie.type == 'start':
- ev_chord.append (musicexp.TieEvent ())
-
- mxl_beams = [b for b in n.get_named_children ('beam')
- if b.get_type () in ('begin', 'end')]
- if mxl_beams:
- beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
- if beam_ev:
- ev_chord.append (beam_ev)
-
- if tuplet_event:
- mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
- frac = (1,1)
- if mod:
- frac = mod.get_fraction ()
-
- tuplet_events.append ((ev_chord, tuplet_event, frac))
-
- ly_voice = group_tuplets (ly_voice, tuplet_events)
-
- seq_music = musicexp.SequentialMusic()
-
- seq_music.elements = ly_voice
- return seq_music
+ ly_voice = []
+ ly_now = Rational (0)
+ pending_skip = Rational (0)
+
+ tuplet_events = []
+
+ for n in voice._elements:
+ if n.get_name () == 'forward':
+ continue
+
+ if isinstance (n, musicxml.Attributes):
+ ly_now += pending_skip
+ pending_skip = Rational (0)
+
+ ly_voice.extend (musicxml_attributes_to_lily (n))
+ continue
+
+ if not n.__class__.__name__ == 'Note':
+ print 'not a Note or Attributes?', n
+ continue
+
+ if n.is_first () and ly_voice:
+ ly_voice[-1].comment += '\n'
+
+
+ main_event = musicxml_note_to_lily_main_event (n)
+
+ ev_chord = None
+ if None == n.get_maybe_exist_typed_child (musicxml.Chord):
+ ly_now += pending_skip
+ pending_skip = main_event.get_length ()
+
+ if ly_now <> n._when:
+ diff = n._when - ly_now
+
+ if diff < Rational (0):
+ print 'huh: negative skip', n._when, ly_now, n._duration
+ diff = Rational (1,314159265)
+
+ ly_voice.append (create_skip_music (diff))
+ ly_now = n._when
+
+ ly_voice.append (musicexp.EventChord())
+ else:
+ pass
+
+ ev_chord = ly_voice[-1]
+ ev_chord.append (main_event)
+
+ notations = n.get_maybe_exist_typed_child (musicxml.Notations)
+ tuplet_event = None
+ span_events = []
+ if notations:
+ if notations.get_tuplet():
+ tuplet_event = notations.get_tuplet()
+ mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
+ frac = (1,1)
+ if mod:
+ frac = mod.get_fraction ()
+
+ tuplet_events.append ((ev_chord, tuplet_event, frac))
+
+ slurs = [s for s in notations.get_named_children ('slur')
+ if s.get_type () in ('start','stop')]
+ if slurs:
+ if len (slurs) > 1:
+ print 'more than 1 slur?'
+
+ lily_ev = musicxml_spanner_to_lily_event (slurs[0])
+ ev_chord.append (lily_ev)
+
+ mxl_tie = notations.get_tie ()
+ if mxl_tie and mxl_tie.type == 'start':
+ ev_chord.append (musicexp.TieEvent ())
+
+ mxl_beams = [b for b in n.get_named_children ('beam')
+ if b.get_type () in ('begin', 'end')]
+ if mxl_beams:
+ beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
+ if beam_ev:
+ ev_chord.append (beam_ev)
+
+ if tuplet_event:
+ mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
+ frac = (1,1)
+ if mod:
+ frac = mod.get_fraction ()
+
+ tuplet_events.append ((ev_chord, tuplet_event, frac))
+
+ ly_voice = group_tuplets (ly_voice, tuplet_events)
+
+ seq_music = musicexp.SequentialMusic()
+
+ seq_music.elements = ly_voice
+ return seq_music
def musicxml_id_to_lily (id):
- digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
- 'nine', 'ten']
-
- for dig in digits:
- d = digits.index (dig) + 1
- dig = dig[0].upper() + dig[1:]
- id = re.sub ('%d' % d, dig, id)
+ digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
+ 'nine', 'ten']
+
+ for dig in digits:
+ d = digits.index (dig) + 1
+ dig = dig[0].upper() + dig[1:]
+ id = re.sub ('%d' % d, dig, id)
- id = re.sub ('[^a-zA-Z]', 'X', id)
- return id
+ id = re.sub ('[^a-zA-Z]', 'X', id)
+ return id
def musicxml_pitch_to_lily (mxl_pitch):
- p = musicexp.Pitch()
- p.alteration = mxl_pitch.get_alteration ()
- p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
- p.octave = mxl_pitch.get_octave () - 4
- return p
+ p = musicexp.Pitch()
+ p.alteration = mxl_pitch.get_alteration ()
+ p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
+ p.octave = mxl_pitch.get_octave () - 4
+ return p
def voices_in_part (part):
- """Return a Name -> Voice dictionary for PART"""
- part.interpret ()
- part.extract_voices ()
- voice_dict = part.get_voices ()
+ """Return a Name -> Voice dictionary for PART"""
+ part.interpret ()
+ part.extract_voices ()
+ voice_dict = part.get_voices ()
- return voice_dict
+ return voice_dict
def voices_in_part_in_parts (parts):
- """return a Part -> Name -> Voice dictionary"""
- return dict([(p, voices_in_part (p)) for p in parts])
+ """return a Part -> Name -> Voice dictionary"""
+ return dict([(p, voices_in_part (p)) for p in parts])
def get_all_voices (parts):
- all_voices = voices_in_part_in_parts (parts)
+ all_voices = voices_in_part_in_parts (parts)
- all_ly_voices = {}
- for p, name_voice in all_voices.items ():
+ all_ly_voices = {}
+ for p, name_voice in all_voices.items ():
- part_ly_voices = {}
- for n, v in name_voice.items ():
- progress ("Converting to LilyPond expressions...")
- part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
+ part_ly_voices = {}
+ for n, v in name_voice.items ():
+ progress ("Converting to LilyPond expressions...")
+ part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
- all_ly_voices[p] = part_ly_voices
-
- return all_ly_voices
+ all_ly_voices[p] = part_ly_voices
+
+ return all_ly_voices
def option_parser ():
- p = ly.get_option_parser(usage='musicxml2ly FILE.xml',
- version = """%prog (LilyPond) @TOPLEVEL_VERSION@
+ p = ly.get_option_parser(usage='musicxml2ly FILE.xml',
+ version = """%prog (LilyPond) @TOPLEVEL_VERSION@
This program is free software. It is covered by the GNU General Public
License and you are welcome to change it and/or distribute copies of it
@@ -390,145 +390,145 @@ under certain conditions. Invoke as `lilypond --warranty' for more
information.
Copyright (c) 2005--2006 by
- Han-Wen Nienhuys and
- Jan Nieuwenhuizen
+ Han-Wen Nienhuys and
+ Jan Nieuwenhuizen
""",
- description =
- """Convert MusicXML file to LilyPond input.
+ description =
+ """Convert MusicXML file to LilyPond input.
"""
- )
- p.add_option ('-v', '--verbose',
- action = "store_true",
- dest = 'verbose',
- help = 'be verbose')
- p.add_option ('-o', '--output',
- metavar = 'FILE',
- action = "store",
- default = None,
- type = 'string',
- dest = 'output',
- help = 'set output file')
-
- p.add_option_group ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
+ )
+ p.add_option ('-v', '--verbose',
+ action = "store_true",
+ dest = 'verbose',
+ help = 'be verbose')
+ p.add_option ('-o', '--output',
+ metavar = 'FILE',
+ action = "store",
+ default = None,
+ type = 'string',
+ dest = 'output',
+ help = 'set output file')
+
+ p.add_option_group ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
''')
- return p
+ return p
def music_xml_voice_name_to_lily_name (part, name):
- str = "Part%sVoice%s" % (part.id, name)
- return musicxml_id_to_lily (str)
+ str = "Part%sVoice%s" % (part.id, name)
+ return musicxml_id_to_lily (str)
def print_voice_definitions (printer, voices):
- for (part, nv_dict) in voices.items():
- for (name, (voice, mxlvoice)) in nv_dict.items ():
- k = music_xml_voice_name_to_lily_name (part, name)
- printer.dump ('%s = ' % k)
- voice.print_ly (printer)
- printer.newline()
+ for (part, nv_dict) in voices.items():
+ for (name, (voice, mxlvoice)) in nv_dict.items ():
+ k = music_xml_voice_name_to_lily_name (part, name)
+ printer.dump ('%s = ' % k)
+ voice.print_ly (printer)
+ printer.newline()
def uniq_list (l):
- return dict ([(elt,1) for elt in l]).keys ()
-
+ return dict ([(elt,1) for elt in l]).keys ()
+
def print_score_setup (printer, part_list, voices):
- part_dict = dict ([(p.id, p) for p in voices.keys ()])
-
- printer ('<<')
- printer.newline ()
- for part_definition in part_list:
- part_name = part_definition.id
- try:
- part = part_dict[part_name]
- except KeyError:
- print 'unknown part in part-list:', part_name
- continue
-
- nv_dict = voices[part]
- staves = reduce (lambda x,y: x+ y,
- [mxlvoice._staves.keys ()
- for (v, mxlvoice) in nv_dict.values ()],
- [])
-
- if len (staves) > 1:
- staves = uniq_list (staves)
- staves.sort ()
- printer ('\\context PianoStaff << ')
- printer.newline ()
-
- for s in staves:
- staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
- for (voice_name, (v, mxlvoice)) in nv_dict.items ()
- if mxlvoice._start_staff == s]
-
- printer ('\\context Staff = "%s" << ' % s)
- printer.newline ()
- for v in staff_voices:
- printer ('\\context Voice = "%s" \\%s' % (v,v))
- printer.newline ()
- printer ('>>')
- printer.newline ()
-
- printer ('>>')
- printer.newline ()
-
- else:
- printer ('\\new Staff <<')
- printer.newline ()
- for (n,v) in nv_dict.items ():
-
- n = music_xml_voice_name_to_lily_name (part, n)
- printer ('\\context Voice = "%s" \\%s' % (n,n))
- printer ('>>')
- printer.newline ()
-
-
- printer ('>>')
- printer.newline ()
-
-
+ part_dict = dict ([(p.id, p) for p in voices.keys ()])
+
+ printer ('<<')
+ printer.newline ()
+ for part_definition in part_list:
+ part_name = part_definition.id
+ try:
+ part = part_dict[part_name]
+ except KeyError:
+ print 'unknown part in part-list:', part_name
+ continue
+
+ nv_dict = voices[part]
+ staves = reduce (lambda x,y: x+ y,
+ [mxlvoice._staves.keys ()
+ for (v, mxlvoice) in nv_dict.values ()],
+ [])
+
+ if len (staves) > 1:
+ staves = uniq_list (staves)
+ staves.sort ()
+ printer ('\\context PianoStaff << ')
+ printer.newline ()
+
+ for s in staves:
+ staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
+ for (voice_name, (v, mxlvoice)) in nv_dict.items ()
+ if mxlvoice._start_staff == s]
+
+ printer ('\\context Staff = "%s" << ' % s)
+ printer.newline ()
+ for v in staff_voices:
+ printer ('\\context Voice = "%s" \\%s' % (v,v))
+ printer.newline ()
+ printer ('>>')
+ printer.newline ()
+
+ printer ('>>')
+ printer.newline ()
+
+ else:
+ printer ('\\new Staff <<')
+ printer.newline ()
+ for (n,v) in nv_dict.items ():
+
+ n = music_xml_voice_name_to_lily_name (part, n)
+ printer ('\\context Voice = "%s" \\%s' % (n,n))
+ printer ('>>')
+ printer.newline ()
+
+
+ printer ('>>')
+ printer.newline ()
+
+
def print_ly_preamble (printer, filename):
- printer.dump_version ()
- printer.print_verbatim ('%% converted from %s\n' % filename)
+ printer.dump_version ()
+ printer.print_verbatim ('%% converted from %s\n' % filename)
def convert (filename, output_name):
- printer = musicexp.Output_printer()
- progress ("Reading MusicXML...")
-
- tree = musicxml.read_musicxml (filename)
- parts = tree.get_typed_children (musicxml.Part)
- voices = get_all_voices (parts)
-
- part_list = []
- if tree.get_maybe_exist_typed_child (musicxml.Part_list):
- pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
- part_list = pl.get_named_children ("score-part")
-
- if not output_name:
- output_name = os.path.basename (filename)
- output_name = os.path.splitext (output_name)[0] + '.ly'
-
-
- if output_name:
- progress ("Output to `%s'" % output_name)
- printer.set_file (open (output_name, 'w'))
-
- progress ("Printing as .ly...")
-
- print_ly_preamble (printer, filename)
- print_voice_definitions (printer, voices)
- print_score_setup (printer, part_list, voices)
- printer.newline ()
- return voices
+ printer = musicexp.Output_printer()
+ progress ("Reading MusicXML...")
+
+ tree = musicxml.read_musicxml (filename)
+ parts = tree.get_typed_children (musicxml.Part)
+ voices = get_all_voices (parts)
+
+ part_list = []
+ if tree.get_maybe_exist_typed_child (musicxml.Part_list):
+ pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
+ part_list = pl.get_named_children ("score-part")
+
+ if not output_name:
+ output_name = os.path.basename (filename)
+ output_name = os.path.splitext (output_name)[0] + '.ly'
+
+
+ if output_name:
+ progress ("Output to `%s'" % output_name)
+ printer.set_file (open (output_name, 'w'))
+
+ progress ("Printing as .ly...")
+
+ print_ly_preamble (printer, filename)
+ print_voice_definitions (printer, voices)
+ print_score_setup (printer, part_list, voices)
+ printer.newline ()
+ return voices
def main ():
- opt_parser = option_parser()
+ opt_parser = option_parser()
- (options, args) = opt_parser.parse_args ()
- if not args:
- opt_parser.print_usage()
- sys.exit (2)
+ (options, args) = opt_parser.parse_args ()
+ if not args:
+ opt_parser.print_usage()
+ sys.exit (2)
- voices = convert (args[0], options.output)
+ voices = convert (args[0], options.output)
if __name__ == '__main__':
- main()
+ main()
--
2.39.2