7 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
10 lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
12 classic lilypond-book:
13 lilypond-book --process="lilypond" BOOK.tely
17 * this script is too complex. Modularize.
19 * ly-options: intertext?
21 * eps in latex / eps by lilypond -b ps?
22 * check latex parameters, twocolumn, multicolumn?
23 * use --png --ps --pdf for making images?
25 * Converting from lilypond-book source, substitute:
26 @mbinclude foo.itely -> @include foo.itely
49 program_version = '@TOPLEVEL_VERSION@'
50 program_name = os.path.basename (sys.argv[0])
52 original_dir = os.getcwd ()
56 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
60 lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
61 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" %(BOOK)s
62 lilypond-book --process='lilypond -I include' %(BOOK)s
63 ''' % {'BOOK': _ ("BOOK")})
65 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
66 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
68 ################################################################
70 if global_options.verbose:
71 raise Exception (_ ('Exiting (%d)...') % i)
76 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
78 progress = ly.progress
81 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
84 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
86 def ps_page_count (ps_name):
87 header = file (ps_name).read (1024)
88 m = re.search ('\n%%Pages: ([0-9]+)', header)
90 return int (m.group (1))
95 ly.encoded_write (sys.stdout, '''
102 ''' % ( _ ('Copyright (c) %s by') % '2001--2007',
104 _ ("Distributed under terms of the GNU General Public License."),
105 _ ("It comes with NO WARRANTY.")))
107 def get_option_parser ():
108 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
109 description=help_summary,
110 add_help_option=False)
112 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
115 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
118 p.add_option ('-f', '--format',
119 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
122 p.add_option("-h", "--help",
124 help=_ ("show this help and exit"))
126 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
128 action='append', dest='include_path',
129 default=[os.path.abspath (os.getcwd ())])
131 p.add_option ('--info-images-dir',
132 help=_ ("format Texinfo output so that Info will "
133 "look for images of music in DIR"),
135 action='store', dest='info_images_dir',
138 p.add_option ('--left-padding',
141 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
145 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
147 action='store', dest='output_dir',
150 p.add_option ('--lily-output-dir',
151 help=_ ("write lily-XXX files to DIR, link into --output dir."),
153 action='store', dest='lily_output_dir',
156 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
157 help = _ ("process ly_files using COMMAND FILE..."),
159 dest='process_cmd', default='')
161 p.add_option ('--pdf',
164 help=_ ("create PDF files for use with PDFTeX"),
167 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
168 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
169 must use this with dvips -h INPUT.psfonts'''),
172 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
177 p.version = "@TOPLEVEL_VERSION@"
178 p.add_option("--version",
180 help=_ ("show version number and exit"))
182 p.add_option ('-w', '--warranty',
183 help=_ ("show warranty and copyright"),
185 p.add_option_group (ly.display_encode (_ ('Bugs')),
186 description=(_ ("Report bugs via")
187 + ''' http://post.gmane.org/post.php'''
188 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
191 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
193 # Only use installed binary when we are installed too.
194 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
195 lilypond_binary = 'lilypond'
197 global_options = None
200 default_ly_options = { 'alt': "[image of music]" }
203 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
205 ADDVERSION = 'addversion'
209 EXAMPLEINDENT = 'exampleindent'
211 FRAGMENT = 'fragment'
216 LINE_WIDTH = 'line-width'
217 LILYQUOTE = 'lilyquote'
218 NOFRAGMENT = 'nofragment'
219 NOINDENT = 'noindent'
224 OUTPUTIMAGE = 'outputimage'
227 PREAMBLE = 'preamble'
228 PRINTFILENAME = 'printfilename'
230 RAGGED_RIGHT = 'ragged-right'
231 RELATIVE = 'relative'
232 STAFFSIZE = 'staffsize'
235 VERBATIM = 'verbatim'
236 FONTLOAD = 'fontload'
237 FILENAME = 'filename'
241 # NOTIME has no opposite so it isn't part of this dictionary.
242 # NOQUOTE is used internally only.
244 NOFRAGMENT: FRAGMENT,
249 # Recognize special sequences in the input.
251 # (?P<name>regex) -- Assign result of REGEX to NAME.
252 # *? -- Match non-greedily.
253 # (?m) -- Multiline regex: Make ^ and $ match at each line.
254 # (?s) -- Make the dot match all characters including newline.
255 # (?x) -- Ignore whitespace in patterns.
266 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
271 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
276 <(?P<inline>(inline)?)mediaobject>\s*<imageobject.*?>\s*<imagedata\s+fileref="(?P<filename>.*?\.ly)"\s*(role="(?P<options>.*?)")?\s*(/>|>\s*</imagedata>)\s*</imageobject>\s*</(inline)?mediaobject>)''',
282 (?P<code><!--\s.*?!-->)
285 'singleline_comment':
304 (\s*(?P<options>.*?)\s*:)?\s*
312 \s*(?P<options>.*?)\s*
321 \s*(?P<options>.*?)\s*
323 \s*(?P<filename>.*?)\s*
330 (?P<code><!--\s.*?!-->)
333 'singleline_comment':
339 (?P<code><pre>.*?</pre>))''',
345 (?P<code><pre>\s.*?</pre>\s))''',
364 \s*(?P<options>.*?)\s*
375 \s*(?P<options>.*?)\s*
379 \\end\s*{lilypond})''',
387 \s*(?P<options>.*?)\s*
395 'singleline_comment':
418 \\end\s*{verbatim}))''',
427 (?P<filename>\S+))''',
431 ^[^\n]*?(?!@c\s+)[^\n]*?
435 \s*(?P<options>.*?)\s*
445 \s*(?P<options>.*?)\s*
448 ^@end\s+lilypond)\s''',
455 \s*(?P<options>.*?)\s*
466 @end\s+ignore))\s''',
468 'singleline_comment':
473 @c([ \t][^\n]*|)\n))''',
475 # Don't do this: It interferes with @code{@{}.
476 # 'verb': r'''(?P<code>@code{.*?})''',
484 @end\s+example\s))''',
493 'intertext': r',?\s*intertext=\".*?\"',
497 'intertext': r',?\s*intertext=\".*?\"',
502 'intertext': r',?\s*intertext=\".*?\"',
503 'option_sep': '\s*,\s*',
507 'intertext': r',?\s*intertext=\".*?\"',
508 'option_sep': '\s*,\s*',
512 # Options without a pattern in ly_options.
530 RELATIVE: r'''\relative c%(relative_quotes)s''',
535 INDENT: r'''indent = %(indent)s''',
537 LINE_WIDTH: r'''line-width = %(line-width)s''',
539 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
541 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
543 RAGGED_RIGHT: r'''ragged-right = ##t''',
545 PACKED: r'''packed = ##t''',
557 \remove Time_signature_engraver
563 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
570 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
573 <imageobject role="latex">
574 <imagedata fileref="%(base)s.pdf" format="PDF"/>
576 <imageobject role="html">
577 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
579 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
581 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
585 FILTER: r'''<lilypond %(options)s>
595 <a href="%(base)s.ly">''',
599 border="0" src="%(image)s" alt="%(alt)s">''',
601 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
603 QUOTE: r'''<blockquote>
616 \ifx\preLilyPondExample \undefined%%
619 \preLilyPondExample%%
621 \def\lilypondbook{}%%
622 \input %(base)s-systems.tex%%
623 \ifx\postLilyPondExample \undefined%%
626 \postLilyPondExample%%
630 PRINTFILENAME: '''\\texttt{%(filename)s}
633 QUOTE: r'''\begin{quotation}%(str)s
636 VERBATIM: r'''\noindent
637 \begin{verbatim}%(verb)s\end{verbatim}''',
639 FILTER: r'''\begin{lilypond}[%(options)s]
646 FILTER: r'''@lilypond[%(options)s]
652 @include %(base)s-systems.texi
656 OUTPUTIMAGE: r'''@noindent
658 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
662 <a href="%(base)s.ly">
664 border="0" src="%(image)s" alt="%(alt)s">
672 <a href="%(base)s.ly">
680 QUOTE: r'''@quotation
681 %(str)s@end quotation
688 VERBATIM: r'''@exampleindent 0
690 %(verb)s@end verbatim
693 ADDVERSION: r'''@example
694 \version @w{"@version{}"}
701 # Maintain line numbers.
706 for f in [HTML, LATEX]:
707 for s in (QUOTE, VERBATIM):
708 output[f][s] = output[f][s].replace("\n"," ")
711 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
712 %%%% Options: [%(option_string)s]
713 \\include "lilypond-book-preamble.ly"
716 %% ****************************************************************
717 %% Start cut-&-pastable-section
718 %% ****************************************************************
723 #(define dump-extents #t)
724 %(font_dump_setting)s
726 force-assignment = #""
727 line-width = #(- line-width (* mm %(padding_mm)f))
740 %% ****************************************************************
741 %% ly snippet contents follows:
742 %% ****************************************************************
746 %% ****************************************************************
748 %% ****************************************************************
755 %% ****************************************************************
757 %% ****************************************************************
761 %% ****************************************************************
763 %% ****************************************************************
766 texinfo_line_widths = {
767 '@afourpaper': '160\\mm',
768 '@afourwide': '6.5\\in',
769 '@afourlatex': '150\\mm',
770 '@smallbook': '5\\in',
771 '@letterpaper': '6\\in',
774 def classic_lilypond_book_compatibility (key, value):
775 if key == 'singleline' and value == None:
776 return (RAGGED_RIGHT, None)
778 m = re.search ('relative\s*([-0-9])', key)
780 return ('relative', m.group (1))
782 m = re.match ('([0-9]+)pt', key)
784 return ('staffsize', m.group (1))
786 if key == 'indent' or key == 'line-width':
787 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
789 f = float (m.group (1))
790 return (key, '%f\\%s' % (f, m.group (2)))
794 def find_file (name, raise_error=True):
795 for i in global_options.include_path:
796 full = os.path.join (i, name)
797 if os.path.exists (full):
801 error (_ ("file not found: %s") % name + '\n')
805 def verbatim_html (s):
806 return re.sub ('>', '>',
808 re.sub ('&', '&', s)))
810 def split_options (option_string):
812 if global_options.format == HTML:
813 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
814 for i in range(len(options)):
815 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
818 return re.split (format_res[global_options.format]['option_sep'],
822 def set_default_options (source):
823 global default_ly_options
824 if not default_ly_options.has_key (LINE_WIDTH):
825 if global_options.format == LATEX:
826 textwidth = get_latex_textwidth (source)
827 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
828 elif global_options.format == TEXINFO:
829 for (k, v) in texinfo_line_widths.items ():
830 # FIXME: @layout is usually not in
833 # \input texinfo @c -*-texinfo-*-
835 # Bluntly search first K items of
837 # s = chunks[0].replacement_text ()
838 if re.search (k, source[:1024]):
839 default_ly_options[LINE_WIDTH] = v
843 def replacement_text (self):
846 def filter_text (self):
847 return self.replacement_text ()
849 def ly_is_outdated (self):
852 def png_is_outdated (self):
858 class Substring (Chunk):
859 """A string that does not require extra memory."""
860 def __init__ (self, source, start, end, line_number):
864 self.line_number = line_number
865 self.override_text = None
870 def replacement_text (self):
871 if self.override_text:
872 return self.override_text
874 return self.source[self.start:self.end]
876 class Snippet (Chunk):
877 def __init__ (self, type, match, format, line_number):
881 self.option_dict = {}
883 self.line_number = line_number
885 def replacement_text (self):
886 return self.match.group ('match')
888 def substring (self, s):
889 return self.match.group (s)
892 return `self.__class__` + ' type = ' + self.type
894 class IncludeSnippet (Snippet):
895 def processed_filename (self):
896 f = self.substring ('filename')
897 return os.path.splitext (f)[0] + format2ext[global_options.format]
899 def replacement_text (self):
900 s = self.match.group ('match')
901 f = self.substring ('filename')
903 return re.sub (f, self.processed_filename (), s)
905 class LilypondSnippet (Snippet):
906 def __init__ (self, type, match, format, line_number):
907 Snippet.__init__ (self, type, match, format, line_number)
908 os = match.group ('options')
909 self.do_options (os, self.type)
912 return self.substring ('code')
915 contents = self.substring ('code')
916 return ('\\sourcefileline %d\n%s'
917 % (self.line_number - 1, contents))
922 return self.compose_ly (s)
925 def do_options (self, option_string, type):
926 self.option_dict = {}
928 options = split_options (option_string)
932 (key, value) = re.split ('\s*=\s*', i)
933 self.option_dict[key] = value
935 if i in no_options.keys ():
936 if no_options[i] in self.option_dict.keys ():
937 del self.option_dict[no_options[i]]
939 self.option_dict[i] = None
941 has_line_width = self.option_dict.has_key (LINE_WIDTH)
942 no_line_width_value = 0
944 # If LINE_WIDTH is used without parameter, set it to default.
945 if has_line_width and self.option_dict[LINE_WIDTH] == None:
946 no_line_width_value = 1
947 del self.option_dict[LINE_WIDTH]
949 for i in default_ly_options.keys ():
950 if i not in self.option_dict.keys ():
951 self.option_dict[i] = default_ly_options[i]
953 if not has_line_width:
954 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
955 self.option_dict[RAGGED_RIGHT] = None
957 if type == 'lilypond':
958 if LINE_WIDTH in self.option_dict.keys ():
959 del self.option_dict[LINE_WIDTH]
961 if RAGGED_RIGHT in self.option_dict.keys ():
962 if LINE_WIDTH in self.option_dict.keys ():
963 del self.option_dict[LINE_WIDTH]
965 if QUOTE in self.option_dict.keys () or type == 'lilypond':
966 if LINE_WIDTH in self.option_dict.keys ():
967 del self.option_dict[LINE_WIDTH]
969 if not INDENT in self.option_dict.keys ():
970 self.option_dict[INDENT] = '0\\mm'
972 # The QUOTE pattern from ly_options only emits the `line-width'
974 if has_line_width and QUOTE in self.option_dict.keys ():
975 if no_line_width_value:
976 del self.option_dict[LINE_WIDTH]
978 del self.option_dict[QUOTE]
980 def compose_ly (self, code):
981 if FRAGMENT in self.option_dict.keys ():
989 # The original concept of the `exampleindent' option is broken.
990 # It is not possible to get a sane value for @exampleindent at all
991 # without processing the document itself. Saying
999 # causes ugly results with the DVI backend of texinfo since the
1000 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1001 # value). Executing the above code changes the environment
1002 # indentation to an unknown value because we don't know the amount
1003 # of 1em in advance since it is font-dependent. Modifying
1004 # @exampleindent in the middle of a document is simply not
1005 # supported within texinfo.
1007 # As a consequence, the only function of @exampleindent is now to
1008 # specify the amount of indentation for the `quote' option.
1010 # To set @exampleindent locally to zero, we use the @format
1011 # environment for non-quoted snippets.
1012 override[EXAMPLEINDENT] = r'0.4\in'
1013 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1014 override.update (default_ly_options)
1017 for (key, value) in self.option_dict.items ():
1019 option_list.append (key)
1021 option_list.append (key + '=' + value)
1022 option_string = ','.join (option_list)
1025 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1026 for a in compose_types:
1027 compose_dict[a] = []
1029 for (key, value) in self.option_dict.items ():
1030 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1034 _ ("deprecated ly-option used: %s=%s"
1037 _ ("compatibility mode translation: %s=%s"
1038 % (c_key, c_value)))
1041 _ ("deprecated ly-option used: %s"
1044 _ ("compatibility mode translation: %s"
1047 (key, value) = (c_key, c_value)
1050 override[key] = value
1052 if not override.has_key (key):
1053 override[key] = None
1056 for type in compose_types:
1057 if ly_options[type].has_key (key):
1058 compose_dict[type].append (ly_options[type][key])
1062 if not found and key not in simple_options:
1063 warning (_ ("ignoring unknown ly option: %s") % key)
1066 if RELATIVE in override.keys () and override[RELATIVE]:
1067 relative = int (override[RELATIVE])
1069 relative_quotes = ''
1073 relative_quotes += ',' * (- relative)
1075 relative_quotes += "'" * relative
1077 paper_string = '\n '.join (compose_dict[PAPER]) % override
1078 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1079 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1080 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1081 padding_mm = global_options.padding_mm
1082 font_dump_setting = ''
1083 if FONTLOAD in self.option_dict:
1084 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1086 d = globals().copy()
1088 return (PREAMBLE_LY + body) % d
1090 def get_checksum (self):
1091 if not self.checksum:
1092 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1094 ## let's not create too long names.
1095 self.checksum = hash.hexdigest ()[:10]
1097 return self.checksum
1099 def basename (self):
1100 if FILENAME in self.option_dict:
1101 return self.option_dict[FILENAME]
1103 cs = self.get_checksum ()
1105 # TODO: use xx/xxxxx directory layout.
1106 name = 'lily-%s' % cs[:10]
1107 if global_options.lily_output_dir:
1108 name = os.path.join (global_options.lily_output_dir, name)
1111 def write_ly (self):
1112 out = file (self.basename () + '.ly', 'w')
1113 out.write (self.full_ly ())
1114 file (self.basename () + '.txt', 'w').write ('image of music')
1116 def relevant_contents (self, ly):
1117 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1119 def link_all_output_files (self, output_dir, output_dir_files, destination):
1120 existing = self.all_output_files (output_dir_files)
1121 for name in existing:
1123 os.unlink (os.path.join (destination, name))
1127 src = os.path.join (output_dir, name)
1128 dst = os.path.join (destination, name)
1132 def all_output_files (self, output_dir_files):
1133 """Return all files generated in lily_output_dir.
1135 output_dir_files is the list of files in the output directory.
1137 base = os.path.basename(self.basename())
1143 result.add (required)
1145 def consider_file (name):
1146 if name in output_dir_files:
1149 map (consider_file, [base + '.tex',
1151 base + '-systems.count',
1152 base + '-systems.texi',
1153 base + '-systems.tex',
1154 base + '-systems.pdftexi'])
1156 if base + '.eps' in result:
1157 page_count = ps_page_count (self.basename() + '.eps')
1159 consider_file (base + '.png')
1161 for a in range (1, page_count + 1):
1162 consider_file (base + '-page%d.png' % a)
1164 if (base + '-systems.count') in result:
1165 system_count = int(file (self.basename () + '-systems.count').read())
1166 for number in range(1, system_count + 1):
1167 systemfile = '%s-%d' % (base, number)
1168 consider_file (systemfile + '.eps')
1169 consider_file (systemfile + '.pdf')
1173 def ly_is_outdated (self):
1174 base = self.basename ()
1175 ly_file = find_file (base + '.ly', raise_error=False)
1176 tex_file = find_file (base + '.tex', raise_error=False)
1177 systems_file = find_file (base + '-systems.tex', raise_error=False)
1179 if (not os.path.exists (ly_file)
1180 or not os.path.exists (systems_file)):
1183 lines = file (systems_file).readlines ()
1187 if not re.match ('% eof', lines[-1]):
1190 # and FILENAME in self.option_dict
1193 if (self.relevant_contents (self.full_ly ())
1194 != self.relevant_contents (file (ly_file).read ())):
1199 def png_is_outdated (self):
1200 base = self.basename ()
1201 eps_file = find_file (base + '.eps', raise_error=False)
1202 png_file = find_file (base + '.png', raise_error=False)
1203 if self.ly_is_outdated ():
1206 if (global_options.format in (HTML, TEXINFO)
1207 and os.path.exists (eps_file)):
1208 page_count = ps_page_count (eps_file)
1210 return not os.path.exists (png_file)
1212 for a in range (1, page_count + 1):
1213 if not find_file (base + '-page%d.png' % a,
1219 def filter_text (self):
1220 """Run snippet bodies through a command (say: convert-ly).
1222 This functionality is rarely used, and this code must have bitrot.
1225 code = self.substring ('code')
1226 s = filter_pipe (code, global_options.filter_cmd)
1229 'options': self.match.group ('options')
1232 return output[self.format][FILTER] % d
1234 def replacement_text (self):
1235 func = LilypondSnippet.__dict__['output_' + self.format]
1238 def get_images (self):
1239 base = self.basename ()
1241 single = '%(base)s.png' % vars ()
1242 multiple = '%(base)s-page1.png' % vars ()
1244 if (os.path.exists (multiple)
1245 and (not os.path.exists (single)
1246 or (os.stat (multiple)[stat.ST_MTIME]
1247 > os.stat (single)[stat.ST_MTIME]))):
1248 count = ps_page_count ('%(base)s.eps' % vars ())
1249 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1250 images = tuple (images)
1253 def output_docbook (self):
1255 base = self.basename ()
1256 for image in self.get_images ():
1257 (base, ext) = os.path.splitext (image)
1258 str += output[DOCBOOK][OUTPUT] % vars ()
1259 str += self.output_print_filename (DOCBOOK)
1260 if (self.substring('inline') == 'inline'):
1261 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1263 str = '<mediaobject>' + str + '</mediaobject>'
1264 if VERBATIM in self.option_dict:
1265 verb = verbatim_html (self.verb_ly ())
1266 str = output[DOCBOOK][VERBATIM] % vars () + str
1269 def output_html (self):
1271 base = self.basename ()
1272 if global_options.format == HTML:
1273 str += self.output_print_filename (HTML)
1274 if VERBATIM in self.option_dict:
1275 verb = verbatim_html (self.verb_ly ())
1276 str += output[HTML][VERBATIM] % vars ()
1277 if QUOTE in self.option_dict:
1278 str = output[HTML][QUOTE] % vars ()
1280 str += output[HTML][BEFORE] % vars ()
1281 for image in self.get_images ():
1282 (base, ext) = os.path.splitext (image)
1283 alt = self.option_dict[ALT]
1284 str += output[HTML][OUTPUT] % vars ()
1285 str += output[HTML][AFTER] % vars ()
1288 def output_info (self):
1290 for image in self.get_images ():
1291 (base, ext) = os.path.splitext (image)
1293 # URG, makeinfo implicitly prepends dot to extension.
1294 # Specifying no extension is most robust.
1296 alt = self.option_dict[ALT]
1297 info_image_path = os.path.join (global_options.info_images_dir, base)
1298 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1300 base = self.basename ()
1301 str += output[global_options.format][OUTPUT] % vars ()
1304 def output_latex (self):
1306 base = self.basename ()
1307 if global_options.format == LATEX:
1308 str += self.output_print_filename (LATEX)
1309 if VERBATIM in self.option_dict:
1310 verb = self.verb_ly ()
1311 str += (output[LATEX][VERBATIM] % vars ())
1313 str += (output[LATEX][OUTPUT] % vars ())
1315 ## todo: maintain breaks
1317 breaks = self.ly ().count ("\n")
1318 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1320 if QUOTE in self.option_dict:
1321 str = output[LATEX][QUOTE] % vars ()
1324 def output_print_filename (self, format):
1326 if PRINTFILENAME in self.option_dict:
1327 base = self.basename ()
1328 filename = os.path.basename (self.substring ('filename'))
1329 str = output[format][PRINTFILENAME] % vars ()
1333 def output_texinfo (self):
1334 str = self.output_print_filename (TEXINFO)
1335 base = self.basename ()
1336 if TEXIDOC in self.option_dict:
1337 texidoc = base + '.texidoc'
1338 if os.path.exists (texidoc):
1339 str += '@include %(texidoc)s\n\n' % vars ()
1342 if VERBATIM in self.option_dict:
1344 if ADDVERSION in self.option_dict:
1345 version = output[TEXINFO][ADDVERSION]
1346 verb = self.verb_ly ()
1347 substr = output[TEXINFO][VERBATIM] % vars ()
1348 substr += self.output_info ()
1349 if LILYQUOTE in self.option_dict:
1350 substr = output[TEXINFO][QUOTE] % {'str':substr}
1353 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1354 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1355 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1357 if QUOTE in self.option_dict:
1358 str = output[TEXINFO][QUOTE] % vars ()
1360 # need par after image
1365 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1366 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1368 class LilypondFileSnippet (LilypondSnippet):
1369 def __init__ (self, type, match, format, line_number):
1370 LilypondSnippet.__init__ (self, type, match, format, line_number)
1371 self.contents = file (find_file (self.substring ('filename'))).read ()
1375 s = re_begin_verbatim.split (s)[-1]
1376 s = re_end_verbatim.split (s)[0]
1380 name = self.substring ('filename')
1381 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1382 % (name, self.contents))
1385 snippet_type_to_class = {
1386 'lilypond_file': LilypondFileSnippet,
1387 'lilypond_block': LilypondSnippet,
1388 'lilypond': LilypondSnippet,
1389 'include': IncludeSnippet,
1392 def find_linestarts (s):
1397 i = s.find ('\n', start)
1405 nls.append (len (s))
1408 def find_toplevel_snippets (s, types):
1411 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1415 found = dict ([(t, None) for t in types])
1417 line_starts = find_linestarts (s)
1419 # We want to search for multiple regexes, without searching
1420 # the string multiple times for one regex.
1421 # Hence, we use earlier results to limit the string portion
1423 # Since every part of the string is traversed at most once for
1424 # every type of snippet, this is linear.
1430 if not found[type] or found[type][0] < index:
1433 m = res[type].search (s[index:endex])
1438 if snippet_type_to_class.has_key (type):
1439 cl = snippet_type_to_class[type]
1442 start = index + m.start ('match')
1443 line_number = line_start_idx
1444 while (line_starts[line_number] < start):
1448 snip = cl (type, m, global_options.format, line_number)
1450 found[type] = (start, snip)
1454 or found[type][0] < found[first][0])):
1459 # Limiting the search space is a cute
1460 # idea, but this *requires* to search
1461 # for possible containing blocks
1462 # first, at least as long as we do not
1463 # search for the start of blocks, but
1464 # always/directly for the entire
1465 # @block ... @end block.
1467 endex = found[first][0]
1470 snippets.append (Substring (s, index, len (s), line_start_idx))
1473 while (start > line_starts[line_start_idx+1]):
1476 (start, snip) = found[first]
1477 snippets.append (Substring (s, index, start, line_start_idx + 1))
1478 snippets.append (snip)
1480 index = start + len (snip.match.group ('match'))
1484 def filter_pipe (input, cmd):
1485 """Pass input through cmd, and return the result."""
1487 if global_options.verbose:
1488 progress (_ ("Opening filter `%s'") % cmd)
1490 (stdin, stdout, stderr) = os.popen3 (cmd)
1492 status = stdin.close ()
1496 output = stdout.read ()
1497 status = stdout.close ()
1498 error = stderr.read ()
1502 signal = 0x0f & status
1503 if status or (not output and error):
1504 exit_status = status >> 8
1505 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1506 error (_ ("The error log is as follows:"))
1507 ly.stderr_write (error)
1508 ly.stderr_write (stderr.read ())
1511 if global_options.verbose:
1516 def system_in_directory (cmd, directory):
1517 """Execute a command in a different directory.
1519 Because of win32 compatibility, we can't simply use subprocess.
1522 current = os.getcwd()
1523 os.chdir (directory)
1524 ly.system(cmd, be_verbose=global_options.verbose,
1529 def process_snippets (cmd, snippets):
1530 """Run cmd on all of the .ly files from snippets."""
1535 if global_options.format in (HTML, TEXINFO) and '--formats' not in cmd:
1536 cmd += ' --formats=png '
1537 elif global_options.format in (DOCBOOK) and '--formats' not in cmd:
1538 cmd += ' --formats=png,pdf '
1540 checksum = snippet_list_checksum (snippets)
1541 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1542 + [snip.basename() for snip in snippets])
1543 name = os.path.join (global_options.lily_output_dir,
1544 'snippet-names-%d' % checksum)
1545 file (name, 'wb').write (contents)
1547 system_in_directory (' '.join ([cmd, name]),
1548 global_options.lily_output_dir)
1552 # Retrieve dimensions from LaTeX
1553 LATEX_INSPECTION_DOCUMENT = r'''
1557 \typeout{textwidth=\the\textwidth}
1558 \typeout{columnsep=\the\columnsep}
1559 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1563 # Do we need anything else besides `textwidth'?
1564 def get_latex_textwidth (source):
1565 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1567 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1569 ## what's a sensible default?
1572 preamble = source[:m.start (0)]
1573 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1575 (handle, tmpfile) = tempfile.mkstemp('.tex')
1576 logfile = os.path.splitext (tmpfile)[0] + '.log'
1577 logfile = os.path.split (logfile)[1]
1579 tmp_handle = os.fdopen (handle,'w')
1580 tmp_handle.write (latex_document)
1583 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1584 parameter_string = file (logfile).read()
1590 m = re.search ('columns=([0-9.]*)', parameter_string)
1592 columns = int (m.group (1))
1595 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1597 columnsep = float (m.group (1))
1600 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1602 textwidth = float (m.group (1))
1604 textwidth = (textwidth - columnsep) / columns
1608 def modify_preamble (chunk):
1609 str = chunk.replacement_text ()
1610 if (re.search (r"\\begin *{document}", str)
1611 and not re.search ("{graphic[sx]", str)):
1612 str = re.sub (r"\\begin{document}",
1613 r"\\usepackage{graphics}" + '\n'
1614 + r"\\begin{document}",
1616 chunk.override_text = str
1621 # TEXINFO: '.texinfo',
1627 class CompileError(Exception):
1630 def snippet_list_checksum (snippets):
1631 return hash (' '.join([l.basename() for l in snippets]))
1633 def write_file_map (lys, name):
1634 snippet_map = file (os.path.join (
1635 global_options.lily_output_dir,
1636 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1637 snippet_map.write ("""
1638 #(define version-seen #t)
1639 #(define output-empty-score-list #f)
1640 #(ly:add-file-name-alist '(
1644 snippet_map.write ('("%s.ly" . "%s")\n'
1645 % (ly.basename (), name))
1647 snippet_map.write ('))\n')
1649 def do_process_cmd (chunks, input_name):
1650 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1651 outdated = [c for c in snippets
1652 if (c.ly_is_outdated () or c.png_is_outdated ())]
1654 write_file_map (outdated, input_name)
1655 progress (_ ("Writing snippets..."))
1656 for snippet in outdated:
1661 progress (_ ("Processing..."))
1663 process_snippets (global_options.process_cmd, outdated)
1666 progress (_ ("All snippets are up to date..."))
1668 if global_options.lily_output_dir != global_options.output_dir:
1669 output_files = set(os.listdir(global_options.lily_output_dir))
1670 for snippet in snippets:
1671 snippet.link_all_output_files (global_options.lily_output_dir,
1673 global_options.output_dir)
1679 # Format guessing data
1688 '.texinfo': TEXINFO,
1693 def guess_format (input_filename):
1695 e = os.path.splitext (input_filename)[1]
1696 if e in ext2format.keys ():
1698 format = ext2format[e]
1700 error (_ ("cannot determine format for: %s"
1705 def write_if_updated (file_name, lines):
1707 f = file (file_name)
1709 new_str = ''.join (lines)
1710 if oldstr == new_str:
1711 progress (_ ("%s is up to date.") % file_name)
1714 # this prevents make from always rerunning lilypond-book:
1715 # output file must be touched in order to be up to date
1716 os.utime (file_name, None)
1720 progress (_ ("Writing `%s'...") % file_name)
1721 file (file_name, 'w').writelines (lines)
1725 def note_input_file (name, inputs=[]):
1726 ## hack: inputs is mutable!
1727 inputs.append (name)
1730 def samefile (f1, f2):
1732 return os.path.samefile (f1, f2)
1733 except AttributeError: # Windoze
1734 f1 = re.sub ("//*", "/", f1)
1735 f2 = re.sub ("//*", "/", f2)
1738 def do_file (input_filename):
1740 if not input_filename or input_filename == '-':
1741 in_handle = sys.stdin
1742 input_fullname = '<stdin>'
1744 if os.path.exists (input_filename):
1745 input_fullname = input_filename
1746 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1747 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1749 input_fullname = find_file (input_filename)
1751 note_input_file (input_fullname)
1752 in_handle = file (input_fullname)
1754 if input_filename == '-':
1755 input_base = 'stdin'
1757 input_base = os.path.basename (
1758 os.path.splitext (input_filename)[0])
1760 # don't complain when global_options.output_dir is existing
1761 if not global_options.output_dir:
1762 global_options.output_dir = os.getcwd()
1764 global_options.output_dir = os.path.abspath(global_options.output_dir)
1766 if not os.path.isdir (global_options.output_dir):
1767 os.mkdir (global_options.output_dir, 0777)
1768 os.chdir (global_options.output_dir)
1770 output_filename = os.path.join(global_options.output_dir,
1771 input_base + format2ext[global_options.format])
1772 if (os.path.exists (input_filename)
1773 and os.path.exists (output_filename)
1774 and samefile (output_filename, input_fullname)):
1776 _ ("Output would overwrite input file; use --output."))
1780 progress (_ ("Reading %s...") % input_fullname)
1781 source = in_handle.read ()
1784 set_default_options (source)
1787 # FIXME: Containing blocks must be first, see
1788 # find_toplevel_snippets.
1790 'multiline_comment',
1794 'singleline_comment',
1799 progress (_ ("Dissecting..."))
1800 chunks = find_toplevel_snippets (source, snippet_types)
1802 if global_options.format == LATEX:
1804 if (c.is_plain () and
1805 re.search (r"\\begin *{document}", c.replacement_text())):
1810 if global_options.filter_cmd:
1811 write_if_updated (output_filename,
1812 [c.filter_text () for c in chunks])
1813 elif global_options.process_cmd:
1814 do_process_cmd (chunks, input_fullname)
1815 progress (_ ("Compiling %s...") % output_filename)
1817 write_if_updated (output_filename,
1818 [s.replacement_text ()
1821 def process_include (snippet):
1822 os.chdir (original_dir)
1823 name = snippet.substring ('filename')
1824 progress (_ ("Processing include: %s") % name)
1826 return do_file (name)
1828 include_chunks = map (process_include,
1829 filter (lambda x: isinstance (x, IncludeSnippet),
1832 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1834 except CompileError:
1835 os.chdir (original_dir)
1836 progress (_ ("Removing `%s'") % output_filename)
1841 global global_options
1843 opt_parser = get_option_parser()
1844 (global_options, args) = opt_parser.parse_args ()
1845 if global_options.format in ('texi-html', 'texi'):
1846 global_options.format = TEXINFO
1848 global_options.include_path = map (os.path.abspath, global_options.include_path)
1850 if global_options.warranty:
1853 if not args or len (args) > 1:
1854 opt_parser.print_help ()
1860 # FIXME: 85 lines of `main' macramee??
1861 files = do_options ()
1863 basename = os.path.splitext (files[0])[0]
1864 basename = os.path.split (basename)[1]
1866 if not global_options.format:
1867 global_options.format = guess_format (files[0])
1870 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1873 if global_options.process_cmd == '':
1874 global_options.process_cmd = (lilypond_binary
1875 + ' --formats=%s -dbackend=eps ' % formats)
1877 if global_options.process_cmd:
1878 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1879 for p in global_options.include_path])
1881 if global_options.format in (TEXINFO, LATEX):
1882 ## prevent PDF from being switched on by default.
1883 global_options.process_cmd += ' --formats=eps '
1884 if global_options.create_pdf:
1885 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1887 if global_options.verbose:
1888 global_options.process_cmd += " --verbose "
1890 if global_options.padding_mm:
1891 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1893 global_options.process_cmd += " -dread-file-list "
1895 if global_options.lily_output_dir:
1896 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1897 if not os.path.isdir (global_options.lily_output_dir):
1898 os.makedirs (global_options.lily_output_dir)
1900 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1905 chunks = do_file (files[0])
1906 except CompileError:
1909 inputs = note_input_file ('')
1912 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1913 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1914 final_output_file = os.path.join (global_options.output_dir,
1916 + '.%s' % global_options.format)
1918 os.chdir (original_dir)
1919 file (dep_file, 'w').write ('%s: %s'
1920 % (final_output_file, ' '.join (inputs)))
1922 if __name__ == '__main__':