]> git.lyx.org Git - lyx.git/blob - lib/scripts/layout2layout.py
*lib/scripts/layout2layout.py: Fix section labelling
[lyx.git] / lib / scripts / layout2layout.py
1 #! /usr/bin/env python
2 # -*- coding: iso-8859-1 -*-
3
4 # file layout2layout.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
7
8 # author Georg Baum
9
10 # Full author contact details are available in file CREDITS
11
12 # This script will update a .layout file to format 2
13
14
15 import os, re, string, sys
16
17
18 def usage(prog_name):
19     return ("Usage: %s inputfile outputfile\n" % prog_name +
20             "or     %s <inputfile >outputfile" % prog_name)
21
22
23 def error(message):
24     sys.stderr.write(message + '\n')
25     sys.exit(1)
26
27
28 def trim_eol(line):
29     " Remove end of line char(s)."
30     if line[-2:-1] == '\r':
31         return line[:-2]
32     elif line[-1:] == '\r' or line[-1:] == '\n':
33         return line[:-1]
34     else:
35         # file with no EOL in last line
36         return line
37
38
39 def read(input):
40     " Read input file and strip lineendings."
41     lines = list()
42     while 1:
43         line = input.readline()
44         if not line:
45             break
46         lines.append(trim_eol(line))
47     return lines
48
49
50 def write(output, lines):
51     " Write output file with native lineendings."
52     for line in lines:
53         output.write(line + os.linesep)
54
55
56 # Concatenates old and new in an intelligent way:
57 # If old is wrapped in ", they are stripped. The result is wrapped in ".
58 def concatenate_label(old, new):
59     # Don't use strip as long as we support python 1.5.2
60     if old[0] == '"':
61         return old[0:-1] + new + '"'
62     else:
63         return '"' + old + new + '"'
64
65
66 def convert(lines):
67     " Convert to new format."
68     re_Comment = re.compile(r'^(\s*)#')
69     re_Empty = re.compile(r'^(\s*)$')
70     re_Format = re.compile(r'^(\s*)(Format)(\s+)(\S+)', re.IGNORECASE)
71     re_Preamble = re.compile(r'^(\s*)Preamble', re.IGNORECASE)
72     re_EndPreamble = re.compile(r'^(\s*)EndPreamble', re.IGNORECASE)
73     re_MaxCounter = re.compile(r'^(\s*)(MaxCounter)(\s+)(\S+)', re.IGNORECASE)
74     re_LabelType = re.compile(r'^(\s*)(LabelType)(\s+)(\S+)', re.IGNORECASE)
75     re_LabelString = re.compile(r'^(\s*)(LabelString)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
76     re_LabelStringAppendix = re.compile(r'^(\s*)(LabelStringAppendix)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
77     re_LatexType = re.compile(r'^(\s*)(LatexType)(\s+)(\S+)', re.IGNORECASE)
78     re_Style = re.compile(r'^(\s*)(Style)(\s+)(\S+)', re.IGNORECASE)
79     re_End = re.compile(r'^(\s*)(End)(\s*)$', re.IGNORECASE)
80
81     # counters for sectioning styles (hardcoded in 1.3)
82     counters = {"part"          : "\\Roman{part}",
83                 "chapter"       : "\\arabic{chapter}",
84                 "section"       : "\\arabic{section}",
85                 "subsection"    : "\\arabic{section}.\\arabic{subsection}",
86                 "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
87                 "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
88                 "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
89
90     # counters for sectioning styles in appendix (hardcoded in 1.3)
91     appendixcounters = {"chapter"       : "\\Alph{chapter}",
92                         "section"       : "\\Alph{section}",
93                         "subsection"    : "\\arabic{section}.\\arabic{subsection}",
94                         "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
95                         "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
96                         "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
97
98     # Value of TocLevel for sectioning styles
99     toclevels = {"part"          : 0,
100                  "chapter"       : 0,
101                  "section"       : 1,
102                  "subsection"    : 2,
103                  "subsubsection" : 3,
104                  "paragraph"     : 4,
105                  "subparagraph"  : 5}
106
107     i = 0
108     only_comment = 1
109     counter = ""
110     label = ""
111     labelstring = ""
112     labelstringappendix = ""
113     space1 = ""
114     labelstring_line = -1
115     labelstringappendix_line = -1
116     labeltype_line = -1
117     latextype_line = -1
118     style = ""
119     maxcounter = 0
120     while i < len(lines):
121
122         # Skip comments and empty lines
123         if re_Comment.match(lines[i]) or re_Empty.match(lines[i]):
124             i = i + 1
125             continue
126
127         # insert file format if not already there
128         if (only_comment):
129                 match = re_Format.match(lines[i])
130                 if match:
131                         format = match.group(4)
132                         if format == '2':
133                                 # nothing to do
134                                 return
135                         error('Cannot convert file format %s' % format)
136                 else:
137                         lines.insert(i, "Format 2")
138                         only_comment = 0
139                         continue
140
141         # Don't get confused by LaTeX code
142         if re_Preamble.match(lines[i]):
143             i = i + 1
144             while i < len(lines) and not re_EndPreamble.match(lines[i]):
145                 i = i + 1
146             continue
147
148         # Delete MaxCounter and remember the value of it
149         match = re_MaxCounter.match(lines[i])
150         if match:
151             level = match.group(4)
152             if string.lower(level) == "counter_chapter":
153                 maxcounter = 0
154             elif string.lower(level) == "counter_section":
155                 maxcounter = 1
156             elif string.lower(level) == "counter_subsection":
157                 maxcounter = 2
158             elif string.lower(level) == "counter_subsubsection":
159                 maxcounter = 3
160             elif string.lower(level) == "counter_paragraph":
161                 maxcounter = 4
162             elif string.lower(level) == "counter_subparagraph":
163                 maxcounter = 5
164             elif string.lower(level) == "counter_enumi":
165                 maxcounter = 6
166             elif string.lower(level) == "counter_enumii":
167                 maxcounter = 7
168             elif string.lower(level) == "counter_enumiii":
169                 maxcounter = 8
170             del lines[i]
171             continue
172
173         # Replace line
174         #
175         # LabelType Counter_EnumI
176         #
177         # with two lines
178         #
179         # LabelType Counter
180         # LabelCounter EnumI
181         #
182         match = re_LabelType.match(lines[i])
183         if match:
184             label = match.group(4)
185             # Remember indenting space for later reuse in added lines
186             space1 = match.group(1)
187             # Remember the line for adding the LabelCounter later.
188             # We can't do it here because it could shift latextype_line etc.
189             labeltype_line = i
190             if string.lower(label[:8]) == "counter_":
191                 counter = string.lower(label[8:])
192                 lines[i] = re_LabelType.sub(r'\1\2\3Counter', lines[i])
193
194         # Remember the LabelString line
195         match = re_LabelString.match(lines[i])
196         if match:
197             labelstring = match.group(4)
198             labelstring_line = i
199
200         # Remember the LabelStringAppendix line
201         match = re_LabelStringAppendix.match(lines[i])
202         if match:
203             labelstringappendix = match.group(4)
204             labelstringappendix_line = i
205
206         # Remember the LatexType line
207         match = re_LatexType.match(lines[i])
208         if match:
209             latextype_line = i
210
211         # Reset variables at the beginning of a style definition
212         match = re_Style.match(lines[i])
213         if match:
214             style = string.lower(match.group(4))
215             counter = ""
216             label = ""
217             space1 = ""
218             labelstring = ""
219             labelstringappendix = ""
220             labelstring_line = -1
221             labelstringappendix_line = -1
222             labeltype_line = -1
223             latextype_line = -1
224
225         if re_End.match(lines[i]):
226
227             # Add a line "LatexType Bib_Environment" if LabelType is Bibliography
228             # (or change the existing LatexType)
229             if string.lower(label) == "bibliography":
230                 if (latextype_line < 0):
231                     lines.insert(i, "%sLatexType Bib_Environment" % space1)
232                     i = i + 1
233                 else:
234                     lines[latextype_line] = re_LatexType.sub(r'\1\2\3Bib_Environment', lines[latextype_line])
235
236             # Replace
237             #
238             # LabelString "Chapter"
239             #
240             # with
241             #
242             # LabelString "Chapter \arabic{chapter}"
243             #
244             # if this style has a counter. Ditto for LabelStringAppendix.
245             # This emulates the hardcoded article style numbering of 1.3
246             #
247             if counter != "":
248                 if counters.has_key(style):
249                     if labelstring_line < 0:
250                         lines.insert(i, '%sLabelString "%s"' % (space1, counters[style]))
251                         i = i + 1
252                     else:
253                         new_labelstring = concatenate_label(labelstring, counters[style])
254                         lines[labelstring_line] = re_LabelString.sub(
255                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
256                                 lines[labelstring_line])
257                 if appendixcounters.has_key(style):
258                     if labelstringappendix_line < 0:
259                         lines.insert(i, '%sLabelStringAppendix "%s"' % (space1, appendixcounters[style]))
260                         i = i + 1
261                     else:
262                         new_labelstring = concatenate_label(labelstring, appendixcounters[style])
263                         lines[labelstringappendix_line] = re_LabelStringAppendix.sub(
264                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
265                                 lines[labelstringappendix_line])
266
267                 # Now we can safely add the LabelCounter line
268                 lines.insert(labeltype_line + 1, "%sLabelCounter %s" % (space1, counter))
269                 i = i + 1
270
271             # Add the TocLevel setting for sectioning styles
272             if toclevels.has_key(style) and maxcounter <= toclevels[style]:
273                 lines.insert(i, '%sTocLevel %d' % (space1, toclevels[style]))
274                 i = i + 1
275
276         i = i + 1
277
278
279 def main(argv):
280
281     # Open files
282     if len(argv) == 1:
283         input = sys.stdin
284         output = sys.stdout
285     elif len(argv) == 3:
286         input = open(argv[1], 'rb')
287         output = open(argv[2], 'wb')
288     else:
289         error(usage(argv[0]))
290
291     # Do the real work
292     lines = read(input)
293     convert(lines)
294     write(output, lines)
295
296     # Close files
297     if len(argv) == 3:
298         input.close()
299         output.close()
300
301     return 0
302
303
304 if __name__ == "__main__":
305     main(sys.argv)