]> git.lyx.org Git - lyx.git/blob - lib/scripts/layout2layout.py
Fix bug 3220
[lyx.git] / lib / scripts / layout2layout.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
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 3
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_CopyStyle = re.compile(r'^(\s*)(CopyStyle)(\s+)(\S+)', re.IGNORECASE)
80     re_NoStyle = re.compile(r'^(\s*)(NoStyle)(\s+)(\S+)', re.IGNORECASE)
81     re_End = re.compile(r'^(\s*)(End)(\s*)$', re.IGNORECASE)
82
83     # counters for sectioning styles (hardcoded in 1.3)
84     counters = {"part"          : "\\Roman{part}",
85                 "chapter"       : "\\arabic{chapter}",
86                 "section"       : "\\arabic{section}",
87                 "subsection"    : "\\arabic{section}.\\arabic{subsection}",
88                 "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
89                 "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
90                 "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
91
92     # counters for sectioning styles in appendix (hardcoded in 1.3)
93     appendixcounters = {"chapter"       : "\\Alph{chapter}",
94                         "section"       : "\\Alph{section}",
95                         "subsection"    : "\\arabic{section}.\\arabic{subsection}",
96                         "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
97                         "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
98                         "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
99
100     # Value of TocLevel for sectioning styles
101     toclevels = {"part"          : 0,
102                  "chapter"       : 0,
103                  "section"       : 1,
104                  "subsection"    : 2,
105                  "subsubsection" : 3,
106                  "paragraph"     : 4,
107                  "subparagraph"  : 5}
108
109     i = 0
110     only_comment = 1
111     counter = ""
112     label = ""
113     labelstring = ""
114     labelstringappendix = ""
115     space1 = ""
116     labelstring_line = -1
117     labelstringappendix_line = -1
118     labeltype_line = -1
119     latextype = ""
120     latextype_line = -1
121     style = ""
122     maxcounter = 0
123     format = 1
124     while i < len(lines):
125
126         # Skip comments and empty lines
127         if re_Comment.match(lines[i]) or re_Empty.match(lines[i]):
128             i = i + 1
129             continue
130
131         # insert file format if not already there
132         if (only_comment):
133                 match = re_Format.match(lines[i])
134                 if match:
135                         format = int(match.group(4))
136                         if format == 2:
137                             lines[i] = "Format 3"
138                             only_comment = 0
139                         elif format == 3:
140                                 # nothing to do
141                                 return
142                         else:
143                             error('Cannot convert file format %s' % format)
144                 else:
145                         lines.insert(i, "Format 3")
146                         only_comment = 0
147                         continue
148
149         # Don't get confused by LaTeX code
150         if re_Preamble.match(lines[i]):
151             i = i + 1
152             while i < len(lines) and not re_EndPreamble.match(lines[i]):
153                 i = i + 1
154             continue
155
156         if format == 2:
157             caption = []
158
159             # delete caption styles
160             match = re_Style.match(lines[i])
161             if match:
162                 style = string.lower(match.group(4))
163                 if style == "caption":
164                     del lines[i]
165                     while i < len(lines) and not re_End.match(lines[i]):
166                         caption.append(lines[i])
167                         del lines[i]
168                     if i == len(lines):
169                         error('Incomplete caption style.')
170                     else:
171                         del lines[i]
172                         continue
173
174             # delete undefinition of caption styles
175             match = re_NoStyle.match(lines[i])
176             if match:
177                 style = string.lower(match.group(4))
178                 if style == "caption":
179                     del lines[i]
180                     continue
181
182             # replace the CopyStyle statement with the definition of the real
183             # style. This may result in duplicate statements, but that is OK
184             # since the second one will overwrite the first one.
185             match = re_CopyStyle.match(lines[i])
186             if match:
187                 style = string.lower(match.group(4))
188                 if style == "caption":
189                     if len(caption) > 0:
190                         lines[i:i+1] = caption
191                     else:
192                         # FIXME: This style comes from an include file, we
193                         # should replace the real style and not this default.
194                         lines[i:i+1] = ['       Margin                First_Dynamic',
195                                         '       LatexType             Command',
196                                         '       LatexName             caption',
197                                         '       NeedProtect           1',
198                                         '       LabelSep              xx',
199                                         '       ParSkip               0.4',
200                                         '       TopSep                0.5',
201                                         '       Align                 Center',
202                                         '       AlignPossible         Center',
203                                         '       LabelType             Sensitive',
204                                         '       LabelString           "Senseless!"',
205                                         '       OptionalArgs          1',
206                                         '       LabelFont',
207                                         '         Series              Bold',
208                                         '       EndFont']
209
210             i = i + 1
211             continue
212
213         # Delete MaxCounter and remember the value of it
214         match = re_MaxCounter.match(lines[i])
215         if match:
216             level = match.group(4)
217             if string.lower(level) == "counter_chapter":
218                 maxcounter = 0
219             elif string.lower(level) == "counter_section":
220                 maxcounter = 1
221             elif string.lower(level) == "counter_subsection":
222                 maxcounter = 2
223             elif string.lower(level) == "counter_subsubsection":
224                 maxcounter = 3
225             elif string.lower(level) == "counter_paragraph":
226                 maxcounter = 4
227             elif string.lower(level) == "counter_subparagraph":
228                 maxcounter = 5
229             elif string.lower(level) == "counter_enumi":
230                 maxcounter = 6
231             elif string.lower(level) == "counter_enumii":
232                 maxcounter = 7
233             elif string.lower(level) == "counter_enumiii":
234                 maxcounter = 8
235             del lines[i]
236             continue
237
238         # Replace line
239         #
240         # LabelType Counter_EnumI
241         #
242         # with two lines
243         #
244         # LabelType Counter
245         # LabelCounter EnumI
246         #
247         match = re_LabelType.match(lines[i])
248         if match:
249             label = match.group(4)
250             # Remember indenting space for later reuse in added lines
251             space1 = match.group(1)
252             # Remember the line for adding the LabelCounter later.
253             # We can't do it here because it could shift latextype_line etc.
254             labeltype_line = i
255             if string.lower(label[:8]) == "counter_":
256                 counter = string.lower(label[8:])
257                 lines[i] = re_LabelType.sub(r'\1\2\3Counter', lines[i])
258
259         # Remember the LabelString line
260         match = re_LabelString.match(lines[i])
261         if match:
262             labelstring = match.group(4)
263             labelstring_line = i
264
265         # Remember the LabelStringAppendix line
266         match = re_LabelStringAppendix.match(lines[i])
267         if match:
268             labelstringappendix = match.group(4)
269             labelstringappendix_line = i
270
271         # Remember the LatexType line
272         match = re_LatexType.match(lines[i])
273         if match:
274             latextype = string.lower(match.group(4))
275             latextype_line = i
276
277         # Reset variables at the beginning of a style definition
278         match = re_Style.match(lines[i])
279         if match:
280             style = string.lower(match.group(4))
281             counter = ""
282             label = ""
283             space1 = ""
284             labelstring = ""
285             labelstringappendix = ""
286             labelstring_line = -1
287             labelstringappendix_line = -1
288             labeltype_line = -1
289             latextype = ""
290             latextype_line = -1
291
292         if re_End.match(lines[i]):
293
294             # Add a line "LatexType Bib_Environment" if LabelType is Bibliography
295             # (or change the existing LatexType)
296             if string.lower(label) == "bibliography":
297                 if (latextype_line < 0):
298                     lines.insert(i, "%sLatexType Bib_Environment" % space1)
299                     i = i + 1
300                 else:
301                     lines[latextype_line] = re_LatexType.sub(r'\1\2\3Bib_Environment', lines[latextype_line])
302
303             # Change "LabelType Static" to "LabelType Itemize" for itemize environments
304             if latextype == "item_environment" and string.lower(label) == "static":
305                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Itemize', lines[labeltype_line])
306
307             # Change "LabelType Counter_EnumI" to "LabelType Enumerate" for enumerate environments
308             if latextype == "item_environment" and string.lower(label) == "counter_enumi":
309                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Enumerate', lines[labeltype_line])
310                 # Don't add the LabelCounter line later
311                 counter = ""
312
313             # Replace
314             #
315             # LabelString "Chapter"
316             #
317             # with
318             #
319             # LabelString "Chapter \arabic{chapter}"
320             #
321             # if this style has a counter. Ditto for LabelStringAppendix.
322             # This emulates the hardcoded article style numbering of 1.3
323             #
324             if counter != "":
325                 if counters.has_key(style):
326                     if labelstring_line < 0:
327                         lines.insert(i, '%sLabelString "%s"' % (space1, counters[style]))
328                         i = i + 1
329                     else:
330                         new_labelstring = concatenate_label(labelstring, counters[style])
331                         lines[labelstring_line] = re_LabelString.sub(
332                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
333                                 lines[labelstring_line])
334                 if appendixcounters.has_key(style):
335                     if labelstringappendix_line < 0:
336                         lines.insert(i, '%sLabelStringAppendix "%s"' % (space1, appendixcounters[style]))
337                         i = i + 1
338                     else:
339                         new_labelstring = concatenate_label(labelstring, appendixcounters[style])
340                         lines[labelstringappendix_line] = re_LabelStringAppendix.sub(
341                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
342                                 lines[labelstringappendix_line])
343
344                 # Now we can safely add the LabelCounter line
345                 lines.insert(labeltype_line + 1, "%sLabelCounter %s" % (space1, counter))
346                 i = i + 1
347
348             # Add the TocLevel setting for sectioning styles
349             if toclevels.has_key(style) and maxcounter <= toclevels[style]:
350                 lines.insert(i, '%sTocLevel %d' % (space1, toclevels[style]))
351                 i = i + 1
352
353         i = i + 1
354
355
356 def main(argv):
357
358     # Open files
359     if len(argv) == 1:
360         input = sys.stdin
361         output = sys.stdout
362     elif len(argv) == 3:
363         input = open(argv[1], 'rb')
364         output = open(argv[2], 'wb')
365     else:
366         error(usage(argv[0]))
367
368     # Do the real work
369     lines = read(input)
370     convert(lines)
371     write(output, lines)
372
373     # Close files
374     if len(argv) == 3:
375         input.close()
376         output.close()
377
378     return 0
379
380
381 if __name__ == "__main__":
382     main(sys.argv)