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