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