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
47 ly.require_python_version ()
50 program_version = '@TOPLEVEL_VERSION@'
51 program_name = os.path.basename (sys.argv[0])
53 # Check if program_version contains @ characters. This will be the case if
54 # the .py file is called directly while building the lilypond documentation.
55 # If so, try to check for the env var LILYPOND_VERSION, which is set by our
56 # makefiles and use its value.
57 at_re = re.compile (r'@')
58 if at_re.match (program_version):
59 if os.environ.has_key('LILYPOND_VERSION'):
60 program_version = os.environ['LILYPOND_VERSION']
62 program_version = "unknown"
64 original_dir = os.getcwd ()
68 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
72 $ lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
73 $ lilypond-book -F "convert-ly --no-version --from=2.0.0 -" %(BOOK)s
74 $ lilypond-book --process='lilypond -I include' %(BOOK)s
75 ''' % {'BOOK': _ ("BOOK")})
77 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
78 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
80 ################################################################
82 if global_options.verbose:
83 raise Exception (_ ('Exiting (%d)...') % i)
88 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
90 progress = ly.progress
93 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
96 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
98 def ps_page_count (ps_name):
99 header = file (ps_name).read (1024)
100 m = re.search ('\n%%Pages: ([0-9]+)', header)
102 return int (m.group (1))
107 ly.encoded_write (sys.stdout, '''
114 ''' % ( _ ('Copyright (c) %s by') % '2001--2009',
115 '\n '.join (authors),
116 _ ("Distributed under terms of the GNU General Public License."),
117 _ ("It comes with NO WARRANTY.")))
119 def get_option_parser ():
120 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
121 description=help_summary,
122 add_help_option=False)
124 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
127 help=_ ("pipe snippets through FILTER [default: `convert-ly -n -']"),
130 p.add_option ('-f', '--format',
131 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
132 metavar=_ ("FORMAT"),
135 p.add_option("-h", "--help",
137 help=_ ("show this help and exit"))
139 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
141 action='append', dest='include_path',
142 default=[os.path.abspath (os.getcwd ())])
144 p.add_option ('--info-images-dir',
145 help=_ ("format Texinfo output so that Info will "
146 "look for images of music in DIR"),
148 action='store', dest='info_images_dir',
151 p.add_option ('--latex-program',
152 help=_ ("run executable PROG instead of latex"),
154 action='store', dest='latex_program',
157 p.add_option ('--left-padding',
160 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
164 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
166 action='store', dest='output_dir',
169 p.add_option ('--skip-lily-check',
170 help=_ ("do not fail if no lilypond output is found"),
172 action='store_true', dest='skip_lilypond_run',
175 p.add_option ('--skip-png-check',
176 help=_ ("do not fail if no PNG images are found for EPS files"),
178 action='store_true', dest='skip_png_check',
181 p.add_option ('--lily-output-dir',
182 help=_ ("write lily-XXX files to DIR, link into --output dir"),
184 action='store', dest='lily_output_dir',
187 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
188 help = _ ("process ly_files using COMMAND FILE..."),
190 dest='process_cmd', default='')
192 p.add_option ('--pdf',
195 help=_ ("create PDF files for use with PDFTeX"),
198 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
203 p.version = "@TOPLEVEL_VERSION@"
204 p.add_option("--version",
206 help=_ ("show version number and exit"))
208 p.add_option ('-w', '--warranty',
209 help=_ ("show warranty and copyright"),
211 p.add_option_group ('',
213 _ ("Report bugs via %s")
214 % ' http://post.gmane.org/post.php'
215 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
218 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
220 # If we are called with full path, try to use lilypond binary
221 # installed in the same path; this is needed in GUB binaries, where
222 # @bindir is always different from the installed binary path.
223 if 'bindir' in globals () and bindir:
224 lilypond_binary = os.path.join (bindir, 'lilypond')
226 # Only use installed binary when we are installed too.
227 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
228 lilypond_binary = 'lilypond'
230 global_options = None
233 default_ly_options = { 'alt': "[image of music]" }
235 document_language = ''
238 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
240 ADDVERSION = 'addversion'
244 EXAMPLEINDENT = 'exampleindent'
246 FRAGMENT = 'fragment'
252 LINE_WIDTH = 'line-width'
253 LILYQUOTE = 'lilyquote'
254 NOFRAGMENT = 'nofragment'
255 NOGETTEXT = 'nogettext'
256 NOINDENT = 'noindent'
258 NORAGGED_RIGHT = 'noragged-right'
262 OUTPUTIMAGE = 'outputimage'
264 PREAMBLE = 'preamble'
265 PRINTFILENAME = 'printfilename'
267 RAGGED_RIGHT = 'ragged-right'
268 RELATIVE = 'relative'
269 STAFFSIZE = 'staffsize'
270 DOCTITLE = 'doctitle'
273 VERBATIM = 'verbatim'
274 VERSION = 'lilypondversion'
275 FILENAME = 'filename'
279 # NOTIME has no opposite so it isn't part of this dictionary.
280 # NOQUOTE is used internally only.
282 NOFRAGMENT: FRAGMENT,
287 # Recognize special sequences in the input.
289 # (?P<name>regex) -- Assign result of REGEX to NAME.
290 # *? -- Match non-greedily.
291 # (?!...) -- Match if `...' doesn't match next (without consuming
294 # (?m) -- Multiline regex: Make ^ and $ match at each line.
295 # (?s) -- Make the dot match all characters including newline.
296 # (?x) -- Ignore whitespace in patterns.
307 <(?P<inline>(inline)?)mediaobject>\s*
309 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
311 </programlisting\s*>\s*
313 </(inline)?mediaobject>)''',
318 <(?P<inline>(inline)?)mediaobject>\s*
320 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
322 </programlisting\s*>\s*
324 </(inline)?mediaobject>)''',
329 <(?P<inline>(inline)?)mediaobject>\s*
332 fileref="(?P<filename>.*?\.ly)"\s*
333 (role="(?P<options>.*?)")?\s*
334 (/>|>\s*</imagedata>)\s*
336 </(inline)?mediaobject>)''',
342 (?P<code><!--\s.*?!-->)
345 'singleline_comment':
366 (\s*(?P<options>.*?)\s*:)?\s*
374 \s*(?P<options>.*?)\s*
383 \s*(?P<options>.*?)\s*
385 \s*(?P<filename>.*?)\s*
392 (?P<code><!--\s.*?!-->)
395 'singleline_comment':
401 (?P<code><pre>.*?</pre>))''',
407 (?P<code><pre>\s.*?</pre>\s))''',
412 <lilypondversion\s*/>)''',
431 \s*(?P<options>.*?)\s*
442 \s*(?P<options>.*?)\s*
446 \\end\s*{lilypond})''',
454 \s*(?P<options>.*?)\s*
462 'singleline_comment':
485 \\end\s*{verbatim}))''',
490 \\lilypondversion)[^a-zA-Z]''',
500 (?P<filename>\S+))''',
504 ^[^\n]*?(?!@c\s+)[^\n]*?
508 \s*(?P<options>.*?)\s*
518 \s*(?P<options>.*?)\s*
521 ^@end\s+lilypond)\s''',
528 \s*(?P<options>.*?)\s*
539 @end\s+ignore))\s''',
541 'singleline_comment':
546 @c([ \t][^\n]*|)\n))''',
548 # Don't do this: It interferes with @code{@{}.
549 # 'verb': r'''(?P<code>@code{.*?})''',
557 @end\s+example\s))''',
562 @lilypondversion)[^a-zA-Z]''',
570 'intertext': r',?\s*intertext=\".*?\"',
574 'intertext': r',?\s*intertext=\".*?\"',
579 'intertext': r',?\s*intertext=\".*?\"',
580 'option_sep': '\s*,\s*',
584 'intertext': r',?\s*intertext=\".*?\"',
585 'option_sep': '\s*,\s*',
590 # Options without a pattern in ly_options.
610 RELATIVE: r'''\relative c%(relative_quotes)s''',
615 INDENT: r'''indent = %(indent)s''',
617 LINE_WIDTH: r'''line-width = %(line-width)s''',
619 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
621 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
623 RAGGED_RIGHT: r'''ragged-right = ##t''',
625 NORAGGED_RIGHT: r'''ragged-right = ##f''',
637 \remove "Time_signature_engraver"
643 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
650 FILTER: r'''<mediaobject>
652 <programlisting language="lilypond"
659 OUTPUT: r'''<imageobject role="latex">
660 <imagedata fileref="%(base)s.pdf" format="PDF"/>
662 <imageobject role="html">
663 <imagedata fileref="%(base)s.png" format="PNG"/>
666 VERBATIM: r'''<programlisting>
667 %(verb)s</programlisting>''',
669 VERSION: program_version,
671 PRINTFILENAME: r'''<textobject>
673 <ulink url="%(base)s.ly">
683 FILTER: r'''<lilypond %(options)s>
693 <a href="%(base)s.ly">''',
701 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
703 QUOTE: r'''<blockquote>
711 VERSION: program_version,
718 \ifx\preLilyPondExample \undefined
720 \expandafter\preLilyPondExample
722 \def\lilypondbook{}%%
723 \input %(base)s-systems.tex
724 \ifx\postLilyPondExample \undefined
726 \expandafter\postLilyPondExample
730 PRINTFILENAME: '''\\texttt{%(filename)s}
733 QUOTE: r'''\begin{quotation}
737 VERBATIM: r'''\noindent
738 \begin{verbatim}%(verb)s\end{verbatim}
741 VERSION: program_version,
743 FILTER: r'''\begin{lilypond}[%(options)s]
750 FILTER: r'''@lilypond[%(options)s]
756 @include %(base)s-systems.texi
760 OUTPUTIMAGE: r'''@noindent
762 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
766 <a href="%(base)s.ly">
778 <a href="%(base)s.ly">
786 QUOTE: r'''@quotation
787 %(str)s@end quotation
794 VERBATIM: r'''@exampleindent 0
796 %(verb)s@end verbatim
799 VERSION: program_version,
801 ADDVERSION: r'''@example
802 \version @w{"@version{}"}
809 # Maintain line numbers.
814 for f in [HTML, LATEX]:
815 for s in (QUOTE, VERBATIM):
816 output[f][s] = output[f][s].replace("\n"," ")
819 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
820 %%%% Options: [%(option_string)s]
821 \\include "lilypond-book-preamble.ly"
824 %% ****************************************************************
825 %% Start cut-&-pastable-section
826 %% ****************************************************************
832 force-assignment = #""
833 line-width = #(- line-width (* mm %(padding_mm)f))
846 %% ****************************************************************
847 %% ly snippet contents follows:
848 %% ****************************************************************
852 %% ****************************************************************
854 %% ****************************************************************
861 %% ****************************************************************
863 %% ****************************************************************
867 %% ****************************************************************
869 %% ****************************************************************
872 texinfo_line_widths = {
873 '@afourpaper': '160\\mm',
874 '@afourwide': '6.5\\in',
875 '@afourlatex': '150\\mm',
876 '@smallbook': '5\\in',
877 '@letterpaper': '6\\in',
880 def classic_lilypond_book_compatibility (key, value):
881 if key == 'singleline' and value == None:
882 return (RAGGED_RIGHT, None)
884 m = re.search ('relative\s*([-0-9])', key)
886 return ('relative', m.group (1))
888 m = re.match ('([0-9]+)pt', key)
890 return ('staffsize', m.group (1))
892 if key == 'indent' or key == 'line-width':
893 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
895 f = float (m.group (1))
896 return (key, '%f\\%s' % (f, m.group (2)))
900 def find_file (name, raise_error=True):
901 for i in global_options.include_path:
902 full = os.path.join (i, name)
903 if os.path.exists (full):
907 error (_ ("file not found: %s") % name + '\n')
911 def verbatim_html (s):
912 return re.sub ('>', '>',
914 re.sub ('&', '&', s)))
916 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
917 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
918 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
919 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
921 def ly_comment_gettext (t, m):
922 return m.group (1) + t (m.group (2))
924 def verb_ly_gettext (s):
925 if not document_language:
928 t = langdefs.translation[document_language]
932 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
934 if langdefs.LANGDICT[document_language].enable_ly_identifier_l10n:
935 for v in ly_var_def_re.findall (s):
936 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
937 "\\1" + t (v) + "\\2",
939 for id in ly_context_id_re.findall (s):
940 s = re.sub (r'(\s+|")%s(\s+|")' % id,
941 "\\1" + t (id) + "\\2",
945 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
946 def set_default_options (source, default_ly_options, format):
947 global document_language
948 if LINE_WIDTH not in default_ly_options:
950 textwidth = get_latex_textwidth (source)
951 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
952 elif format == TEXINFO:
953 m = texinfo_lang_re.search (source)
954 if m and not m.group (1).startswith ('en'):
955 document_language = m.group (1)
957 document_language = ''
958 for regex in texinfo_line_widths:
959 # FIXME: @layout is usually not in
962 # \input texinfo @c -*-texinfo-*-
964 # Bluntly search first K items of
966 # s = chunks[0].replacement_text ()
967 if re.search (regex, source[:1024]):
968 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
972 def replacement_text (self):
975 def filter_text (self):
976 return self.replacement_text ()
981 class Substring (Chunk):
982 """A string that does not require extra memory."""
983 def __init__ (self, source, start, end, line_number):
987 self.line_number = line_number
988 self.override_text = None
993 def replacement_text (self):
994 if self.override_text:
995 return self.override_text
997 return self.source[self.start:self.end]
999 class Snippet (Chunk):
1000 def __init__ (self, type, match, format, line_number):
1004 self.option_dict = {}
1005 self.format = format
1006 self.line_number = line_number
1008 def replacement_text (self):
1009 return self.match.group ('match')
1011 def substring (self, s):
1012 return self.match.group (s)
1014 def __repr__ (self):
1015 return `self.__class__` + ' type = ' + self.type
1017 class IncludeSnippet (Snippet):
1018 def processed_filename (self):
1019 f = self.substring ('filename')
1020 return os.path.splitext (f)[0] + format2ext[self.format]
1022 def replacement_text (self):
1023 s = self.match.group ('match')
1024 f = self.substring ('filename')
1026 return re.sub (f, self.processed_filename (), s)
1028 class LilypondSnippet (Snippet):
1029 def __init__ (self, type, match, format, line_number):
1030 Snippet.__init__ (self, type, match, format, line_number)
1031 os = match.group ('options')
1032 self.do_options (os, self.type)
1035 verb_text = self.substring ('code')
1036 if not NOGETTEXT in self.option_dict:
1037 verb_text = verb_ly_gettext (verb_text)
1038 if not verb_text.endswith ('\n'):
1043 contents = self.substring ('code')
1044 return ('\\sourcefileline %d\n%s'
1045 % (self.line_number - 1, contents))
1050 return self.compose_ly (s)
1053 def split_options (self, option_string):
1055 if self.format == HTML:
1056 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
1058 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
1062 return re.split (format_res[self.format]['option_sep'],
1066 def do_options (self, option_string, type):
1067 self.option_dict = {}
1069 options = self.split_options (option_string)
1071 for option in options:
1073 (key, value) = re.split ('\s*=\s*', option)
1074 self.option_dict[key] = value
1076 if option in no_options:
1077 if no_options[option] in self.option_dict:
1078 del self.option_dict[no_options[option]]
1080 self.option_dict[option] = None
1082 has_line_width = self.option_dict.has_key (LINE_WIDTH)
1083 no_line_width_value = 0
1085 # If LINE_WIDTH is used without parameter, set it to default.
1086 if has_line_width and self.option_dict[LINE_WIDTH] == None:
1087 no_line_width_value = 1
1088 del self.option_dict[LINE_WIDTH]
1090 for k in default_ly_options:
1091 if k not in self.option_dict:
1092 self.option_dict[k] = default_ly_options[k]
1094 # RELATIVE does not work without FRAGMENT;
1095 # make RELATIVE imply FRAGMENT
1096 has_relative = self.option_dict.has_key (RELATIVE)
1097 if has_relative and not self.option_dict.has_key (FRAGMENT):
1098 self.option_dict[FRAGMENT] = None
1100 if not has_line_width:
1101 if type == 'lilypond' or FRAGMENT in self.option_dict:
1102 self.option_dict[RAGGED_RIGHT] = None
1104 if type == 'lilypond':
1105 if LINE_WIDTH in self.option_dict:
1106 del self.option_dict[LINE_WIDTH]
1108 if RAGGED_RIGHT in self.option_dict:
1109 if LINE_WIDTH in self.option_dict:
1110 del self.option_dict[LINE_WIDTH]
1112 if QUOTE in self.option_dict or type == 'lilypond':
1113 if LINE_WIDTH in self.option_dict:
1114 del self.option_dict[LINE_WIDTH]
1116 if not INDENT in self.option_dict:
1117 self.option_dict[INDENT] = '0\\mm'
1119 def compose_ly (self, code):
1120 if FRAGMENT in self.option_dict:
1128 # The original concept of the `exampleindent' option is broken.
1129 # It is not possible to get a sane value for @exampleindent at all
1130 # without processing the document itself. Saying
1138 # causes ugly results with the DVI backend of texinfo since the
1139 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1140 # value). Executing the above code changes the environment
1141 # indentation to an unknown value because we don't know the amount
1142 # of 1em in advance since it is font-dependent. Modifying
1143 # @exampleindent in the middle of a document is simply not
1144 # supported within texinfo.
1146 # As a consequence, the only function of @exampleindent is now to
1147 # specify the amount of indentation for the `quote' option.
1149 # To set @exampleindent locally to zero, we use the @format
1150 # environment for non-quoted snippets.
1151 override[EXAMPLEINDENT] = r'0.4\in'
1152 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1153 override.update (default_ly_options)
1156 for (key, value) in self.option_dict.items ():
1158 option_list.append (key)
1160 option_list.append (key + '=' + value)
1161 option_string = ','.join (option_list)
1164 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1165 for a in compose_types:
1166 compose_dict[a] = []
1168 for (key, value) in self.option_dict.items ():
1169 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1173 _ ("deprecated ly-option used: %s=%s") % (key, value))
1175 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1178 _ ("deprecated ly-option used: %s") % key)
1180 _ ("compatibility mode translation: %s") % c_key)
1182 (key, value) = (c_key, c_value)
1185 override[key] = value
1187 if not override.has_key (key):
1188 override[key] = None
1191 for type in compose_types:
1192 if ly_options[type].has_key (key):
1193 compose_dict[type].append (ly_options[type][key])
1197 if not found and key not in simple_options:
1198 warning (_ ("ignoring unknown ly option: %s") % key)
1201 if RELATIVE in override and override[RELATIVE]:
1202 relative = int (override[RELATIVE])
1204 relative_quotes = ''
1208 relative_quotes += ',' * (- relative)
1210 relative_quotes += "'" * relative
1212 paper_string = '\n '.join (compose_dict[PAPER]) % override
1213 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1214 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1215 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1216 padding_mm = global_options.padding_mm
1218 d = globals().copy()
1220 return (PREAMBLE_LY + body) % d
1222 def get_checksum (self):
1223 if not self.checksum:
1224 # Work-around for md5 module deprecation warning in python 2.5+:
1226 from hashlib import md5
1230 hash = md5 (self.relevant_contents (self.full_ly ()))
1232 ## let's not create too long names.
1233 self.checksum = hash.hexdigest ()[:10]
1235 return self.checksum
1237 def basename (self):
1238 cs = self.get_checksum ()
1239 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1242 def write_ly (self):
1243 base = self.basename ()
1244 path = os.path.join (global_options.lily_output_dir, base)
1245 directory = os.path.split(path)[0]
1246 if not os.path.isdir (directory):
1247 os.makedirs (directory)
1248 out = file (path + '.ly', 'w')
1249 out.write (self.full_ly ())
1250 file (path + '.txt', 'w').write ('image of music')
1252 def relevant_contents (self, ly):
1253 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n|' +
1254 NOGETTEXT + '[,\]]', '', ly)
1256 def link_all_output_files (self, output_dir, output_dir_files, destination):
1257 existing, missing = self.all_output_files (output_dir, output_dir_files)
1259 print '\nMissing', missing
1260 raise CompileError(self.basename())
1261 for name in existing:
1263 os.unlink (os.path.join (destination, name))
1267 src = os.path.join (output_dir, name)
1268 dst = os.path.join (destination, name)
1269 dst_path = os.path.split(dst)[0]
1270 if not os.path.isdir (dst_path):
1271 os.makedirs (dst_path)
1275 def all_output_files (self, output_dir, output_dir_files):
1276 """Return all files generated in lily_output_dir, a set.
1278 output_dir_files is the list of files in the output directory.
1282 base = self.basename()
1283 full = os.path.join (output_dir, base)
1284 def consider_file (name):
1285 if name in output_dir_files:
1288 def require_file (name):
1289 if name in output_dir_files:
1294 # UGH - junk global_options
1295 skip_lily = global_options.skip_lilypond_run
1296 for required in [base + '.ly',
1298 require_file (required)
1300 require_file (base + '-systems.count')
1302 if 'ddump-profile' in global_options.process_cmd:
1303 require_file (base + '.profile')
1304 if 'dseparate-log-file' in global_options.process_cmd:
1305 require_file (base + '.log')
1307 map (consider_file, [base + '.tex',
1311 base + '-systems.texi',
1312 base + '-systems.tex',
1313 base + '-systems.pdftexi'])
1314 if document_language:
1316 [base + '.texidoc' + document_language,
1317 base + '.doctitle' + document_language])
1319 # UGH - junk global_options
1320 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1321 and not global_options.skip_png_check):
1322 page_count = ps_page_count (full + '.eps')
1324 require_file (base + '.png')
1326 for page in range (1, page_count + 1):
1327 require_file (base + '-page%d.png' % page)
1330 if not skip_lily and not missing:
1331 system_count = int(file (full + '-systems.count').read())
1333 for number in range(1, system_count + 1):
1334 systemfile = '%s-%d' % (base, number)
1335 require_file (systemfile + '.eps')
1336 consider_file (systemfile + '.pdf')
1338 # We can't require signatures, since books and toplevel
1339 # markups do not output a signature.
1340 if 'ddump-signature' in global_options.process_cmd:
1341 consider_file (systemfile + '.signature')
1344 return (result, missing)
1346 def is_outdated (self, output_dir, current_files):
1347 found, missing = self.all_output_files (output_dir, current_files)
1350 def filter_text (self):
1351 """Run snippet bodies through a command (say: convert-ly).
1353 This functionality is rarely used, and this code must have bitrot.
1355 code = self.substring ('code')
1356 s = filter_pipe (code, global_options.filter_cmd)
1359 'options': self.match.group ('options')
1362 return output[self.format][FILTER] % d
1364 def replacement_text (self):
1365 func = LilypondSnippet.__dict__['output_' + self.format]
1368 def get_images (self):
1369 base = self.basename ()
1371 single = '%(base)s.png' % vars ()
1372 multiple = '%(base)s-page1.png' % vars ()
1374 if (os.path.exists (multiple)
1375 and (not os.path.exists (single)
1376 or (os.stat (multiple)[stat.ST_MTIME]
1377 > os.stat (single)[stat.ST_MTIME]))):
1378 count = ps_page_count ('%(base)s.eps' % vars ())
1379 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1380 images = tuple (images)
1384 def output_docbook (self):
1386 base = self.basename ()
1387 for image in self.get_images ():
1388 (base, ext) = os.path.splitext (image)
1389 str += output[DOCBOOK][OUTPUT] % vars ()
1390 str += self.output_print_filename (DOCBOOK)
1391 if (self.substring('inline') == 'inline'):
1392 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1394 str = '<mediaobject>' + str + '</mediaobject>'
1395 if VERBATIM in self.option_dict:
1396 verb = verbatim_html (self.verb_ly ())
1397 str = output[DOCBOOK][VERBATIM] % vars () + str
1400 def output_html (self):
1402 base = self.basename ()
1403 if self.format == HTML:
1404 str += self.output_print_filename (HTML)
1405 if VERBATIM in self.option_dict:
1406 verb = verbatim_html (self.verb_ly ())
1407 str += output[HTML][VERBATIM] % vars ()
1408 if QUOTE in self.option_dict:
1409 str = output[HTML][QUOTE] % vars ()
1411 str += output[HTML][BEFORE] % vars ()
1412 for image in self.get_images ():
1413 (base, ext) = os.path.splitext (image)
1414 alt = self.option_dict[ALT]
1415 str += output[HTML][OUTPUT] % vars ()
1416 str += output[HTML][AFTER] % vars ()
1419 def output_info (self):
1421 for image in self.get_images ():
1422 (base, ext) = os.path.splitext (image)
1424 # URG, makeinfo implicitly prepends dot to extension.
1425 # Specifying no extension is most robust.
1427 alt = self.option_dict[ALT]
1428 info_image_path = os.path.join (global_options.info_images_dir, base)
1429 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1431 base = self.basename ()
1432 str += output[self.format][OUTPUT] % vars ()
1435 def output_latex (self):
1437 base = self.basename ()
1438 if self.format == LATEX:
1439 str += self.output_print_filename (LATEX)
1440 if VERBATIM in self.option_dict:
1441 verb = self.verb_ly ()
1442 str += (output[LATEX][VERBATIM] % vars ())
1444 str += (output[LATEX][OUTPUT] % vars ())
1446 ## todo: maintain breaks
1448 breaks = self.ly ().count ("\n")
1449 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1451 if QUOTE in self.option_dict:
1452 str = output[LATEX][QUOTE] % vars ()
1455 def output_print_filename (self, format):
1457 if PRINTFILENAME in self.option_dict:
1458 base = self.basename ()
1459 filename = os.path.basename (self.substring ('filename'))
1460 str = output[format][PRINTFILENAME] % vars ()
1464 def output_texinfo (self):
1465 str = self.output_print_filename (TEXINFO)
1466 base = self.basename ()
1467 if DOCTITLE in self.option_dict:
1468 doctitle = base + '.doctitle'
1469 translated_doctitle = doctitle + document_language
1470 if os.path.exists (translated_doctitle):
1471 str += '@lydoctitle %s\n\n' % open (translated_doctitle).read ()
1472 elif os.path.exists (doctitle):
1473 str += '@lydoctitle %s\n\n' % open (doctitle).read ()
1474 if TEXIDOC in self.option_dict:
1475 texidoc = base + '.texidoc'
1476 translated_texidoc = texidoc + document_language
1477 if os.path.exists (translated_texidoc):
1478 str += '@include %(translated_texidoc)s\n\n' % vars ()
1479 elif os.path.exists (texidoc):
1480 str += '@include %(texidoc)s\n\n' % vars ()
1483 if VERBATIM in self.option_dict:
1485 if ADDVERSION in self.option_dict:
1486 version = output[TEXINFO][ADDVERSION]
1487 verb = self.verb_ly ()
1488 substr = output[TEXINFO][VERBATIM] % vars ()
1489 substr += self.output_info ()
1490 if LILYQUOTE in self.option_dict:
1491 substr = output[TEXINFO][QUOTE] % {'str':substr}
1494 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1495 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1496 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1498 if QUOTE in self.option_dict:
1499 str = output[TEXINFO][QUOTE] % vars ()
1501 # need par after image
1506 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1507 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1509 class LilypondFileSnippet (LilypondSnippet):
1510 def __init__ (self, type, match, format, line_number):
1511 LilypondSnippet.__init__ (self, type, match, format, line_number)
1512 self.contents = file (find_file (self.substring ('filename'))).read ()
1516 s = re_begin_verbatim.split (s)[-1]
1517 s = re_end_verbatim.split (s)[0]
1518 if not NOGETTEXT in self.option_dict:
1519 s = verb_ly_gettext (s)
1520 if not s.endswith ('\n'):
1525 name = self.substring ('filename')
1526 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1527 % (name, self.contents))
1530 class LilyPondVersionString (Snippet):
1531 """A string that does not require extra memory."""
1532 def __init__ (self, type, match, format, line_number):
1533 Snippet.__init__ (self, type, match, format, line_number)
1535 def replacement_text (self):
1536 return output[self.format][self.type]
1539 snippet_type_to_class = {
1540 'lilypond_file': LilypondFileSnippet,
1541 'lilypond_block': LilypondSnippet,
1542 'lilypond': LilypondSnippet,
1543 'include': IncludeSnippet,
1544 'lilypondversion': LilyPondVersionString,
1547 def find_linestarts (s):
1552 i = s.find ('\n', start)
1560 nls.append (len (s))
1563 def find_toplevel_snippets (input_string, format, types):
1566 res[t] = re.compile (snippet_res[format][t])
1570 found = dict ([(t, None) for t in types])
1572 line_starts = find_linestarts (input_string)
1574 # We want to search for multiple regexes, without searching
1575 # the string multiple times for one regex.
1576 # Hence, we use earlier results to limit the string portion
1578 # Since every part of the string is traversed at most once for
1579 # every type of snippet, this is linear.
1585 if not found[type] or found[type][0] < index:
1588 m = res[type].search (input_string[index:endex])
1593 if type in snippet_type_to_class:
1594 klass = snippet_type_to_class[type]
1596 start = index + m.start ('match')
1597 line_number = line_start_idx
1598 while (line_starts[line_number] < start):
1602 snip = klass (type, m, format, line_number)
1604 found[type] = (start, snip)
1608 or found[type][0] < found[first][0])):
1613 # Limiting the search space is a cute
1614 # idea, but this *requires* to search
1615 # for possible containing blocks
1616 # first, at least as long as we do not
1617 # search for the start of blocks, but
1618 # always/directly for the entire
1619 # @block ... @end block.
1621 endex = found[first][0]
1624 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1627 while (start > line_starts[line_start_idx+1]):
1630 (start, snip) = found[first]
1631 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1632 snippets.append (snip)
1634 index = start + len (snip.match.group ('match'))
1638 def filter_pipe (input, cmd):
1639 """Pass input through cmd, and return the result."""
1641 if global_options.verbose:
1642 progress (_ ("Opening filter `%s'") % cmd)
1644 (stdin, stdout, stderr) = os.popen3 (cmd)
1646 status = stdin.close ()
1650 output = stdout.read ()
1651 status = stdout.close ()
1652 error = stderr.read ()
1656 signal = 0x0f & status
1657 if status or (not output and error):
1658 exit_status = status >> 8
1659 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1660 error (_ ("The error log is as follows:"))
1661 ly.stderr_write (error)
1662 ly.stderr_write (stderr.read ())
1665 if global_options.verbose:
1670 def system_in_directory (cmd, directory):
1671 """Execute a command in a different directory.
1673 Because of win32 compatibility, we can't simply use subprocess.
1676 current = os.getcwd()
1677 os.chdir (directory)
1678 ly.system(cmd, be_verbose=global_options.verbose,
1683 def process_snippets (cmd, snippets,
1684 format, lily_output_dir):
1685 """Run cmd on all of the .ly files from snippets."""
1690 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1691 cmd += ' --formats=png '
1692 elif format in (DOCBOOK) and '--formats' not in cmd:
1693 cmd += ' --formats=png,pdf '
1695 checksum = snippet_list_checksum (snippets)
1696 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1697 + [snip.basename() + '.ly' for snip in snippets])
1698 name = os.path.join (lily_output_dir,
1699 'snippet-names-%d.ly' % checksum)
1700 file (name, 'wb').write (contents)
1702 system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1707 # Retrieve dimensions from LaTeX
1708 LATEX_INSPECTION_DOCUMENT = r'''
1712 \typeout{textwidth=\the\textwidth}
1713 \typeout{columnsep=\the\columnsep}
1714 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1718 # Do we need anything else besides `textwidth'?
1719 def get_latex_textwidth (source):
1720 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1722 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1724 ## what's a sensible default?
1727 preamble = source[:m.start (0)]
1728 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1730 (handle, tmpfile) = tempfile.mkstemp('.tex')
1731 logfile = os.path.splitext (tmpfile)[0] + '.log'
1732 logfile = os.path.split (logfile)[1]
1734 tmp_handle = os.fdopen (handle,'w')
1735 tmp_handle.write (latex_document)
1738 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1739 be_verbose=global_options.verbose)
1740 parameter_string = file (logfile).read()
1746 m = re.search ('columns=([0-9.]+)', parameter_string)
1748 columns = int (m.group (1))
1751 m = re.search ('columnsep=([0-9.]+)pt', parameter_string)
1753 columnsep = float (m.group (1))
1756 m = re.search ('textwidth=([0-9.]+)pt', parameter_string)
1758 textwidth = float (m.group (1))
1760 textwidth = (textwidth - columnsep) / columns
1764 def modify_preamble (chunk):
1765 str = chunk.replacement_text ()
1766 if (re.search (r"\\begin *{document}", str)
1767 and not re.search ("{graphic[sx]", str)):
1768 str = re.sub (r"\\begin{document}",
1769 r"\\usepackage{graphics}" + '\n'
1770 + r"\\begin{document}",
1772 chunk.override_text = str
1777 # TEXINFO: '.texinfo',
1783 class CompileError(Exception):
1786 def snippet_list_checksum (snippets):
1787 return hash (' '.join([l.basename() for l in snippets]))
1789 def write_file_map (lys, name):
1790 snippet_map = file (os.path.join (
1791 global_options.lily_output_dir,
1792 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1794 snippet_map.write ("""
1795 #(define version-seen #t)
1796 #(define output-empty-score-list #f)
1797 #(ly:add-file-name-alist '(%s
1799 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1802 def split_output_files(directory):
1803 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1805 Return value is a set of strings.
1808 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1809 base_subdir = os.path.split (subdir)[1]
1810 sub_files = [os.path.join (base_subdir, name)
1811 for name in os.listdir (subdir)]
1815 def do_process_cmd (chunks, input_name, options):
1816 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1818 output_files = split_output_files (options.lily_output_dir)
1819 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1821 write_file_map (outdated, input_name)
1822 progress (_ ("Writing snippets..."))
1823 for snippet in outdated:
1828 progress (_ ("Processing..."))
1830 process_snippets (options.process_cmd, outdated,
1831 options.format, options.lily_output_dir)
1834 progress (_ ("All snippets are up to date..."))
1836 if options.lily_output_dir != options.output_dir:
1837 output_files = split_output_files (options.lily_output_dir)
1838 for snippet in snippets:
1839 snippet.link_all_output_files (options.lily_output_dir,
1847 # Format guessing data
1856 '.texinfo': TEXINFO,
1861 def guess_format (input_filename):
1863 e = os.path.splitext (input_filename)[1]
1866 format = ext2format[e]
1868 error (_ ("cannot determine format for: %s"
1873 def write_if_updated (file_name, lines):
1875 f = file (file_name)
1877 new_str = ''.join (lines)
1878 if oldstr == new_str:
1879 progress (_ ("%s is up to date.") % file_name)
1882 # this prevents make from always rerunning lilypond-book:
1883 # output file must be touched in order to be up to date
1884 os.utime (file_name, None)
1889 output_dir = os.path.dirname (file_name)
1890 if not os.path.exists (output_dir):
1891 os.makedirs (output_dir)
1893 progress (_ ("Writing `%s'...") % file_name)
1894 file (file_name, 'w').writelines (lines)
1898 def note_input_file (name, inputs=[]):
1899 ## hack: inputs is mutable!
1900 inputs.append (name)
1903 def samefile (f1, f2):
1905 return os.path.samefile (f1, f2)
1906 except AttributeError: # Windoze
1907 f1 = re.sub ("//*", "/", f1)
1908 f2 = re.sub ("//*", "/", f2)
1911 def do_file (input_filename, included=False):
1913 if not input_filename or input_filename == '-':
1914 in_handle = sys.stdin
1915 input_fullname = '<stdin>'
1917 if os.path.exists (input_filename):
1918 input_fullname = input_filename
1919 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1920 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1922 input_fullname = find_file (input_filename)
1924 note_input_file (input_fullname)
1925 in_handle = file (input_fullname)
1927 if input_filename == '-':
1928 input_base = 'stdin'
1930 input_base = os.path.splitext (input_filename)[0]
1932 input_base = os.path.basename (
1933 os.path.splitext (input_filename)[0])
1935 # don't complain when global_options.output_dir is existing
1936 if not global_options.output_dir:
1937 global_options.output_dir = os.getcwd()
1939 global_options.output_dir = os.path.abspath(global_options.output_dir)
1941 if not os.path.isdir (global_options.output_dir):
1942 os.mkdir (global_options.output_dir, 0777)
1943 os.chdir (global_options.output_dir)
1945 output_filename = os.path.join(global_options.output_dir,
1946 input_base + format2ext[global_options.format])
1947 if (os.path.exists (input_filename)
1948 and os.path.exists (output_filename)
1949 and samefile (output_filename, input_fullname)):
1951 _ ("Output would overwrite input file; use --output."))
1955 progress (_ ("Reading %s...") % input_fullname)
1956 source = in_handle.read ()
1959 set_default_options (source, default_ly_options, global_options.format)
1962 # FIXME: Containing blocks must be first, see
1963 # find_toplevel_snippets.
1965 'multiline_comment',
1969 'singleline_comment',
1975 progress (_ ("Dissecting..."))
1976 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1978 if global_options.format == LATEX:
1980 if (c.is_plain () and
1981 re.search (r"\\begin *{document}", c.replacement_text())):
1986 if global_options.filter_cmd:
1987 write_if_updated (output_filename,
1988 [c.filter_text () for c in chunks])
1989 elif global_options.process_cmd:
1990 do_process_cmd (chunks, input_fullname, global_options)
1991 progress (_ ("Compiling %s...") % output_filename)
1993 write_if_updated (output_filename,
1994 [s.replacement_text ()
1997 def process_include (snippet):
1998 os.chdir (original_dir)
1999 name = snippet.substring ('filename')
2000 progress (_ ("Processing include: %s") % name)
2002 return do_file (name, included=True)
2004 include_chunks = map (process_include,
2005 filter (lambda x: isinstance (x, IncludeSnippet),
2008 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
2010 except CompileError:
2011 os.chdir (original_dir)
2012 progress (_ ("Removing `%s'") % output_filename)
2017 global global_options
2019 opt_parser = get_option_parser()
2020 (global_options, args) = opt_parser.parse_args ()
2021 if global_options.format in ('texi-html', 'texi'):
2022 global_options.format = TEXINFO
2024 global_options.include_path = map (os.path.abspath, global_options.include_path)
2026 if global_options.warranty:
2029 if not args or len (args) > 1:
2030 opt_parser.print_help ()
2036 # FIXME: 85 lines of `main' macramee??
2037 files = do_options ()
2039 basename = os.path.splitext (files[0])[0]
2040 basename = os.path.split (basename)[1]
2042 if not global_options.format:
2043 global_options.format = guess_format (files[0])
2046 if global_options.format in (TEXINFO, HTML, DOCBOOK):
2049 if global_options.process_cmd == '':
2050 global_options.process_cmd = (lilypond_binary
2051 + ' --formats=%s -dbackend=eps ' % formats)
2053 if global_options.process_cmd:
2054 includes = global_options.include_path
2055 if global_options.lily_output_dir:
2056 # This must be first, so lilypond prefers to read .ly
2057 # files in the other lybookdb dir.
2058 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
2059 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
2062 if global_options.format in (TEXINFO, LATEX):
2063 ## prevent PDF from being switched on by default.
2064 global_options.process_cmd += ' --formats=eps '
2065 if global_options.create_pdf:
2066 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
2068 if global_options.verbose:
2069 global_options.process_cmd += " --verbose "
2071 if global_options.padding_mm:
2072 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
2074 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
2076 if global_options.lily_output_dir:
2077 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
2078 if not os.path.isdir (global_options.lily_output_dir):
2079 os.makedirs (global_options.lily_output_dir)
2081 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
2086 chunks = do_file (files[0])
2087 except CompileError:
2090 inputs = note_input_file ('')
2093 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
2094 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
2095 final_output_file = os.path.join (global_options.output_dir,
2097 + '.%s' % global_options.format)
2099 os.chdir (original_dir)
2100 file (dep_file, 'w').write ('%s: %s'
2101 % (final_output_file, ' '.join (inputs)))
2103 if __name__ == '__main__':