Debian Codegraph @

texmf-dist/doc/latex/songproj/song2tex.py

raw
1 #!/usr/bin/env python3
2
3 import argparse
4 import enum
5 import re
6
7
8 # The following regexp match the typical markers of refrain and couplet:
9 re_refrain = re.compile(r'(R(efrain)?|C(horus)?)( |[-./] ?)', re.IGNORECASE)
10 re_couplet = re.compile(r'\d+( |[-./] ?)')
11 re_txt_ext = re.compile(r'\.te?xt$')
12
13
14 def match_rest(regexp, s):
15 """Match the start of string s against the given regexp:
16 * if it matches, return the non-matching part;
17 * it it does not matches, return None."""
18 if (m := regexp.match(s)) is not None:
19 return s[m.end():]
20 else:
21 return None
22
23
24 class State(enum.Enum):
25 """A state indicates in what context we are while parsing a song."""
26 LIMBO = 0 # Not in the refrain or in a couplet
27 REFRAIN = 1 # In the refrain
28 COUPLET = 2 # In a couplet
29
30
31 def parse_song(lines, re_refrain, re_couplet):
32 # At the beginning of the song, we are not in the refrain or in a couplet.
33 state = State.LIMBO
34 # This variable will be used to record the longest line seen so far.
35 longest = ''
36 for line in lines:
37 line = line.rstrip()
38 if state == State.LIMBO:
39 # We are not in the refrain or in a couplet. Depending on what we find:
40 if (rest := match_rest(re_refrain, line)) is not None:
41 # when a refrain start marker is found, enter the refrain.
42 yield '\\begin{refrain}\n'
43 state = State.REFRAIN
44 line = rest
45 yield ' {}'.format(line)
46 elif (rest := match_rest(re_couplet, line)) is not None:
47 # when a couplet start marker is found, enter a couplet.
48 yield '\\begin{couplet}\n'
49 state = State.COUPLET
50 line = rest
51 yield ' {}'.format(line)
52 elif line != '':
53 # when a non-empty line is found, also enter a couplet as all.
54 yield '\\begin{couplet}\n'
55 state = State.COUPLET
56 yield ' {}'.format(line)
57 elif state == State.REFRAIN:
58 # We are in the refrain. Depending on what we find:
59 if line != '':
60 # when a non-empty line is found, stay in the refrain.
61 yield ' \\\\\n {}'.format(line)
62 else:
63 # when an empty line is found, leave the refrain.
64 yield '\n\\end{refrain}\n\n'
65 state = State.LIMBO
66 elif state == State.COUPLET:
67 # We are in a couplet. Depending on what we find:
68 if line != '':
69 # when a non-empty line is found, stay in the couplet.
70 yield ' \\\\\n {}'.format(line)
71 else:
72 # when an empty line is found, leave the couplet.
73 yield '\n\\end{couplet}\n\n'
74 state = State.LIMBO
75 # No matter what we found, we have a song line, possibly empty, that we
76 # have to check to see if it could not be the new longest line seen so far.
77 if len(line) > len(longest):
78 longest = line
79 # The song text file is now finished. We may still be in the refrain or in a
80 # couplet, that we have to close.
81 if state == State.REFRAIN:
82 yield '\n\\end{refrain}\n\n'
83 elif state == State.COUPLET:
84 yield '\n\\end{couplet}\n\n'
85 # Now print the longest line of the entire song.
86 yield '\\longest{{{}}}\n'.format(longest)
87
88
89 def main(args=None):
90 parser = argparse.ArgumentParser(description="Convert song text to LaTeX songproj markup")
91 parser.add_argument("--refrain", '-r', type=re.compile, default=re_refrain, metavar="REGEXP",
92 help="specify the refrain marker (regexp, default to \"{}\")".format(re_refrain.pattern))
93 parser.add_argument("--couplet", '-c', type=re.compile, default=re_couplet, metavar="REGEXP",
94 help="specify the couplet marker (regexp, default \"{}\")".format(re_couplet.pattern))
95 parser.add_argument("infile", help="input song text file", type=argparse.FileType('r'))
96 parser.add_argument("outfile", help="output LaTeX file", type=argparse.FileType('w'), nargs='?')
97 args = parser.parse_args(args)
98 if args.outfile is None:
99 try:
100 args.outfile = open(re_txt_ext.sub('', args.infile.name) + '.tex', 'w')
101 except AttributeError:
102 parser.error("the following argument is required: outfile")
103 for line in parse_song(args.infile, args.refrain, args.couplet):
104 args.outfile.write(line)
105
106 if __name__ == "__main__":
107 main()