]> git.lyx.org Git - lyx.git/blob - lib/scripts/layout2layout.py
New layout tags for better counter handling
[lyx.git] / lib / scripts / layout2layout.py
1 # -*- coding: utf-8 -*-
2
3 # file layout2layout.py
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
6
7 # author Georg Baum
8
9 # Full author contact details are available in file CREDITS
10
11 # This script will update a .layout file to current format
12
13 # The latest layout format is also defined in src/TextClass.cpp
14 currentFormat = 61
15
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 # CopyStyle added to InsetLayout
32
33 # Incremented to format 9, 5 October 2008 by rgh
34 # ForcePlain and CustomPars tags added to InsetLayout
35
36 # Incremented to format 10, 6 October 2008 by rgh
37 # Change format of counters
38
39 # Incremented to format 11, 14 October 2008 by rgh
40 # Add ProvidesModule, ExcludesModule tags
41
42 # Incremented to format 12, 10 January 2009 by gb
43 # Add I18NPreamble tag
44
45 # Incremented to format 13, 5 February 2009 by rgh
46 # Add InToc tag for InsetLayout
47
48 # Incremented to format 14, 14 February 2009 by gb
49 # Rename I18NPreamble to BabelPreamble and add LangPreamble
50
51 # Incremented to format 15, 28 May 2009 by lasgouttes
52 # Add new tag OutputFormat; modules can be conditioned on feature 
53 # "from->to".
54
55 # Incremented to format 16, 5 June 2009 by rgh
56 # Add new tags for Text Class:
57 #   HTMLPreamble, HTMLAddToPreamble
58 # For Layout:
59 #   HTMLTag, HTMLAttr, HTMLLabel, HTMLLabelAttr, HTMLItem, HTMLItemAttr
60 #   HTMLStyle, and HTMLPreamble
61 # For InsetLayout:
62 #   HTMLTag, HTMLAttr, HTMLStyle, and HTMLPreamble
63 # For Floats:
64 #   HTMLType, HTMLClass, HTMLStyle
65
66 # Incremented to format 17, 12 August 2009 by rgh
67 # Add IfStyle and IfCounter tags for layout.
68
69 # Incremented to format 18, 27 October 2009 by rgh
70 # Added some new tags for HTML output.
71
72 # Incremented to format 19, 17 November 2009 by rgh
73 # Added InPreamble tag.
74
75 # Incremented to format 20, 17 December 2009 by rgh
76 # Added ContentAsLabel tag.
77
78 # Incremented to format 21, 12 January 2010 by rgh
79 # Added HTMLTocLayout and HTMLTitle tags.
80
81 # Incremented to format 22, 20 January 2010 by rgh
82 # Added HTMLFormat tag to Counters.
83
84 # Incremented to format 23, 13 February 2010 by spitz
85 # Added Spellcheck tag.
86
87 # Incremented to format 24, 5 March 2010 by rgh
88 # Changed LaTeXBuiltin tag to NeedsFloatPkg and
89 # added new tag ListCommand.
90
91 # Incremented to format 25, 12 March 2010 by rgh
92 # Added RefPrefix tag for layouts and floats.
93
94 # Incremented to format 26, 29 March 2010 by rgh
95 # Added CiteFormat.
96
97 # Incremented to format 27, 4 June 2010 by rgh
98 # Added RequiredArgs tag.
99
100 # Incremented to format 28, 6 August 2010 by lasgouttes
101 # Added ParbreakIsNewline tag for Layout and InsetLayout.
102
103 # Incremented to format 29, 10 August 2010 by rgh
104 # Changed Custom:Style, CharStyle:Style, and Element:Style
105 # uniformly to Flex:Style.
106
107 # Incremented to format 30, 13 August 2010 by rgh
108 # Introduced ResetsFont tag for InsetLayout.
109
110 # Incremented to format 31, 12 January 2011 by rgh
111 # Introducted NoCounter tag.
112
113 # Incremented to format 32, 30 January 2011 by forenr
114 # Added Display tag for InsetLayout
115
116 # Incremented to format 33, 2 February 2011 by rgh
117 # Changed NeedsFloatPkg to UsesFloatPkg
118
119 # Incremented to format 34, 28 March 2011 by rgh
120 # Remove obsolete Fill_(Top|Bottom) tags
121
122 # Incremented to format 35, 28 March 2011 by rgh
123 # Try to add "Flex:" to any flex insets that don't have it.
124
125 # Incremented to format 36, 7 December 2011, by rgh
126 # Added HTMLStyles and AddToHTMLStyles tags.
127
128 # Incremented to format 37, 29 February 2012 by jrioux
129 # Implement the citation engine machinery in layouts.
130 # Change CiteFormat to CiteFormat (default|authoryear|numerical).
131
132 # Incremented to format 38, 08 April 2012 by gb
133 # Introduce LangPreamble and BabelPreamble for InsetLayout.
134
135 # Incremented to format 39, 15 April 2012 by sanda
136 # Introduce styling of branches via "InsetLayout Branch:".
137
138 # Incremented to format 40, 10 October 2012 by rgh
139 # Re-do layout names for layout categories
140
141 # Incremented to format 41, 20 November 2012 by spitz
142 # New Argument syntax
143
144 # Incremented to format 42, 22 December 2012 by spitz
145 # New Style tag "ItemCommand"
146
147 # Incremented to format 43, 30 December 2012 by spitz
148 # Extended InsetCaption format
149
150 # Incremented to format 44, 9 February 2013 by rgh
151 # Remove COUNTER label style; rename as STATIC
152 # Rename TOP_ENVIRONMENT to ABOVE and CENTERED_TOP_ENVIRONMENT to CENTERED
153
154 # Incremented to format 45, 12 February 2013 by rgh
155 # New Tag "NoInsetLayout"
156
157 # Incremented to format 46, 15 May 2013 by gb
158 # New Tag "ForceLocal"
159
160 # Incremented to format 47, 23 May 2013 by rgh
161 # Add PackageOptions tag
162
163 # Incremented to format 48, 31 May 2013 by rgh
164 # Add InitialValue tag for counters
165
166 # Incremented to format 49, 10 Feb 2014 by gb
167 # Change default of "ResetsFont" tag to false
168
169 # Incremented to format 50, 9 May 2014 by forenr
170 # Removal of "Separator" layouts
171
172 # Incremented to format 51, 29 May 2014 by spitz
173 # New Style tag "ToggleIndent"
174
175 # Incremented to format 52, 1 December 2014 by spitz
176 # New InsetLayout tag "ForceOwnlines"
177
178 # Incremented to format 53, 7 December 2014 by spitz
179 # New InsetLayout tag "ObsoletedBy"
180
181 # Incremented to format 54, 11 Jan 2014 by gb
182 # New InsetLayout tag "FixedWidthPreambleEncoding"
183
184 # Incremented to format 55, 20 April 2015 by spitz
185 # New InsetLayout and Layout tags "PassThruChars"
186
187 # Incremented to format 56, 20 May 2015 by spitz
188 # New Float tags "AllowedPlacement", "AllowsWide", "AllowsSideways"
189
190 # Incremented to format 57, 30 May 2015 by spitz
191 # New Layout tag "ParagraphGroup"
192
193 # Incremented to format 58, 5 December 2015, by rgh
194 # New Layout tag "ProvideStyle"
195 # Change "IfStyle" to "ModifyStyle"
196
197 # Incremented to format 59, 22 November 2015 by gm
198 # New Tag "OutlinerName"
199 # New Layout tags "AddToToc", "IsTocCaption"
200 # New Layout argument tag "IsTocCaption"
201
202 # Incremented to format 60, 25 March 2016 by lasgouttes
203 # Rename caption subtype LongTableNoNumber to Unnumbered
204
205 # Incremented to format 61, 14 October 2016 by spitz
206 # New Layout tags "ResumeCounter", "StepMasterCounter"
207
208 # Do not forget to document format change in Customization
209 # Manual (section "Declaring a new text class").
210
211 # You might also want to consider running the
212 # development/tools/updatelayouts.py script to update all
213 # layout files to the new format.
214
215
216 import os, re, string, sys
217 import argparse
218
219 # Provide support for both python 2 and 3
220 # (copied from lyx2lyx)
221 PY2 = sys.version_info[0] == 2
222 if PY2:
223     # argparse returns strings in the commandline encoding, we need to convert.
224     # sys.getdefaultencoding() would not always be correct, see
225     # http://legacy.python.org/dev/peps/pep-0383/
226     def cmd_arg(arg):
227         return arg.decode(sys.getfilesystemencoding())
228 else:
229     cmd_arg = str
230 # End of code to support for both python 2 and 3
231
232
233 def error(message):
234     sys.stderr.write(message + '\n')
235     sys.exit(1)
236
237
238 def trim_bom(line):
239     " Remove byte order mark."
240     if line[0:3] == "\357\273\277":
241         return line[3:]
242     else:
243         return line
244
245
246 def read(source):
247     " Read input file and strip lineendings."
248     lines = source.read().splitlines() or ['']
249     lines[0] = trim_bom(lines[0])
250     return lines
251
252
253 def write(output, lines):
254     " Write output file with native lineendings."
255     output.write(os.linesep.join(lines) + os.linesep)
256
257
258 # Concatenates old and new in an intelligent way:
259 # If old is wrapped in ", they are stripped. The result is wrapped in ".
260 def concatenate_label(old, new):
261     # Don't use strip as long as we support python 1.5.2
262     if old[0] == '"':
263         return old[0:-1] + new + '"'
264     else:
265         return '"' + old + new + '"'
266
267 # appends a string to a list unless it's already there
268 def addstring(s, l):
269     if l.count(s) > 0:
270         return
271     l.append(s)
272
273
274 def convert(lines, end_format):
275     " Convert to new format."
276     re_Comment = re.compile(r'^(\s*)#')
277     re_Counter = re.compile(r'\s*Counter\s*', re.IGNORECASE)
278     re_Name = re.compile(r'\s*Name\s+(\S+)\s*', re.IGNORECASE)
279     re_UseMod = re.compile(r'^\s*UseModule\s+(.*)', re.IGNORECASE)
280     re_Empty = re.compile(r'^(\s*)$')
281     re_Format = re.compile(r'^(\s*)(Format)(\s+)(\S+)', re.IGNORECASE)
282     re_Preamble = re.compile(r'^(\s*)Preamble', re.IGNORECASE)
283     re_EndPreamble = re.compile(r'^(\s*)EndPreamble', re.IGNORECASE)
284     re_LangPreamble = re.compile(r'^(\s*)LangPreamble', re.IGNORECASE)
285     re_EndLangPreamble = re.compile(r'^(\s*)EndLangPreamble', re.IGNORECASE)
286     re_BabelPreamble = re.compile(r'^(\s*)BabelPreamble', re.IGNORECASE)
287     re_EndBabelPreamble = re.compile(r'^(\s*)EndBabelPreamble', re.IGNORECASE)
288     re_MaxCounter = re.compile(r'^(\s*)(MaxCounter)(\s+)(\S+)', re.IGNORECASE)
289     re_LabelType = re.compile(r'^(\s*)(LabelType)(\s+)(\S+)', re.IGNORECASE)
290     re_LabelString = re.compile(r'^(\s*)(LabelString)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
291     re_LabelStringAppendix = re.compile(r'^(\s*)(LabelStringAppendix)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
292     re_LatexType = re.compile(r'^(\s*)(LatexType)(\s+)(\S+)', re.IGNORECASE)
293     re_Style = re.compile(r'^(\s*)(Style)(\s+)(\S+)', re.IGNORECASE)
294     re_IfStyle = re.compile(r'^(\s*)IfStyle(\s+\S+)', re.IGNORECASE)
295     re_CopyStyle = re.compile(r'^(\s*)(CopyStyle)(\s+)(\S+)', re.IGNORECASE)
296     re_NoStyle = re.compile(r'^(\s*)(NoStyle)(\s+)(\S+)', re.IGNORECASE)
297     re_End = re.compile(r'^(\s*)(End)(\s*)$', re.IGNORECASE)
298     re_Provides = re.compile(r'^(\s*)Provides(\S+)(\s+)(\S+)', re.IGNORECASE)
299     re_CharStyle = re.compile(r'^(\s*)CharStyle(\s+)(\S+)$', re.IGNORECASE)
300     re_CiteFormat = re.compile(r'^(\s*)(CiteFormat)(?:(\s*)()|(\s+)(default|authoryear|numerical))', re.IGNORECASE)
301     re_AMSMaths = re.compile(r'^\s*Input ams(?:math|def)s.inc\s*')
302     re_AMSMathsPlain = re.compile(r'^\s*Input amsmaths-plain.inc\s*')
303     re_AMSMathsSeq = re.compile(r'^\s*Input amsmaths-seq.inc\s*')
304     re_TocLevel = re.compile(r'^(\s*)(TocLevel)(\s+)(\S+)', re.IGNORECASE)
305     re_I18nPreamble = re.compile(r'^(\s*)I18nPreamble', re.IGNORECASE)
306     re_EndI18nPreamble = re.compile(r'^(\s*)EndI18nPreamble', re.IGNORECASE)
307     re_Float = re.compile(r'^\s*Float\s*$', re.IGNORECASE)
308     re_Type = re.compile(r'\s*Type\s+(\w+)', re.IGNORECASE)
309     re_Builtin = re.compile(r'^(\s*)LaTeXBuiltin\s+(\w*)', re.IGNORECASE)
310     re_True = re.compile(r'^\s*(?:true|1)\s*$', re.IGNORECASE)
311     re_InsetLayout = re.compile(r'^\s*InsetLayout\s+(?:Custom|CharStyle|Element):(\S+)\s*$', re.IGNORECASE)
312     re_ResetsFont = re.compile(r'^(\s*)ResetsFont(\s+)(\S+)$', re.IGNORECASE)
313     # with quotes
314     re_QInsetLayout = re.compile(r'^\s*InsetLayout\s+"(?:Custom|CharStyle|Element):([^"]+)"\s*$', re.IGNORECASE)
315     re_InsetLayout_CopyStyle = re.compile(r'^\s*CopyStyle\s+(?:Custom|CharStyle|Element):(\S+)\s*$', re.IGNORECASE)
316     re_QInsetLayout_CopyStyle = re.compile(r'^\s*CopyStyle\s+"(?:Custom|CharStyle|Element):([^"]+)"\s*$', re.IGNORECASE)
317     re_NeedsFloatPkg = re.compile(r'^(\s*)NeedsFloatPkg\s+(\w+)\s*$', re.IGNORECASE)
318     re_Fill = re.compile(r'^\s*Fill_(?:Top|Bottom).*$', re.IGNORECASE)
319     re_InsetLayout2 = re.compile(r'^\s*InsetLayout\s+(\S+)\s*$', re.IGNORECASE)
320     # with quotes
321     re_QInsetLayout2 = re.compile(r'^\s*InsetLayout\s+"([^"]+)"\s*$', re.IGNORECASE)
322     re_IsFlex = re.compile(r'\s*LyXType.*$', re.IGNORECASE)
323     re_CopyStyle2 = re.compile(r'(\s*CopyStyle\s+)"?([^"]+)"?\s*$')
324     re_Separator = re.compile(r'^(?:(-*)|(\s*))(Separator|EndOfSlide)(?:(-*)|(\s*))$', re.IGNORECASE)
325     # for categories
326     re_Declaration = re.compile(r'^#\s*\\Declare\w+Class.*$')
327     re_ExtractCategory = re.compile(r'^(#\s*\\Declare\w+Class(?:\[[^]]*?\])?){([^(]+?)\s+\(([^)]+?)\)\s*}\s*$')
328     ConvDict = {"article": "Articles", "book" : "Books", "letter" : "Letters", "report": "Reports", \
329                 "presentation" : "Presentations", "curriculum vitae" : "Curricula Vitae", "handout" : "Handouts"}
330     # Arguments
331     re_OptArgs = re.compile(r'^(\s*)OptionalArgs(\s+)(\d+)\D*$', re.IGNORECASE)
332     re_ReqArgs = re.compile(r'^(\s*)RequiredArgs(\s+)(\d+)\D*$', re.IGNORECASE)
333     
334     # various changes associated with changing how chapters are handled
335     re_LabelTypeIsCounter = re.compile(r'^(\s*)LabelType(\s*)Counter\s*$', re.IGNORECASE)
336     re_TopEnvironment = re.compile(r'^(\s*)LabelType(\s+)Top_Environment\s*$', re.IGNORECASE)
337     re_CenteredEnvironment = re.compile(r'^(\s*)LabelType(\s+)Centered_Top_Environment\s*$', re.IGNORECASE)
338     re_ChapterStyle = re.compile(r'^\s*Style\s+Chapter\s*$', re.IGNORECASE)
339     re_InsetLayout_CaptionLTNN = re.compile(r'^(\s*InsetLayout\s+)(Caption:LongTableNonumber)', re.IGNORECASE)
340
341
342     # counters for sectioning styles (hardcoded in 1.3)
343     counters = {"part"          : "\\Roman{part}",
344                 "chapter"       : "\\arabic{chapter}",
345                 "section"       : "\\arabic{section}",
346                 "subsection"    : "\\arabic{section}.\\arabic{subsection}",
347                 "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
348                 "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
349                 "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
350
351     # counters for sectioning styles in appendix (hardcoded in 1.3)
352     appendixcounters = {"chapter"       : "\\Alph{chapter}",
353                         "section"       : "\\Alph{section}",
354                         "subsection"    : "\\arabic{section}.\\arabic{subsection}",
355                         "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
356                         "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
357                         "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
358
359     # Value of TocLevel for sectioning styles
360     toclevels = {"part"          : -1,
361                  "chapter"       : 0,
362                  "section"       : 1,
363                  "subsection"    : 2,
364                  "subsubsection" : 3,
365                  "paragraph"     : 4,
366                  "subparagraph"  : 5}
367
368     i = 0
369     only_comment = 1
370     counter = ""
371     toclevel = ""
372     label = ""
373     labelstring = ""
374     labelstringappendix = ""
375     space1 = ""
376     labelstring_line = -1
377     labelstringappendix_line = -1
378     labeltype_line = -1
379     latextype = ""
380     latextype_line = -1
381     style = ""
382     maxcounter = 0
383     format = 1
384     formatline = 0
385     usemodules = []
386     flexstyles = []
387     opts = 0
388     reqs = 0
389     inchapter = False
390     isflexlayout = False         # only used for 48 -> 49
391     # Whether a style is inherited (works only for CopyStyle currently,
392     # not for true inherited styles, see bug 8920
393     inherited = False        # only used for 48 -> 49
394     resetsfont_found = False # only used for 48 -> 49
395
396     while i < len(lines):
397         # Skip comments and empty lines
398         if (re_Comment.match(lines[i]) or re_Empty.match(lines[i])):
399           # We need to deal with this conversion here, because it happens
400           # inside the initial comment block.
401           if only_comment and format == 39:
402               match = re_ExtractCategory.match(lines[i])
403               if match:
404                   lpre = match.group(1)
405                   lcat = match.group(2)
406                   lnam = match.group(3)
407                   if lcat in ConvDict:
408                       lcat = ConvDict[lcat]
409                   lines[i] = lpre + "{" + lnam + "}"
410                   lines.insert(i+1, "#  \\DeclareCategory{" + lcat + "}")
411                   i += 1 
412           i += 1
413           continue
414
415         # insert file format if not already there
416         if (only_comment):
417             match = re_Format.match(lines[i])
418             if match:
419                 formatline = i
420                 format = int(match.group(4))
421                 if format > 1 and format < end_format:
422                     lines[i] = "Format %d" % (format + 1)
423                     only_comment = 0
424                 elif format == end_format:
425                     # nothing to do
426                     return format
427                 else:
428                     error('Cannot convert file format %s to %s' % (format, end_format))
429             else:
430                 lines.insert(i, "Format 2")
431                 only_comment = 0
432                 continue
433
434         # Don't get confused by LaTeX code
435         if re_Preamble.match(lines[i]):
436             i += 1
437             while i < len(lines) and not re_EndPreamble.match(lines[i]):
438                 i += 1
439             continue
440         if re_LangPreamble.match(lines[i]):
441             i += 1
442             while i < len(lines) and not re_EndLangPreamble.match(lines[i]):
443                 i += 1
444             continue
445         if re_BabelPreamble.match(lines[i]):
446             i += 1
447             while i < len(lines) and not re_EndBabelPreamble.match(lines[i]):
448                 i += 1
449             continue
450
451         if format == 60:
452             # nothing to do.
453             i += 1
454             continue
455
456         if format == 59:
457             match = re_InsetLayout_CaptionLTNN.match(lines[i])
458             if not match:
459                 i += 1
460                 continue
461             # '^(\s*InsetLayout\s+)(Caption:LongTableNonumber)'
462             lead  = match.group(1)
463             lines[i] = lead + "Caption:Unnumbered"
464             i += 1
465             continue
466
467         if format == 58:
468             # nothing to do.
469             i += 1
470             continue
471
472         if format == 57:
473             match = re_IfStyle.match(lines[i])
474             if not match:
475                 i += 1
476                 continue
477             # r'^(\s*)IfStyle(\s+\S+)
478             lead  = match.group(1)
479             trail = match.group(2)
480             lines[i] = lead + "ModifyStyle" + trail
481             i += 1
482             continue
483
484         if format >= 50 and format <= 56:
485             # nothing to do.
486             i += 1
487             continue
488
489         if format == 49:
490             separator = []
491
492             # delete separator styles
493             match = re_Style.match(lines[i])
494             if match:
495                 style = string.lower(match.group(4))
496                 if re_Separator.match(style):
497                     del lines[i]
498                     while i < len(lines) and not re_End.match(lines[i]):
499                         separator.append(lines[i])
500                         del lines[i]
501                     if i == len(lines):
502                         error('Incomplete separator style.')
503                     else:
504                         del lines[i]
505                         continue
506
507             # delete undefinition of separator styles
508             match = re_NoStyle.match(lines[i])
509             if match:
510                 style = string.lower(match.group(4))
511                 if re_Separator.match(style):
512                     del lines[i]
513                     continue
514
515             # replace the CopyStyle statement with the definition of the real
516             # style. This may result in duplicate statements, but that is OK
517             # since the second one will overwrite the first one.
518             match = re_CopyStyle.match(lines[i])
519             if match:
520                 style = string.lower(match.group(4))
521                 if re_Separator.match(style):
522                     if len(separator) > 0:
523                         lines[i:i+1] = separator
524                     else:
525                         # FIXME: If this style was redefined in an include file,
526                         # we should replace the real style and not this default.
527                         lines[i:i+1] = ['       Category              MainText',
528                                         '       KeepEmpty             1',
529                                         '       Margin                Dynamic',
530                                         '       LatexType             Paragraph',
531                                         '       LatexName             dummy',
532                                         '       ParIndent             MM',
533                                         '       Align                 Block',
534                                         '       LabelType             Static',
535                                         '       LabelString           "--- Separate Environment ---"',
536                                         '       LabelFont',
537                                         '         Family              Roman',
538                                         '         Series              Medium',
539                                         '         Size                Normal',
540                                         '         Color               Blue',
541                                         '       EndFont',
542                                         '       HTMLLabel             NONE']
543             i += 1
544             continue
545
546         if format == 48:
547             # The default of ResetsFont in LyX changed from true to false,
548             # because it is now used for all InsetLayouts, not only flex ones.
549             # Therefore we need to set it to true for all flex insets which do
550             # do not already have a ResetsFont.
551             match = re_InsetLayout2.match(lines[i])
552             if not match:
553                 i += 1
554                 continue
555
556             name = string.lower(match.group(1))
557             if name != "flex" and name != "\"flex\"" and name[0:5] != "flex:" and name [0:6] != "\"flex:":
558                 i += 1
559                 continue
560
561             resetsfont_found = False
562             inherited = False
563             notdone = True
564             while i < len(lines):
565               match = re_ResetsFont.match(lines[i])
566               if match:
567                   resetsfont_found = True
568               else:
569                 match = re_CopyStyle.match(lines[i])
570                 if match:
571                   inherited = True
572                 else:
573                   match = re_End.match(lines[i])
574                   if match:
575                     break
576               i += 1
577             if not resetsfont_found and not inherited:
578               lines.insert(i, "\tResetsFont true")
579
580             continue
581
582         if format >= 44 and format <= 47:
583             # nothing to do.
584             i += 1
585             continue
586
587         if format == 43:
588           match = re_LabelTypeIsCounter.match(lines[i])
589           if match:
590             if inchapter:
591              lines[i] = match.group(1) + "LabelType" + match.group(2) + "Above"              
592             else:
593               lines[i] = match.group(1) + "LabelType" + match.group(2) + "Static"
594
595           match = re_TopEnvironment.match(lines[i])
596           if match:
597             lines[i] = match.group(1) + "LabelType" + match.group(2) + "Above"
598
599           match = re_CenteredEnvironment.match(lines[i])
600           if match:
601             lines[i] = match.group(1) + "LabelType" + match.group(2) + "Centered"
602
603           if inchapter:
604             match = re_Style.match(lines[i])
605             if match:
606               inchapter = False
607           else:
608             match = re_ChapterStyle.match(lines[i])
609             if match:
610               inchapter = True
611
612           i += 1
613           continue
614
615         if format == 42:
616           if lines[i] == "InsetLayout Caption":
617             lines[i] = "InsetLayout Caption:Standard"
618           i += 1
619           continue
620         
621         if format == 41:
622             # nothing to do.
623             i += 1
624             continue
625
626         if format == 40:
627             # reset counters on Style beginning
628             match = re_Style.match(lines[i])
629             if match:
630                 opts = 0
631                 reqs = 0
632                 i += 1
633                 continue
634             match = re_OptArgs.match(lines[i])
635             if match:
636                 # Save number of optional arguments
637                 space1 = match.group(1)
638                 opts = int(match.group(3))
639                 # OptionalArgs 0 > ResetArgs 1
640                 if opts == 0:
641                     lines[i] = space1 + "ResetArgs\t1"
642                     i += 1
643                 else:
644                     del lines[i]
645                 continue
646             match = re_ReqArgs.match(lines[i])
647             if match:
648                 # Save number of required arguments
649                 space1 = match.group(1)
650                 reqs = int(match.group(3))
651                 del lines[i]
652                 continue
653             # Insert the required number of arguments at the end of the style definition
654             match = re_End.match(lines[i])
655             if match:
656                 newarg = ['']
657                 # First the optionals (this is the required order pre 2.1)
658                 if opts > 0:
659                     if opts == 1:
660                         newarg = [ '%sArgument 1' % (space1),
661                                    '%s\tLabelString\t\"Optional Layout Argument\"' % (space1),
662                                    '%sEndArgument' % (space1)]
663                     elif opts > 1:
664                         actopt = 1
665                         while actopt < (opts + 1):
666                             newarg += [ '%sArgument %d' % (space1, actopt),
667                                '%s\tLabelString\t\"Optional Layout Argument %d\"' % (space1, actopt),
668                                '%sEndArgument' % (space1)]
669                             actopt += 1
670                 # Now the mandatories
671                 if reqs > 0:
672                     actopt = opts + 1
673                     while actopt < (opts +  reqs + 1):
674                         newarg += [ '%sArgument %d' % (space1, actopt),
675                            '%s\tLabelString\t"Required Layout Argument %d"' % (space1, actopt - opts),
676                            '%s\tMandatory\t1' % (space1),
677                            '%sEndArgument' % (space1)]
678                         actopt += 1
679                 # Since we replace the "End" line, re-add this line
680                 if len(newarg) > 1:
681                     newarg += ['End']
682                     lines[i:i+1] = newarg
683                     i += len(newarg)
684                 # Reset the counters
685                 opts = 0
686                 reqs = 0
687             i += 1
688             continue
689         
690         if format == 39:
691             # There is a conversion with format 40, but it is done within the
692             # initial comment block and so is above.
693             i += 1
694             continue
695
696         if format == 37 or format == 38:
697             i += 1
698             continue
699
700         if format == 36:
701             match = re_CiteFormat.match(lines[i]);
702             if match and match.group(4) == "":
703                 lines[i] = match.group(0) + " default"
704             i += 1
705             continue
706
707         if format == 35:
708           i += 1
709           continue
710
711         if format == 34:
712           match = re_QInsetLayout2.match(lines[i])
713           if not match:
714             match = re_InsetLayout2.match(lines[i])
715           if not match:
716             match = re_CopyStyle2.match(lines[i])
717             if not match:
718               i += 1
719               continue
720             style = match.group(2)
721             
722             if flexstyles.count(style):
723               lines[i] = match.group(1) + "\"Flex:" + style + "\""
724             i += 1
725             continue
726
727           name = match.group(1)
728           names = name.split(":", 1)
729           if len(names) > 1 and names[0] == "Flex":
730             i += 1
731             continue
732
733           isflex = False
734           for j in range(i + 1, len(lines)):
735             if re_IsFlex.match(lines[j]):
736               isflex = True
737               break
738             if re_End.match(lines[j]):
739               break
740
741           if isflex:
742             flexstyles.append(name)
743             lines[i] = "InsetLayout \"Flex:" + name + "\""
744
745           i += 1
746           continue
747
748         if format == 33:
749           m = re_Fill.match(lines[i])
750           if m:
751             lines[i] = ""
752           i += 1
753           continue
754
755         if format == 32:
756           match = re_NeedsFloatPkg.match(lines[i])
757           if match:
758             space = match.group(1)
759             val = match.group(2)
760             lines[i] = space + "UsesFloatPkg " + val
761             newval = 'true'
762             if val == '1' or val.lower() == 'true':
763               newval = 'false'
764             lines.insert(i, space + "IsPredefined " + newval)
765             i += 1
766           i += 1
767           continue
768
769         # Only new features
770         if format >= 29 and format <= 31:
771           i += 1
772           continue
773
774         if format == 28:
775           match = re_InsetLayout.match(lines[i])
776           if match:
777             lines[i] = "InsetLayout Flex:" + match.group(1)
778           else:
779             match = re_QInsetLayout.match(lines[i])
780             if match:
781               lines[i] = "InsetLayout \"Flex:" + match.group(1) + "\""
782             else:
783               match = re_InsetLayout_CopyStyle.match(lines[i])
784               if match:
785                 lines[i] = "\tCopyStyle Flex:" + match.group(1)
786               else:
787                 match = re_QInsetLayout_CopyStyle.match(lines[i])
788                 if match:
789                   lines[i] = "\tCopyStyle \"Flex:" + match.group(1) + "\""
790           i += 1
791           continue
792         
793         # Only new features
794         if format >= 24 and format <= 27:
795           i += 1
796           continue
797
798         if format == 23:
799           match = re_Float.match(lines[i])
800           i += 1
801           if not match:
802             continue
803           # we need to do two things:
804           # (i)  Convert Builtin to NeedsFloatPkg
805           # (ii) Write ListCommand lines for the builtin floats table and figure
806           builtin = False
807           cmd = ""
808           while True and i < len(lines):
809             m1 = re_End.match(lines[i])
810             if m1:
811               if builtin and cmd:
812                 line = "    ListCommand " + cmd
813                 lines.insert(i, line)
814                 i += 1
815               break
816             m2 = re_Builtin.match(lines[i])
817             if m2:
818               builtin = True
819               ws1 = m2.group(1)
820               arg = m2.group(2)
821               newarg = ""
822               if re_True.match(arg):
823                 newarg = "false"
824               else:
825                 newarg = "true"
826               lines[i] = ws1 + "NeedsFloatPkg " + newarg
827             m3 = re_Type.match(lines[i])
828             if m3:
829               fltype = m3.group(1)
830               fltype = fltype.lower()
831               if fltype == "table":
832                 cmd = "listoftables"
833               elif fltype == "figure":
834                 cmd = "listoffigures"
835               # else unknown, which is why we're doing this
836             i += 1
837           continue              
838           
839         # This just involved new features, not any changes to old ones
840         if format >= 14 and format <= 22:
841           i += 1
842           continue
843
844         # Rename I18NPreamble to BabelPreamble
845         if format == 13:
846             match = re_I18nPreamble.match(lines[i])
847             if match:
848                 lines[i] = match.group(1) + "BabelPreamble"
849                 i += 1
850                 match = re_EndI18nPreamble.match(lines[i])
851                 while i < len(lines) and not match:
852                     i += 1
853                     match = re_EndI18nPreamble.match(lines[i])
854                 lines[i] = match.group(1) + "EndBabelPreamble"
855                 i += 1
856                 continue
857
858         # These just involved new features, not any changes to old ones
859         if format == 11 or format == 12:
860           i += 1
861           continue
862
863         if format == 10:
864             match = re_UseMod.match(lines[i])
865             if match:
866                 module = match.group(1)
867                 lines[i] = "DefaultModule " + module
868             i += 1
869             continue
870
871         if format == 9:
872             match = re_Counter.match(lines[i])
873             if match:
874                 counterline = i
875                 i += 1
876                 while i < len(lines):
877                     namem = re_Name.match(lines[i])
878                     if namem:
879                         name = namem.group(1)
880                         lines.pop(i)
881                         lines[counterline] = "Counter %s" % name
882                         # we don't need to increment i
883                         continue
884                     endem = re_End.match(lines[i])
885                     if endem:
886                         i += 1
887                         break
888                     i += 1
889             i += 1
890             continue
891
892         if format == 8:
893             # We want to scan for ams-type includes and, if we find them,
894             # add corresponding UseModule tags to the layout.
895             match = re_AMSMaths.match(lines[i])
896             if match:
897                 addstring("theorems-ams", usemodules)
898                 addstring("theorems-ams-extended", usemodules)
899                 addstring("theorems-sec", usemodules)
900                 lines.pop(i)
901                 continue
902             match = re_AMSMathsPlain.match(lines[i])
903             if match:
904                 addstring("theorems-starred", usemodules)
905                 lines.pop(i)
906                 continue
907             match = re_AMSMathsSeq.match(lines[i])
908             if match:
909                 addstring("theorems-ams", usemodules)
910                 addstring("theorems-ams-extended", usemodules)
911                 lines.pop(i)
912                 continue
913             i += 1
914             continue
915
916         # These just involved new features, not any changes to old ones
917         if format >= 5 and format <= 7:
918           i += 1
919           continue
920
921         if format == 4:
922             # Handle conversion to long CharStyle names
923             match = re_CharStyle.match(lines[i])
924             if match:
925                 lines[i] = "InsetLayout CharStyle:%s" % (match.group(3))
926                 i += 1
927                 lines.insert(i, "\tLyXType charstyle")
928                 i += 1
929                 lines.insert(i, "")
930                 lines[i] = "\tLabelString %s" % (match.group(3))
931             i += 1
932             continue
933
934         if format == 3:
935             # convert 'providesamsmath x',  'providesmakeidx x',  'providesnatbib x',  'providesurl x' to
936             #         'provides amsmath x', 'provides makeidx x', 'provides natbib x', 'provides url x'
937             # x is either 0 or 1
938             match = re_Provides.match(lines[i])
939             if match:
940                 lines[i] = "%sProvides %s%s%s" % (match.group(1), match.group(2).lower(),
941                                                   match.group(3), match.group(4))
942             i += 1
943             continue
944
945         if format == 2:
946             caption = []
947
948             # delete caption styles
949             match = re_Style.match(lines[i])
950             if match:
951                 style = string.lower(match.group(4))
952                 if style == "caption":
953                     del lines[i]
954                     while i < len(lines) and not re_End.match(lines[i]):
955                         caption.append(lines[i])
956                         del lines[i]
957                     if i == len(lines):
958                         error('Incomplete caption style.')
959                     else:
960                         del lines[i]
961                         continue
962
963             # delete undefinition of caption styles
964             match = re_NoStyle.match(lines[i])
965             if match:
966                 style = string.lower(match.group(4))
967                 if style == "caption":
968                     del lines[i]
969                     continue
970
971             # replace the CopyStyle statement with the definition of the real
972             # style. This may result in duplicate statements, but that is OK
973             # since the second one will overwrite the first one.
974             match = re_CopyStyle.match(lines[i])
975             if match:
976                 style = string.lower(match.group(4))
977                 if style == "caption":
978                     if len(caption) > 0:
979                         lines[i:i+1] = caption
980                     else:
981                         # FIXME: This style comes from an include file, we
982                         # should replace the real style and not this default.
983                         lines[i:i+1] = ['       Margin                First_Dynamic',
984                                         '       LatexType             Command',
985                                         '       LatexName             caption',
986                                         '       NeedProtect           1',
987                                         '       LabelSep              xx',
988                                         '       ParSkip               0.4',
989                                         '       TopSep                0.5',
990                                         '       Align                 Center',
991                                         '       AlignPossible         Center',
992                                         '       LabelType             Sensitive',
993                                         '       LabelString           "Senseless!"',
994                                         '       OptionalArgs          1',
995                                         '       LabelFont',
996                                         '         Series              Bold',
997                                         '       EndFont']
998
999             i += 1
1000             continue
1001
1002         # Delete MaxCounter and remember the value of it
1003         match = re_MaxCounter.match(lines[i])
1004         if match:
1005             level = match.group(4)
1006             if string.lower(level) == "counter_chapter":
1007                 maxcounter = 0
1008             elif string.lower(level) == "counter_section":
1009                 maxcounter = 1
1010             elif string.lower(level) == "counter_subsection":
1011                 maxcounter = 2
1012             elif string.lower(level) == "counter_subsubsection":
1013                 maxcounter = 3
1014             elif string.lower(level) == "counter_paragraph":
1015                 maxcounter = 4
1016             elif string.lower(level) == "counter_subparagraph":
1017                 maxcounter = 5
1018             elif string.lower(level) == "counter_enumi":
1019                 maxcounter = 6
1020             elif string.lower(level) == "counter_enumii":
1021                 maxcounter = 7
1022             elif string.lower(level) == "counter_enumiii":
1023                 maxcounter = 8
1024             del lines[i]
1025             continue
1026
1027         # Replace line
1028         #
1029         # LabelType Counter_EnumI
1030         #
1031         # with two lines
1032         #
1033         # LabelType Counter
1034         # LabelCounter EnumI
1035         #
1036         match = re_LabelType.match(lines[i])
1037         if match:
1038             label = match.group(4)
1039             # Remember indenting space for later reuse in added lines
1040             space1 = match.group(1)
1041             # Remember the line for adding the LabelCounter later.
1042             # We can't do it here because it could shift latextype_line etc.
1043             labeltype_line = i
1044             if string.lower(label[:8]) == "counter_":
1045                 counter = string.lower(label[8:])
1046                 lines[i] = re_LabelType.sub(r'\1\2\3Counter', lines[i])
1047
1048         # Remember the LabelString line
1049         match = re_LabelString.match(lines[i])
1050         if match:
1051             labelstring = match.group(4)
1052             labelstring_line = i
1053
1054         # Remember the LabelStringAppendix line
1055         match = re_LabelStringAppendix.match(lines[i])
1056         if match:
1057             labelstringappendix = match.group(4)
1058             labelstringappendix_line = i
1059
1060         # Remember the LatexType line
1061         match = re_LatexType.match(lines[i])
1062         if match:
1063             latextype = string.lower(match.group(4))
1064             latextype_line = i
1065
1066         # Remember the TocLevel line
1067         match = re_TocLevel.match(lines[i])
1068         if match:
1069             toclevel = string.lower(match.group(4))
1070
1071         # Reset variables at the beginning of a style definition
1072         match = re_Style.match(lines[i])
1073         if match:
1074             style = string.lower(match.group(4))
1075             counter = ""
1076             toclevel = ""
1077             label = ""
1078             space1 = ""
1079             labelstring = ""
1080             labelstringappendix = ""
1081             labelstring_line = -1
1082             labelstringappendix_line = -1
1083             labeltype_line = -1
1084             latextype = ""
1085             latextype_line = -1
1086
1087         if re_End.match(lines[i]):
1088
1089             # Add a line "LatexType Bib_Environment" if LabelType is Bibliography
1090             # (or change the existing LatexType)
1091             if string.lower(label) == "bibliography":
1092                 if (latextype_line < 0):
1093                     lines.insert(i, "%sLatexType Bib_Environment" % space1)
1094                     i += 1
1095                 else:
1096                     lines[latextype_line] = re_LatexType.sub(r'\1\2\3Bib_Environment', lines[latextype_line])
1097
1098             # Change "LabelType Static" to "LabelType Itemize" for itemize environments
1099             if latextype == "item_environment" and string.lower(label) == "static":
1100                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Itemize', lines[labeltype_line])
1101
1102             # Change "LabelType Counter_EnumI" to "LabelType Enumerate" for enumerate environments
1103             if latextype == "item_environment" and string.lower(label) == "counter_enumi":
1104                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Enumerate', lines[labeltype_line])
1105                 # Don't add the LabelCounter line later
1106                 counter = ""
1107
1108             # Replace
1109             #
1110             # LabelString "Chapter"
1111             #
1112             # with
1113             #
1114             # LabelString "Chapter \arabic{chapter}"
1115             #
1116             # if this style has a counter. Ditto for LabelStringAppendix.
1117             # This emulates the hardcoded article style numbering of 1.3
1118             #
1119             if counter != "":
1120                 if style in counters:
1121                     if labelstring_line < 0:
1122                         lines.insert(i, '%sLabelString "%s"' % (space1, counters[style]))
1123                         i += 1
1124                     else:
1125                         new_labelstring = concatenate_label(labelstring, counters[style])
1126                         lines[labelstring_line] = re_LabelString.sub(
1127                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
1128                                 lines[labelstring_line])
1129                 if style in appendixcounters:
1130                     if labelstringappendix_line < 0:
1131                         lines.insert(i, '%sLabelStringAppendix "%s"' % (space1, appendixcounters[style]))
1132                         i += 1
1133                     else:
1134                         new_labelstring = concatenate_label(labelstring, appendixcounters[style])
1135                         lines[labelstringappendix_line] = re_LabelStringAppendix.sub(
1136                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
1137                                 lines[labelstringappendix_line])
1138
1139                 # Now we can safely add the LabelCounter line
1140                 lines.insert(labeltype_line + 1, "%sLabelCounter %s" % (space1, counter))
1141                 i += 1
1142
1143             # Add the TocLevel setting for sectioning styles
1144             if toclevel == "" and style in toclevels and maxcounter <= toclevels[style]:
1145                 lines.insert(i, '%s\tTocLevel %d' % (space1, toclevels[style]))
1146                 i += 1
1147
1148         i += 1
1149
1150     if only_comment:
1151         lines.insert(i, "Format 2")
1152     if usemodules:
1153         i = formatline + 1
1154         for mod in usemodules:
1155             lines.insert(i, "UseModule " + mod)
1156             i += 1
1157
1158     return format + 1
1159
1160
1161 def main(argv):
1162     args = {}
1163     args["description"] = "Convert layout file <inputfile> to a newer format."
1164
1165     parser = argparse.ArgumentParser(**args)
1166
1167     parser.add_argument("-t", "--to", type=int, dest="format",
1168                         help=("destination layout format, default %i (latest)") % currentFormat)
1169     parser.add_argument("input_file", nargs='?', type=cmd_arg, default=None,
1170                         help="input file (default stdin)")
1171     parser.add_argument("output_file", nargs='?', type=cmd_arg, default=None,
1172                         help="output file (default stdout)")
1173
1174     options = parser.parse_args()
1175
1176     # Open files
1177     if options.input_file:
1178         source = open(options.input_file, 'rb')
1179     else:
1180         source = sys.stdin
1181
1182     if options.output_file:
1183         output = open(options.output_file, 'wb')
1184     else:
1185         output = sys.stdout
1186
1187     if options.format:
1188         end_format = options.format
1189     else:
1190         end_format = currentFormat
1191
1192     if end_format > currentFormat:
1193         error("Format %i does not exist" % end_format);
1194
1195     # Do the real work
1196     lines = read(source)
1197     format = 1
1198     while (format < end_format):
1199         format = convert(lines, end_format)
1200     write(output, lines)
1201
1202     # Close files
1203     if options.input_file:
1204         source.close()
1205     if options.output_file:
1206         output.close()
1207
1208     return 0
1209
1210
1211 if __name__ == "__main__":
1212     main(sys.argv)