]> git.lyx.org Git - lyx.git/blob - lib/scripts/layout2layout.py
251492b42f8642633da815069209e7b84a951076
[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 6
13
14
15 import os, re, string, sys
16
17
18 # incremented 24 March 2008 by rgh
19 # AddToPreamble tag added to layout files
20 currentFormat = 7
21
22
23 def usage(prog_name):
24     return ("Usage: %s inputfile outputfile\n" % prog_name +
25             "or     %s <inputfile >outputfile" % prog_name)
26
27
28 def error(message):
29     sys.stderr.write(message + '\n')
30     sys.exit(1)
31
32
33 def trim_eol(line):
34     " Remove end of line char(s)."
35     if line[-2:-1] == '\r':
36         return line[:-2]
37     elif line[-1:] == '\r' or line[-1:] == '\n':
38         return line[:-1]
39     else:
40         # file with no EOL in last line
41         return line
42
43
44 def read(input):
45     " Read input file and strip lineendings."
46     lines = list()
47     while 1:
48         line = input.readline()
49         if not line:
50             break
51         lines.append(trim_eol(line))
52     return lines
53
54
55 def write(output, lines):
56     " Write output file with native lineendings."
57     for line in lines:
58         output.write(line + os.linesep)
59
60
61 # Concatenates old and new in an intelligent way:
62 # If old is wrapped in ", they are stripped. The result is wrapped in ".
63 def concatenate_label(old, new):
64     # Don't use strip as long as we support python 1.5.2
65     if old[0] == '"':
66         return old[0:-1] + new + '"'
67     else:
68         return '"' + old + new + '"'
69
70
71 def convert(lines):
72     " Convert to new format."
73     re_Comment = re.compile(r'^(\s*)#')
74     re_Empty = re.compile(r'^(\s*)$')
75     re_Format = re.compile(r'^(\s*)(Format)(\s+)(\S+)', re.IGNORECASE)
76     re_Preamble = re.compile(r'^(\s*)Preamble', re.IGNORECASE)
77     re_EndPreamble = re.compile(r'^(\s*)EndPreamble', re.IGNORECASE)
78     re_MaxCounter = re.compile(r'^(\s*)(MaxCounter)(\s+)(\S+)', re.IGNORECASE)
79     re_LabelType = re.compile(r'^(\s*)(LabelType)(\s+)(\S+)', re.IGNORECASE)
80     re_LabelString = re.compile(r'^(\s*)(LabelString)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
81     re_LabelStringAppendix = re.compile(r'^(\s*)(LabelStringAppendix)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
82     re_LatexType = re.compile(r'^(\s*)(LatexType)(\s+)(\S+)', re.IGNORECASE)
83     re_Style = re.compile(r'^(\s*)(Style)(\s+)(\S+)', re.IGNORECASE)
84     re_CopyStyle = re.compile(r'^(\s*)(CopyStyle)(\s+)(\S+)', re.IGNORECASE)
85     re_NoStyle = re.compile(r'^(\s*)(NoStyle)(\s+)(\S+)', re.IGNORECASE)
86     re_End = re.compile(r'^(\s*)(End)(\s*)$', re.IGNORECASE)
87     re_Provides = re.compile(r'^(\s*)Provides(\S+)(\s+)(\S+)', re.IGNORECASE)
88     re_CharStyle = re.compile(r'^(\s*)CharStyle(\s+)(\S+)$', re.IGNORECASE)
89
90     # counters for sectioning styles (hardcoded in 1.3)
91     counters = {"part"          : "\\Roman{part}",
92                 "chapter"       : "\\arabic{chapter}",
93                 "section"       : "\\arabic{section}",
94                 "subsection"    : "\\arabic{section}.\\arabic{subsection}",
95                 "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
96                 "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
97                 "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
98
99     # counters for sectioning styles in appendix (hardcoded in 1.3)
100     appendixcounters = {"chapter"       : "\\Alph{chapter}",
101                         "section"       : "\\Alph{section}",
102                         "subsection"    : "\\arabic{section}.\\arabic{subsection}",
103                         "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
104                         "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
105                         "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
106
107     # Value of TocLevel for sectioning styles
108     toclevels = {"part"          : 0,
109                  "chapter"       : 0,
110                  "section"       : 1,
111                  "subsection"    : 2,
112                  "subsubsection" : 3,
113                  "paragraph"     : 4,
114                  "subparagraph"  : 5}
115
116     i = 0
117     only_comment = 1
118     counter = ""
119     label = ""
120     labelstring = ""
121     labelstringappendix = ""
122     space1 = ""
123     labelstring_line = -1
124     labelstringappendix_line = -1
125     labeltype_line = -1
126     latextype = ""
127     latextype_line = -1
128     style = ""
129     maxcounter = 0
130     format = 1
131     while i < len(lines):
132
133         # Skip comments and empty lines
134         if re_Comment.match(lines[i]) or re_Empty.match(lines[i]):
135             i += 1
136             continue
137
138         # insert file format if not already there
139         if (only_comment):
140                 match = re_Format.match(lines[i])
141                 if match:
142                         format = int(match.group(4))
143                         if format > 1 and format < currentFormat:
144                             lines[i] = "Format %d" % (format + 1)
145                             only_comment = 0
146                         elif format == currentFormat:
147                                 # nothing to do
148                                 return format
149                         else:
150                             error('Cannot convert file format %s' % format)
151                 else:
152                         lines.insert(i, "Format 2")
153                         only_comment = 0
154                         continue
155
156         # Don't get confused by LaTeX code
157         if re_Preamble.match(lines[i]):
158             i += 1
159             while i < len(lines) and not re_EndPreamble.match(lines[i]):
160                 i += 1
161             continue
162
163         if format == 6:
164           i += 1
165           continue
166
167         if format == 5:
168           i += 1
169           continue
170
171         if format == 4:
172             # Handle conversion to long CharStyle names
173             match = re_CharStyle.match(lines[i])
174             if match:
175                 lines[i] = "InsetLayout CharStyle:%s" % (match.group(3))
176                 i += 1
177                 lines.insert(i, "\tLyXType charstyle")
178                 i += 1
179                 lines.insert(i, "")
180                 lines[i] = "\tLabelString %s" % (match.group(3))
181             i += 1
182             continue
183
184         if format == 3:
185             # convert 'providesamsmath x',  'providesmakeidx x',  'providesnatbib x',  'providesurl x' to
186             #         'provides amsmath x', 'provides makeidx x', 'provides natbib x', 'provides url x'
187             # x is either 0 or 1
188             match = re_Provides.match(lines[i])
189             if match:
190                 lines[i] = "%sProvides %s%s%s" % (match.group(1), match.group(2).lower(),
191                                                   match.group(3), match.group(4))
192             i += 1
193             continue
194
195         if format == 2:
196             caption = []
197
198             # delete caption styles
199             match = re_Style.match(lines[i])
200             if match:
201                 style = string.lower(match.group(4))
202                 if style == "caption":
203                     del lines[i]
204                     while i < len(lines) and not re_End.match(lines[i]):
205                         caption.append(lines[i])
206                         del lines[i]
207                     if i == len(lines):
208                         error('Incomplete caption style.')
209                     else:
210                         del lines[i]
211                         continue
212
213             # delete undefinition of caption styles
214             match = re_NoStyle.match(lines[i])
215             if match:
216                 style = string.lower(match.group(4))
217                 if style == "caption":
218                     del lines[i]
219                     continue
220
221             # replace the CopyStyle statement with the definition of the real
222             # style. This may result in duplicate statements, but that is OK
223             # since the second one will overwrite the first one.
224             match = re_CopyStyle.match(lines[i])
225             if match:
226                 style = string.lower(match.group(4))
227                 if style == "caption":
228                     if len(caption) > 0:
229                         lines[i:i+1] = caption
230                     else:
231                         # FIXME: This style comes from an include file, we
232                         # should replace the real style and not this default.
233                         lines[i:i+1] = ['       Margin                First_Dynamic',
234                                         '       LatexType             Command',
235                                         '       LatexName             caption',
236                                         '       NeedProtect           1',
237                                         '       LabelSep              xx',
238                                         '       ParSkip               0.4',
239                                         '       TopSep                0.5',
240                                         '       Align                 Center',
241                                         '       AlignPossible         Center',
242                                         '       LabelType             Sensitive',
243                                         '       LabelString           "Senseless!"',
244                                         '       OptionalArgs          1',
245                                         '       LabelFont',
246                                         '         Series              Bold',
247                                         '       EndFont']
248
249             i += 1
250             continue
251
252         # Delete MaxCounter and remember the value of it
253         match = re_MaxCounter.match(lines[i])
254         if match:
255             level = match.group(4)
256             if string.lower(level) == "counter_chapter":
257                 maxcounter = 0
258             elif string.lower(level) == "counter_section":
259                 maxcounter = 1
260             elif string.lower(level) == "counter_subsection":
261                 maxcounter = 2
262             elif string.lower(level) == "counter_subsubsection":
263                 maxcounter = 3
264             elif string.lower(level) == "counter_paragraph":
265                 maxcounter = 4
266             elif string.lower(level) == "counter_subparagraph":
267                 maxcounter = 5
268             elif string.lower(level) == "counter_enumi":
269                 maxcounter = 6
270             elif string.lower(level) == "counter_enumii":
271                 maxcounter = 7
272             elif string.lower(level) == "counter_enumiii":
273                 maxcounter = 8
274             del lines[i]
275             continue
276
277         # Replace line
278         #
279         # LabelType Counter_EnumI
280         #
281         # with two lines
282         #
283         # LabelType Counter
284         # LabelCounter EnumI
285         #
286         match = re_LabelType.match(lines[i])
287         if match:
288             label = match.group(4)
289             # Remember indenting space for later reuse in added lines
290             space1 = match.group(1)
291             # Remember the line for adding the LabelCounter later.
292             # We can't do it here because it could shift latextype_line etc.
293             labeltype_line = i
294             if string.lower(label[:8]) == "counter_":
295                 counter = string.lower(label[8:])
296                 lines[i] = re_LabelType.sub(r'\1\2\3Counter', lines[i])
297
298         # Remember the LabelString line
299         match = re_LabelString.match(lines[i])
300         if match:
301             labelstring = match.group(4)
302             labelstring_line = i
303
304         # Remember the LabelStringAppendix line
305         match = re_LabelStringAppendix.match(lines[i])
306         if match:
307             labelstringappendix = match.group(4)
308             labelstringappendix_line = i
309
310         # Remember the LatexType line
311         match = re_LatexType.match(lines[i])
312         if match:
313             latextype = string.lower(match.group(4))
314             latextype_line = i
315
316         # Reset variables at the beginning of a style definition
317         match = re_Style.match(lines[i])
318         if match:
319             style = string.lower(match.group(4))
320             counter = ""
321             label = ""
322             space1 = ""
323             labelstring = ""
324             labelstringappendix = ""
325             labelstring_line = -1
326             labelstringappendix_line = -1
327             labeltype_line = -1
328             latextype = ""
329             latextype_line = -1
330
331         if re_End.match(lines[i]):
332
333             # Add a line "LatexType Bib_Environment" if LabelType is Bibliography
334             # (or change the existing LatexType)
335             if string.lower(label) == "bibliography":
336                 if (latextype_line < 0):
337                     lines.insert(i, "%sLatexType Bib_Environment" % space1)
338                     i += 1
339                 else:
340                     lines[latextype_line] = re_LatexType.sub(r'\1\2\3Bib_Environment', lines[latextype_line])
341
342             # Change "LabelType Static" to "LabelType Itemize" for itemize environments
343             if latextype == "item_environment" and string.lower(label) == "static":
344                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Itemize', lines[labeltype_line])
345
346             # Change "LabelType Counter_EnumI" to "LabelType Enumerate" for enumerate environments
347             if latextype == "item_environment" and string.lower(label) == "counter_enumi":
348                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Enumerate', lines[labeltype_line])
349                 # Don't add the LabelCounter line later
350                 counter = ""
351
352             # Replace
353             #
354             # LabelString "Chapter"
355             #
356             # with
357             #
358             # LabelString "Chapter \arabic{chapter}"
359             #
360             # if this style has a counter. Ditto for LabelStringAppendix.
361             # This emulates the hardcoded article style numbering of 1.3
362             #
363             if counter != "":
364                 if counters.has_key(style):
365                     if labelstring_line < 0:
366                         lines.insert(i, '%sLabelString "%s"' % (space1, counters[style]))
367                         i += 1
368                     else:
369                         new_labelstring = concatenate_label(labelstring, counters[style])
370                         lines[labelstring_line] = re_LabelString.sub(
371                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
372                                 lines[labelstring_line])
373                 if appendixcounters.has_key(style):
374                     if labelstringappendix_line < 0:
375                         lines.insert(i, '%sLabelStringAppendix "%s"' % (space1, appendixcounters[style]))
376                         i += 1
377                     else:
378                         new_labelstring = concatenate_label(labelstring, appendixcounters[style])
379                         lines[labelstringappendix_line] = re_LabelStringAppendix.sub(
380                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
381                                 lines[labelstringappendix_line])
382
383                 # Now we can safely add the LabelCounter line
384                 lines.insert(labeltype_line + 1, "%sLabelCounter %s" % (space1, counter))
385                 i += 1
386
387             # Add the TocLevel setting for sectioning styles
388             if toclevels.has_key(style) and maxcounter <= toclevels[style]:
389                 lines.insert(i, '%sTocLevel %d' % (space1, toclevels[style]))
390                 i += 1
391
392         i += 1
393
394     return format + 1
395
396
397 def main(argv):
398
399     # Open files
400     if len(argv) == 1:
401         input = sys.stdin
402         output = sys.stdout
403     elif len(argv) == 3:
404         input = open(argv[1], 'rb')
405         output = open(argv[2], 'wb')
406     else:
407         error(usage(argv[0]))
408
409     # Do the real work
410     lines = read(input)
411     format = 1
412     while (format < currentFormat):
413         format = convert(lines)
414     write(output, lines)
415
416     # Close files
417     if len(argv) == 3:
418         input.close()
419         output.close()
420
421     return 0
422
423
424 if __name__ == "__main__":
425     main(sys.argv)