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 ('--latex',
139 help=_ ("Run executable PROG instead of latex"),
141 action='store', dest='latex_program',
144 p.add_option ('--left-padding',
147 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
151 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
153 action='store', dest='output_dir',
156 p.add_option ('--skip-lily-check',
157 help=_ ("do not fail if no lilypond output is found."),
159 action='store_true', dest='skip_lilypond_run',
162 p.add_option ('--skip-png-check',
163 help=_ ("do not fail if no PNG images are found for EPS files"),
165 action='store_true', dest='skip_png_check',
168 p.add_option ('--lily-output-dir',
169 help=_ ("write lily-XXX files to DIR, link into --output dir."),
171 action='store', dest='lily_output_dir',
174 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
175 help = _ ("process ly_files using COMMAND FILE..."),
177 dest='process_cmd', default='')
179 p.add_option ('--pdf',
182 help=_ ("create PDF files for use with PDFTeX"),
185 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
186 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
187 must use this with dvips -h INPUT.psfonts'''),
190 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
195 p.version = "@TOPLEVEL_VERSION@"
196 p.add_option("--version",
198 help=_ ("show version number and exit"))
200 p.add_option ('-w', '--warranty',
201 help=_ ("show warranty and copyright"),
203 p.add_option_group (ly.display_encode (_ ('Bugs')),
205 _ ("Report bugs via")
206 + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
209 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
211 # Only use installed binary when we are installed too.
212 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
213 lilypond_binary = 'lilypond'
215 global_options = None
218 default_ly_options = { 'alt': "[image of music]" }
221 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
223 ADDVERSION = 'addversion'
227 EXAMPLEINDENT = 'exampleindent'
229 FRAGMENT = 'fragment'
235 LINE_WIDTH = 'line-width'
236 LILYQUOTE = 'lilyquote'
237 NOFRAGMENT = 'nofragment'
238 NOINDENT = 'noindent'
243 OUTPUTIMAGE = 'outputimage'
246 PREAMBLE = 'preamble'
247 PRINTFILENAME = 'printfilename'
249 RAGGED_RIGHT = 'ragged-right'
250 RELATIVE = 'relative'
251 STAFFSIZE = 'staffsize'
254 VERBATIM = 'verbatim'
255 FONTLOAD = 'fontload'
256 FILENAME = 'filename'
260 # NOTIME has no opposite so it isn't part of this dictionary.
261 # NOQUOTE is used internally only.
263 NOFRAGMENT: FRAGMENT,
268 # Recognize special sequences in the input.
270 # (?P<name>regex) -- Assign result of REGEX to NAME.
271 # *? -- Match non-greedily.
272 # (?m) -- Multiline regex: Make ^ and $ match at each line.
273 # (?s) -- Make the dot match all characters including newline.
274 # (?x) -- Ignore whitespace in patterns.
285 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
290 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
295 <(?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>)''',
301 (?P<code><!--\s.*?!-->)
304 'singleline_comment':
323 (\s*(?P<options>.*?)\s*:)?\s*
331 \s*(?P<options>.*?)\s*
340 \s*(?P<options>.*?)\s*
342 \s*(?P<filename>.*?)\s*
349 (?P<code><!--\s.*?!-->)
352 'singleline_comment':
358 (?P<code><pre>.*?</pre>))''',
364 (?P<code><pre>\s.*?</pre>\s))''',
383 \s*(?P<options>.*?)\s*
394 \s*(?P<options>.*?)\s*
398 \\end\s*{lilypond})''',
406 \s*(?P<options>.*?)\s*
414 'singleline_comment':
437 \\end\s*{verbatim}))''',
446 (?P<filename>\S+))''',
450 ^[^\n]*?(?!@c\s+)[^\n]*?
454 \s*(?P<options>.*?)\s*
464 \s*(?P<options>.*?)\s*
467 ^@end\s+lilypond)\s''',
474 \s*(?P<options>.*?)\s*
485 @end\s+ignore))\s''',
487 'singleline_comment':
492 @c([ \t][^\n]*|)\n))''',
494 # Don't do this: It interferes with @code{@{}.
495 # 'verb': r'''(?P<code>@code{.*?})''',
503 @end\s+example\s))''',
512 'intertext': r',?\s*intertext=\".*?\"',
516 'intertext': r',?\s*intertext=\".*?\"',
521 'intertext': r',?\s*intertext=\".*?\"',
522 'option_sep': '\s*,\s*',
526 'intertext': r',?\s*intertext=\".*?\"',
527 'option_sep': '\s*,\s*',
531 # Options without a pattern in ly_options.
550 RELATIVE: r'''\relative c%(relative_quotes)s''',
555 INDENT: r'''indent = %(indent)s''',
557 LINE_WIDTH: r'''line-width = %(line-width)s''',
559 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
561 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
563 RAGGED_RIGHT: r'''ragged-right = ##t''',
565 PACKED: r'''packed = ##t''',
577 \remove Time_signature_engraver
583 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
590 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
593 <imageobject role="latex">
594 <imagedata fileref="%(base)s.pdf" format="PDF"/>
596 <imageobject role="html">
597 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
599 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
601 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
605 FILTER: r'''<lilypond %(options)s>
615 <a href="%(base)s.ly">''',
619 border="0" src="%(image)s" alt="%(alt)s">''',
621 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
623 QUOTE: r'''<blockquote>
636 \ifx\preLilyPondExample \undefined%%
639 \preLilyPondExample%%
641 \def\lilypondbook{}%%
642 \input %(base)s-systems.tex%%
643 \ifx\postLilyPondExample \undefined%%
646 \postLilyPondExample%%
650 PRINTFILENAME: '''\\texttt{%(filename)s}
653 QUOTE: r'''\begin{quotation}%(str)s
656 VERBATIM: r'''\noindent
657 \begin{verbatim}%(verb)s\end{verbatim}''',
659 FILTER: r'''\begin{lilypond}[%(options)s]
666 FILTER: r'''@lilypond[%(options)s]
672 @include %(base)s-systems.texi
676 OUTPUTIMAGE: r'''@noindent
678 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
682 <a href="%(base)s.ly">
684 border="0" src="%(image)s" alt="%(alt)s">
692 <a href="%(base)s.ly">
700 QUOTE: r'''@quotation
701 %(str)s@end quotation
708 VERBATIM: r'''@exampleindent 0
710 %(verb)s@end verbatim
713 ADDVERSION: r'''@example
714 \version @w{"@version{}"}
721 # Maintain line numbers.
726 for f in [HTML, LATEX]:
727 for s in (QUOTE, VERBATIM):
728 output[f][s] = output[f][s].replace("\n"," ")
731 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
732 %%%% Options: [%(option_string)s]
733 \\include "lilypond-book-preamble.ly"
736 %% ****************************************************************
737 %% Start cut-&-pastable-section
738 %% ****************************************************************
743 #(define dump-extents #t)
744 %(font_dump_setting)s
746 force-assignment = #""
747 line-width = #(- line-width (* mm %(padding_mm)f))
760 %% ****************************************************************
761 %% ly snippet contents follows:
762 %% ****************************************************************
766 %% ****************************************************************
768 %% ****************************************************************
775 %% ****************************************************************
777 %% ****************************************************************
781 %% ****************************************************************
783 %% ****************************************************************
786 texinfo_line_widths = {
787 '@afourpaper': '160\\mm',
788 '@afourwide': '6.5\\in',
789 '@afourlatex': '150\\mm',
790 '@smallbook': '5\\in',
791 '@letterpaper': '6\\in',
794 def classic_lilypond_book_compatibility (key, value):
795 if key == 'singleline' and value == None:
796 return (RAGGED_RIGHT, None)
798 m = re.search ('relative\s*([-0-9])', key)
800 return ('relative', m.group (1))
802 m = re.match ('([0-9]+)pt', key)
804 return ('staffsize', m.group (1))
806 if key == 'indent' or key == 'line-width':
807 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
809 f = float (m.group (1))
810 return (key, '%f\\%s' % (f, m.group (2)))
814 def find_file (name, raise_error=True):
815 for i in global_options.include_path:
816 full = os.path.join (i, name)
817 if os.path.exists (full):
821 error (_ ("file not found: %s") % name + '\n')
825 def verbatim_html (s):
826 return re.sub ('>', '>',
828 re.sub ('&', '&', s)))
831 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
832 def set_default_options (source, default_ly_options, format):
833 if LINE_WIDTH not in default_ly_options:
835 textwidth = get_latex_textwidth (source)
836 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
837 elif format == TEXINFO:
838 m = texinfo_lang_re.search (source)
839 if m and not m.group (1).startswith ('en'):
840 default_ly_options[LANG] = m.group (1)
842 default_ly_options[LANG] = ''
843 for regex in texinfo_line_widths:
844 # FIXME: @layout is usually not in
847 # \input texinfo @c -*-texinfo-*-
849 # Bluntly search first K items of
851 # s = chunks[0].replacement_text ()
852 if re.search (regex, source[:1024]):
853 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
857 def replacement_text (self):
860 def filter_text (self):
861 return self.replacement_text ()
866 class Substring (Chunk):
867 """A string that does not require extra memory."""
868 def __init__ (self, source, start, end, line_number):
872 self.line_number = line_number
873 self.override_text = None
878 def replacement_text (self):
879 if self.override_text:
880 return self.override_text
882 return self.source[self.start:self.end]
884 class Snippet (Chunk):
885 def __init__ (self, type, match, format, line_number):
889 self.option_dict = {}
891 self.line_number = line_number
893 def replacement_text (self):
894 return self.match.group ('match')
896 def substring (self, s):
897 return self.match.group (s)
900 return `self.__class__` + ' type = ' + self.type
902 class IncludeSnippet (Snippet):
903 def processed_filename (self):
904 f = self.substring ('filename')
905 return os.path.splitext (f)[0] + format2ext[self.format]
907 def replacement_text (self):
908 s = self.match.group ('match')
909 f = self.substring ('filename')
911 return re.sub (f, self.processed_filename (), s)
913 class LilypondSnippet (Snippet):
914 def __init__ (self, type, match, format, line_number):
915 Snippet.__init__ (self, type, match, format, line_number)
916 os = match.group ('options')
917 self.do_options (os, self.type)
920 return self.substring ('code')
923 contents = self.substring ('code')
924 return ('\\sourcefileline %d\n%s'
925 % (self.line_number - 1, contents))
930 return self.compose_ly (s)
933 def split_options (self, option_string):
935 if self.format == HTML:
936 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
938 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
942 return re.split (format_res[self.format]['option_sep'],
946 def do_options (self, option_string, type):
947 self.option_dict = {}
949 options = self.split_options (option_string)
951 for option in options:
953 (key, value) = re.split ('\s*=\s*', option)
954 self.option_dict[key] = value
956 if option in no_options:
957 if no_options[option] in self.option_dict:
958 del self.option_dict[no_options[option]]
960 self.option_dict[option] = None
962 has_line_width = self.option_dict.has_key (LINE_WIDTH)
963 no_line_width_value = 0
965 # If LINE_WIDTH is used without parameter, set it to default.
966 if has_line_width and self.option_dict[LINE_WIDTH] == None:
967 no_line_width_value = 1
968 del self.option_dict[LINE_WIDTH]
970 for k in default_ly_options:
971 if k not in self.option_dict:
972 self.option_dict[k] = default_ly_options[k]
974 if not has_line_width:
975 if type == 'lilypond' or FRAGMENT in self.option_dict:
976 self.option_dict[RAGGED_RIGHT] = None
978 if type == 'lilypond':
979 if LINE_WIDTH in self.option_dict:
980 del self.option_dict[LINE_WIDTH]
982 if RAGGED_RIGHT in self.option_dict:
983 if LINE_WIDTH in self.option_dict:
984 del self.option_dict[LINE_WIDTH]
986 if QUOTE in self.option_dict or type == 'lilypond':
987 if LINE_WIDTH in self.option_dict:
988 del self.option_dict[LINE_WIDTH]
990 if not INDENT in self.option_dict:
991 self.option_dict[INDENT] = '0\\mm'
993 # The QUOTE pattern from ly_options only emits the `line-width'
995 if has_line_width and QUOTE in self.option_dict:
996 if no_line_width_value:
997 del self.option_dict[LINE_WIDTH]
999 del self.option_dict[QUOTE]
1001 def compose_ly (self, code):
1002 if FRAGMENT in self.option_dict:
1010 # The original concept of the `exampleindent' option is broken.
1011 # It is not possible to get a sane value for @exampleindent at all
1012 # without processing the document itself. Saying
1020 # causes ugly results with the DVI backend of texinfo since the
1021 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1022 # value). Executing the above code changes the environment
1023 # indentation to an unknown value because we don't know the amount
1024 # of 1em in advance since it is font-dependent. Modifying
1025 # @exampleindent in the middle of a document is simply not
1026 # supported within texinfo.
1028 # As a consequence, the only function of @exampleindent is now to
1029 # specify the amount of indentation for the `quote' option.
1031 # To set @exampleindent locally to zero, we use the @format
1032 # environment for non-quoted snippets.
1033 override[EXAMPLEINDENT] = r'0.4\in'
1034 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1035 override.update (default_ly_options)
1038 for (key, value) in self.option_dict.items ():
1040 option_list.append (key)
1042 option_list.append (key + '=' + value)
1043 option_string = ','.join (option_list)
1046 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1047 for a in compose_types:
1048 compose_dict[a] = []
1050 for (key, value) in self.option_dict.items ():
1051 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1055 _ ("deprecated ly-option used: %s=%s") % (key, value))
1057 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1060 _ ("deprecated ly-option used: %s") % key)
1062 _ ("compatibility mode translation: %s") % c_key)
1064 (key, value) = (c_key, c_value)
1067 override[key] = value
1069 if not override.has_key (key):
1070 override[key] = None
1073 for type in compose_types:
1074 if ly_options[type].has_key (key):
1075 compose_dict[type].append (ly_options[type][key])
1079 if not found and key not in simple_options:
1080 warning (_ ("ignoring unknown ly option: %s") % key)
1083 if RELATIVE in override and override[RELATIVE]:
1084 relative = int (override[RELATIVE])
1086 relative_quotes = ''
1090 relative_quotes += ',' * (- relative)
1092 relative_quotes += "'" * relative
1094 paper_string = '\n '.join (compose_dict[PAPER]) % override
1095 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1096 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1097 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1098 padding_mm = global_options.padding_mm
1099 font_dump_setting = ''
1100 if FONTLOAD in self.option_dict:
1101 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1103 d = globals().copy()
1105 return (PREAMBLE_LY + body) % d
1107 def get_checksum (self):
1108 if not self.checksum:
1109 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1111 ## let's not create too long names.
1112 self.checksum = hash.hexdigest ()[:10]
1114 return self.checksum
1116 def basename (self):
1117 cs = self.get_checksum ()
1118 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1121 def write_ly (self):
1122 base = self.basename ()
1123 path = os.path.join (global_options.lily_output_dir, base)
1124 directory = os.path.split(path)[0]
1125 if not os.path.isdir (directory):
1126 os.makedirs (directory)
1127 out = file (path + '.ly', 'w')
1128 out.write (self.full_ly ())
1129 file (path + '.txt', 'w').write ('image of music')
1131 def relevant_contents (self, ly):
1132 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1134 def link_all_output_files (self, output_dir, output_dir_files, destination):
1135 existing, missing = self.all_output_files (output_dir, output_dir_files)
1137 print '\nMissing', missing
1138 raise CompileError(self.basename())
1139 for name in existing:
1141 os.unlink (os.path.join (destination, name))
1145 src = os.path.join (output_dir, name)
1146 dst = os.path.join (destination, name)
1147 dst_path = os.path.split(dst)[0]
1148 if not os.path.isdir (dst_path):
1149 os.makedirs (dst_path)
1153 def all_output_files (self, output_dir, output_dir_files):
1154 """Return all files generated in lily_output_dir, a set.
1156 output_dir_files is the list of files in the output directory.
1160 base = self.basename()
1161 full = os.path.join (output_dir, base)
1162 def consider_file (name):
1163 if name in output_dir_files:
1166 def require_file (name):
1167 if name in output_dir_files:
1172 # UGH - junk global_options
1173 skip_lily = global_options.skip_lilypond_run
1174 for required in [base + '.ly',
1176 require_file (required)
1178 require_file (base + '-systems.count')
1180 map (consider_file, [base + '.tex',
1183 base + '-systems.texi',
1184 base + '-systems.tex',
1185 base + '-systems.pdftexi'])
1187 # UGH - junk global_options
1188 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1189 and not global_options.skip_png_check):
1190 page_count = ps_page_count (full + '.eps')
1192 require_file (base + '.png')
1194 for page in range (1, page_count + 1):
1195 require_file (base + '-page%d.png' % page)
1198 if not skip_lily and not missing:
1199 system_count = int(file (full + '-systems.count').read())
1200 for number in range(1, system_count + 1):
1201 systemfile = '%s-%d' % (base, number)
1202 require_file (systemfile + '.eps')
1203 consider_file (systemfile + '.pdf')
1205 return (result, missing)
1207 def is_outdated (self, output_dir, current_files):
1208 found, missing = self.all_output_files (output_dir, current_files)
1211 def filter_text (self):
1212 """Run snippet bodies through a command (say: convert-ly).
1214 This functionality is rarely used, and this code must have bitrot.
1216 code = self.substring ('code')
1217 s = filter_pipe (code, global_options.filter_cmd)
1220 'options': self.match.group ('options')
1223 return output[self.format][FILTER] % d
1225 def replacement_text (self):
1226 func = LilypondSnippet.__dict__['output_' + self.format]
1229 def get_images (self):
1230 base = self.basename ()
1232 single = '%(base)s.png' % vars ()
1233 multiple = '%(base)s-page1.png' % vars ()
1235 if (os.path.exists (multiple)
1236 and (not os.path.exists (single)
1237 or (os.stat (multiple)[stat.ST_MTIME]
1238 > os.stat (single)[stat.ST_MTIME]))):
1239 count = ps_page_count ('%(base)s.eps' % vars ())
1240 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1241 images = tuple (images)
1245 def output_docbook (self):
1247 base = self.basename ()
1248 for image in self.get_images ():
1249 (base, ext) = os.path.splitext (image)
1250 str += output[DOCBOOK][OUTPUT] % vars ()
1251 str += self.output_print_filename (DOCBOOK)
1252 if (self.substring('inline') == 'inline'):
1253 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1255 str = '<mediaobject>' + str + '</mediaobject>'
1256 if VERBATIM in self.option_dict:
1257 verb = verbatim_html (self.verb_ly ())
1258 str = output[DOCBOOK][VERBATIM] % vars () + str
1261 def output_html (self):
1263 base = self.basename ()
1264 if self.format == HTML:
1265 str += self.output_print_filename (HTML)
1266 if VERBATIM in self.option_dict:
1267 verb = verbatim_html (self.verb_ly ())
1268 str += output[HTML][VERBATIM] % vars ()
1269 if QUOTE in self.option_dict:
1270 str = output[HTML][QUOTE] % vars ()
1272 str += output[HTML][BEFORE] % vars ()
1273 for image in self.get_images ():
1274 (base, ext) = os.path.splitext (image)
1275 alt = self.option_dict[ALT]
1276 str += output[HTML][OUTPUT] % vars ()
1277 str += output[HTML][AFTER] % vars ()
1280 def output_info (self):
1282 for image in self.get_images ():
1283 (base, ext) = os.path.splitext (image)
1285 # URG, makeinfo implicitly prepends dot to extension.
1286 # Specifying no extension is most robust.
1288 alt = self.option_dict[ALT]
1289 info_image_path = os.path.join (global_options.info_images_dir, base)
1290 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1292 base = self.basename ()
1293 str += output[self.format][OUTPUT] % vars ()
1296 def output_latex (self):
1298 base = self.basename ()
1299 if self.format == LATEX:
1300 str += self.output_print_filename (LATEX)
1301 if VERBATIM in self.option_dict:
1302 verb = self.verb_ly ()
1303 str += (output[LATEX][VERBATIM] % vars ())
1305 str += (output[LATEX][OUTPUT] % vars ())
1307 ## todo: maintain breaks
1309 breaks = self.ly ().count ("\n")
1310 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1312 if QUOTE in self.option_dict:
1313 str = output[LATEX][QUOTE] % vars ()
1316 def output_print_filename (self, format):
1318 if PRINTFILENAME in self.option_dict:
1319 base = self.basename ()
1320 filename = os.path.basename (self.substring ('filename'))
1321 str = output[format][PRINTFILENAME] % vars ()
1325 def output_texinfo (self):
1326 str = self.output_print_filename (TEXINFO)
1327 base = self.basename ()
1328 if TEXIDOC in self.option_dict:
1329 texidoc = base + '.texidoc'
1330 translated_texidoc = texidoc + default_ly_options[LANG]
1331 if os.path.exists (translated_texidoc):
1332 str += '@include %(translated_texidoc)s\n\n' % vars ()
1333 elif os.path.exists (texidoc):
1334 str += '@include %(texidoc)s\n\n' % vars ()
1337 if VERBATIM in self.option_dict:
1339 if ADDVERSION in self.option_dict:
1340 version = output[TEXINFO][ADDVERSION]
1341 verb = self.verb_ly ()
1342 substr = output[TEXINFO][VERBATIM] % vars ()
1343 substr += self.output_info ()
1344 if LILYQUOTE in self.option_dict:
1345 substr = output[TEXINFO][QUOTE] % {'str':substr}
1348 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1349 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1350 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1352 if QUOTE in self.option_dict:
1353 str = output[TEXINFO][QUOTE] % vars ()
1355 # need par after image
1360 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1361 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1363 class LilypondFileSnippet (LilypondSnippet):
1364 def __init__ (self, type, match, format, line_number):
1365 LilypondSnippet.__init__ (self, type, match, format, line_number)
1366 self.contents = file (find_file (self.substring ('filename'))).read ()
1370 s = re_begin_verbatim.split (s)[-1]
1371 s = re_end_verbatim.split (s)[0]
1375 name = self.substring ('filename')
1376 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1377 % (name, self.contents))
1380 snippet_type_to_class = {
1381 'lilypond_file': LilypondFileSnippet,
1382 'lilypond_block': LilypondSnippet,
1383 'lilypond': LilypondSnippet,
1384 'include': IncludeSnippet,
1387 def find_linestarts (s):
1392 i = s.find ('\n', start)
1400 nls.append (len (s))
1403 def find_toplevel_snippets (input_string, format, types):
1406 res[t] = re.compile (snippet_res[format][t])
1410 found = dict ([(t, None) for t in types])
1412 line_starts = find_linestarts (input_string)
1414 # We want to search for multiple regexes, without searching
1415 # the string multiple times for one regex.
1416 # Hence, we use earlier results to limit the string portion
1418 # Since every part of the string is traversed at most once for
1419 # every type of snippet, this is linear.
1425 if not found[type] or found[type][0] < index:
1428 m = res[type].search (input_string[index:endex])
1433 if type in snippet_type_to_class:
1434 klass = snippet_type_to_class[type]
1436 start = index + m.start ('match')
1437 line_number = line_start_idx
1438 while (line_starts[line_number] < start):
1442 snip = klass (type, m, format, line_number)
1444 found[type] = (start, snip)
1448 or found[type][0] < found[first][0])):
1453 # Limiting the search space is a cute
1454 # idea, but this *requires* to search
1455 # for possible containing blocks
1456 # first, at least as long as we do not
1457 # search for the start of blocks, but
1458 # always/directly for the entire
1459 # @block ... @end block.
1461 endex = found[first][0]
1464 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1467 while (start > line_starts[line_start_idx+1]):
1470 (start, snip) = found[first]
1471 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1472 snippets.append (snip)
1474 index = start + len (snip.match.group ('match'))
1478 def filter_pipe (input, cmd):
1479 """Pass input through cmd, and return the result."""
1481 if global_options.verbose:
1482 progress (_ ("Opening filter `%s'") % cmd)
1484 (stdin, stdout, stderr) = os.popen3 (cmd)
1486 status = stdin.close ()
1490 output = stdout.read ()
1491 status = stdout.close ()
1492 error = stderr.read ()
1496 signal = 0x0f & status
1497 if status or (not output and error):
1498 exit_status = status >> 8
1499 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1500 error (_ ("The error log is as follows:"))
1501 ly.stderr_write (error)
1502 ly.stderr_write (stderr.read ())
1505 if global_options.verbose:
1510 def system_in_directory (cmd, directory):
1511 """Execute a command in a different directory.
1513 Because of win32 compatibility, we can't simply use subprocess.
1516 current = os.getcwd()
1517 os.chdir (directory)
1518 ly.system(cmd, be_verbose=global_options.verbose,
1523 def process_snippets (cmd, snippets,
1524 format, lily_output_dir):
1525 """Run cmd on all of the .ly files from snippets."""
1530 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1531 cmd += ' --formats=png '
1532 elif format in (DOCBOOK) and '--formats' not in cmd:
1533 cmd += ' --formats=png,pdf '
1535 checksum = snippet_list_checksum (snippets)
1536 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1537 + [snip.basename() + '.ly' for snip in snippets])
1538 name = os.path.join (lily_output_dir,
1539 'snippet-names-%d.ly' % checksum)
1540 file (name, 'wb').write (contents)
1542 system_in_directory (' '.join ([cmd, name]),
1547 # Retrieve dimensions from LaTeX
1548 LATEX_INSPECTION_DOCUMENT = r'''
1552 \typeout{textwidth=\the\textwidth}
1553 \typeout{columnsep=\the\columnsep}
1554 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1558 # Do we need anything else besides `textwidth'?
1559 def get_latex_textwidth (source):
1560 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1562 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1564 ## what's a sensible default?
1567 preamble = source[:m.start (0)]
1568 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1570 (handle, tmpfile) = tempfile.mkstemp('.tex')
1571 logfile = os.path.splitext (tmpfile)[0] + '.log'
1572 logfile = os.path.split (logfile)[1]
1574 tmp_handle = os.fdopen (handle,'w')
1575 tmp_handle.write (latex_document)
1578 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1579 be_verbose=global_options.verbose)
1580 parameter_string = file (logfile).read()
1586 m = re.search ('columns=([0-9.]*)', parameter_string)
1588 columns = int (m.group (1))
1591 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1593 columnsep = float (m.group (1))
1596 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1598 textwidth = float (m.group (1))
1600 textwidth = (textwidth - columnsep) / columns
1604 def modify_preamble (chunk):
1605 str = chunk.replacement_text ()
1606 if (re.search (r"\\begin *{document}", str)
1607 and not re.search ("{graphic[sx]", str)):
1608 str = re.sub (r"\\begin{document}",
1609 r"\\usepackage{graphics}" + '\n'
1610 + r"\\begin{document}",
1612 chunk.override_text = str
1617 # TEXINFO: '.texinfo',
1623 class CompileError(Exception):
1626 def snippet_list_checksum (snippets):
1627 return hash (' '.join([l.basename() for l in snippets]))
1629 def write_file_map (lys, name):
1630 snippet_map = file (os.path.join (
1631 global_options.lily_output_dir,
1632 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1634 snippet_map.write ("""
1635 #(define version-seen #t)
1636 #(define output-empty-score-list #f)
1637 #(ly:add-file-name-alist '(%s
1639 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1642 def split_output_files(directory):
1643 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1645 Return value is a set of strings.
1648 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1649 base_subdir = os.path.split (subdir)[1]
1650 sub_files = [os.path.join (base_subdir, name)
1651 for name in os.listdir (subdir)]
1655 def do_process_cmd (chunks, input_name, options):
1656 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1658 output_files = split_output_files (options.lily_output_dir)
1659 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1661 write_file_map (outdated, input_name)
1662 progress (_ ("Writing snippets..."))
1663 for snippet in outdated:
1668 progress (_ ("Processing..."))
1670 process_snippets (options.process_cmd, outdated,
1671 options.format, options.lily_output_dir)
1674 progress (_ ("All snippets are up to date..."))
1676 if options.lily_output_dir != options.output_dir:
1677 output_files = split_output_files (options.lily_output_dir)
1678 for snippet in snippets:
1679 snippet.link_all_output_files (options.lily_output_dir,
1687 # Format guessing data
1696 '.texinfo': TEXINFO,
1701 def guess_format (input_filename):
1703 e = os.path.splitext (input_filename)[1]
1706 format = ext2format[e]
1708 error (_ ("cannot determine format for: %s"
1713 def write_if_updated (file_name, lines):
1715 f = file (file_name)
1717 new_str = ''.join (lines)
1718 if oldstr == new_str:
1719 progress (_ ("%s is up to date.") % file_name)
1722 # this prevents make from always rerunning lilypond-book:
1723 # output file must be touched in order to be up to date
1724 os.utime (file_name, None)
1728 progress (_ ("Writing `%s'...") % file_name)
1729 file (file_name, 'w').writelines (lines)
1733 def note_input_file (name, inputs=[]):
1734 ## hack: inputs is mutable!
1735 inputs.append (name)
1738 def samefile (f1, f2):
1740 return os.path.samefile (f1, f2)
1741 except AttributeError: # Windoze
1742 f1 = re.sub ("//*", "/", f1)
1743 f2 = re.sub ("//*", "/", f2)
1746 def do_file (input_filename):
1748 if not input_filename or input_filename == '-':
1749 in_handle = sys.stdin
1750 input_fullname = '<stdin>'
1752 if os.path.exists (input_filename):
1753 input_fullname = input_filename
1754 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1755 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1757 input_fullname = find_file (input_filename)
1759 note_input_file (input_fullname)
1760 in_handle = file (input_fullname)
1762 if input_filename == '-':
1763 input_base = 'stdin'
1765 input_base = os.path.basename (
1766 os.path.splitext (input_filename)[0])
1768 # don't complain when global_options.output_dir is existing
1769 if not global_options.output_dir:
1770 global_options.output_dir = os.getcwd()
1772 global_options.output_dir = os.path.abspath(global_options.output_dir)
1774 if not os.path.isdir (global_options.output_dir):
1775 os.mkdir (global_options.output_dir, 0777)
1776 os.chdir (global_options.output_dir)
1778 output_filename = os.path.join(global_options.output_dir,
1779 input_base + format2ext[global_options.format])
1780 if (os.path.exists (input_filename)
1781 and os.path.exists (output_filename)
1782 and samefile (output_filename, input_fullname)):
1784 _ ("Output would overwrite input file; use --output."))
1788 progress (_ ("Reading %s...") % input_fullname)
1789 source = in_handle.read ()
1792 set_default_options (source, default_ly_options, global_options.format)
1795 # FIXME: Containing blocks must be first, see
1796 # find_toplevel_snippets.
1798 'multiline_comment',
1802 'singleline_comment',
1807 progress (_ ("Dissecting..."))
1808 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1810 if global_options.format == LATEX:
1812 if (c.is_plain () and
1813 re.search (r"\\begin *{document}", c.replacement_text())):
1818 if global_options.filter_cmd:
1819 write_if_updated (output_filename,
1820 [c.filter_text () for c in chunks])
1821 elif global_options.process_cmd:
1822 do_process_cmd (chunks, input_fullname, global_options)
1823 progress (_ ("Compiling %s...") % output_filename)
1825 write_if_updated (output_filename,
1826 [s.replacement_text ()
1829 def process_include (snippet):
1830 os.chdir (original_dir)
1831 name = snippet.substring ('filename')
1832 progress (_ ("Processing include: %s") % name)
1834 return do_file (name)
1836 include_chunks = map (process_include,
1837 filter (lambda x: isinstance (x, IncludeSnippet),
1840 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1842 except CompileError:
1843 os.chdir (original_dir)
1844 progress (_ ("Removing `%s'") % output_filename)
1849 global global_options
1851 opt_parser = get_option_parser()
1852 (global_options, args) = opt_parser.parse_args ()
1853 if global_options.format in ('texi-html', 'texi'):
1854 global_options.format = TEXINFO
1856 global_options.include_path = map (os.path.abspath, global_options.include_path)
1858 if global_options.warranty:
1861 if not args or len (args) > 1:
1862 opt_parser.print_help ()
1868 # FIXME: 85 lines of `main' macramee??
1869 files = do_options ()
1871 basename = os.path.splitext (files[0])[0]
1872 basename = os.path.split (basename)[1]
1874 if not global_options.format:
1875 global_options.format = guess_format (files[0])
1878 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1881 if global_options.process_cmd == '':
1882 global_options.process_cmd = (lilypond_binary
1883 + ' --formats=%s -dbackend=eps ' % formats)
1885 if global_options.process_cmd:
1886 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1887 for p in global_options.include_path])
1889 if global_options.format in (TEXINFO, LATEX):
1890 ## prevent PDF from being switched on by default.
1891 global_options.process_cmd += ' --formats=eps '
1892 if global_options.create_pdf:
1893 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1895 if global_options.verbose:
1896 global_options.process_cmd += " --verbose "
1898 if global_options.padding_mm:
1899 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1901 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
1903 if global_options.lily_output_dir:
1904 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1905 if not os.path.isdir (global_options.lily_output_dir):
1906 os.makedirs (global_options.lily_output_dir)
1908 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1913 chunks = do_file (files[0])
1914 except CompileError:
1917 inputs = note_input_file ('')
1920 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1921 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1922 final_output_file = os.path.join (global_options.output_dir,
1924 + '.%s' % global_options.format)
1926 os.chdir (original_dir)
1927 file (dep_file, 'w').write ('%s: %s'
1928 % (final_output_file, ' '.join (inputs)))
1930 if __name__ == '__main__':