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