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]" }
220 document_language = ''
223 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
225 ADDVERSION = 'addversion'
229 EXAMPLEINDENT = 'exampleindent'
231 FRAGMENT = 'fragment'
237 LINE_WIDTH = 'line-width'
238 LILYQUOTE = 'lilyquote'
239 NOFRAGMENT = 'nofragment'
240 NOINDENT = 'noindent'
245 OUTPUTIMAGE = 'outputimage'
248 PREAMBLE = 'preamble'
249 PRINTFILENAME = 'printfilename'
251 RAGGED_RIGHT = 'ragged-right'
252 RELATIVE = 'relative'
253 STAFFSIZE = 'staffsize'
256 VERBATIM = 'verbatim'
257 FONTLOAD = 'fontload'
258 FILENAME = 'filename'
262 # NOTIME has no opposite so it isn't part of this dictionary.
263 # NOQUOTE is used internally only.
265 NOFRAGMENT: FRAGMENT,
270 # Recognize special sequences in the input.
272 # (?P<name>regex) -- Assign result of REGEX to NAME.
273 # *? -- Match non-greedily.
274 # (?m) -- Multiline regex: Make ^ and $ match at each line.
275 # (?s) -- Make the dot match all characters including newline.
276 # (?x) -- Ignore whitespace in patterns.
287 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
292 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
297 <(?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>)''',
303 (?P<code><!--\s.*?!-->)
306 'singleline_comment':
325 (\s*(?P<options>.*?)\s*:)?\s*
333 \s*(?P<options>.*?)\s*
342 \s*(?P<options>.*?)\s*
344 \s*(?P<filename>.*?)\s*
351 (?P<code><!--\s.*?!-->)
354 'singleline_comment':
360 (?P<code><pre>.*?</pre>))''',
366 (?P<code><pre>\s.*?</pre>\s))''',
385 \s*(?P<options>.*?)\s*
396 \s*(?P<options>.*?)\s*
400 \\end\s*{lilypond})''',
408 \s*(?P<options>.*?)\s*
416 'singleline_comment':
439 \\end\s*{verbatim}))''',
448 (?P<filename>\S+))''',
452 ^[^\n]*?(?!@c\s+)[^\n]*?
456 \s*(?P<options>.*?)\s*
466 \s*(?P<options>.*?)\s*
469 ^@end\s+lilypond)\s''',
476 \s*(?P<options>.*?)\s*
487 @end\s+ignore))\s''',
489 'singleline_comment':
494 @c([ \t][^\n]*|)\n))''',
496 # Don't do this: It interferes with @code{@{}.
497 # 'verb': r'''(?P<code>@code{.*?})''',
505 @end\s+example\s))''',
514 'intertext': r',?\s*intertext=\".*?\"',
518 'intertext': r',?\s*intertext=\".*?\"',
523 'intertext': r',?\s*intertext=\".*?\"',
524 'option_sep': '\s*,\s*',
528 'intertext': r',?\s*intertext=\".*?\"',
529 'option_sep': '\s*,\s*',
533 # Options without a pattern in ly_options.
552 RELATIVE: r'''\relative c%(relative_quotes)s''',
557 INDENT: r'''indent = %(indent)s''',
559 LINE_WIDTH: r'''line-width = %(line-width)s''',
561 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
563 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
565 RAGGED_RIGHT: r'''ragged-right = ##t''',
567 PACKED: r'''packed = ##t''',
579 \remove Time_signature_engraver
585 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
592 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
595 <imageobject role="latex">
596 <imagedata fileref="%(base)s.pdf" format="PDF"/>
598 <imageobject role="html">
599 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
601 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
603 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
607 FILTER: r'''<lilypond %(options)s>
617 <a href="%(base)s.ly">''',
621 border="0" src="%(image)s" alt="%(alt)s">''',
623 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
625 QUOTE: r'''<blockquote>
638 \ifx\preLilyPondExample \undefined%%
641 \preLilyPondExample%%
643 \def\lilypondbook{}%%
644 \input %(base)s-systems.tex%%
645 \ifx\postLilyPondExample \undefined%%
648 \postLilyPondExample%%
652 PRINTFILENAME: '''\\texttt{%(filename)s}
655 QUOTE: r'''\begin{quotation}%(str)s
658 VERBATIM: r'''\noindent
659 \begin{verbatim}%(verb)s\end{verbatim}''',
661 FILTER: r'''\begin{lilypond}[%(options)s]
668 FILTER: r'''@lilypond[%(options)s]
674 @include %(base)s-systems.texi
678 OUTPUTIMAGE: r'''@noindent
680 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
684 <a href="%(base)s.ly">
686 border="0" src="%(image)s" alt="%(alt)s">
694 <a href="%(base)s.ly">
702 QUOTE: r'''@quotation
703 %(str)s@end quotation
710 VERBATIM: r'''@exampleindent 0
712 %(verb)s@end verbatim
715 ADDVERSION: r'''@example
716 \version @w{"@version{}"}
723 # Maintain line numbers.
728 for f in [HTML, LATEX]:
729 for s in (QUOTE, VERBATIM):
730 output[f][s] = output[f][s].replace("\n"," ")
733 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
734 %%%% Options: [%(option_string)s]
735 \\include "lilypond-book-preamble.ly"
738 %% ****************************************************************
739 %% Start cut-&-pastable-section
740 %% ****************************************************************
745 #(define dump-extents #t)
746 %(font_dump_setting)s
748 force-assignment = #""
749 line-width = #(- line-width (* mm %(padding_mm)f))
762 %% ****************************************************************
763 %% ly snippet contents follows:
764 %% ****************************************************************
768 %% ****************************************************************
770 %% ****************************************************************
777 %% ****************************************************************
779 %% ****************************************************************
783 %% ****************************************************************
785 %% ****************************************************************
788 texinfo_line_widths = {
789 '@afourpaper': '160\\mm',
790 '@afourwide': '6.5\\in',
791 '@afourlatex': '150\\mm',
792 '@smallbook': '5\\in',
793 '@letterpaper': '6\\in',
796 def classic_lilypond_book_compatibility (key, value):
797 if key == 'singleline' and value == None:
798 return (RAGGED_RIGHT, None)
800 m = re.search ('relative\s*([-0-9])', key)
802 return ('relative', m.group (1))
804 m = re.match ('([0-9]+)pt', key)
806 return ('staffsize', m.group (1))
808 if key == 'indent' or key == 'line-width':
809 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
811 f = float (m.group (1))
812 return (key, '%f\\%s' % (f, m.group (2)))
816 def find_file (name, raise_error=True):
817 for i in global_options.include_path:
818 full = os.path.join (i, name)
819 if os.path.exists (full):
823 error (_ ("file not found: %s") % name + '\n')
827 def verbatim_html (s):
828 return re.sub ('>', '>',
830 re.sub ('&', '&', s)))
833 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
834 def set_default_options (source, default_ly_options, format):
835 global document_language
836 if LINE_WIDTH not in default_ly_options:
838 textwidth = get_latex_textwidth (source)
839 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
840 elif format == TEXINFO:
841 m = texinfo_lang_re.search (source)
842 if m and not m.group (1).startswith ('en'):
843 document_language = m.group (1)
845 document_language = ''
846 for regex in texinfo_line_widths:
847 # FIXME: @layout is usually not in
850 # \input texinfo @c -*-texinfo-*-
852 # Bluntly search first K items of
854 # s = chunks[0].replacement_text ()
855 if re.search (regex, source[:1024]):
856 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
860 def replacement_text (self):
863 def filter_text (self):
864 return self.replacement_text ()
869 class Substring (Chunk):
870 """A string that does not require extra memory."""
871 def __init__ (self, source, start, end, line_number):
875 self.line_number = line_number
876 self.override_text = None
881 def replacement_text (self):
882 if self.override_text:
883 return self.override_text
885 return self.source[self.start:self.end]
887 class Snippet (Chunk):
888 def __init__ (self, type, match, format, line_number):
892 self.option_dict = {}
894 self.line_number = line_number
896 def replacement_text (self):
897 return self.match.group ('match')
899 def substring (self, s):
900 return self.match.group (s)
903 return `self.__class__` + ' type = ' + self.type
905 class IncludeSnippet (Snippet):
906 def processed_filename (self):
907 f = self.substring ('filename')
908 return os.path.splitext (f)[0] + format2ext[self.format]
910 def replacement_text (self):
911 s = self.match.group ('match')
912 f = self.substring ('filename')
914 return re.sub (f, self.processed_filename (), s)
916 class LilypondSnippet (Snippet):
917 def __init__ (self, type, match, format, line_number):
918 Snippet.__init__ (self, type, match, format, line_number)
919 os = match.group ('options')
920 self.do_options (os, self.type)
923 return self.substring ('code')
926 contents = self.substring ('code')
927 return ('\\sourcefileline %d\n%s'
928 % (self.line_number - 1, contents))
933 return self.compose_ly (s)
936 def split_options (self, option_string):
938 if self.format == HTML:
939 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
941 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
945 return re.split (format_res[self.format]['option_sep'],
949 def do_options (self, option_string, type):
950 self.option_dict = {}
952 options = self.split_options (option_string)
954 for option in options:
956 (key, value) = re.split ('\s*=\s*', option)
957 self.option_dict[key] = value
959 if option in no_options:
960 if no_options[option] in self.option_dict:
961 del self.option_dict[no_options[option]]
963 self.option_dict[option] = None
965 has_line_width = self.option_dict.has_key (LINE_WIDTH)
966 no_line_width_value = 0
968 # If LINE_WIDTH is used without parameter, set it to default.
969 if has_line_width and self.option_dict[LINE_WIDTH] == None:
970 no_line_width_value = 1
971 del self.option_dict[LINE_WIDTH]
973 for k in default_ly_options:
974 if k not in self.option_dict:
975 self.option_dict[k] = default_ly_options[k]
977 if not has_line_width:
978 if type == 'lilypond' or FRAGMENT in self.option_dict:
979 self.option_dict[RAGGED_RIGHT] = None
981 if type == 'lilypond':
982 if LINE_WIDTH in self.option_dict:
983 del self.option_dict[LINE_WIDTH]
985 if RAGGED_RIGHT in self.option_dict:
986 if LINE_WIDTH in self.option_dict:
987 del self.option_dict[LINE_WIDTH]
989 if QUOTE in self.option_dict or type == 'lilypond':
990 if LINE_WIDTH in self.option_dict:
991 del self.option_dict[LINE_WIDTH]
993 if not INDENT in self.option_dict:
994 self.option_dict[INDENT] = '0\\mm'
996 # The QUOTE pattern from ly_options only emits the `line-width'
998 if has_line_width and QUOTE in self.option_dict:
999 if no_line_width_value:
1000 del self.option_dict[LINE_WIDTH]
1002 del self.option_dict[QUOTE]
1004 def compose_ly (self, code):
1005 if FRAGMENT in self.option_dict:
1013 # The original concept of the `exampleindent' option is broken.
1014 # It is not possible to get a sane value for @exampleindent at all
1015 # without processing the document itself. Saying
1023 # causes ugly results with the DVI backend of texinfo since the
1024 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1025 # value). Executing the above code changes the environment
1026 # indentation to an unknown value because we don't know the amount
1027 # of 1em in advance since it is font-dependent. Modifying
1028 # @exampleindent in the middle of a document is simply not
1029 # supported within texinfo.
1031 # As a consequence, the only function of @exampleindent is now to
1032 # specify the amount of indentation for the `quote' option.
1034 # To set @exampleindent locally to zero, we use the @format
1035 # environment for non-quoted snippets.
1036 override[EXAMPLEINDENT] = r'0.4\in'
1037 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1038 override.update (default_ly_options)
1041 for (key, value) in self.option_dict.items ():
1043 option_list.append (key)
1045 option_list.append (key + '=' + value)
1046 option_string = ','.join (option_list)
1049 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1050 for a in compose_types:
1051 compose_dict[a] = []
1053 for (key, value) in self.option_dict.items ():
1054 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1058 _ ("deprecated ly-option used: %s=%s") % (key, value))
1060 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1063 _ ("deprecated ly-option used: %s") % key)
1065 _ ("compatibility mode translation: %s") % c_key)
1067 (key, value) = (c_key, c_value)
1070 override[key] = value
1072 if not override.has_key (key):
1073 override[key] = None
1076 for type in compose_types:
1077 if ly_options[type].has_key (key):
1078 compose_dict[type].append (ly_options[type][key])
1082 if not found and key not in simple_options:
1083 warning (_ ("ignoring unknown ly option: %s") % key)
1086 if RELATIVE in override and override[RELATIVE]:
1087 relative = int (override[RELATIVE])
1089 relative_quotes = ''
1093 relative_quotes += ',' * (- relative)
1095 relative_quotes += "'" * relative
1097 paper_string = '\n '.join (compose_dict[PAPER]) % override
1098 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1099 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1100 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1101 padding_mm = global_options.padding_mm
1102 font_dump_setting = ''
1103 if FONTLOAD in self.option_dict:
1104 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1106 d = globals().copy()
1108 return (PREAMBLE_LY + body) % d
1110 def get_checksum (self):
1111 if not self.checksum:
1112 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1114 ## let's not create too long names.
1115 self.checksum = hash.hexdigest ()[:10]
1117 return self.checksum
1119 def basename (self):
1120 cs = self.get_checksum ()
1121 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1124 def write_ly (self):
1125 base = self.basename ()
1126 path = os.path.join (global_options.lily_output_dir, base)
1127 directory = os.path.split(path)[0]
1128 if not os.path.isdir (directory):
1129 os.makedirs (directory)
1130 out = file (path + '.ly', 'w')
1131 out.write (self.full_ly ())
1132 file (path + '.txt', 'w').write ('image of music')
1134 def relevant_contents (self, ly):
1135 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1137 def link_all_output_files (self, output_dir, output_dir_files, destination):
1138 existing, missing = self.all_output_files (output_dir, output_dir_files)
1140 print '\nMissing', missing
1141 raise CompileError(self.basename())
1142 for name in existing:
1144 os.unlink (os.path.join (destination, name))
1148 src = os.path.join (output_dir, name)
1149 dst = os.path.join (destination, name)
1150 dst_path = os.path.split(dst)[0]
1151 if not os.path.isdir (dst_path):
1152 os.makedirs (dst_path)
1156 def all_output_files (self, output_dir, output_dir_files):
1157 """Return all files generated in lily_output_dir, a set.
1159 output_dir_files is the list of files in the output directory.
1163 base = self.basename()
1164 full = os.path.join (output_dir, base)
1165 def consider_file (name):
1166 if name in output_dir_files:
1169 def require_file (name):
1170 if name in output_dir_files:
1175 # UGH - junk global_options
1176 skip_lily = global_options.skip_lilypond_run
1177 for required in [base + '.ly',
1179 require_file (required)
1181 require_file (base + '-systems.count')
1183 map (consider_file, [base + '.tex',
1186 base + '-systems.texi',
1187 base + '-systems.tex',
1188 base + '-systems.pdftexi'])
1190 # UGH - junk global_options
1191 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1192 and not global_options.skip_png_check):
1193 page_count = ps_page_count (full + '.eps')
1195 require_file (base + '.png')
1197 for page in range (1, page_count + 1):
1198 require_file (base + '-page%d.png' % page)
1201 if not skip_lily and not missing:
1202 system_count = int(file (full + '-systems.count').read())
1203 for number in range(1, system_count + 1):
1204 systemfile = '%s-%d' % (base, number)
1205 require_file (systemfile + '.eps')
1206 consider_file (systemfile + '.pdf')
1208 return (result, missing)
1210 def is_outdated (self, output_dir, current_files):
1211 found, missing = self.all_output_files (output_dir, current_files)
1214 def filter_text (self):
1215 """Run snippet bodies through a command (say: convert-ly).
1217 This functionality is rarely used, and this code must have bitrot.
1219 code = self.substring ('code')
1220 s = filter_pipe (code, global_options.filter_cmd)
1223 'options': self.match.group ('options')
1226 return output[self.format][FILTER] % d
1228 def replacement_text (self):
1229 func = LilypondSnippet.__dict__['output_' + self.format]
1232 def get_images (self):
1233 base = self.basename ()
1235 single = '%(base)s.png' % vars ()
1236 multiple = '%(base)s-page1.png' % vars ()
1238 if (os.path.exists (multiple)
1239 and (not os.path.exists (single)
1240 or (os.stat (multiple)[stat.ST_MTIME]
1241 > os.stat (single)[stat.ST_MTIME]))):
1242 count = ps_page_count ('%(base)s.eps' % vars ())
1243 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1244 images = tuple (images)
1248 def output_docbook (self):
1250 base = self.basename ()
1251 for image in self.get_images ():
1252 (base, ext) = os.path.splitext (image)
1253 str += output[DOCBOOK][OUTPUT] % vars ()
1254 str += self.output_print_filename (DOCBOOK)
1255 if (self.substring('inline') == 'inline'):
1256 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1258 str = '<mediaobject>' + str + '</mediaobject>'
1259 if VERBATIM in self.option_dict:
1260 verb = verbatim_html (self.verb_ly ())
1261 str = output[DOCBOOK][VERBATIM] % vars () + str
1264 def output_html (self):
1266 base = self.basename ()
1267 if self.format == HTML:
1268 str += self.output_print_filename (HTML)
1269 if VERBATIM in self.option_dict:
1270 verb = verbatim_html (self.verb_ly ())
1271 str += output[HTML][VERBATIM] % vars ()
1272 if QUOTE in self.option_dict:
1273 str = output[HTML][QUOTE] % vars ()
1275 str += output[HTML][BEFORE] % vars ()
1276 for image in self.get_images ():
1277 (base, ext) = os.path.splitext (image)
1278 alt = self.option_dict[ALT]
1279 str += output[HTML][OUTPUT] % vars ()
1280 str += output[HTML][AFTER] % vars ()
1283 def output_info (self):
1285 for image in self.get_images ():
1286 (base, ext) = os.path.splitext (image)
1288 # URG, makeinfo implicitly prepends dot to extension.
1289 # Specifying no extension is most robust.
1291 alt = self.option_dict[ALT]
1292 info_image_path = os.path.join (global_options.info_images_dir, base)
1293 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1295 base = self.basename ()
1296 str += output[self.format][OUTPUT] % vars ()
1299 def output_latex (self):
1301 base = self.basename ()
1302 if self.format == LATEX:
1303 str += self.output_print_filename (LATEX)
1304 if VERBATIM in self.option_dict:
1305 verb = self.verb_ly ()
1306 str += (output[LATEX][VERBATIM] % vars ())
1308 str += (output[LATEX][OUTPUT] % vars ())
1310 ## todo: maintain breaks
1312 breaks = self.ly ().count ("\n")
1313 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1315 if QUOTE in self.option_dict:
1316 str = output[LATEX][QUOTE] % vars ()
1319 def output_print_filename (self, format):
1321 if PRINTFILENAME in self.option_dict:
1322 base = self.basename ()
1323 filename = os.path.basename (self.substring ('filename'))
1324 str = output[format][PRINTFILENAME] % vars ()
1328 def output_texinfo (self):
1329 str = self.output_print_filename (TEXINFO)
1330 base = self.basename ()
1331 if TEXIDOC in self.option_dict:
1332 texidoc = base + '.texidoc'
1333 translated_texidoc = texidoc + document_language
1334 if os.path.exists (translated_texidoc):
1335 str += '@include %(translated_texidoc)s\n\n' % vars ()
1336 elif os.path.exists (texidoc):
1337 str += '@include %(texidoc)s\n\n' % vars ()
1340 if VERBATIM in self.option_dict:
1342 if ADDVERSION in self.option_dict:
1343 version = output[TEXINFO][ADDVERSION]
1344 verb = self.verb_ly ()
1345 substr = output[TEXINFO][VERBATIM] % vars ()
1346 substr += self.output_info ()
1347 if LILYQUOTE in self.option_dict:
1348 substr = output[TEXINFO][QUOTE] % {'str':substr}
1351 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1352 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1353 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1355 if QUOTE in self.option_dict:
1356 str = output[TEXINFO][QUOTE] % vars ()
1358 # need par after image
1363 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1364 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1366 class LilypondFileSnippet (LilypondSnippet):
1367 def __init__ (self, type, match, format, line_number):
1368 LilypondSnippet.__init__ (self, type, match, format, line_number)
1369 self.contents = file (find_file (self.substring ('filename'))).read ()
1373 s = re_begin_verbatim.split (s)[-1]
1374 s = re_end_verbatim.split (s)[0]
1378 name = self.substring ('filename')
1379 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1380 % (name, self.contents))
1383 snippet_type_to_class = {
1384 'lilypond_file': LilypondFileSnippet,
1385 'lilypond_block': LilypondSnippet,
1386 'lilypond': LilypondSnippet,
1387 'include': IncludeSnippet,
1390 def find_linestarts (s):
1395 i = s.find ('\n', start)
1403 nls.append (len (s))
1406 def find_toplevel_snippets (input_string, format, types):
1409 res[t] = re.compile (snippet_res[format][t])
1413 found = dict ([(t, None) for t in types])
1415 line_starts = find_linestarts (input_string)
1417 # We want to search for multiple regexes, without searching
1418 # the string multiple times for one regex.
1419 # Hence, we use earlier results to limit the string portion
1421 # Since every part of the string is traversed at most once for
1422 # every type of snippet, this is linear.
1428 if not found[type] or found[type][0] < index:
1431 m = res[type].search (input_string[index:endex])
1436 if type in snippet_type_to_class:
1437 klass = snippet_type_to_class[type]
1439 start = index + m.start ('match')
1440 line_number = line_start_idx
1441 while (line_starts[line_number] < start):
1445 snip = klass (type, m, format, line_number)
1447 found[type] = (start, snip)
1451 or found[type][0] < found[first][0])):
1456 # Limiting the search space is a cute
1457 # idea, but this *requires* to search
1458 # for possible containing blocks
1459 # first, at least as long as we do not
1460 # search for the start of blocks, but
1461 # always/directly for the entire
1462 # @block ... @end block.
1464 endex = found[first][0]
1467 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1470 while (start > line_starts[line_start_idx+1]):
1473 (start, snip) = found[first]
1474 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1475 snippets.append (snip)
1477 index = start + len (snip.match.group ('match'))
1481 def filter_pipe (input, cmd):
1482 """Pass input through cmd, and return the result."""
1484 if global_options.verbose:
1485 progress (_ ("Opening filter `%s'") % cmd)
1487 (stdin, stdout, stderr) = os.popen3 (cmd)
1489 status = stdin.close ()
1493 output = stdout.read ()
1494 status = stdout.close ()
1495 error = stderr.read ()
1499 signal = 0x0f & status
1500 if status or (not output and error):
1501 exit_status = status >> 8
1502 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1503 error (_ ("The error log is as follows:"))
1504 ly.stderr_write (error)
1505 ly.stderr_write (stderr.read ())
1508 if global_options.verbose:
1513 def system_in_directory (cmd, directory):
1514 """Execute a command in a different directory.
1516 Because of win32 compatibility, we can't simply use subprocess.
1519 current = os.getcwd()
1520 os.chdir (directory)
1521 ly.system(cmd, be_verbose=global_options.verbose,
1526 def process_snippets (cmd, snippets,
1527 format, lily_output_dir):
1528 """Run cmd on all of the .ly files from snippets."""
1533 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1534 cmd += ' --formats=png '
1535 elif format in (DOCBOOK) and '--formats' not in cmd:
1536 cmd += ' --formats=png,pdf '
1538 checksum = snippet_list_checksum (snippets)
1539 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1540 + [snip.basename() + '.ly' for snip in snippets])
1541 name = os.path.join (lily_output_dir,
1542 'snippet-names-%d.ly' % checksum)
1543 file (name, 'wb').write (contents)
1545 system_in_directory (' '.join ([cmd, name]),
1550 # Retrieve dimensions from LaTeX
1551 LATEX_INSPECTION_DOCUMENT = r'''
1555 \typeout{textwidth=\the\textwidth}
1556 \typeout{columnsep=\the\columnsep}
1557 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1561 # Do we need anything else besides `textwidth'?
1562 def get_latex_textwidth (source):
1563 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1565 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1567 ## what's a sensible default?
1570 preamble = source[:m.start (0)]
1571 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1573 (handle, tmpfile) = tempfile.mkstemp('.tex')
1574 logfile = os.path.splitext (tmpfile)[0] + '.log'
1575 logfile = os.path.split (logfile)[1]
1577 tmp_handle = os.fdopen (handle,'w')
1578 tmp_handle.write (latex_document)
1581 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1582 be_verbose=global_options.verbose)
1583 parameter_string = file (logfile).read()
1589 m = re.search ('columns=([0-9.]*)', parameter_string)
1591 columns = int (m.group (1))
1594 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1596 columnsep = float (m.group (1))
1599 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1601 textwidth = float (m.group (1))
1603 textwidth = (textwidth - columnsep) / columns
1607 def modify_preamble (chunk):
1608 str = chunk.replacement_text ()
1609 if (re.search (r"\\begin *{document}", str)
1610 and not re.search ("{graphic[sx]", str)):
1611 str = re.sub (r"\\begin{document}",
1612 r"\\usepackage{graphics}" + '\n'
1613 + r"\\begin{document}",
1615 chunk.override_text = str
1620 # TEXINFO: '.texinfo',
1626 class CompileError(Exception):
1629 def snippet_list_checksum (snippets):
1630 return hash (' '.join([l.basename() for l in snippets]))
1632 def write_file_map (lys, name):
1633 snippet_map = file (os.path.join (
1634 global_options.lily_output_dir,
1635 '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 '(%s
1642 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1645 def split_output_files(directory):
1646 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1648 Return value is a set of strings.
1651 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1652 base_subdir = os.path.split (subdir)[1]
1653 sub_files = [os.path.join (base_subdir, name)
1654 for name in os.listdir (subdir)]
1658 def do_process_cmd (chunks, input_name, options):
1659 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1661 output_files = split_output_files (options.lily_output_dir)
1662 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1664 write_file_map (outdated, input_name)
1665 progress (_ ("Writing snippets..."))
1666 for snippet in outdated:
1671 progress (_ ("Processing..."))
1673 process_snippets (options.process_cmd, outdated,
1674 options.format, options.lily_output_dir)
1677 progress (_ ("All snippets are up to date..."))
1679 if options.lily_output_dir != options.output_dir:
1680 output_files = split_output_files (options.lily_output_dir)
1681 for snippet in snippets:
1682 snippet.link_all_output_files (options.lily_output_dir,
1690 # Format guessing data
1699 '.texinfo': TEXINFO,
1704 def guess_format (input_filename):
1706 e = os.path.splitext (input_filename)[1]
1709 format = ext2format[e]
1711 error (_ ("cannot determine format for: %s"
1716 def write_if_updated (file_name, lines):
1718 f = file (file_name)
1720 new_str = ''.join (lines)
1721 if oldstr == new_str:
1722 progress (_ ("%s is up to date.") % file_name)
1725 # this prevents make from always rerunning lilypond-book:
1726 # output file must be touched in order to be up to date
1727 os.utime (file_name, None)
1731 progress (_ ("Writing `%s'...") % file_name)
1732 file (file_name, 'w').writelines (lines)
1736 def note_input_file (name, inputs=[]):
1737 ## hack: inputs is mutable!
1738 inputs.append (name)
1741 def samefile (f1, f2):
1743 return os.path.samefile (f1, f2)
1744 except AttributeError: # Windoze
1745 f1 = re.sub ("//*", "/", f1)
1746 f2 = re.sub ("//*", "/", f2)
1749 def do_file (input_filename):
1751 if not input_filename or input_filename == '-':
1752 in_handle = sys.stdin
1753 input_fullname = '<stdin>'
1755 if os.path.exists (input_filename):
1756 input_fullname = input_filename
1757 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1758 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1760 input_fullname = find_file (input_filename)
1762 note_input_file (input_fullname)
1763 in_handle = file (input_fullname)
1765 if input_filename == '-':
1766 input_base = 'stdin'
1768 input_base = os.path.basename (
1769 os.path.splitext (input_filename)[0])
1771 # don't complain when global_options.output_dir is existing
1772 if not global_options.output_dir:
1773 global_options.output_dir = os.getcwd()
1775 global_options.output_dir = os.path.abspath(global_options.output_dir)
1777 if not os.path.isdir (global_options.output_dir):
1778 os.mkdir (global_options.output_dir, 0777)
1779 os.chdir (global_options.output_dir)
1781 output_filename = os.path.join(global_options.output_dir,
1782 input_base + format2ext[global_options.format])
1783 if (os.path.exists (input_filename)
1784 and os.path.exists (output_filename)
1785 and samefile (output_filename, input_fullname)):
1787 _ ("Output would overwrite input file; use --output."))
1791 progress (_ ("Reading %s...") % input_fullname)
1792 source = in_handle.read ()
1795 set_default_options (source, default_ly_options, global_options.format)
1798 # FIXME: Containing blocks must be first, see
1799 # find_toplevel_snippets.
1801 'multiline_comment',
1805 'singleline_comment',
1810 progress (_ ("Dissecting..."))
1811 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1813 if global_options.format == LATEX:
1815 if (c.is_plain () and
1816 re.search (r"\\begin *{document}", c.replacement_text())):
1821 if global_options.filter_cmd:
1822 write_if_updated (output_filename,
1823 [c.filter_text () for c in chunks])
1824 elif global_options.process_cmd:
1825 do_process_cmd (chunks, input_fullname, global_options)
1826 progress (_ ("Compiling %s...") % output_filename)
1828 write_if_updated (output_filename,
1829 [s.replacement_text ()
1832 def process_include (snippet):
1833 os.chdir (original_dir)
1834 name = snippet.substring ('filename')
1835 progress (_ ("Processing include: %s") % name)
1837 return do_file (name)
1839 include_chunks = map (process_include,
1840 filter (lambda x: isinstance (x, IncludeSnippet),
1843 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1845 except CompileError:
1846 os.chdir (original_dir)
1847 progress (_ ("Removing `%s'") % output_filename)
1852 global global_options
1854 opt_parser = get_option_parser()
1855 (global_options, args) = opt_parser.parse_args ()
1856 if global_options.format in ('texi-html', 'texi'):
1857 global_options.format = TEXINFO
1859 global_options.include_path = map (os.path.abspath, global_options.include_path)
1861 if global_options.warranty:
1864 if not args or len (args) > 1:
1865 opt_parser.print_help ()
1871 # FIXME: 85 lines of `main' macramee??
1872 files = do_options ()
1874 basename = os.path.splitext (files[0])[0]
1875 basename = os.path.split (basename)[1]
1877 if not global_options.format:
1878 global_options.format = guess_format (files[0])
1881 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1884 if global_options.process_cmd == '':
1885 global_options.process_cmd = (lilypond_binary
1886 + ' --formats=%s -dbackend=eps ' % formats)
1888 if global_options.process_cmd:
1889 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1890 for p in global_options.include_path])
1892 if global_options.format in (TEXINFO, LATEX):
1893 ## prevent PDF from being switched on by default.
1894 global_options.process_cmd += ' --formats=eps '
1895 if global_options.create_pdf:
1896 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1898 if global_options.verbose:
1899 global_options.process_cmd += " --verbose "
1901 if global_options.padding_mm:
1902 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1904 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
1906 if global_options.lily_output_dir:
1907 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1908 if not os.path.isdir (global_options.lily_output_dir):
1909 os.makedirs (global_options.lily_output_dir)
1911 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1916 chunks = do_file (files[0])
1917 except CompileError:
1920 inputs = note_input_file ('')
1923 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1924 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1925 final_output_file = os.path.join (global_options.output_dir,
1927 + '.%s' % global_options.format)
1929 os.chdir (original_dir)
1930 file (dep_file, 'w').write ('%s: %s'
1931 % (final_output_file, ' '.join (inputs)))
1933 if __name__ == '__main__':