#!@PYTHON@
# run lily, setup LaTeX input.
-""" TODO: --dependencies
+# Note: gettext work best if we use ' for docstrings and "
+# for gettextable strings
-"""
+'''
+TODO:
+
+ * check --dependencies
+
+ * move versatile taglines,
+
+ \header {
+ beginfooter=\mutopiaPD
+ endfooter=\tagline -> 'lily was here <version>'
+ }
+
+ * head/header tagline/endfooter
+
+ * dvi from lilypond .tex output? This is hairy, because we create dvi
+ from lilypond .tex *and* header output.
+
+'''
import os
import operator
import tempfile
+sys.path.append ('@datadir@/python')
+import gettext
+gettext.bindtextdomain ('lilypond', '@localedir@')
+gettext.textdomain('lilypond')
+_ = gettext.gettext
+
layout_fields = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
'language' : [],
'latexheaders' : [],
'latexpackages' : ['geometry'],
- 'papersizename' : [],
- 'pagenumber' : [],
+ 'papersize' : [],
+ 'pagenumber' : [1],
'textheight' : [],
'linewidth' : [],
'orientation' : []
postscript_p = 0
option_definitions = [
- ('', 'h', 'help', 'print help'),
- ('KEY=VAL', 's', 'set', 'change global setting KEY to VAL'),
- ('', 'P', 'postscript', 'Generate PostScript output'),
- ('', 'k', 'keep', 'Keep all output, and name the directory ly2dvi.dir'),
- ('', '', 'no-lily', 'Don\'t run lilypond'),
- ('', 'v', 'version', "Print version and copyright info"),
- ('DIR', '', 'outdir', 'Dump all final output into DIR'),
- ('', 'd', 'dependencies', 'Dump all final output into DIR'),
+ ('', 'h', 'help', _ ("this help")),
+ ('KEY=VAL', 's', 'set', _ ("change global setting KEY to VAL")),
+ ('', 'P', 'postscript', _ ("generate PostScript output")),
+ ('', 'k', 'keep', _ ("keep all output, and name the directory ly2dvi.dir")),
+ ('', '', 'no-lily', _ ("don't run LilyPond")),
+ ('', 'v', 'version', _ ("print version number")),
+ ('', 'w', 'warranty', _ ("show warranty and copyright")),
+ ('DIR', '', 'outdir', _ ("dump all final output into DIR")),
+ ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
]
-
-
-def identify():
- sys.stdout.write ('lilypond-book (GNU LilyPond) %s\n' % program_version)
-
-def print_version ():
- identify()
- sys.stdout.write (r"""Copyright 1998--1999
+def identify ():
+ sys.stdout.write ('ly2dvi (GNU LilyPond) %s\n' % program_version)
+
+def warranty ():
+ identify ()
+ sys.stdout.write ('\n')
+ sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998-2001'))
+ sys.stdout.write ('\n')
+ sys.stdout.write (' Han-Wen Nienhuys')
+ sys.stdout.write ('\n')
+ sys.stdout.write (_ (r'''
Distributed under terms of the GNU General Public License. It comes with
-NO WARRANTY.""")
+NO WARRANTY.'''))
+ sys.stdout.write ('\n')
def progress (s):
- """Make the progress messages stand out between lilypond stuff"""
- sys.stderr.write (' *** ' + s+ '\n')
+ '''Make the progress messages stand out between lilypond stuff'''
+ # Why should they have to stand out? Blend in would be nice too.
+ sys.stderr.write ('*** ' + s+ '\n')
+
+def warning (s):
+ sys.stderr.write (_ ("warning: ") + s)
+ sys.stderr.write ('\n')
+
def error (s):
- sys.stderr.write (s)
- raise 'Exiting ... '
+ sys.stderr.write (_ ("error: ") + s)
+ sys.stderr.write ('\n')
+ raise _ ("Exiting ... ")
def find_file (name):
- """
+ '''
Search the include path for NAME. If found, return the (CONTENTS, PATH) of the file.
- """
+ '''
f = None
nm = ''
except IOError:
pass
if f:
- sys.stderr.write ("Reading `%s'\n" % nm)
+ sys.stderr.write (_ ("Reading `%s'") % nm)
+ sys.stderr.write ('\n');
return (f.read (), nm)
else:
- error ("File not found `%s'\n" % name)
+ error (_ ("can't open file: `%s'" % name))
+ sys.stderr.write ('\n');
return ('', '')
def getopt_args (opts):
- "Construct arguments (LONG, SHORT) for getopt from list of options."
+ '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
short = ''
long = []
for o in opts:
return (short, long)
def option_help_str (o):
- "Transform one option description (4-tuple ) into neatly formatted string"
+ '''Transform one option description (4-tuple ) into neatly formatted string'''
sh = ' '
if o[1]:
sh = '-%s' % o[1]
def options_help_str (opts):
- "Convert a list of options into a neatly formatted string"
+ '''Convert a list of options into a neatly formatted string'''
w = 0
strs =[]
helps = []
str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
return str
-def help():
- sys.stdout.write("""Usage: lyvi [options] FILE\n
-Generate .dvi with LaTeX for lilypond
-Options:
-""")
+def help ():
+ sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % 'ly2dvi')
+ sys.stdout.write ('\n\n')
+ sys.stdout.write (_ ("Generate .dvi with LaTeX for LilyPond"))
+ sys.stdout.write ('\n\n')
+ sys.stdout.write (_ ("Options:"))
+ sys.stdout.write ('\n')
sys.stdout.write (options_help_str (option_definitions))
- sys.stdout.write (r"""Warning all output is written in the CURRENT directory
-
-
-
-Report bugs to bug-gnu-music@gnu.org.
-
-Written by
-Han-Wen Nienhuys <hanwen@cs.uu.nl>
-""")
-
+ sys.stdout.write ('\n\n')
+ warning (_ ("all output is written in the CURRENT directory"))
+ sys.stdout.write ('\n')
+ sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
+ sys.stdout.write ('\n')
sys.exit (0)
temp_dir = tempfile.mktemp ('ly2dvi')
try:
- os.mkdir (temp_dir)
+ os.mkdir (temp_dir, 0777)
except OSError:
pass
os.environ['TFMFONTS'] = original_dir + fp
os.chdir (temp_dir)
- progress ('Temp directory is `%s\'\n' % temp_dir)
+ progress (_ ('Temp directory is `%s\'\n') % temp_dir)
def system (cmd, ignore_error = 0):
- sys.stderr.write ("invoking `%s\'\n" % cmd)
+ sys.stderr.write (_ ("Invoking `%s\'") % cmd)
+ sys.stderr.write ('\n')
st = os.system (cmd)
if st:
- msg = ('Error command exited with value %d' % st)
+ msg = ( _ ("error: ") + _ ("command exited with value %d") % st)
if ignore_error:
- sys.stderr.write (msg + ' (ignored)\n')
+ sys.stderr.write (msg + ' ' + _ ("(ignored)") + ' ')
else:
error (msg)
def cleanup_temp ():
if not keep_temp_dir:
- progress ('Cleaning up `%s\'' % temp_dir)
+ progress (_ ('Cleaning up `%s\'') % temp_dir)
system ('rm -rf %s' % temp_dir)
try:
val = string.atof (val)
except ValueError:
+ #warning (_ ("invalid value: %s") % `val`)
pass
try:
dict[key].append (val)
except KeyError:
+ warning (_ ("no such setting: %s") % `key`)
dict[key] = [val]
def analyse_lilypond_output (filename, extra):
- """Grep FILENAME for interesting stuff, and
- put relevant info into EXTRA."""
+ '''Grep FILENAME for interesting stuff, and
+ put relevant info into EXTRA.'''
filename = filename+'.tex'
- progress ("Analyzing `%s'" % filename)
+ progress (_ ("Analyzing `%s'") % filename)
s = open (filename).read ()
# search only the first 10k
s = s[:10240]
- for x in ('textheight', 'linewidth', 'papersizename', 'orientation'):
+ for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
if m:
set_setting (extra, x, m.group (1))
x = 0
while 1:
fname = os.path.basename (f)
- fname = os.path.splitext (fname)[0]
+ fname = strip_ly_suffix (fname)
if x:
fname = fname + '-%d' % x
else:
break
- x = x +1
+ x = x + 1
+ if not x:
+ warning (_ ("no lilypond output found for %s") % `files`)
return tfiles
def one_latex_definition (defn, first):
- s = ''
+ s = '\n'
for (k,v) in defn[1].items ():
- s = r"""\def\the%s{%s}""" % (k,open (v).read ())
+ val = open (v).read ()
+ if (string.strip (val)):
+ s = s + r'''\def\lilypond%s{%s}''' % (k, val)
+ else:
+ s = s + r'''\let\lilypond%s\relax''' % k
+ s = s + '\n'
if first:
- s = s + '\\makelilytitle\n'
+ s = s + '\\def\\mustmakelilypondtitle{}\n'
else:
- s = s + '\\makelilypiecetitle\n'
+ s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
s = s + '\\input %s' % defn[0]
return s
ly_paper_to_latexpaper = {
'a4' : 'a4paper',
-
+ 'letter' : 'letterpaper',
}
def global_latex_definition (tfiles, extra):
- """construct preamble from EXTRA,
+ '''construct preamble from EXTRA,
dump lily output files after that, and return result.
- """
+ '''
s = ""
paper = ''
- if extra['papersizename']:
- paper = '[%s]' % ly_paper_to_latexpaper[extra['papersizename'][0]]
+ if extra['papersize']:
+ try:
+ paper = '[%s]' % ly_paper_to_latexpaper[extra['papersize'][0]]
+ except:
+ warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
+ pass
+
s = s + '\\documentclass%s{article}\n' % paper
if extra['language']:
orientation = 'portrait'
if extra['orientation']:
orientation = extra['orientation'][0]
-
- s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (extra['linewidth'][0], textheight, orientation)
- s= s + r"""
-\usepackage[latin1]{inputenc}
+ # set sane geometry width (a4-width) for linewidth = -1.
+ linewidth = extra['linewidth'][0]
+ if linewidth < 0:
+ linewidth = 597
+ s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
+
+ s = s + r'''
+\usepackage[latin1]{inputenc}
\input{titledefs}
\makeatletter
-\renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%%
-"""
- if extra['pagenumber'] and extra['pagenumber'][-1]:
- s = s + r"""
- \renewcommand{\@oddhead}{\parbox{\textwidth}%%
- {\mbox{}\small\theheader\hfill\textbf{\thepage}}}%%"""
+\renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
+'''
+
+ if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
+ s = s + r'''
+\renewcommand{\@oddhead}{\parbox{\textwidth}%
+ {\mbox{}\small\theheader\hfill\textbf{\thepage}}}
+'''
else:
- s = s + '\\pagestyle{empty}'
-
- s = s + '\\begin{document}'
+ s = s + '\\pagestyle{empty}\n'
+
+ s = s + '\\makeatother\n'
+ s = s + '\\begin{document}\n'
+
first = 1
for t in tfiles:
s = s + one_latex_definition (t, first)
first = 0
-
+
+ s = s + r'''
+\makeatletter
+\renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\lilypondtagline}}%
+\makeatother
+'''
s = s + '\\end{document}'
return s
def do_files (fs, extra):
- """process the list of filenames in FS, using standard settings in EXTRA.
- """
+ '''process the list of filenames in FS, using standard settings in EXTRA.
+ '''
if not no_lily:
run_lilypond (fs)
return latex_file + '.dvi'
def generate_postscript (dvi_name, extra):
- """Run dvips on DVI_NAME, optionally doing -t landscape"""
+ '''Run dvips on DVI_NAME, optionally doing -t landscape'''
opts = ''
- if extra['papersizename']:
- opts = opts + ' -t %s' % extra['papersizename'][0]
+ if extra['papersize']:
+ opts = opts + ' -t %s' % extra['papersize'][0]
if extra['orientation'] and extra['orientation'][0] == 'landscape':
opts = opts + ' -t landscape'
df.close ();
(sh, long) = getopt_args (__main__.option_definitions)
-(options, files) = getopt.getopt(sys.argv[1:], sh, long)
+try:
+ (options, files) = getopt.getopt(sys.argv[1:], sh, long)
+except:
+ help ()
+ sys.exit (2)
+
for opt in options:
o = opt[0]
a = opt[1]
track_dependencies_p = 1
elif o == '--version' or o == '-v':
identify ()
+ sys.exit (0)
+ elif o == '--warranty' or o == '-w':
+ warranty ()
+ sys.exit (0)
include_path = map (os.path.abspath, include_path)
type = 'DVI'
dest = os.path.join (outdir, dest)
+ if outdir != '.':
+ system ('mkdir -p %s' % outdir)
system ('cp \"%s\" \"%s\"' % (srcname, dest ))
system ('cp *.midi %s' % outdir, ignore_error = 1)
- progress ("%s file left in `%s'\n" % (type, dest))
-
depfile = os.path.join (outdir, base + '.dep')
if track_dependencies_p:
generate_dependency_file (depfile, dest)
- progress ("Dependency file left in `%s'\n" % depfile)
+ os.chdir (original_dir)
cleanup_temp ()
+ # most insteresting info last
+ progress (_ ("dependencies output to %s...") % depfile)
+ progress (_ ("%s file left in `%s'") % (type, dest))
+
+