7 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
10 lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
12 classic lilypond-book:
13 lilypond-book --process="lilypond" BOOK.tely
17 * this script is too complex. Modularize.
19 * ly-options: intertext?
21 * eps in latex / eps by lilypond -b ps?
22 * check latex parameters, twocolumn, multicolumn?
23 * use --png --ps --pdf for making images?
25 * Converting from lilypond-book source, substitute:
26 @mbinclude foo.itely -> @include foo.itely
49 program_version = '@TOPLEVEL_VERSION@'
50 program_name = os.path.basename (sys.argv[0])
52 original_dir = os.getcwd ()
56 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
60 lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
61 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" %(BOOK)s
62 lilypond-book --process='lilypond -I include' %(BOOK)s
63 ''' % {'BOOK': _ ("BOOK")})
65 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
66 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
68 ################################################################
70 if global_options.verbose:
71 raise Exception (_ ('Exiting (%d)...') % i)
76 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
78 progress = ly.progress
81 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
84 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
86 def ps_page_count (ps_name):
87 header = file (ps_name).read (1024)
88 m = re.search ('\n%%Pages: ([0-9]+)', header)
90 return int (m.group (1))
95 ly.encoded_write (sys.stdout, '''
102 ''' % ( _ ('Copyright (c) %s by') % '2001--2007',
104 _ ("Distributed under terms of the GNU General Public License."),
105 _ ("It comes with NO WARRANTY.")))
107 def get_option_parser ():
108 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
109 description=help_summary,
110 add_help_option=False)
112 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
115 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
118 p.add_option ('-f', '--format',
119 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
122 p.add_option("-h", "--help",
124 help=_ ("show this help and exit"))
126 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
128 action='append', dest='include_path',
129 default=[os.path.abspath (os.getcwd ())])
131 p.add_option ('--info-images-dir',
132 help=_ ("format Texinfo output so that Info will "
133 "look for images of music in DIR"),
135 action='store', dest='info_images_dir',
138 p.add_option ('--left-padding',
141 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
145 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
147 action='store', dest='output_dir',
150 p.add_option ('--lily-output-dir',
151 help=_ ("write lily-XXX files to DIR, link into --output dir."),
153 action='store', dest='lily_output_dir',
156 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
157 help = _ ("process ly_files using COMMAND FILE..."),
159 dest='process_cmd', default='')
161 p.add_option ('--pdf',
164 help=_ ("create PDF files for use with PDFTeX"),
167 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
168 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
169 must use this with dvips -h INPUT.psfonts'''),
172 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
177 p.version = "@TOPLEVEL_VERSION@"
178 p.add_option("--version",
180 help=_ ("show version number and exit"))
182 p.add_option ('-w', '--warranty',
183 help=_ ("show warranty and copyright"),
185 p.add_option_group (ly.display_encode (_ ('Bugs')),
187 _ ("Report bugs via")
188 + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
191 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
193 # Only use installed binary when we are installed too.
194 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
195 lilypond_binary = 'lilypond'
197 global_options = None
200 default_ly_options = { 'alt': "[image of music]" }
203 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
205 ADDVERSION = 'addversion'
209 EXAMPLEINDENT = 'exampleindent'
211 FRAGMENT = 'fragment'
216 LINE_WIDTH = 'line-width'
217 LILYQUOTE = 'lilyquote'
218 NOFRAGMENT = 'nofragment'
219 NOINDENT = 'noindent'
224 OUTPUTIMAGE = 'outputimage'
227 PREAMBLE = 'preamble'
228 PRINTFILENAME = 'printfilename'
230 RAGGED_RIGHT = 'ragged-right'
231 RELATIVE = 'relative'
232 STAFFSIZE = 'staffsize'
235 VERBATIM = 'verbatim'
236 FONTLOAD = 'fontload'
237 FILENAME = 'filename'
241 # NOTIME has no opposite so it isn't part of this dictionary.
242 # NOQUOTE is used internally only.
244 NOFRAGMENT: FRAGMENT,
249 # Recognize special sequences in the input.
251 # (?P<name>regex) -- Assign result of REGEX to NAME.
252 # *? -- Match non-greedily.
253 # (?m) -- Multiline regex: Make ^ and $ match at each line.
254 # (?s) -- Make the dot match all characters including newline.
255 # (?x) -- Ignore whitespace in patterns.
266 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
271 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
276 <(?P<inline>(inline)?)mediaobject>\s*<imageobject.*?>\s*<imagedata\s+fileref="(?P<filename>.*?\.ly)"\s*(role="(?P<options>.*?)")?\s*(/>|>\s*</imagedata>)\s*</imageobject>\s*</(inline)?mediaobject>)''',
282 (?P<code><!--\s.*?!-->)
285 'singleline_comment':
304 (\s*(?P<options>.*?)\s*:)?\s*
312 \s*(?P<options>.*?)\s*
321 \s*(?P<options>.*?)\s*
323 \s*(?P<filename>.*?)\s*
330 (?P<code><!--\s.*?!-->)
333 'singleline_comment':
339 (?P<code><pre>.*?</pre>))''',
345 (?P<code><pre>\s.*?</pre>\s))''',
364 \s*(?P<options>.*?)\s*
375 \s*(?P<options>.*?)\s*
379 \\end\s*{lilypond})''',
387 \s*(?P<options>.*?)\s*
395 'singleline_comment':
418 \\end\s*{verbatim}))''',
427 (?P<filename>\S+))''',
431 ^[^\n]*?(?!@c\s+)[^\n]*?
435 \s*(?P<options>.*?)\s*
445 \s*(?P<options>.*?)\s*
448 ^@end\s+lilypond)\s''',
455 \s*(?P<options>.*?)\s*
466 @end\s+ignore))\s''',
468 'singleline_comment':
473 @c([ \t][^\n]*|)\n))''',
475 # Don't do this: It interferes with @code{@{}.
476 # 'verb': r'''(?P<code>@code{.*?})''',
484 @end\s+example\s))''',
493 'intertext': r',?\s*intertext=\".*?\"',
497 'intertext': r',?\s*intertext=\".*?\"',
502 'intertext': r',?\s*intertext=\".*?\"',
503 'option_sep': '\s*,\s*',
507 'intertext': r',?\s*intertext=\".*?\"',
508 'option_sep': '\s*,\s*',
512 # Options without a pattern in ly_options.
530 RELATIVE: r'''\relative c%(relative_quotes)s''',
535 INDENT: r'''indent = %(indent)s''',
537 LINE_WIDTH: r'''line-width = %(line-width)s''',
539 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
541 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
543 RAGGED_RIGHT: r'''ragged-right = ##t''',
545 PACKED: r'''packed = ##t''',
557 \remove Time_signature_engraver
563 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
570 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
573 <imageobject role="latex">
574 <imagedata fileref="%(base)s.pdf" format="PDF"/>
576 <imageobject role="html">
577 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
579 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
581 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
585 FILTER: r'''<lilypond %(options)s>
595 <a href="%(base)s.ly">''',
599 border="0" src="%(image)s" alt="%(alt)s">''',
601 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
603 QUOTE: r'''<blockquote>
616 \ifx\preLilyPondExample \undefined%%
619 \preLilyPondExample%%
621 \def\lilypondbook{}%%
622 \input %(base)s-systems.tex%%
623 \ifx\postLilyPondExample \undefined%%
626 \postLilyPondExample%%
630 PRINTFILENAME: '''\\texttt{%(filename)s}
633 QUOTE: r'''\begin{quotation}%(str)s
636 VERBATIM: r'''\noindent
637 \begin{verbatim}%(verb)s\end{verbatim}''',
639 FILTER: r'''\begin{lilypond}[%(options)s]
646 FILTER: r'''@lilypond[%(options)s]
652 @include %(base)s-systems.texi
656 OUTPUTIMAGE: r'''@noindent
658 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
662 <a href="%(base)s.ly">
664 border="0" src="%(image)s" alt="%(alt)s">
672 <a href="%(base)s.ly">
680 QUOTE: r'''@quotation
681 %(str)s@end quotation
688 VERBATIM: r'''@exampleindent 0
690 %(verb)s@end verbatim
693 ADDVERSION: r'''@example
694 \version @w{"@version{}"}
701 # Maintain line numbers.
706 for f in [HTML, LATEX]:
707 for s in (QUOTE, VERBATIM):
708 output[f][s] = output[f][s].replace("\n"," ")
711 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
712 %%%% Options: [%(option_string)s]
713 \\include "lilypond-book-preamble.ly"
716 %% ****************************************************************
717 %% Start cut-&-pastable-section
718 %% ****************************************************************
723 #(define dump-extents #t)
724 %(font_dump_setting)s
726 force-assignment = #""
727 line-width = #(- line-width (* mm %(padding_mm)f))
740 %% ****************************************************************
741 %% ly snippet contents follows:
742 %% ****************************************************************
746 %% ****************************************************************
748 %% ****************************************************************
755 %% ****************************************************************
757 %% ****************************************************************
761 %% ****************************************************************
763 %% ****************************************************************
766 texinfo_line_widths = {
767 '@afourpaper': '160\\mm',
768 '@afourwide': '6.5\\in',
769 '@afourlatex': '150\\mm',
770 '@smallbook': '5\\in',
771 '@letterpaper': '6\\in',
774 def classic_lilypond_book_compatibility (key, value):
775 if key == 'singleline' and value == None:
776 return (RAGGED_RIGHT, None)
778 m = re.search ('relative\s*([-0-9])', key)
780 return ('relative', m.group (1))
782 m = re.match ('([0-9]+)pt', key)
784 return ('staffsize', m.group (1))
786 if key == 'indent' or key == 'line-width':
787 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
789 f = float (m.group (1))
790 return (key, '%f\\%s' % (f, m.group (2)))
794 def find_file (name, raise_error=True):
795 for i in global_options.include_path:
796 full = os.path.join (i, name)
797 if os.path.exists (full):
801 error (_ ("file not found: %s") % name + '\n')
805 def verbatim_html (s):
806 return re.sub ('>', '>',
808 re.sub ('&', '&', s)))
811 def set_default_options (source, default_ly_options, format):
812 if LINE_WIDTH not in default_ly_options:
814 textwidth = get_latex_textwidth (source)
815 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
816 elif format == TEXINFO:
817 for regex in texinfo_line_widths:
818 # FIXME: @layout is usually not in
821 # \input texinfo @c -*-texinfo-*-
823 # Bluntly search first K items of
825 # s = chunks[0].replacement_text ()
826 if re.search (regex, source[:1024]):
827 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
831 def replacement_text (self):
834 def filter_text (self):
835 return self.replacement_text ()
837 def ly_is_outdated (self):
840 def png_is_outdated (self):
846 class Substring (Chunk):
847 """A string that does not require extra memory."""
848 def __init__ (self, source, start, end, line_number):
852 self.line_number = line_number
853 self.override_text = None
858 def replacement_text (self):
859 if self.override_text:
860 return self.override_text
862 return self.source[self.start:self.end]
864 class Snippet (Chunk):
865 def __init__ (self, type, match, format, line_number):
869 self.option_dict = {}
871 self.line_number = line_number
873 def replacement_text (self):
874 return self.match.group ('match')
876 def substring (self, s):
877 return self.match.group (s)
880 return `self.__class__` + ' type = ' + self.type
882 class IncludeSnippet (Snippet):
883 def processed_filename (self):
884 f = self.substring ('filename')
885 return os.path.splitext (f)[0] + format2ext[self.format]
887 def replacement_text (self):
888 s = self.match.group ('match')
889 f = self.substring ('filename')
891 return re.sub (f, self.processed_filename (), s)
893 class LilypondSnippet (Snippet):
894 def __init__ (self, type, match, format, line_number):
895 Snippet.__init__ (self, type, match, format, line_number)
896 os = match.group ('options')
897 self.do_options (os, self.type)
900 return self.substring ('code')
903 contents = self.substring ('code')
904 return ('\\sourcefileline %d\n%s'
905 % (self.line_number - 1, contents))
910 return self.compose_ly (s)
913 def split_options (self, option_string):
915 if self.format == HTML:
916 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
918 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
922 return re.split (format_res[self.format]['option_sep'],
926 def do_options (self, option_string, type):
927 self.option_dict = {}
929 options = self.split_options (option_string)
931 for option in options:
933 (key, value) = re.split ('\s*=\s*', option)
934 self.option_dict[key] = value
936 if option in no_options:
937 if no_options[option] in self.option_dict:
938 del self.option_dict[no_options[option]]
940 self.option_dict[option] = None
942 has_line_width = self.option_dict.has_key (LINE_WIDTH)
943 no_line_width_value = 0
945 # If LINE_WIDTH is used without parameter, set it to default.
946 if has_line_width and self.option_dict[LINE_WIDTH] == None:
947 no_line_width_value = 1
948 del self.option_dict[LINE_WIDTH]
950 for k in default_ly_options:
951 if k not in self.option_dict:
952 self.option_dict[k] = default_ly_options[k]
954 if not has_line_width:
955 if type == 'lilypond' or FRAGMENT in self.option_dict:
956 self.option_dict[RAGGED_RIGHT] = None
958 if type == 'lilypond':
959 if LINE_WIDTH in self.option_dict:
960 del self.option_dict[LINE_WIDTH]
962 if RAGGED_RIGHT in self.option_dict:
963 if LINE_WIDTH in self.option_dict:
964 del self.option_dict[LINE_WIDTH]
966 if QUOTE in self.option_dict or type == 'lilypond':
967 if LINE_WIDTH in self.option_dict:
968 del self.option_dict[LINE_WIDTH]
970 if not INDENT in self.option_dict:
971 self.option_dict[INDENT] = '0\\mm'
973 # The QUOTE pattern from ly_options only emits the `line-width'
975 if has_line_width and QUOTE in self.option_dict:
976 if no_line_width_value:
977 del self.option_dict[LINE_WIDTH]
979 del self.option_dict[QUOTE]
981 def compose_ly (self, code):
982 if FRAGMENT in self.option_dict:
990 # The original concept of the `exampleindent' option is broken.
991 # It is not possible to get a sane value for @exampleindent at all
992 # without processing the document itself. Saying
1000 # causes ugly results with the DVI backend of texinfo since the
1001 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1002 # value). Executing the above code changes the environment
1003 # indentation to an unknown value because we don't know the amount
1004 # of 1em in advance since it is font-dependent. Modifying
1005 # @exampleindent in the middle of a document is simply not
1006 # supported within texinfo.
1008 # As a consequence, the only function of @exampleindent is now to
1009 # specify the amount of indentation for the `quote' option.
1011 # To set @exampleindent locally to zero, we use the @format
1012 # environment for non-quoted snippets.
1013 override[EXAMPLEINDENT] = r'0.4\in'
1014 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1015 override.update (default_ly_options)
1018 for (key, value) in self.option_dict.items ():
1020 option_list.append (key)
1022 option_list.append (key + '=' + value)
1023 option_string = ','.join (option_list)
1026 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1027 for a in compose_types:
1028 compose_dict[a] = []
1030 for (key, value) in self.option_dict.items ():
1031 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1035 _ ("deprecated ly-option used: %s=%s"
1038 _ ("compatibility mode translation: %s=%s"
1039 % (c_key, c_value)))
1042 _ ("deprecated ly-option used: %s"
1045 _ ("compatibility mode translation: %s"
1048 (key, value) = (c_key, c_value)
1051 override[key] = value
1053 if not override.has_key (key):
1054 override[key] = None
1057 for type in compose_types:
1058 if ly_options[type].has_key (key):
1059 compose_dict[type].append (ly_options[type][key])
1063 if not found and key not in simple_options:
1064 warning (_ ("ignoring unknown ly option: %s") % key)
1067 if RELATIVE in override and override[RELATIVE]:
1068 relative = int (override[RELATIVE])
1070 relative_quotes = ''
1074 relative_quotes += ',' * (- relative)
1076 relative_quotes += "'" * relative
1078 paper_string = '\n '.join (compose_dict[PAPER]) % override
1079 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1080 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1081 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1082 padding_mm = global_options.padding_mm
1083 font_dump_setting = ''
1084 if FONTLOAD in self.option_dict:
1085 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1087 d = globals().copy()
1089 return (PREAMBLE_LY + body) % d
1091 def get_checksum (self):
1092 if not self.checksum:
1093 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1095 ## let's not create too long names.
1096 self.checksum = hash.hexdigest ()[:10]
1098 return self.checksum
1100 def basename (self):
1101 if FILENAME in self.option_dict:
1102 return self.option_dict[FILENAME]
1104 cs = self.get_checksum ()
1106 # TODO: use xx/xxxxx directory layout.
1107 name = 'lily-%s' % cs[:10]
1108 if global_options.lily_output_dir:
1109 name = os.path.join (global_options.lily_output_dir, name)
1112 def write_ly (self):
1113 out = file (self.basename () + '.ly', 'w')
1114 out.write (self.full_ly ())
1115 file (self.basename () + '.txt', 'w').write ('image of music')
1117 def relevant_contents (self, ly):
1118 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1120 def link_all_output_files (self, output_dir, output_dir_files, destination):
1121 existing = self.all_output_files (output_dir_files)
1122 for name in existing:
1124 os.unlink (os.path.join (destination, name))
1128 src = os.path.join (output_dir, name)
1129 dst = os.path.join (destination, name)
1133 def all_output_files (self, output_dir_files):
1134 """Return all files generated in lily_output_dir, a set.
1136 output_dir_files is the list of files in the output directory.
1138 class Missing(Exception):
1142 base = os.path.basename(self.basename())
1143 def consider_file (name):
1144 if name in output_dir_files:
1147 def require_file (name):
1148 if name not in output_dir_files:
1153 for required in [base + '.ly',
1155 base + '-systems.count']:
1156 require_file (required)
1158 map (consider_file, [base + '.tex',
1160 base + '-systems.texi',
1161 base + '-systems.tex',
1162 base + '-systems.pdftexi'])
1164 if base + '.eps' in result and self.format in (HTML, TEXINFO):
1165 page_count = ps_page_count (self.basename() + '.eps')
1167 require_file (base + '.png')
1169 for page in range (1, page_count + 1):
1170 require_file (base + '-page%d.png' % page)
1172 system_count = int(file (self.basename () + '-systems.count').read())
1173 for number in range(1, system_count + 1):
1174 systemfile = '%s-%d' % (base, number)
1175 require_file (systemfile + '.eps')
1176 if 'pdf' in self.format:
1177 require_file (systemfile + '.pdf')
1183 def is_outdated (self, current_files):
1184 return self.all_output_files (current_files) is None
1186 def filter_text (self):
1187 """Run snippet bodies through a command (say: convert-ly).
1189 This functionality is rarely used, and this code must have bitrot.
1192 code = self.substring ('code')
1193 s = filter_pipe (code, global_options.filter_cmd)
1196 'options': self.match.group ('options')
1199 return output[self.format][FILTER] % d
1201 def replacement_text (self):
1202 func = LilypondSnippet.__dict__['output_' + self.format]
1205 def get_images (self):
1206 base = self.basename ()
1208 single = '%(base)s.png' % vars ()
1209 multiple = '%(base)s-page1.png' % vars ()
1211 if (os.path.exists (multiple)
1212 and (not os.path.exists (single)
1213 or (os.stat (multiple)[stat.ST_MTIME]
1214 > os.stat (single)[stat.ST_MTIME]))):
1215 count = ps_page_count ('%(base)s.eps' % vars ())
1216 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1217 images = tuple (images)
1221 def output_docbook (self):
1223 base = self.basename ()
1224 for image in self.get_images ():
1225 (base, ext) = os.path.splitext (image)
1226 str += output[DOCBOOK][OUTPUT] % vars ()
1227 str += self.output_print_filename (DOCBOOK)
1228 if (self.substring('inline') == 'inline'):
1229 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1231 str = '<mediaobject>' + str + '</mediaobject>'
1232 if VERBATIM in self.option_dict:
1233 verb = verbatim_html (self.verb_ly ())
1234 str = output[DOCBOOK][VERBATIM] % vars () + str
1237 def output_html (self):
1239 base = self.basename ()
1240 if self.format == HTML:
1241 str += self.output_print_filename (HTML)
1242 if VERBATIM in self.option_dict:
1243 verb = verbatim_html (self.verb_ly ())
1244 str += output[HTML][VERBATIM] % vars ()
1245 if QUOTE in self.option_dict:
1246 str = output[HTML][QUOTE] % vars ()
1248 str += output[HTML][BEFORE] % vars ()
1249 for image in self.get_images ():
1250 (base, ext) = os.path.splitext (image)
1251 alt = self.option_dict[ALT]
1252 str += output[HTML][OUTPUT] % vars ()
1253 str += output[HTML][AFTER] % vars ()
1256 def output_info (self):
1258 for image in self.get_images ():
1259 (base, ext) = os.path.splitext (image)
1261 # URG, makeinfo implicitly prepends dot to extension.
1262 # Specifying no extension is most robust.
1264 alt = self.option_dict[ALT]
1265 info_image_path = os.path.join (global_options.info_images_dir, base)
1266 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1268 base = self.basename ()
1269 str += output[self.format][OUTPUT] % vars ()
1272 def output_latex (self):
1274 base = self.basename ()
1275 if self.format == LATEX:
1276 str += self.output_print_filename (LATEX)
1277 if VERBATIM in self.option_dict:
1278 verb = self.verb_ly ()
1279 str += (output[LATEX][VERBATIM] % vars ())
1281 str += (output[LATEX][OUTPUT] % vars ())
1283 ## todo: maintain breaks
1285 breaks = self.ly ().count ("\n")
1286 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1288 if QUOTE in self.option_dict:
1289 str = output[LATEX][QUOTE] % vars ()
1292 def output_print_filename (self, format):
1294 if PRINTFILENAME in self.option_dict:
1295 base = self.basename ()
1296 filename = os.path.basename (self.substring ('filename'))
1297 str = output[format][PRINTFILENAME] % vars ()
1301 def output_texinfo (self):
1302 str = self.output_print_filename (TEXINFO)
1303 base = self.basename ()
1304 if TEXIDOC in self.option_dict:
1305 texidoc = base + '.texidoc'
1306 if os.path.exists (texidoc):
1307 str += '@include %(texidoc)s\n\n' % vars ()
1310 if VERBATIM in self.option_dict:
1312 if ADDVERSION in self.option_dict:
1313 version = output[TEXINFO][ADDVERSION]
1314 verb = self.verb_ly ()
1315 substr = output[TEXINFO][VERBATIM] % vars ()
1316 substr += self.output_info ()
1317 if LILYQUOTE in self.option_dict:
1318 substr = output[TEXINFO][QUOTE] % {'str':substr}
1321 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1322 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1323 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1325 if QUOTE in self.option_dict:
1326 str = output[TEXINFO][QUOTE] % vars ()
1328 # need par after image
1333 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1334 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1336 class LilypondFileSnippet (LilypondSnippet):
1337 def __init__ (self, type, match, format, line_number):
1338 LilypondSnippet.__init__ (self, type, match, format, line_number)
1339 self.contents = file (find_file (self.substring ('filename'))).read ()
1343 s = re_begin_verbatim.split (s)[-1]
1344 s = re_end_verbatim.split (s)[0]
1348 name = self.substring ('filename')
1349 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1350 % (name, self.contents))
1353 snippet_type_to_class = {
1354 'lilypond_file': LilypondFileSnippet,
1355 'lilypond_block': LilypondSnippet,
1356 'lilypond': LilypondSnippet,
1357 'include': IncludeSnippet,
1360 def find_linestarts (s):
1365 i = s.find ('\n', start)
1373 nls.append (len (s))
1376 def find_toplevel_snippets (input_string, format, types):
1379 res[t] = ly.re.compile (snippet_res[format][t])
1383 found = dict ([(t, None) for t in types])
1385 line_starts = find_linestarts (input_string)
1387 # We want to search for multiple regexes, without searching
1388 # the string multiple times for one regex.
1389 # Hence, we use earlier results to limit the string portion
1391 # Since every part of the string is traversed at most once for
1392 # every type of snippet, this is linear.
1398 if not found[type] or found[type][0] < index:
1401 m = res[type].search (input_string[index:endex])
1406 if type in snippet_type_to_class:
1407 klass = snippet_type_to_class[type]
1409 start = index + m.start ('match')
1410 line_number = line_start_idx
1411 while (line_starts[line_number] < start):
1415 snip = klass (type, m, format, line_number)
1417 found[type] = (start, snip)
1421 or found[type][0] < found[first][0])):
1426 # Limiting the search space is a cute
1427 # idea, but this *requires* to search
1428 # for possible containing blocks
1429 # first, at least as long as we do not
1430 # search for the start of blocks, but
1431 # always/directly for the entire
1432 # @block ... @end block.
1434 endex = found[first][0]
1437 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1440 while (start > line_starts[line_start_idx+1]):
1443 (start, snip) = found[first]
1444 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1445 snippets.append (snip)
1447 index = start + len (snip.match.group ('match'))
1451 def filter_pipe (input, cmd):
1452 """Pass input through cmd, and return the result."""
1454 if global_options.verbose:
1455 progress (_ ("Opening filter `%s'") % cmd)
1457 (stdin, stdout, stderr) = os.popen3 (cmd)
1459 status = stdin.close ()
1463 output = stdout.read ()
1464 status = stdout.close ()
1465 error = stderr.read ()
1469 signal = 0x0f & status
1470 if status or (not output and error):
1471 exit_status = status >> 8
1472 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1473 error (_ ("The error log is as follows:"))
1474 ly.stderr_write (error)
1475 ly.stderr_write (stderr.read ())
1478 if global_options.verbose:
1483 def system_in_directory (cmd, directory):
1484 """Execute a command in a different directory.
1486 Because of win32 compatibility, we can't simply use subprocess.
1489 current = os.getcwd()
1490 os.chdir (directory)
1491 ly.system(cmd, be_verbose=global_options.verbose,
1496 def process_snippets (cmd, snippets,
1497 format, lily_output_dir):
1498 """Run cmd on all of the .ly files from snippets."""
1503 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1504 cmd += ' --formats=png '
1505 elif format in (DOCBOOK) and '--formats' not in cmd:
1506 cmd += ' --formats=png,pdf '
1508 checksum = snippet_list_checksum (snippets)
1509 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1510 + [snip.basename() for snip in snippets])
1511 name = os.path.join (lily_output_dir,
1512 'snippet-names-%d' % checksum)
1513 file (name, 'wb').write (contents)
1515 system_in_directory (' '.join ([cmd, name]),
1520 # Retrieve dimensions from LaTeX
1521 LATEX_INSPECTION_DOCUMENT = r'''
1525 \typeout{textwidth=\the\textwidth}
1526 \typeout{columnsep=\the\columnsep}
1527 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1531 # Do we need anything else besides `textwidth'?
1532 def get_latex_textwidth (source):
1533 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1535 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1537 ## what's a sensible default?
1540 preamble = source[:m.start (0)]
1541 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1543 (handle, tmpfile) = tempfile.mkstemp('.tex')
1544 logfile = os.path.splitext (tmpfile)[0] + '.log'
1545 logfile = os.path.split (logfile)[1]
1547 tmp_handle = os.fdopen (handle,'w')
1548 tmp_handle.write (latex_document)
1551 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1552 parameter_string = file (logfile).read()
1558 m = re.search ('columns=([0-9.]*)', parameter_string)
1560 columns = int (m.group (1))
1563 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1565 columnsep = float (m.group (1))
1568 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1570 textwidth = float (m.group (1))
1572 textwidth = (textwidth - columnsep) / columns
1576 def modify_preamble (chunk):
1577 str = chunk.replacement_text ()
1578 if (re.search (r"\\begin *{document}", str)
1579 and not re.search ("{graphic[sx]", str)):
1580 str = re.sub (r"\\begin{document}",
1581 r"\\usepackage{graphics}" + '\n'
1582 + r"\\begin{document}",
1584 chunk.override_text = str
1589 # TEXINFO: '.texinfo',
1595 class CompileError(Exception):
1598 def snippet_list_checksum (snippets):
1599 return hash (' '.join([l.basename() for l in snippets]))
1601 def write_file_map (lys, name):
1602 snippet_map = file (os.path.join (
1603 global_options.lily_output_dir,
1604 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1606 snippet_map.write ("""
1607 #(define version-seen #t)
1608 #(define output-empty-score-list #f)
1609 #(ly:add-file-name-alist '(%s
1611 """ % '\n'.join('("%s.ly" . "%s")\n' % (ly.basename (), name)
1614 def do_process_cmd (chunks, input_name, options):
1615 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1618 output_files = set(os.listdir(options.lily_output_dir))
1619 outdated = [c for c in snippets if c.is_outdated (output_files)]
1621 write_file_map (outdated, input_name)
1622 progress (_ ("Writing snippets..."))
1623 for snippet in outdated:
1628 progress (_ ("Processing..."))
1630 process_snippets (options.process_cmd, outdated,
1631 options.format, options.lily_output_dir)
1634 progress (_ ("All snippets are up to date..."))
1636 if options.lily_output_dir != options.output_dir:
1637 output_files = set(os.listdir(options.lily_output_dir))
1638 for snippet in snippets:
1639 snippet.link_all_output_files (options.lily_output_dir,
1647 # Format guessing data
1656 '.texinfo': TEXINFO,
1661 def guess_format (input_filename):
1663 e = os.path.splitext (input_filename)[1]
1666 format = ext2format[e]
1668 error (_ ("cannot determine format for: %s"
1673 def write_if_updated (file_name, lines):
1675 f = file (file_name)
1677 new_str = ''.join (lines)
1678 if oldstr == new_str:
1679 progress (_ ("%s is up to date.") % file_name)
1682 # this prevents make from always rerunning lilypond-book:
1683 # output file must be touched in order to be up to date
1684 os.utime (file_name, None)
1688 progress (_ ("Writing `%s'...") % file_name)
1689 file (file_name, 'w').writelines (lines)
1693 def note_input_file (name, inputs=[]):
1694 ## hack: inputs is mutable!
1695 inputs.append (name)
1698 def samefile (f1, f2):
1700 return os.path.samefile (f1, f2)
1701 except AttributeError: # Windoze
1702 f1 = re.sub ("//*", "/", f1)
1703 f2 = re.sub ("//*", "/", f2)
1706 def do_file (input_filename):
1708 if not input_filename or input_filename == '-':
1709 in_handle = sys.stdin
1710 input_fullname = '<stdin>'
1712 if os.path.exists (input_filename):
1713 input_fullname = input_filename
1714 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1715 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1717 input_fullname = find_file (input_filename)
1719 note_input_file (input_fullname)
1720 in_handle = file (input_fullname)
1722 if input_filename == '-':
1723 input_base = 'stdin'
1725 input_base = os.path.basename (
1726 os.path.splitext (input_filename)[0])
1728 # don't complain when global_options.output_dir is existing
1729 if not global_options.output_dir:
1730 global_options.output_dir = os.getcwd()
1732 global_options.output_dir = os.path.abspath(global_options.output_dir)
1734 if not os.path.isdir (global_options.output_dir):
1735 os.mkdir (global_options.output_dir, 0777)
1736 os.chdir (global_options.output_dir)
1738 output_filename = os.path.join(global_options.output_dir,
1739 input_base + format2ext[global_options.format])
1740 if (os.path.exists (input_filename)
1741 and os.path.exists (output_filename)
1742 and samefile (output_filename, input_fullname)):
1744 _ ("Output would overwrite input file; use --output."))
1748 progress (_ ("Reading %s...") % input_fullname)
1749 source = in_handle.read ()
1752 set_default_options (source, default_ly_options, global_options.format)
1755 # FIXME: Containing blocks must be first, see
1756 # find_toplevel_snippets.
1758 'multiline_comment',
1762 'singleline_comment',
1767 progress (_ ("Dissecting..."))
1768 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1770 if global_options.format == LATEX:
1772 if (c.is_plain () and
1773 re.search (r"\\begin *{document}", c.replacement_text())):
1778 if global_options.filter_cmd:
1779 write_if_updated (output_filename,
1780 [c.filter_text () for c in chunks])
1781 elif global_options.process_cmd:
1782 do_process_cmd (chunks, input_fullname, global_options)
1783 progress (_ ("Compiling %s...") % output_filename)
1785 write_if_updated (output_filename,
1786 [s.replacement_text ()
1789 def process_include (snippet):
1790 os.chdir (original_dir)
1791 name = snippet.substring ('filename')
1792 progress (_ ("Processing include: %s") % name)
1794 return do_file (name)
1796 include_chunks = map (process_include,
1797 filter (lambda x: isinstance (x, IncludeSnippet),
1800 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1802 except CompileError:
1803 os.chdir (original_dir)
1804 progress (_ ("Removing `%s'") % output_filename)
1809 global global_options
1811 opt_parser = get_option_parser()
1812 (global_options, args) = opt_parser.parse_args ()
1813 if global_options.format in ('texi-html', 'texi'):
1814 global_options.format = TEXINFO
1816 global_options.include_path = map (os.path.abspath, global_options.include_path)
1818 if global_options.warranty:
1821 if not args or len (args) > 1:
1822 opt_parser.print_help ()
1828 # FIXME: 85 lines of `main' macramee??
1829 files = do_options ()
1831 basename = os.path.splitext (files[0])[0]
1832 basename = os.path.split (basename)[1]
1834 if not global_options.format:
1835 global_options.format = guess_format (files[0])
1838 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1841 if global_options.process_cmd == '':
1842 global_options.process_cmd = (lilypond_binary
1843 + ' --formats=%s -dbackend=eps ' % formats)
1845 if global_options.process_cmd:
1846 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1847 for p in global_options.include_path])
1849 if global_options.format in (TEXINFO, LATEX):
1850 ## prevent PDF from being switched on by default.
1851 global_options.process_cmd += ' --formats=eps '
1852 if global_options.create_pdf:
1853 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1855 if global_options.verbose:
1856 global_options.process_cmd += " --verbose "
1858 if global_options.padding_mm:
1859 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1861 global_options.process_cmd += " -dread-file-list "
1863 if global_options.lily_output_dir:
1864 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1865 if not os.path.isdir (global_options.lily_output_dir):
1866 os.makedirs (global_options.lily_output_dir)
1868 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1873 chunks = do_file (files[0])
1874 except CompileError:
1877 inputs = note_input_file ('')
1880 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1881 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1882 final_output_file = os.path.join (global_options.output_dir,
1884 + '.%s' % global_options.format)
1886 os.chdir (original_dir)
1887 file (dep_file, 'w').write ('%s: %s'
1888 % (final_output_file, ' '.join (inputs)))
1890 if __name__ == '__main__':