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
48 program_version = '@TOPLEVEL_VERSION@'
49 program_name = os.path.basename (sys.argv[0])
51 original_dir = os.getcwd ()
55 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
59 lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
60 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" %(BOOK)s
61 lilypond-book --process='lilypond -I include' %(BOOK)s
62 ''' % {'BOOK': _ ("BOOK")})
64 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
65 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
67 ################################################################
69 if global_options.verbose:
70 raise Exception (_ ('Exiting (%d)...') % i)
75 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
77 progress = ly.progress
80 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
83 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
85 def ps_page_count (ps_name):
86 header = file (ps_name).read (1024)
87 m = re.search ('\n%%Pages: ([0-9]+)', header)
89 return int (m.group (1))
94 ly.encoded_write (sys.stdout, '''
101 ''' % ( _ ('Copyright (c) %s by') % '2001--2007',
103 _ ("Distributed under terms of the GNU General Public License."),
104 _ ("It comes with NO WARRANTY.")))
106 def get_option_parser ():
107 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
108 description=help_summary,
109 add_help_option=False)
111 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
114 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
117 p.add_option ('-f', '--format',
118 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
121 p.add_option("-h", "--help",
123 help=_ ("show this help and exit"))
125 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
127 action='append', dest='include_path',
128 default=[os.path.abspath (os.getcwd ())])
130 p.add_option ('--info-images-dir',
131 help=_ ("format Texinfo output so that Info will "
132 "look for images of music in DIR"),
134 action='store', dest='info_images_dir',
137 p.add_option ('--left-padding',
140 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
144 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
146 action='store', dest='output_dir',
149 p.add_option ('--skip-lily-check',
150 help=_ ("do not fail if no lilypond output is found."),
152 action='store_true', dest='skip_lilypond_run',
155 p.add_option ('--skip-png-check',
156 help=_ ("do not fail if no PNG images are found for EPS files"),
158 action='store_true', dest='skip_png_check',
161 p.add_option ('--lily-output-dir',
162 help=_ ("write lily-XXX files to DIR, link into --output dir."),
164 action='store', dest='lily_output_dir',
167 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
168 help = _ ("process ly_files using COMMAND FILE..."),
170 dest='process_cmd', default='')
172 p.add_option ('--pdf',
175 help=_ ("create PDF files for use with PDFTeX"),
178 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
179 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
180 must use this with dvips -h INPUT.psfonts'''),
183 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
188 p.version = "@TOPLEVEL_VERSION@"
189 p.add_option("--version",
191 help=_ ("show version number and exit"))
193 p.add_option ('-w', '--warranty',
194 help=_ ("show warranty and copyright"),
196 p.add_option_group (ly.display_encode (_ ('Bugs')),
198 _ ("Report bugs via")
199 + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
202 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
204 # Only use installed binary when we are installed too.
205 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
206 lilypond_binary = 'lilypond'
208 global_options = None
211 default_ly_options = { 'alt': "[image of music]" }
214 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
216 ADDVERSION = 'addversion'
220 EXAMPLEINDENT = 'exampleindent'
222 FRAGMENT = 'fragment'
228 LINE_WIDTH = 'line-width'
229 LILYQUOTE = 'lilyquote'
230 NOFRAGMENT = 'nofragment'
231 NOINDENT = 'noindent'
236 OUTPUTIMAGE = 'outputimage'
239 PREAMBLE = 'preamble'
240 PRINTFILENAME = 'printfilename'
242 RAGGED_RIGHT = 'ragged-right'
243 RELATIVE = 'relative'
244 STAFFSIZE = 'staffsize'
247 VERBATIM = 'verbatim'
248 FONTLOAD = 'fontload'
249 FILENAME = 'filename'
253 # NOTIME has no opposite so it isn't part of this dictionary.
254 # NOQUOTE is used internally only.
256 NOFRAGMENT: FRAGMENT,
261 # Recognize special sequences in the input.
263 # (?P<name>regex) -- Assign result of REGEX to NAME.
264 # *? -- Match non-greedily.
265 # (?m) -- Multiline regex: Make ^ and $ match at each line.
266 # (?s) -- Make the dot match all characters including newline.
267 # (?x) -- Ignore whitespace in patterns.
278 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
283 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
288 <(?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>)''',
294 (?P<code><!--\s.*?!-->)
297 'singleline_comment':
316 (\s*(?P<options>.*?)\s*:)?\s*
324 \s*(?P<options>.*?)\s*
333 \s*(?P<options>.*?)\s*
335 \s*(?P<filename>.*?)\s*
342 (?P<code><!--\s.*?!-->)
345 'singleline_comment':
351 (?P<code><pre>.*?</pre>))''',
357 (?P<code><pre>\s.*?</pre>\s))''',
376 \s*(?P<options>.*?)\s*
387 \s*(?P<options>.*?)\s*
391 \\end\s*{lilypond})''',
399 \s*(?P<options>.*?)\s*
407 'singleline_comment':
430 \\end\s*{verbatim}))''',
439 (?P<filename>\S+))''',
443 ^[^\n]*?(?!@c\s+)[^\n]*?
447 \s*(?P<options>.*?)\s*
457 \s*(?P<options>.*?)\s*
460 ^@end\s+lilypond)\s''',
467 \s*(?P<options>.*?)\s*
478 @end\s+ignore))\s''',
480 'singleline_comment':
485 @c([ \t][^\n]*|)\n))''',
487 # Don't do this: It interferes with @code{@{}.
488 # 'verb': r'''(?P<code>@code{.*?})''',
496 @end\s+example\s))''',
505 'intertext': r',?\s*intertext=\".*?\"',
509 'intertext': r',?\s*intertext=\".*?\"',
514 'intertext': r',?\s*intertext=\".*?\"',
515 'option_sep': '\s*,\s*',
519 'intertext': r',?\s*intertext=\".*?\"',
520 'option_sep': '\s*,\s*',
524 # Options without a pattern in ly_options.
543 RELATIVE: r'''\relative c%(relative_quotes)s''',
548 INDENT: r'''indent = %(indent)s''',
550 LINE_WIDTH: r'''line-width = %(line-width)s''',
552 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
554 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
556 RAGGED_RIGHT: r'''ragged-right = ##t''',
558 PACKED: r'''packed = ##t''',
570 \remove Time_signature_engraver
576 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
583 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
586 <imageobject role="latex">
587 <imagedata fileref="%(base)s.pdf" format="PDF"/>
589 <imageobject role="html">
590 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
592 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
594 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
598 FILTER: r'''<lilypond %(options)s>
608 <a href="%(base)s.ly">''',
612 border="0" src="%(image)s" alt="%(alt)s">''',
614 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
616 QUOTE: r'''<blockquote>
629 \ifx\preLilyPondExample \undefined%%
632 \preLilyPondExample%%
634 \def\lilypondbook{}%%
635 \input %(base)s-systems.tex%%
636 \ifx\postLilyPondExample \undefined%%
639 \postLilyPondExample%%
643 PRINTFILENAME: '''\\texttt{%(filename)s}
646 QUOTE: r'''\begin{quotation}%(str)s
649 VERBATIM: r'''\noindent
650 \begin{verbatim}%(verb)s\end{verbatim}''',
652 FILTER: r'''\begin{lilypond}[%(options)s]
659 FILTER: r'''@lilypond[%(options)s]
665 @include %(base)s-systems.texi
669 OUTPUTIMAGE: r'''@noindent
671 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
675 <a href="%(base)s.ly">
677 border="0" src="%(image)s" alt="%(alt)s">
685 <a href="%(base)s.ly">
693 QUOTE: r'''@quotation
694 %(str)s@end quotation
701 VERBATIM: r'''@exampleindent 0
703 %(verb)s@end verbatim
706 ADDVERSION: r'''@example
707 \version @w{"@version{}"}
714 # Maintain line numbers.
719 for f in [HTML, LATEX]:
720 for s in (QUOTE, VERBATIM):
721 output[f][s] = output[f][s].replace("\n"," ")
724 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
725 %%%% Options: [%(option_string)s]
726 \\include "lilypond-book-preamble.ly"
729 %% ****************************************************************
730 %% Start cut-&-pastable-section
731 %% ****************************************************************
736 #(define dump-extents #t)
737 %(font_dump_setting)s
739 force-assignment = #""
740 line-width = #(- line-width (* mm %(padding_mm)f))
753 %% ****************************************************************
754 %% ly snippet contents follows:
755 %% ****************************************************************
759 %% ****************************************************************
761 %% ****************************************************************
768 %% ****************************************************************
770 %% ****************************************************************
774 %% ****************************************************************
776 %% ****************************************************************
779 texinfo_line_widths = {
780 '@afourpaper': '160\\mm',
781 '@afourwide': '6.5\\in',
782 '@afourlatex': '150\\mm',
783 '@smallbook': '5\\in',
784 '@letterpaper': '6\\in',
787 def classic_lilypond_book_compatibility (key, value):
788 if key == 'singleline' and value == None:
789 return (RAGGED_RIGHT, None)
791 m = re.search ('relative\s*([-0-9])', key)
793 return ('relative', m.group (1))
795 m = re.match ('([0-9]+)pt', key)
797 return ('staffsize', m.group (1))
799 if key == 'indent' or key == 'line-width':
800 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
802 f = float (m.group (1))
803 return (key, '%f\\%s' % (f, m.group (2)))
807 def find_file (name, raise_error=True):
808 for i in global_options.include_path:
809 full = os.path.join (i, name)
810 if os.path.exists (full):
814 error (_ ("file not found: %s") % name + '\n')
818 def verbatim_html (s):
819 return re.sub ('>', '>',
821 re.sub ('&', '&', s)))
824 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
825 def set_default_options (source, default_ly_options, format):
826 if LINE_WIDTH not in default_ly_options:
828 textwidth = get_latex_textwidth (source)
829 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
830 elif format == TEXINFO:
831 m = texinfo_lang_re.search (source)
832 if m and not m.group (1).startswith ('en'):
833 default_ly_options[LANG] = m.group (1)
835 default_ly_options[LANG] = ''
836 for regex in texinfo_line_widths:
837 # FIXME: @layout is usually not in
840 # \input texinfo @c -*-texinfo-*-
842 # Bluntly search first K items of
844 # s = chunks[0].replacement_text ()
845 if re.search (regex, source[:1024]):
846 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
850 def replacement_text (self):
853 def filter_text (self):
854 return self.replacement_text ()
859 class Substring (Chunk):
860 """A string that does not require extra memory."""
861 def __init__ (self, source, start, end, line_number):
865 self.line_number = line_number
866 self.override_text = None
871 def replacement_text (self):
872 if self.override_text:
873 return self.override_text
875 return self.source[self.start:self.end]
877 class Snippet (Chunk):
878 def __init__ (self, type, match, format, line_number):
882 self.option_dict = {}
884 self.line_number = line_number
886 def replacement_text (self):
887 return self.match.group ('match')
889 def substring (self, s):
890 return self.match.group (s)
893 return `self.__class__` + ' type = ' + self.type
895 class IncludeSnippet (Snippet):
896 def processed_filename (self):
897 f = self.substring ('filename')
898 return os.path.splitext (f)[0] + format2ext[self.format]
900 def replacement_text (self):
901 s = self.match.group ('match')
902 f = self.substring ('filename')
904 return re.sub (f, self.processed_filename (), s)
906 class LilypondSnippet (Snippet):
907 def __init__ (self, type, match, format, line_number):
908 Snippet.__init__ (self, type, match, format, line_number)
909 os = match.group ('options')
910 self.do_options (os, self.type)
913 return self.substring ('code')
916 contents = self.substring ('code')
917 return ('\\sourcefileline %d\n%s'
918 % (self.line_number - 1, contents))
923 return self.compose_ly (s)
926 def split_options (self, option_string):
928 if self.format == HTML:
929 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
931 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
935 return re.split (format_res[self.format]['option_sep'],
939 def do_options (self, option_string, type):
940 self.option_dict = {}
942 options = self.split_options (option_string)
944 for option in options:
946 (key, value) = re.split ('\s*=\s*', option)
947 self.option_dict[key] = value
949 if option in no_options:
950 if no_options[option] in self.option_dict:
951 del self.option_dict[no_options[option]]
953 self.option_dict[option] = None
955 has_line_width = self.option_dict.has_key (LINE_WIDTH)
956 no_line_width_value = 0
958 # If LINE_WIDTH is used without parameter, set it to default.
959 if has_line_width and self.option_dict[LINE_WIDTH] == None:
960 no_line_width_value = 1
961 del self.option_dict[LINE_WIDTH]
963 for k in default_ly_options:
964 if k not in self.option_dict:
965 self.option_dict[k] = default_ly_options[k]
967 if not has_line_width:
968 if type == 'lilypond' or FRAGMENT in self.option_dict:
969 self.option_dict[RAGGED_RIGHT] = None
971 if type == 'lilypond':
972 if LINE_WIDTH in self.option_dict:
973 del self.option_dict[LINE_WIDTH]
975 if RAGGED_RIGHT in self.option_dict:
976 if LINE_WIDTH in self.option_dict:
977 del self.option_dict[LINE_WIDTH]
979 if QUOTE in self.option_dict or type == 'lilypond':
980 if LINE_WIDTH in self.option_dict:
981 del self.option_dict[LINE_WIDTH]
983 if not INDENT in self.option_dict:
984 self.option_dict[INDENT] = '0\\mm'
986 # The QUOTE pattern from ly_options only emits the `line-width'
988 if has_line_width and QUOTE in self.option_dict:
989 if no_line_width_value:
990 del self.option_dict[LINE_WIDTH]
992 del self.option_dict[QUOTE]
994 def compose_ly (self, code):
995 if FRAGMENT in self.option_dict:
1003 # The original concept of the `exampleindent' option is broken.
1004 # It is not possible to get a sane value for @exampleindent at all
1005 # without processing the document itself. Saying
1013 # causes ugly results with the DVI backend of texinfo since the
1014 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1015 # value). Executing the above code changes the environment
1016 # indentation to an unknown value because we don't know the amount
1017 # of 1em in advance since it is font-dependent. Modifying
1018 # @exampleindent in the middle of a document is simply not
1019 # supported within texinfo.
1021 # As a consequence, the only function of @exampleindent is now to
1022 # specify the amount of indentation for the `quote' option.
1024 # To set @exampleindent locally to zero, we use the @format
1025 # environment for non-quoted snippets.
1026 override[EXAMPLEINDENT] = r'0.4\in'
1027 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1028 override.update (default_ly_options)
1031 for (key, value) in self.option_dict.items ():
1033 option_list.append (key)
1035 option_list.append (key + '=' + value)
1036 option_string = ','.join (option_list)
1039 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1040 for a in compose_types:
1041 compose_dict[a] = []
1043 for (key, value) in self.option_dict.items ():
1044 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1048 _ ("deprecated ly-option used: %s=%s") % (key, value))
1050 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1053 _ ("deprecated ly-option used: %s") % key)
1055 _ ("compatibility mode translation: %s") % c_key)
1057 (key, value) = (c_key, c_value)
1060 override[key] = value
1062 if not override.has_key (key):
1063 override[key] = None
1066 for type in compose_types:
1067 if ly_options[type].has_key (key):
1068 compose_dict[type].append (ly_options[type][key])
1072 if not found and key not in simple_options:
1073 warning (_ ("ignoring unknown ly option: %s") % key)
1076 if RELATIVE in override and override[RELATIVE]:
1077 relative = int (override[RELATIVE])
1079 relative_quotes = ''
1083 relative_quotes += ',' * (- relative)
1085 relative_quotes += "'" * relative
1087 paper_string = '\n '.join (compose_dict[PAPER]) % override
1088 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1089 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1090 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1091 padding_mm = global_options.padding_mm
1092 font_dump_setting = ''
1093 if FONTLOAD in self.option_dict:
1094 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1096 d = globals().copy()
1098 return (PREAMBLE_LY + body) % d
1100 def get_checksum (self):
1101 if not self.checksum:
1102 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1104 ## let's not create too long names.
1105 self.checksum = hash.hexdigest ()[:10]
1107 return self.checksum
1109 def basename (self):
1110 cs = self.get_checksum ()
1112 # TODO: use xx/xxxxx directory layout.
1113 name = 'lily-%s' % cs[:10]
1116 def write_ly (self):
1117 base = self.basename ()
1118 path = os.path.join (global_options.lily_output_dir, base)
1120 out = file (path + '.ly', 'w')
1121 out.write (self.full_ly ())
1122 file (path + '.txt', 'w').write ('image of music')
1124 def relevant_contents (self, ly):
1125 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1127 def link_all_output_files (self, output_dir, output_dir_files, destination):
1128 existing, missing = self.all_output_files (output_dir, output_dir_files)
1130 print '\nMissing', missing
1131 raise CompileError(self.basename())
1132 for name in existing:
1134 os.unlink (os.path.join (destination, name))
1138 src = os.path.join (output_dir, name)
1139 dst = os.path.join (destination, name)
1143 def all_output_files (self, output_dir, output_dir_files):
1144 """Return all files generated in lily_output_dir, a set.
1146 output_dir_files is the list of files in the output directory.
1150 base = self.basename()
1151 full = os.path.join (output_dir, base)
1152 def consider_file (name):
1153 if name in output_dir_files:
1156 def require_file (name):
1157 if name in output_dir_files:
1162 # UGH - junk global_options
1163 skip_lily = global_options.skip_lilypond_run
1164 for required in [base + '.ly',
1166 require_file (required)
1168 require_file (base + '-systems.count')
1170 map (consider_file, [base + '.tex',
1173 base + '-systems.texi',
1174 base + '-systems.tex',
1175 base + '-systems.pdftexi'])
1177 # UGH - junk global_options
1178 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1179 and not global_options.skip_png_check):
1180 page_count = ps_page_count (full + '.eps')
1182 require_file (base + '.png')
1184 for page in range (1, page_count + 1):
1185 require_file (base + '-page%d.png' % page)
1188 if not skip_lily and not missing:
1189 system_count = int(file (full + '-systems.count').read())
1190 for number in range(1, system_count + 1):
1191 systemfile = '%s-%d' % (base, number)
1192 require_file (systemfile + '.eps')
1193 consider_file (systemfile + '.pdf')
1195 return (result, missing)
1197 def is_outdated (self, output_dir, current_files):
1198 found, missing = self.all_output_files (output_dir, current_files)
1201 def filter_text (self):
1202 """Run snippet bodies through a command (say: convert-ly).
1204 This functionality is rarely used, and this code must have bitrot.
1206 code = self.substring ('code')
1207 s = filter_pipe (code, global_options.filter_cmd)
1210 'options': self.match.group ('options')
1213 return output[self.format][FILTER] % d
1215 def replacement_text (self):
1216 func = LilypondSnippet.__dict__['output_' + self.format]
1219 def get_images (self):
1220 base = self.basename ()
1222 single = '%(base)s.png' % vars ()
1223 multiple = '%(base)s-page1.png' % vars ()
1225 if (os.path.exists (multiple)
1226 and (not os.path.exists (single)
1227 or (os.stat (multiple)[stat.ST_MTIME]
1228 > os.stat (single)[stat.ST_MTIME]))):
1229 count = ps_page_count ('%(base)s.eps' % vars ())
1230 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1231 images = tuple (images)
1235 def output_docbook (self):
1237 base = self.basename ()
1238 for image in self.get_images ():
1239 (base, ext) = os.path.splitext (image)
1240 str += output[DOCBOOK][OUTPUT] % vars ()
1241 str += self.output_print_filename (DOCBOOK)
1242 if (self.substring('inline') == 'inline'):
1243 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1245 str = '<mediaobject>' + str + '</mediaobject>'
1246 if VERBATIM in self.option_dict:
1247 verb = verbatim_html (self.verb_ly ())
1248 str = output[DOCBOOK][VERBATIM] % vars () + str
1251 def output_html (self):
1253 base = self.basename ()
1254 if self.format == HTML:
1255 str += self.output_print_filename (HTML)
1256 if VERBATIM in self.option_dict:
1257 verb = verbatim_html (self.verb_ly ())
1258 str += output[HTML][VERBATIM] % vars ()
1259 if QUOTE in self.option_dict:
1260 str = output[HTML][QUOTE] % vars ()
1262 str += output[HTML][BEFORE] % vars ()
1263 for image in self.get_images ():
1264 (base, ext) = os.path.splitext (image)
1265 alt = self.option_dict[ALT]
1266 str += output[HTML][OUTPUT] % vars ()
1267 str += output[HTML][AFTER] % vars ()
1270 def output_info (self):
1272 for image in self.get_images ():
1273 (base, ext) = os.path.splitext (image)
1275 # URG, makeinfo implicitly prepends dot to extension.
1276 # Specifying no extension is most robust.
1278 alt = self.option_dict[ALT]
1279 info_image_path = os.path.join (global_options.info_images_dir, base)
1280 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1282 base = self.basename ()
1283 str += output[self.format][OUTPUT] % vars ()
1286 def output_latex (self):
1288 base = self.basename ()
1289 if self.format == LATEX:
1290 str += self.output_print_filename (LATEX)
1291 if VERBATIM in self.option_dict:
1292 verb = self.verb_ly ()
1293 str += (output[LATEX][VERBATIM] % vars ())
1295 str += (output[LATEX][OUTPUT] % vars ())
1297 ## todo: maintain breaks
1299 breaks = self.ly ().count ("\n")
1300 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1302 if QUOTE in self.option_dict:
1303 str = output[LATEX][QUOTE] % vars ()
1306 def output_print_filename (self, format):
1308 if PRINTFILENAME in self.option_dict:
1309 base = self.basename ()
1310 filename = os.path.basename (self.substring ('filename'))
1311 str = output[format][PRINTFILENAME] % vars ()
1315 def output_texinfo (self):
1316 str = self.output_print_filename (TEXINFO)
1317 base = self.basename ()
1318 if TEXIDOC in self.option_dict:
1319 texidoc = base + '.texidoc'
1320 translated_texidoc = texidoc + default_ly_options[LANG]
1321 if os.path.exists (translated_texidoc):
1322 str += '@include %(translated_texidoc)s\n\n' % vars ()
1323 elif os.path.exists (texidoc):
1324 str += '@include %(texidoc)s\n\n' % vars ()
1327 if VERBATIM in self.option_dict:
1329 if ADDVERSION in self.option_dict:
1330 version = output[TEXINFO][ADDVERSION]
1331 verb = self.verb_ly ()
1332 substr = output[TEXINFO][VERBATIM] % vars ()
1333 substr += self.output_info ()
1334 if LILYQUOTE in self.option_dict:
1335 substr = output[TEXINFO][QUOTE] % {'str':substr}
1338 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1339 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1340 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1342 if QUOTE in self.option_dict:
1343 str = output[TEXINFO][QUOTE] % vars ()
1345 # need par after image
1350 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1351 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1353 class LilypondFileSnippet (LilypondSnippet):
1354 def __init__ (self, type, match, format, line_number):
1355 LilypondSnippet.__init__ (self, type, match, format, line_number)
1356 self.contents = file (find_file (self.substring ('filename'))).read ()
1360 s = re_begin_verbatim.split (s)[-1]
1361 s = re_end_verbatim.split (s)[0]
1365 name = self.substring ('filename')
1366 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1367 % (name, self.contents))
1370 snippet_type_to_class = {
1371 'lilypond_file': LilypondFileSnippet,
1372 'lilypond_block': LilypondSnippet,
1373 'lilypond': LilypondSnippet,
1374 'include': IncludeSnippet,
1377 def find_linestarts (s):
1382 i = s.find ('\n', start)
1390 nls.append (len (s))
1393 def find_toplevel_snippets (input_string, format, types):
1396 res[t] = re.compile (snippet_res[format][t])
1400 found = dict ([(t, None) for t in types])
1402 line_starts = find_linestarts (input_string)
1404 # We want to search for multiple regexes, without searching
1405 # the string multiple times for one regex.
1406 # Hence, we use earlier results to limit the string portion
1408 # Since every part of the string is traversed at most once for
1409 # every type of snippet, this is linear.
1415 if not found[type] or found[type][0] < index:
1418 m = res[type].search (input_string[index:endex])
1423 if type in snippet_type_to_class:
1424 klass = snippet_type_to_class[type]
1426 start = index + m.start ('match')
1427 line_number = line_start_idx
1428 while (line_starts[line_number] < start):
1432 snip = klass (type, m, format, line_number)
1434 found[type] = (start, snip)
1438 or found[type][0] < found[first][0])):
1443 # Limiting the search space is a cute
1444 # idea, but this *requires* to search
1445 # for possible containing blocks
1446 # first, at least as long as we do not
1447 # search for the start of blocks, but
1448 # always/directly for the entire
1449 # @block ... @end block.
1451 endex = found[first][0]
1454 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1457 while (start > line_starts[line_start_idx+1]):
1460 (start, snip) = found[first]
1461 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1462 snippets.append (snip)
1464 index = start + len (snip.match.group ('match'))
1468 def filter_pipe (input, cmd):
1469 """Pass input through cmd, and return the result."""
1471 if global_options.verbose:
1472 progress (_ ("Opening filter `%s'") % cmd)
1474 (stdin, stdout, stderr) = os.popen3 (cmd)
1476 status = stdin.close ()
1480 output = stdout.read ()
1481 status = stdout.close ()
1482 error = stderr.read ()
1486 signal = 0x0f & status
1487 if status or (not output and error):
1488 exit_status = status >> 8
1489 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1490 error (_ ("The error log is as follows:"))
1491 ly.stderr_write (error)
1492 ly.stderr_write (stderr.read ())
1495 if global_options.verbose:
1500 def system_in_directory (cmd, directory):
1501 """Execute a command in a different directory.
1503 Because of win32 compatibility, we can't simply use subprocess.
1506 current = os.getcwd()
1507 os.chdir (directory)
1508 ly.system(cmd, be_verbose=global_options.verbose,
1513 def process_snippets (cmd, snippets,
1514 format, lily_output_dir):
1515 """Run cmd on all of the .ly files from snippets."""
1520 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1521 cmd += ' --formats=png '
1522 elif format in (DOCBOOK) and '--formats' not in cmd:
1523 cmd += ' --formats=png,pdf '
1525 checksum = snippet_list_checksum (snippets)
1526 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1527 + [snip.basename() for snip in snippets])
1528 name = os.path.join (lily_output_dir,
1529 'snippet-names-%d' % checksum)
1530 file (name, 'wb').write (contents)
1532 system_in_directory (' '.join ([cmd, name]),
1537 # Retrieve dimensions from LaTeX
1538 LATEX_INSPECTION_DOCUMENT = r'''
1542 \typeout{textwidth=\the\textwidth}
1543 \typeout{columnsep=\the\columnsep}
1544 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1548 # Do we need anything else besides `textwidth'?
1549 def get_latex_textwidth (source):
1550 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1552 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1554 ## what's a sensible default?
1557 preamble = source[:m.start (0)]
1558 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1560 (handle, tmpfile) = tempfile.mkstemp('.tex')
1561 logfile = os.path.splitext (tmpfile)[0] + '.log'
1562 logfile = os.path.split (logfile)[1]
1564 tmp_handle = os.fdopen (handle,'w')
1565 tmp_handle.write (latex_document)
1568 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1569 parameter_string = file (logfile).read()
1575 m = re.search ('columns=([0-9.]*)', parameter_string)
1577 columns = int (m.group (1))
1580 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1582 columnsep = float (m.group (1))
1585 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1587 textwidth = float (m.group (1))
1589 textwidth = (textwidth - columnsep) / columns
1593 def modify_preamble (chunk):
1594 str = chunk.replacement_text ()
1595 if (re.search (r"\\begin *{document}", str)
1596 and not re.search ("{graphic[sx]", str)):
1597 str = re.sub (r"\\begin{document}",
1598 r"\\usepackage{graphics}" + '\n'
1599 + r"\\begin{document}",
1601 chunk.override_text = str
1606 # TEXINFO: '.texinfo',
1612 class CompileError(Exception):
1615 def snippet_list_checksum (snippets):
1616 return hash (' '.join([l.basename() for l in snippets]))
1618 def write_file_map (lys, name):
1619 snippet_map = file (os.path.join (
1620 global_options.lily_output_dir,
1621 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1623 snippet_map.write ("""
1624 #(define version-seen #t)
1625 #(define output-empty-score-list #f)
1626 #(ly:add-file-name-alist '(%s
1628 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1631 def do_process_cmd (chunks, input_name, options):
1632 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1635 output_files = set(os.listdir(options.lily_output_dir))
1636 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1638 write_file_map (outdated, input_name)
1639 progress (_ ("Writing snippets..."))
1640 for snippet in outdated:
1645 progress (_ ("Processing..."))
1647 process_snippets (options.process_cmd, outdated,
1648 options.format, options.lily_output_dir)
1651 progress (_ ("All snippets are up to date..."))
1653 if options.lily_output_dir != options.output_dir:
1654 output_files = set(os.listdir(options.lily_output_dir))
1655 for snippet in snippets:
1656 snippet.link_all_output_files (options.lily_output_dir,
1664 # Format guessing data
1673 '.texinfo': TEXINFO,
1678 def guess_format (input_filename):
1680 e = os.path.splitext (input_filename)[1]
1683 format = ext2format[e]
1685 error (_ ("cannot determine format for: %s"
1690 def write_if_updated (file_name, lines):
1692 f = file (file_name)
1694 new_str = ''.join (lines)
1695 if oldstr == new_str:
1696 progress (_ ("%s is up to date.") % file_name)
1699 # this prevents make from always rerunning lilypond-book:
1700 # output file must be touched in order to be up to date
1701 os.utime (file_name, None)
1705 progress (_ ("Writing `%s'...") % file_name)
1706 file (file_name, 'w').writelines (lines)
1710 def note_input_file (name, inputs=[]):
1711 ## hack: inputs is mutable!
1712 inputs.append (name)
1715 def samefile (f1, f2):
1717 return os.path.samefile (f1, f2)
1718 except AttributeError: # Windoze
1719 f1 = re.sub ("//*", "/", f1)
1720 f2 = re.sub ("//*", "/", f2)
1723 def do_file (input_filename):
1725 if not input_filename or input_filename == '-':
1726 in_handle = sys.stdin
1727 input_fullname = '<stdin>'
1729 if os.path.exists (input_filename):
1730 input_fullname = input_filename
1731 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1732 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1734 input_fullname = find_file (input_filename)
1736 note_input_file (input_fullname)
1737 in_handle = file (input_fullname)
1739 if input_filename == '-':
1740 input_base = 'stdin'
1742 input_base = os.path.basename (
1743 os.path.splitext (input_filename)[0])
1745 # don't complain when global_options.output_dir is existing
1746 if not global_options.output_dir:
1747 global_options.output_dir = os.getcwd()
1749 global_options.output_dir = os.path.abspath(global_options.output_dir)
1751 if not os.path.isdir (global_options.output_dir):
1752 os.mkdir (global_options.output_dir, 0777)
1753 os.chdir (global_options.output_dir)
1755 output_filename = os.path.join(global_options.output_dir,
1756 input_base + format2ext[global_options.format])
1757 if (os.path.exists (input_filename)
1758 and os.path.exists (output_filename)
1759 and samefile (output_filename, input_fullname)):
1761 _ ("Output would overwrite input file; use --output."))
1765 progress (_ ("Reading %s...") % input_fullname)
1766 source = in_handle.read ()
1769 set_default_options (source, default_ly_options, global_options.format)
1772 # FIXME: Containing blocks must be first, see
1773 # find_toplevel_snippets.
1775 'multiline_comment',
1779 'singleline_comment',
1784 progress (_ ("Dissecting..."))
1785 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1787 if global_options.format == LATEX:
1789 if (c.is_plain () and
1790 re.search (r"\\begin *{document}", c.replacement_text())):
1795 if global_options.filter_cmd:
1796 write_if_updated (output_filename,
1797 [c.filter_text () for c in chunks])
1798 elif global_options.process_cmd:
1799 do_process_cmd (chunks, input_fullname, global_options)
1800 progress (_ ("Compiling %s...") % output_filename)
1802 write_if_updated (output_filename,
1803 [s.replacement_text ()
1806 def process_include (snippet):
1807 os.chdir (original_dir)
1808 name = snippet.substring ('filename')
1809 progress (_ ("Processing include: %s") % name)
1811 return do_file (name)
1813 include_chunks = map (process_include,
1814 filter (lambda x: isinstance (x, IncludeSnippet),
1817 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1819 except CompileError:
1820 os.chdir (original_dir)
1821 progress (_ ("Removing `%s'") % output_filename)
1826 global global_options
1828 opt_parser = get_option_parser()
1829 (global_options, args) = opt_parser.parse_args ()
1830 if global_options.format in ('texi-html', 'texi'):
1831 global_options.format = TEXINFO
1833 global_options.include_path = map (os.path.abspath, global_options.include_path)
1835 if global_options.warranty:
1838 if not args or len (args) > 1:
1839 opt_parser.print_help ()
1845 # FIXME: 85 lines of `main' macramee??
1846 files = do_options ()
1848 basename = os.path.splitext (files[0])[0]
1849 basename = os.path.split (basename)[1]
1851 if not global_options.format:
1852 global_options.format = guess_format (files[0])
1855 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1858 if global_options.process_cmd == '':
1859 global_options.process_cmd = (lilypond_binary
1860 + ' --formats=%s -dbackend=eps ' % formats)
1862 if global_options.process_cmd:
1863 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1864 for p in global_options.include_path])
1866 if global_options.format in (TEXINFO, LATEX):
1867 ## prevent PDF from being switched on by default.
1868 global_options.process_cmd += ' --formats=eps '
1869 if global_options.create_pdf:
1870 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1872 if global_options.verbose:
1873 global_options.process_cmd += " --verbose "
1875 if global_options.padding_mm:
1876 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1878 global_options.process_cmd += " -dread-file-list "
1880 if global_options.lily_output_dir:
1881 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1882 if not os.path.isdir (global_options.lily_output_dir):
1883 os.makedirs (global_options.lily_output_dir)
1885 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1890 chunks = do_file (files[0])
1891 except CompileError:
1894 inputs = note_input_file ('')
1897 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1898 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1899 final_output_file = os.path.join (global_options.output_dir,
1901 + '.%s' % global_options.format)
1903 os.chdir (original_dir)
1904 file (dep_file, 'w').write ('%s: %s'
1905 % (final_output_file, ' '.join (inputs)))
1907 if __name__ == '__main__':