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 ('--skip-lily-check',
151 help=_ ("do not fail if no lilypond output is found."),
153 action='store_true', dest='skip_lilypond_run',
156 p.add_option ('--skip-png-check',
157 help=_ ("do not fail if no PNG images are found for EPS files"),
159 action='store_true', dest='skip_png_check',
162 p.add_option ('--lily-output-dir',
163 help=_ ("write lily-XXX files to DIR, link into --output dir."),
165 action='store', dest='lily_output_dir',
168 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
169 help = _ ("process ly_files using COMMAND FILE..."),
171 dest='process_cmd', default='')
173 p.add_option ('--pdf',
176 help=_ ("create PDF files for use with PDFTeX"),
179 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
180 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
181 must use this with dvips -h INPUT.psfonts'''),
184 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
189 p.version = "@TOPLEVEL_VERSION@"
190 p.add_option("--version",
192 help=_ ("show version number and exit"))
194 p.add_option ('-w', '--warranty',
195 help=_ ("show warranty and copyright"),
197 p.add_option_group (ly.display_encode (_ ('Bugs')),
199 _ ("Report bugs via")
200 + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
203 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
205 # Only use installed binary when we are installed too.
206 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
207 lilypond_binary = 'lilypond'
209 global_options = None
212 default_ly_options = { 'alt': "[image of music]" }
214 document_language = ''
217 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
219 ADDVERSION = 'addversion'
223 EXAMPLEINDENT = 'exampleindent'
225 FRAGMENT = 'fragment'
231 LINE_WIDTH = 'line-width'
232 LILYQUOTE = 'lilyquote'
233 NOFRAGMENT = 'nofragment'
234 NOINDENT = 'noindent'
239 OUTPUTIMAGE = 'outputimage'
242 PREAMBLE = 'preamble'
243 PRINTFILENAME = 'printfilename'
245 RAGGED_RIGHT = 'ragged-right'
246 RELATIVE = 'relative'
247 STAFFSIZE = 'staffsize'
250 VERBATIM = 'verbatim'
251 FONTLOAD = 'fontload'
252 FILENAME = 'filename'
256 # NOTIME has no opposite so it isn't part of this dictionary.
257 # NOQUOTE is used internally only.
259 NOFRAGMENT: FRAGMENT,
264 # Recognize special sequences in the input.
266 # (?P<name>regex) -- Assign result of REGEX to NAME.
267 # *? -- Match non-greedily.
268 # (?m) -- Multiline regex: Make ^ and $ match at each line.
269 # (?s) -- Make the dot match all characters including newline.
270 # (?x) -- Ignore whitespace in patterns.
281 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
286 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
291 <(?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>)''',
297 (?P<code><!--\s.*?!-->)
300 'singleline_comment':
319 (\s*(?P<options>.*?)\s*:)?\s*
327 \s*(?P<options>.*?)\s*
336 \s*(?P<options>.*?)\s*
338 \s*(?P<filename>.*?)\s*
345 (?P<code><!--\s.*?!-->)
348 'singleline_comment':
354 (?P<code><pre>.*?</pre>))''',
360 (?P<code><pre>\s.*?</pre>\s))''',
379 \s*(?P<options>.*?)\s*
390 \s*(?P<options>.*?)\s*
394 \\end\s*{lilypond})''',
402 \s*(?P<options>.*?)\s*
410 'singleline_comment':
433 \\end\s*{verbatim}))''',
442 (?P<filename>\S+))''',
446 ^[^\n]*?(?!@c\s+)[^\n]*?
450 \s*(?P<options>.*?)\s*
460 \s*(?P<options>.*?)\s*
463 ^@end\s+lilypond)\s''',
470 \s*(?P<options>.*?)\s*
481 @end\s+ignore))\s''',
483 'singleline_comment':
488 @c([ \t][^\n]*|)\n))''',
490 # Don't do this: It interferes with @code{@{}.
491 # 'verb': r'''(?P<code>@code{.*?})''',
499 @end\s+example\s))''',
508 'intertext': r',?\s*intertext=\".*?\"',
512 'intertext': r',?\s*intertext=\".*?\"',
517 'intertext': r',?\s*intertext=\".*?\"',
518 'option_sep': '\s*,\s*',
522 'intertext': r',?\s*intertext=\".*?\"',
523 'option_sep': '\s*,\s*',
527 # Options without a pattern in ly_options.
546 RELATIVE: r'''\relative c%(relative_quotes)s''',
551 INDENT: r'''indent = %(indent)s''',
553 LINE_WIDTH: r'''line-width = %(line-width)s''',
555 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
557 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
559 RAGGED_RIGHT: r'''ragged-right = ##t''',
561 PACKED: r'''packed = ##t''',
573 \remove Time_signature_engraver
579 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
586 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
589 <imageobject role="latex">
590 <imagedata fileref="%(base)s.pdf" format="PDF"/>
592 <imageobject role="html">
593 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
595 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
597 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
601 FILTER: r'''<lilypond %(options)s>
611 <a href="%(base)s.ly">''',
615 border="0" src="%(image)s" alt="%(alt)s">''',
617 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
619 QUOTE: r'''<blockquote>
632 \ifx\preLilyPondExample \undefined%%
635 \preLilyPondExample%%
637 \def\lilypondbook{}%%
638 \input %(base)s-systems.tex%%
639 \ifx\postLilyPondExample \undefined%%
642 \postLilyPondExample%%
646 PRINTFILENAME: '''\\texttt{%(filename)s}
649 QUOTE: r'''\begin{quotation}%(str)s
652 VERBATIM: r'''\noindent
653 \begin{verbatim}%(verb)s\end{verbatim}''',
655 FILTER: r'''\begin{lilypond}[%(options)s]
662 FILTER: r'''@lilypond[%(options)s]
668 @include %(base)s-systems.texi
672 OUTPUTIMAGE: r'''@noindent
674 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
678 <a href="%(base)s.ly">
680 border="0" src="%(image)s" alt="%(alt)s">
688 <a href="%(base)s.ly">
696 QUOTE: r'''@quotation
697 %(str)s@end quotation
704 VERBATIM: r'''@exampleindent 0
706 %(verb)s@end verbatim
709 ADDVERSION: r'''@example
710 \version @w{"@version{}"}
717 # Maintain line numbers.
722 for f in [HTML, LATEX]:
723 for s in (QUOTE, VERBATIM):
724 output[f][s] = output[f][s].replace("\n"," ")
727 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
728 %%%% Options: [%(option_string)s]
729 \\include "lilypond-book-preamble.ly"
732 %% ****************************************************************
733 %% Start cut-&-pastable-section
734 %% ****************************************************************
739 #(define dump-extents #t)
740 %(font_dump_setting)s
742 force-assignment = #""
743 line-width = #(- line-width (* mm %(padding_mm)f))
756 %% ****************************************************************
757 %% ly snippet contents follows:
758 %% ****************************************************************
762 %% ****************************************************************
764 %% ****************************************************************
771 %% ****************************************************************
773 %% ****************************************************************
777 %% ****************************************************************
779 %% ****************************************************************
782 texinfo_line_widths = {
783 '@afourpaper': '160\\mm',
784 '@afourwide': '6.5\\in',
785 '@afourlatex': '150\\mm',
786 '@smallbook': '5\\in',
787 '@letterpaper': '6\\in',
790 def classic_lilypond_book_compatibility (key, value):
791 if key == 'singleline' and value == None:
792 return (RAGGED_RIGHT, None)
794 m = re.search ('relative\s*([-0-9])', key)
796 return ('relative', m.group (1))
798 m = re.match ('([0-9]+)pt', key)
800 return ('staffsize', m.group (1))
802 if key == 'indent' or key == 'line-width':
803 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
805 f = float (m.group (1))
806 return (key, '%f\\%s' % (f, m.group (2)))
810 def find_file (name, raise_error=True):
811 for i in global_options.include_path:
812 full = os.path.join (i, name)
813 if os.path.exists (full):
817 error (_ ("file not found: %s") % name + '\n')
821 def verbatim_html (s):
822 return re.sub ('>', '>',
824 re.sub ('&', '&', s)))
827 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
828 def set_default_options (source, default_ly_options, format):
829 global document_language
830 if LINE_WIDTH not in default_ly_options:
832 textwidth = get_latex_textwidth (source)
833 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
834 elif format == TEXINFO:
835 m = texinfo_lang_re.search (source)
836 if m and not m.group (1).startswith ('en'):
837 document_language = m.group (1)
839 document_language = ''
840 for regex in texinfo_line_widths:
841 # FIXME: @layout is usually not in
844 # \input texinfo @c -*-texinfo-*-
846 # Bluntly search first K items of
848 # s = chunks[0].replacement_text ()
849 if re.search (regex, source[:1024]):
850 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
854 def replacement_text (self):
857 def filter_text (self):
858 return self.replacement_text ()
863 class Substring (Chunk):
864 """A string that does not require extra memory."""
865 def __init__ (self, source, start, end, line_number):
869 self.line_number = line_number
870 self.override_text = None
875 def replacement_text (self):
876 if self.override_text:
877 return self.override_text
879 return self.source[self.start:self.end]
881 class Snippet (Chunk):
882 def __init__ (self, type, match, format, line_number):
886 self.option_dict = {}
888 self.line_number = line_number
890 def replacement_text (self):
891 return self.match.group ('match')
893 def substring (self, s):
894 return self.match.group (s)
897 return `self.__class__` + ' type = ' + self.type
899 class IncludeSnippet (Snippet):
900 def processed_filename (self):
901 f = self.substring ('filename')
902 return os.path.splitext (f)[0] + format2ext[self.format]
904 def replacement_text (self):
905 s = self.match.group ('match')
906 f = self.substring ('filename')
908 return re.sub (f, self.processed_filename (), s)
910 class LilypondSnippet (Snippet):
911 def __init__ (self, type, match, format, line_number):
912 Snippet.__init__ (self, type, match, format, line_number)
913 os = match.group ('options')
914 self.do_options (os, self.type)
917 return self.substring ('code')
920 contents = self.substring ('code')
921 return ('\\sourcefileline %d\n%s'
922 % (self.line_number - 1, contents))
927 return self.compose_ly (s)
930 def split_options (self, option_string):
932 if self.format == HTML:
933 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
935 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
939 return re.split (format_res[self.format]['option_sep'],
943 def do_options (self, option_string, type):
944 self.option_dict = {}
946 options = self.split_options (option_string)
948 for option in options:
950 (key, value) = re.split ('\s*=\s*', option)
951 self.option_dict[key] = value
953 if option in no_options:
954 if no_options[option] in self.option_dict:
955 del self.option_dict[no_options[option]]
957 self.option_dict[option] = None
959 has_line_width = self.option_dict.has_key (LINE_WIDTH)
960 no_line_width_value = 0
962 # If LINE_WIDTH is used without parameter, set it to default.
963 if has_line_width and self.option_dict[LINE_WIDTH] == None:
964 no_line_width_value = 1
965 del self.option_dict[LINE_WIDTH]
967 for k in default_ly_options:
968 if k not in self.option_dict:
969 self.option_dict[k] = default_ly_options[k]
971 if not has_line_width:
972 if type == 'lilypond' or FRAGMENT in self.option_dict:
973 self.option_dict[RAGGED_RIGHT] = None
975 if type == 'lilypond':
976 if LINE_WIDTH in self.option_dict:
977 del self.option_dict[LINE_WIDTH]
979 if RAGGED_RIGHT in self.option_dict:
980 if LINE_WIDTH in self.option_dict:
981 del self.option_dict[LINE_WIDTH]
983 if QUOTE in self.option_dict or type == 'lilypond':
984 if LINE_WIDTH in self.option_dict:
985 del self.option_dict[LINE_WIDTH]
987 if not INDENT in self.option_dict:
988 self.option_dict[INDENT] = '0\\mm'
990 # The QUOTE pattern from ly_options only emits the `line-width'
992 if has_line_width and QUOTE in self.option_dict:
993 if no_line_width_value:
994 del self.option_dict[LINE_WIDTH]
996 del self.option_dict[QUOTE]
998 def compose_ly (self, code):
999 if FRAGMENT in self.option_dict:
1007 # The original concept of the `exampleindent' option is broken.
1008 # It is not possible to get a sane value for @exampleindent at all
1009 # without processing the document itself. Saying
1017 # causes ugly results with the DVI backend of texinfo since the
1018 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1019 # value). Executing the above code changes the environment
1020 # indentation to an unknown value because we don't know the amount
1021 # of 1em in advance since it is font-dependent. Modifying
1022 # @exampleindent in the middle of a document is simply not
1023 # supported within texinfo.
1025 # As a consequence, the only function of @exampleindent is now to
1026 # specify the amount of indentation for the `quote' option.
1028 # To set @exampleindent locally to zero, we use the @format
1029 # environment for non-quoted snippets.
1030 override[EXAMPLEINDENT] = r'0.4\in'
1031 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1032 override.update (default_ly_options)
1035 for (key, value) in self.option_dict.items ():
1037 option_list.append (key)
1039 option_list.append (key + '=' + value)
1040 option_string = ','.join (option_list)
1043 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1044 for a in compose_types:
1045 compose_dict[a] = []
1047 for (key, value) in self.option_dict.items ():
1048 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1052 _ ("deprecated ly-option used: %s=%s") % (key, value))
1054 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1057 _ ("deprecated ly-option used: %s") % key)
1059 _ ("compatibility mode translation: %s") % c_key)
1061 (key, value) = (c_key, c_value)
1064 override[key] = value
1066 if not override.has_key (key):
1067 override[key] = None
1070 for type in compose_types:
1071 if ly_options[type].has_key (key):
1072 compose_dict[type].append (ly_options[type][key])
1076 if not found and key not in simple_options:
1077 warning (_ ("ignoring unknown ly option: %s") % key)
1080 if RELATIVE in override and override[RELATIVE]:
1081 relative = int (override[RELATIVE])
1083 relative_quotes = ''
1087 relative_quotes += ',' * (- relative)
1089 relative_quotes += "'" * relative
1091 paper_string = '\n '.join (compose_dict[PAPER]) % override
1092 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1093 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1094 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1095 padding_mm = global_options.padding_mm
1096 font_dump_setting = ''
1097 if FONTLOAD in self.option_dict:
1098 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1100 d = globals().copy()
1102 return (PREAMBLE_LY + body) % d
1104 def get_checksum (self):
1105 if not self.checksum:
1106 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1108 ## let's not create too long names.
1109 self.checksum = hash.hexdigest ()[:10]
1111 return self.checksum
1113 def basename (self):
1114 cs = self.get_checksum ()
1115 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1118 def write_ly (self):
1119 base = self.basename ()
1120 path = os.path.join (global_options.lily_output_dir, base)
1121 directory = os.path.split(path)[0]
1122 if not os.path.isdir (directory):
1123 os.makedirs (directory)
1124 out = file (path + '.ly', 'w')
1125 out.write (self.full_ly ())
1126 file (path + '.txt', 'w').write ('image of music')
1128 def relevant_contents (self, ly):
1129 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1131 def link_all_output_files (self, output_dir, output_dir_files, destination):
1132 existing, missing = self.all_output_files (output_dir, output_dir_files)
1134 print '\nMissing', missing
1135 raise CompileError(self.basename())
1136 for name in existing:
1138 os.unlink (os.path.join (destination, name))
1142 src = os.path.join (output_dir, name)
1143 dst = os.path.join (destination, name)
1144 dst_path = os.path.split(dst)[0]
1145 if not os.path.isdir (dst_path):
1146 os.makedirs (dst_path)
1150 def all_output_files (self, output_dir, output_dir_files):
1151 """Return all files generated in lily_output_dir, a set.
1153 output_dir_files is the list of files in the output directory.
1157 base = self.basename()
1158 full = os.path.join (output_dir, base)
1159 def consider_file (name):
1160 if name in output_dir_files:
1163 def require_file (name):
1164 if name in output_dir_files:
1169 # UGH - junk global_options
1170 skip_lily = global_options.skip_lilypond_run
1171 for required in [base + '.ly',
1173 require_file (required)
1175 require_file (base + '-systems.count')
1177 map (consider_file, [base + '.tex',
1180 base + '-systems.texi',
1181 base + '-systems.tex',
1182 base + '-systems.pdftexi'])
1184 # UGH - junk global_options
1185 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1186 and not global_options.skip_png_check):
1187 page_count = ps_page_count (full + '.eps')
1189 require_file (base + '.png')
1191 for page in range (1, page_count + 1):
1192 require_file (base + '-page%d.png' % page)
1195 if not skip_lily and not missing:
1196 system_count = int(file (full + '-systems.count').read())
1197 for number in range(1, system_count + 1):
1198 systemfile = '%s-%d' % (base, number)
1199 require_file (systemfile + '.eps')
1200 consider_file (systemfile + '.pdf')
1202 return (result, missing)
1204 def is_outdated (self, output_dir, current_files):
1205 found, missing = self.all_output_files (output_dir, current_files)
1208 def filter_text (self):
1209 """Run snippet bodies through a command (say: convert-ly).
1211 This functionality is rarely used, and this code must have bitrot.
1213 code = self.substring ('code')
1214 s = filter_pipe (code, global_options.filter_cmd)
1217 'options': self.match.group ('options')
1220 return output[self.format][FILTER] % d
1222 def replacement_text (self):
1223 func = LilypondSnippet.__dict__['output_' + self.format]
1226 def get_images (self):
1227 base = self.basename ()
1229 single = '%(base)s.png' % vars ()
1230 multiple = '%(base)s-page1.png' % vars ()
1232 if (os.path.exists (multiple)
1233 and (not os.path.exists (single)
1234 or (os.stat (multiple)[stat.ST_MTIME]
1235 > os.stat (single)[stat.ST_MTIME]))):
1236 count = ps_page_count ('%(base)s.eps' % vars ())
1237 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1238 images = tuple (images)
1242 def output_docbook (self):
1244 base = self.basename ()
1245 for image in self.get_images ():
1246 (base, ext) = os.path.splitext (image)
1247 str += output[DOCBOOK][OUTPUT] % vars ()
1248 str += self.output_print_filename (DOCBOOK)
1249 if (self.substring('inline') == 'inline'):
1250 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1252 str = '<mediaobject>' + str + '</mediaobject>'
1253 if VERBATIM in self.option_dict:
1254 verb = verbatim_html (self.verb_ly ())
1255 str = output[DOCBOOK][VERBATIM] % vars () + str
1258 def output_html (self):
1260 base = self.basename ()
1261 if self.format == HTML:
1262 str += self.output_print_filename (HTML)
1263 if VERBATIM in self.option_dict:
1264 verb = verbatim_html (self.verb_ly ())
1265 str += output[HTML][VERBATIM] % vars ()
1266 if QUOTE in self.option_dict:
1267 str = output[HTML][QUOTE] % vars ()
1269 str += output[HTML][BEFORE] % vars ()
1270 for image in self.get_images ():
1271 (base, ext) = os.path.splitext (image)
1272 alt = self.option_dict[ALT]
1273 str += output[HTML][OUTPUT] % vars ()
1274 str += output[HTML][AFTER] % vars ()
1277 def output_info (self):
1279 for image in self.get_images ():
1280 (base, ext) = os.path.splitext (image)
1282 # URG, makeinfo implicitly prepends dot to extension.
1283 # Specifying no extension is most robust.
1285 alt = self.option_dict[ALT]
1286 info_image_path = os.path.join (global_options.info_images_dir, base)
1287 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1289 base = self.basename ()
1290 str += output[self.format][OUTPUT] % vars ()
1293 def output_latex (self):
1295 base = self.basename ()
1296 if self.format == LATEX:
1297 str += self.output_print_filename (LATEX)
1298 if VERBATIM in self.option_dict:
1299 verb = self.verb_ly ()
1300 str += (output[LATEX][VERBATIM] % vars ())
1302 str += (output[LATEX][OUTPUT] % vars ())
1304 ## todo: maintain breaks
1306 breaks = self.ly ().count ("\n")
1307 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1309 if QUOTE in self.option_dict:
1310 str = output[LATEX][QUOTE] % vars ()
1313 def output_print_filename (self, format):
1315 if PRINTFILENAME in self.option_dict:
1316 base = self.basename ()
1317 filename = os.path.basename (self.substring ('filename'))
1318 str = output[format][PRINTFILENAME] % vars ()
1322 def output_texinfo (self):
1323 str = self.output_print_filename (TEXINFO)
1324 base = self.basename ()
1325 if TEXIDOC in self.option_dict:
1326 texidoc = base + '.texidoc'
1327 translated_texidoc = texidoc + document_language
1328 if os.path.exists (translated_texidoc):
1329 str += '@include %(translated_texidoc)s\n\n' % vars ()
1330 elif os.path.exists (texidoc):
1331 str += '@include %(texidoc)s\n\n' % vars ()
1334 if VERBATIM in self.option_dict:
1336 if ADDVERSION in self.option_dict:
1337 version = output[TEXINFO][ADDVERSION]
1338 verb = self.verb_ly ()
1339 substr = output[TEXINFO][VERBATIM] % vars ()
1340 substr += self.output_info ()
1341 if LILYQUOTE in self.option_dict:
1342 substr = output[TEXINFO][QUOTE] % {'str':substr}
1345 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1346 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1347 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1349 if QUOTE in self.option_dict:
1350 str = output[TEXINFO][QUOTE] % vars ()
1352 # need par after image
1357 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1358 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1360 class LilypondFileSnippet (LilypondSnippet):
1361 def __init__ (self, type, match, format, line_number):
1362 LilypondSnippet.__init__ (self, type, match, format, line_number)
1363 self.contents = file (find_file (self.substring ('filename'))).read ()
1367 s = re_begin_verbatim.split (s)[-1]
1368 s = re_end_verbatim.split (s)[0]
1372 name = self.substring ('filename')
1373 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1374 % (name, self.contents))
1377 snippet_type_to_class = {
1378 'lilypond_file': LilypondFileSnippet,
1379 'lilypond_block': LilypondSnippet,
1380 'lilypond': LilypondSnippet,
1381 'include': IncludeSnippet,
1384 def find_linestarts (s):
1389 i = s.find ('\n', start)
1397 nls.append (len (s))
1400 def find_toplevel_snippets (input_string, format, types):
1403 res[t] = re.compile (snippet_res[format][t])
1407 found = dict ([(t, None) for t in types])
1409 line_starts = find_linestarts (input_string)
1411 # We want to search for multiple regexes, without searching
1412 # the string multiple times for one regex.
1413 # Hence, we use earlier results to limit the string portion
1415 # Since every part of the string is traversed at most once for
1416 # every type of snippet, this is linear.
1422 if not found[type] or found[type][0] < index:
1425 m = res[type].search (input_string[index:endex])
1430 if type in snippet_type_to_class:
1431 klass = snippet_type_to_class[type]
1433 start = index + m.start ('match')
1434 line_number = line_start_idx
1435 while (line_starts[line_number] < start):
1439 snip = klass (type, m, format, line_number)
1441 found[type] = (start, snip)
1445 or found[type][0] < found[first][0])):
1450 # Limiting the search space is a cute
1451 # idea, but this *requires* to search
1452 # for possible containing blocks
1453 # first, at least as long as we do not
1454 # search for the start of blocks, but
1455 # always/directly for the entire
1456 # @block ... @end block.
1458 endex = found[first][0]
1461 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1464 while (start > line_starts[line_start_idx+1]):
1467 (start, snip) = found[first]
1468 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1469 snippets.append (snip)
1471 index = start + len (snip.match.group ('match'))
1475 def filter_pipe (input, cmd):
1476 """Pass input through cmd, and return the result."""
1478 if global_options.verbose:
1479 progress (_ ("Opening filter `%s'") % cmd)
1481 (stdin, stdout, stderr) = os.popen3 (cmd)
1483 status = stdin.close ()
1487 output = stdout.read ()
1488 status = stdout.close ()
1489 error = stderr.read ()
1493 signal = 0x0f & status
1494 if status or (not output and error):
1495 exit_status = status >> 8
1496 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1497 error (_ ("The error log is as follows:"))
1498 ly.stderr_write (error)
1499 ly.stderr_write (stderr.read ())
1502 if global_options.verbose:
1507 def system_in_directory (cmd, directory):
1508 """Execute a command in a different directory.
1510 Because of win32 compatibility, we can't simply use subprocess.
1513 current = os.getcwd()
1514 os.chdir (directory)
1515 ly.system(cmd, be_verbose=global_options.verbose,
1520 def process_snippets (cmd, snippets,
1521 format, lily_output_dir):
1522 """Run cmd on all of the .ly files from snippets."""
1527 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1528 cmd += ' --formats=png '
1529 elif format in (DOCBOOK) and '--formats' not in cmd:
1530 cmd += ' --formats=png,pdf '
1532 checksum = snippet_list_checksum (snippets)
1533 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1534 + [snip.basename() + '.ly' for snip in snippets])
1535 name = os.path.join (lily_output_dir,
1536 'snippet-names-%d.ly' % checksum)
1537 file (name, 'wb').write (contents)
1539 system_in_directory (' '.join ([cmd, name]),
1544 # Retrieve dimensions from LaTeX
1545 LATEX_INSPECTION_DOCUMENT = r'''
1549 \typeout{textwidth=\the\textwidth}
1550 \typeout{columnsep=\the\columnsep}
1551 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1555 # Do we need anything else besides `textwidth'?
1556 def get_latex_textwidth (source):
1557 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1559 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1561 ## what's a sensible default?
1564 preamble = source[:m.start (0)]
1565 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1567 (handle, tmpfile) = tempfile.mkstemp('.tex')
1568 logfile = os.path.splitext (tmpfile)[0] + '.log'
1569 logfile = os.path.split (logfile)[1]
1571 tmp_handle = os.fdopen (handle,'w')
1572 tmp_handle.write (latex_document)
1575 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1576 parameter_string = file (logfile).read()
1582 m = re.search ('columns=([0-9.]*)', parameter_string)
1584 columns = int (m.group (1))
1587 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1589 columnsep = float (m.group (1))
1592 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1594 textwidth = float (m.group (1))
1596 textwidth = (textwidth - columnsep) / columns
1600 def modify_preamble (chunk):
1601 str = chunk.replacement_text ()
1602 if (re.search (r"\\begin *{document}", str)
1603 and not re.search ("{graphic[sx]", str)):
1604 str = re.sub (r"\\begin{document}",
1605 r"\\usepackage{graphics}" + '\n'
1606 + r"\\begin{document}",
1608 chunk.override_text = str
1613 # TEXINFO: '.texinfo',
1619 class CompileError(Exception):
1622 def snippet_list_checksum (snippets):
1623 return hash (' '.join([l.basename() for l in snippets]))
1625 def write_file_map (lys, name):
1626 snippet_map = file (os.path.join (
1627 global_options.lily_output_dir,
1628 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1630 snippet_map.write ("""
1631 #(define version-seen #t)
1632 #(define output-empty-score-list #f)
1633 #(ly:add-file-name-alist '(%s
1635 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1638 def split_output_files(directory):
1639 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1641 Return value is a set of strings.
1644 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1645 base_subdir = os.path.split (subdir)[1]
1646 sub_files = [os.path.join (base_subdir, name)
1647 for name in os.listdir (subdir)]
1651 def do_process_cmd (chunks, input_name, options):
1652 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1654 output_files = split_output_files (options.lily_output_dir)
1655 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1657 write_file_map (outdated, input_name)
1658 progress (_ ("Writing snippets..."))
1659 for snippet in outdated:
1664 progress (_ ("Processing..."))
1666 process_snippets (options.process_cmd, outdated,
1667 options.format, options.lily_output_dir)
1670 progress (_ ("All snippets are up to date..."))
1672 if options.lily_output_dir != options.output_dir:
1673 output_files = split_output_files (options.lily_output_dir)
1674 for snippet in snippets:
1675 snippet.link_all_output_files (options.lily_output_dir,
1683 # Format guessing data
1692 '.texinfo': TEXINFO,
1697 def guess_format (input_filename):
1699 e = os.path.splitext (input_filename)[1]
1702 format = ext2format[e]
1704 error (_ ("cannot determine format for: %s"
1709 def write_if_updated (file_name, lines):
1711 f = file (file_name)
1713 new_str = ''.join (lines)
1714 if oldstr == new_str:
1715 progress (_ ("%s is up to date.") % file_name)
1718 # this prevents make from always rerunning lilypond-book:
1719 # output file must be touched in order to be up to date
1720 os.utime (file_name, None)
1724 progress (_ ("Writing `%s'...") % file_name)
1725 file (file_name, 'w').writelines (lines)
1729 def note_input_file (name, inputs=[]):
1730 ## hack: inputs is mutable!
1731 inputs.append (name)
1734 def samefile (f1, f2):
1736 return os.path.samefile (f1, f2)
1737 except AttributeError: # Windoze
1738 f1 = re.sub ("//*", "/", f1)
1739 f2 = re.sub ("//*", "/", f2)
1742 def do_file (input_filename):
1744 if not input_filename or input_filename == '-':
1745 in_handle = sys.stdin
1746 input_fullname = '<stdin>'
1748 if os.path.exists (input_filename):
1749 input_fullname = input_filename
1750 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1751 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1753 input_fullname = find_file (input_filename)
1755 note_input_file (input_fullname)
1756 in_handle = file (input_fullname)
1758 if input_filename == '-':
1759 input_base = 'stdin'
1761 input_base = os.path.basename (
1762 os.path.splitext (input_filename)[0])
1764 # don't complain when global_options.output_dir is existing
1765 if not global_options.output_dir:
1766 global_options.output_dir = os.getcwd()
1768 global_options.output_dir = os.path.abspath(global_options.output_dir)
1770 if not os.path.isdir (global_options.output_dir):
1771 os.mkdir (global_options.output_dir, 0777)
1772 os.chdir (global_options.output_dir)
1774 output_filename = os.path.join(global_options.output_dir,
1775 input_base + format2ext[global_options.format])
1776 if (os.path.exists (input_filename)
1777 and os.path.exists (output_filename)
1778 and samefile (output_filename, input_fullname)):
1780 _ ("Output would overwrite input file; use --output."))
1784 progress (_ ("Reading %s...") % input_fullname)
1785 source = in_handle.read ()
1788 set_default_options (source, default_ly_options, global_options.format)
1791 # FIXME: Containing blocks must be first, see
1792 # find_toplevel_snippets.
1794 'multiline_comment',
1798 'singleline_comment',
1803 progress (_ ("Dissecting..."))
1804 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1806 if global_options.format == LATEX:
1808 if (c.is_plain () and
1809 re.search (r"\\begin *{document}", c.replacement_text())):
1814 if global_options.filter_cmd:
1815 write_if_updated (output_filename,
1816 [c.filter_text () for c in chunks])
1817 elif global_options.process_cmd:
1818 do_process_cmd (chunks, input_fullname, global_options)
1819 progress (_ ("Compiling %s...") % output_filename)
1821 write_if_updated (output_filename,
1822 [s.replacement_text ()
1825 def process_include (snippet):
1826 os.chdir (original_dir)
1827 name = snippet.substring ('filename')
1828 progress (_ ("Processing include: %s") % name)
1830 return do_file (name)
1832 include_chunks = map (process_include,
1833 filter (lambda x: isinstance (x, IncludeSnippet),
1836 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1838 except CompileError:
1839 os.chdir (original_dir)
1840 progress (_ ("Removing `%s'") % output_filename)
1845 global global_options
1847 opt_parser = get_option_parser()
1848 (global_options, args) = opt_parser.parse_args ()
1849 if global_options.format in ('texi-html', 'texi'):
1850 global_options.format = TEXINFO
1852 global_options.include_path = map (os.path.abspath, global_options.include_path)
1854 if global_options.warranty:
1857 if not args or len (args) > 1:
1858 opt_parser.print_help ()
1864 # FIXME: 85 lines of `main' macramee??
1865 files = do_options ()
1867 basename = os.path.splitext (files[0])[0]
1868 basename = os.path.split (basename)[1]
1870 if not global_options.format:
1871 global_options.format = guess_format (files[0])
1874 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1877 if global_options.process_cmd == '':
1878 global_options.process_cmd = (lilypond_binary
1879 + ' --formats=%s -dbackend=eps ' % formats)
1881 if global_options.process_cmd:
1882 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1883 for p in global_options.include_path])
1885 if global_options.format in (TEXINFO, LATEX):
1886 ## prevent PDF from being switched on by default.
1887 global_options.process_cmd += ' --formats=eps '
1888 if global_options.create_pdf:
1889 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1891 if global_options.verbose:
1892 global_options.process_cmd += " --verbose "
1894 if global_options.padding_mm:
1895 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1897 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
1899 if global_options.lily_output_dir:
1900 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1901 if not os.path.isdir (global_options.lily_output_dir):
1902 os.makedirs (global_options.lily_output_dir)
1904 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1909 chunks = do_file (files[0])
1910 except CompileError:
1913 inputs = note_input_file ('')
1916 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1917 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1918 final_output_file = os.path.join (global_options.output_dir,
1920 + '.%s' % global_options.format)
1922 os.chdir (original_dir)
1923 file (dep_file, 'w').write ('%s: %s'
1924 % (final_output_file, ' '.join (inputs)))
1926 if __name__ == '__main__':