]> git.lyx.org Git - features.git/blob - lib/scripts/layout2layout.py
Remove the shebang line from our python scripts, per Jose's suggestion.
[features.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 # Do not forget to document format change in Customization
166 # Manual (section "Declaring a new text class").
167
168 # You might also want to consider running the
169 # development/tools/updatelayouts.sh script to update all
170 # layout files to the new format.
171
172 currentFormat = 48
173
174
175 def usage(prog_name):
176     return ("Usage: %s inputfile outputfile\n" % prog_name +
177             "or     %s <inputfile >outputfile" % prog_name)
178
179
180 def error(message):
181     sys.stderr.write(message + '\n')
182     sys.exit(1)
183
184
185 def trim_bom(line):
186     " Remove byte order mark."
187     if line[0:3] == "\357\273\277":
188         return line[3:]
189     else:
190         return line
191
192
193 def read(source):
194     " Read input file and strip lineendings."
195     lines = source.read().splitlines() or ['']
196     lines[0] = trim_bom(lines[0])
197     return lines
198
199
200 def write(output, lines):
201     " Write output file with native lineendings."
202     output.write(os.linesep.join(lines) + os.linesep)
203
204
205 # Concatenates old and new in an intelligent way:
206 # If old is wrapped in ", they are stripped. The result is wrapped in ".
207 def concatenate_label(old, new):
208     # Don't use strip as long as we support python 1.5.2
209     if old[0] == '"':
210         return old[0:-1] + new + '"'
211     else:
212         return '"' + old + new + '"'
213
214 # appends a string to a list unless it's already there
215 def addstring(s, l):
216     if l.count(s) > 0:
217         return
218     l.append(s)
219
220
221 def convert(lines):
222     " Convert to new format."
223     re_Comment = re.compile(r'^(\s*)#')
224     re_Counter = re.compile(r'\s*Counter\s*', re.IGNORECASE)
225     re_Name = re.compile(r'\s*Name\s+(\S+)\s*', re.IGNORECASE)
226     re_UseMod = re.compile(r'^\s*UseModule\s+(.*)', re.IGNORECASE)
227     re_Empty = re.compile(r'^(\s*)$')
228     re_Format = re.compile(r'^(\s*)(Format)(\s+)(\S+)', re.IGNORECASE)
229     re_Preamble = re.compile(r'^(\s*)Preamble', re.IGNORECASE)
230     re_EndPreamble = re.compile(r'^(\s*)EndPreamble', re.IGNORECASE)
231     re_LangPreamble = re.compile(r'^(\s*)LangPreamble', re.IGNORECASE)
232     re_EndLangPreamble = re.compile(r'^(\s*)EndLangPreamble', re.IGNORECASE)
233     re_BabelPreamble = re.compile(r'^(\s*)BabelPreamble', re.IGNORECASE)
234     re_EndBabelPreamble = re.compile(r'^(\s*)EndBabelPreamble', re.IGNORECASE)
235     re_MaxCounter = re.compile(r'^(\s*)(MaxCounter)(\s+)(\S+)', re.IGNORECASE)
236     re_LabelType = re.compile(r'^(\s*)(LabelType)(\s+)(\S+)', re.IGNORECASE)
237     re_LabelString = re.compile(r'^(\s*)(LabelString)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
238     re_LabelStringAppendix = re.compile(r'^(\s*)(LabelStringAppendix)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
239     re_LatexType = re.compile(r'^(\s*)(LatexType)(\s+)(\S+)', re.IGNORECASE)
240     re_Style = re.compile(r'^(\s*)(Style)(\s+)(\S+)', re.IGNORECASE)
241     re_CopyStyle = re.compile(r'^(\s*)(CopyStyle)(\s+)(\S+)', re.IGNORECASE)
242     re_NoStyle = re.compile(r'^(\s*)(NoStyle)(\s+)(\S+)', re.IGNORECASE)
243     re_End = re.compile(r'^(\s*)(End)(\s*)$', re.IGNORECASE)
244     re_Provides = re.compile(r'^(\s*)Provides(\S+)(\s+)(\S+)', re.IGNORECASE)
245     re_CharStyle = re.compile(r'^(\s*)CharStyle(\s+)(\S+)$', re.IGNORECASE)
246     re_CiteFormat = re.compile(r'^(\s*)(CiteFormat)(?:(\s*)()|(\s+)(default|authoryear|numerical))', re.IGNORECASE)
247     re_AMSMaths = re.compile(r'^\s*Input ams(?:math|def)s.inc\s*')
248     re_AMSMathsPlain = re.compile(r'^\s*Input amsmaths-plain.inc\s*')
249     re_AMSMathsSeq = re.compile(r'^\s*Input amsmaths-seq.inc\s*')
250     re_TocLevel = re.compile(r'^(\s*)(TocLevel)(\s+)(\S+)', re.IGNORECASE)
251     re_I18nPreamble = re.compile(r'^(\s*)I18nPreamble', re.IGNORECASE)
252     re_EndI18nPreamble = re.compile(r'^(\s*)EndI18nPreamble', re.IGNORECASE)
253     re_Float = re.compile(r'^\s*Float\s*$', re.IGNORECASE)
254     re_Type = re.compile(r'\s*Type\s+(\w+)', re.IGNORECASE)
255     re_Builtin = re.compile(r'^(\s*)LaTeXBuiltin\s+(\w*)', re.IGNORECASE)
256     re_True = re.compile(r'^\s*(?:true|1)\s*$', re.IGNORECASE)
257     re_InsetLayout = re.compile(r'^\s*InsetLayout\s+(?:Custom|CharStyle|Element):(\S+)\s*$', re.IGNORECASE)
258     # with quotes
259     re_QInsetLayout = re.compile(r'^\s*InsetLayout\s+"(?:Custom|CharStyle|Element):([^"]+)"\s*$', re.IGNORECASE)
260     re_InsetLayout_CopyStyle = re.compile(r'^\s*CopyStyle\s+(?:Custom|CharStyle|Element):(\S+)\s*$', re.IGNORECASE)
261     re_QInsetLayout_CopyStyle = re.compile(r'^\s*CopyStyle\s+"(?:Custom|CharStyle|Element):([^"]+)"\s*$', re.IGNORECASE)
262     re_NeedsFloatPkg = re.compile(r'^(\s*)NeedsFloatPkg\s+(\w+)\s*$', re.IGNORECASE)
263     re_Fill = re.compile(r'^\s*Fill_(?:Top|Bottom).*$', re.IGNORECASE)
264     re_InsetLayout2 = re.compile(r'^\s*InsetLayout\s+(\S+)\s*$', re.IGNORECASE)
265     # with quotes
266     re_QInsetLayout2 = re.compile(r'^\s*InsetLayout\s+"([^"]+)"\s*$', re.IGNORECASE)
267     re_IsFlex = re.compile(r'\s*LyXType.*$', re.IGNORECASE)
268     re_CopyStyle2 = re.compile(r'(\s*CopyStyle\s+)"?([^"]+)"?\s*$')
269     # for categories
270     re_Declaration = re.compile(r'^#\s*\\Declare\w+Class.*$')
271     re_ExtractCategory = re.compile(r'^(#\s*\\Declare\w+Class(?:\[[^]]*?\])?){([^(]+?)\s+\(([^)]+?)\)\s*}\s*$')
272     ConvDict = {"article": "Articles", "book" : "Books", "letter" : "Letters", "report": "Reports", \
273                 "presentation" : "Presentations", "curriculum vitae" : "Curricula Vitae", "handout" : "Handouts"}
274     # Arguments
275     re_OptArgs = re.compile(r'^(\s*)OptionalArgs(\s+)(\d+)\D*$', re.IGNORECASE)
276     re_ReqArgs = re.compile(r'^(\s*)RequiredArgs(\s+)(\d+)\D*$', re.IGNORECASE)
277     
278     # various changes associated with changing how chapters are handled
279     re_LabelTypeIsCounter = re.compile(r'^(\s*)LabelType(\s*)Counter\s*$', re.IGNORECASE)
280     re_TopEnvironment = re.compile(r'^(\s*)LabelType(\s+)Top_Environment\s*$', re.IGNORECASE)
281     re_CenteredEnvironment = re.compile(r'^(\s*)LabelType(\s+)Centered_Top_Environment\s*$', re.IGNORECASE)
282     re_ChapterStyle = re.compile(r'^\s*Style\s+Chapter\s*$', re.IGNORECASE)
283
284
285     # counters for sectioning styles (hardcoded in 1.3)
286     counters = {"part"          : "\\Roman{part}",
287                 "chapter"       : "\\arabic{chapter}",
288                 "section"       : "\\arabic{section}",
289                 "subsection"    : "\\arabic{section}.\\arabic{subsection}",
290                 "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
291                 "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
292                 "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
293
294     # counters for sectioning styles in appendix (hardcoded in 1.3)
295     appendixcounters = {"chapter"       : "\\Alph{chapter}",
296                         "section"       : "\\Alph{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     # Value of TocLevel for sectioning styles
303     toclevels = {"part"          : -1,
304                  "chapter"       : 0,
305                  "section"       : 1,
306                  "subsection"    : 2,
307                  "subsubsection" : 3,
308                  "paragraph"     : 4,
309                  "subparagraph"  : 5}
310
311     i = 0
312     only_comment = 1
313     counter = ""
314     toclevel = ""
315     label = ""
316     labelstring = ""
317     labelstringappendix = ""
318     space1 = ""
319     labelstring_line = -1
320     labelstringappendix_line = -1
321     labeltype_line = -1
322     latextype = ""
323     latextype_line = -1
324     style = ""
325     maxcounter = 0
326     format = 1
327     formatline = 0
328     usemodules = []
329     flexstyles = []
330     opts = 0
331     reqs = 0
332     inchapter = False
333
334     while i < len(lines):
335         # Skip comments and empty lines
336         if (re_Comment.match(lines[i]) or re_Empty.match(lines[i])):
337           # We need to deal with this conversion here, because it happens
338           # inside the initial comment block.
339           if only_comment and format == 39:
340               match = re_ExtractCategory.match(lines[i])
341               if match:
342                   lpre = match.group(1)
343                   lcat = match.group(2)
344                   lnam = match.group(3)
345                   if lcat in ConvDict:
346                       lcat = ConvDict[lcat]
347                   lines[i] = lpre + "{" + lnam + "}"
348                   lines.insert(i+1, "#  \\DeclareCategory{" + lcat + "}")
349                   i += 1 
350           i += 1
351           continue
352
353         # insert file format if not already there
354         if (only_comment):
355             match = re_Format.match(lines[i])
356             if match:
357                 formatline = i
358                 format = int(match.group(4))
359                 if format > 1 and format < currentFormat:
360                     lines[i] = "Format %d" % (format + 1)
361                     only_comment = 0
362                 elif format == currentFormat:
363                     # nothing to do
364                     return format
365                 else:
366                     error('Cannot convert file format %s to %s' % (format, currentFormat))
367             else:
368                 lines.insert(i, "Format 2")
369                 only_comment = 0
370                 continue
371
372         # Don't get confused by LaTeX code
373         if re_Preamble.match(lines[i]):
374             i += 1
375             while i < len(lines) and not re_EndPreamble.match(lines[i]):
376                 i += 1
377             continue
378         if re_LangPreamble.match(lines[i]):
379             i += 1
380             while i < len(lines) and not re_EndLangPreamble.match(lines[i]):
381                 i += 1
382             continue
383         if re_BabelPreamble.match(lines[i]):
384             i += 1
385             while i < len(lines) and not re_EndBabelPreamble.match(lines[i]):
386                 i += 1
387             continue
388
389         if format >= 44 and format <= 47:
390             # nothing to do.
391             i += 1
392             continue
393
394         if format == 43:
395           match = re_LabelTypeIsCounter.match(lines[i])
396           if match:
397             if inchapter:
398              lines[i] = match.group(1) + "LabelType" + match.group(2) + "Above"              
399             else:
400               lines[i] = match.group(1) + "LabelType" + match.group(2) + "Static"
401
402           match = re_TopEnvironment.match(lines[i])
403           if match:
404             lines[i] = match.group(1) + "LabelType" + match.group(2) + "Above"
405
406           match = re_CenteredEnvironment.match(lines[i])
407           if match:
408             lines[i] = match.group(1) + "LabelType" + match.group(2) + "Centered"
409
410           if inchapter:
411             match = re_Style.match(lines[i])
412             if match:
413               inchapter = False
414           else:
415             match = re_ChapterStyle.match(lines[i])
416             if match:
417               inchapter = True
418
419           i += 1
420           continue
421
422         if format == 42:
423           if lines[i] == "InsetLayout Caption":
424             lines[i] = "InsetLayout Caption:Standard"
425           i += 1
426           continue
427         
428         if format == 41:
429             # nothing to do.
430             i += 1
431             continue
432
433         if format == 40:
434             # reset counters on Style beginning
435             match = re_Style.match(lines[i])
436             if match:
437                 opts = 0
438                 reqs = 0
439                 i += 1
440                 continue
441             match = re_OptArgs.match(lines[i])
442             if match:
443                 # Save number of optional arguments
444                 space1 = match.group(1)
445                 opts = int(match.group(3))
446                 # OptionalArgs 0 > ResetArgs 1
447                 if opts == 0:
448                     lines[i] = space1 + "ResetArgs\t1"
449                     i += 1
450                 else:
451                     del lines[i]
452                 continue
453             match = re_ReqArgs.match(lines[i])
454             if match:
455                 # Save number of required arguments
456                 space1 = match.group(1)
457                 reqs = int(match.group(3))
458                 del lines[i]
459                 continue
460             # Insert the required number of arguments at the end of the style definition
461             match = re_End.match(lines[i])
462             if match:
463                 newarg = ['']
464                 # First the optionals (this is the required order pre 2.1)
465                 if opts > 0:
466                     if opts == 1:
467                         newarg = [ '%sArgument 1' % (space1),
468                                    '%s\tLabelString\t\"Optional Layout Argument\"' % (space1),
469                                    '%sEndArgument' % (space1)]
470                     elif opts > 1:
471                         actopt = 1
472                         while actopt < (opts + 1):
473                             newarg += [ '%sArgument %d' % (space1, actopt),
474                                '%s\tLabelString\t\"Optional Layout Argument %d\"' % (space1, actopt),
475                                '%sEndArgument' % (space1)]
476                             actopt += 1
477                 # Now the mandatories
478                 if reqs > 0:
479                     actopt = opts + 1
480                     while actopt < (opts +  reqs + 1):
481                         newarg += [ '%sArgument %d' % (space1, actopt),
482                            '%s\tLabelString\t"Required Layout Argument %d"' % (space1, actopt - opts),
483                            '%s\tMandatory\t1' % (space1),
484                            '%sEndArgument' % (space1)]
485                         actopt += 1
486                 # Since we replace the "End" line, re-add this line
487                 if len(newarg) > 1:
488                     newarg += ['End']
489                     lines[i:i+1] = newarg
490                     i += len(newarg)
491                 # Reset the counters
492                 opts = 0
493                 reqs = 0
494             i += 1
495             continue
496         
497         if format == 39:
498             # There is a conversion with format 40, but it is done within the
499             # initial comment block and so is above.
500             i += 1
501             continue
502
503         if format == 37 or format == 38:
504             i += 1
505             continue
506
507         if format == 36:
508             match = re_CiteFormat.match(lines[i]);
509             if match and match.group(4) == "":
510                 lines[i] = match.group(0) + " default"
511             i += 1
512             continue
513
514         if format == 35:
515           i += 1
516           continue
517
518         if format == 34:
519           match = re_QInsetLayout2.match(lines[i])
520           if not match:
521             match = re_InsetLayout2.match(lines[i])
522           if not match:
523             match = re_CopyStyle2.match(lines[i])
524             if not match:
525               i += 1
526               continue
527             style = match.group(2)
528             
529             if flexstyles.count(style):
530               lines[i] = match.group(1) + "\"Flex:" + style + "\""
531             i += 1
532             continue
533
534           name = match.group(1)
535           names = name.split(":", 1)
536           if len(names) > 1 and names[0] == "Flex":
537             i += 1
538             continue
539
540           isflex = False
541           for j in range(i + 1, len(lines)):
542             if re_IsFlex.match(lines[j]):
543               isflex = True
544               break
545             if re_End.match(lines[j]):
546               break
547
548           if isflex:
549             flexstyles.append(name)
550             lines[i] = "InsetLayout \"Flex:" + name + "\""
551
552           i += 1
553           continue
554
555         if format == 33:
556           m = re_Fill.match(lines[i])
557           if m:
558             lines[i] = ""
559           i += 1
560           continue
561
562         if format == 32:
563           match = re_NeedsFloatPkg.match(lines[i])
564           if match:
565             space = match.group(1)
566             val = match.group(2)
567             lines[i] = space + "UsesFloatPkg " + val
568             newval = 'true'
569             if val == '1' or val.lower() == 'true':
570               newval = 'false'
571             lines.insert(i, space + "IsPredefined " + newval)
572             i += 1
573           i += 1
574           continue
575
576         # Only new features
577         if format >= 29 and format <= 31:
578           i += 1
579           continue
580
581         if format == 28:
582           match = re_InsetLayout.match(lines[i])
583           if match:
584             lines[i] = "InsetLayout Flex:" + match.group(1)
585           else:
586             match = re_QInsetLayout.match(lines[i])
587             if match:
588               lines[i] = "InsetLayout \"Flex:" + match.group(1) + "\""
589             else:
590               match = re_InsetLayout_CopyStyle.match(lines[i])
591               if match:
592                 lines[i] = "\tCopyStyle Flex:" + match.group(1)
593               else:
594                 match = re_QInsetLayout_CopyStyle.match(lines[i])
595                 if match:
596                   lines[i] = "\tCopyStyle \"Flex:" + match.group(1) + "\""
597           i += 1
598           continue
599         
600         # Only new features
601         if format >= 24 and format <= 27:
602           i += 1
603           continue
604
605         if format == 23:
606           match = re_Float.match(lines[i])
607           i += 1
608           if not match:
609             continue
610           # we need to do two things:
611           # (i)  Convert Builtin to NeedsFloatPkg
612           # (ii) Write ListCommand lines for the builtin floats table and figure
613           builtin = False
614           cmd = ""
615           while True and i < len(lines):
616             m1 = re_End.match(lines[i])
617             if m1:
618               if builtin and cmd:
619                 line = "    ListCommand " + cmd
620                 lines.insert(i, line)
621                 i += 1
622               break
623             m2 = re_Builtin.match(lines[i])
624             if m2:
625               builtin = True
626               ws1 = m2.group(1)
627               arg = m2.group(2)
628               newarg = ""
629               if re_True.match(arg):
630                 newarg = "false"
631               else:
632                 newarg = "true"
633               lines[i] = ws1 + "NeedsFloatPkg " + newarg
634             m3 = re_Type.match(lines[i])
635             if m3:
636               fltype = m3.group(1)
637               fltype = fltype.lower()
638               if fltype == "table":
639                 cmd = "listoftables"
640               elif fltype == "figure":
641                 cmd = "listoffigures"
642               # else unknown, which is why we're doing this
643             i += 1
644           continue              
645           
646         # This just involved new features, not any changes to old ones
647         if format >= 14 and format <= 22:
648           i += 1
649           continue
650
651         # Rename I18NPreamble to BabelPreamble
652         if format == 13:
653             match = re_I18nPreamble.match(lines[i])
654             if match:
655                 lines[i] = match.group(1) + "BabelPreamble"
656                 i += 1
657                 match = re_EndI18nPreamble.match(lines[i])
658                 while i < len(lines) and not match:
659                     i += 1
660                     match = re_EndI18nPreamble.match(lines[i])
661                 lines[i] = match.group(1) + "EndBabelPreamble"
662                 i += 1
663                 continue
664
665         # These just involved new features, not any changes to old ones
666         if format == 11 or format == 12:
667           i += 1
668           continue
669
670         if format == 10:
671             match = re_UseMod.match(lines[i])
672             if match:
673                 module = match.group(1)
674                 lines[i] = "DefaultModule " + module
675             i += 1
676             continue
677
678         if format == 9:
679             match = re_Counter.match(lines[i])
680             if match:
681                 counterline = i
682                 i += 1
683                 while i < len(lines):
684                     namem = re_Name.match(lines[i])
685                     if namem:
686                         name = namem.group(1)
687                         lines.pop(i)
688                         lines[counterline] = "Counter %s" % name
689                         # we don't need to increment i
690                         continue
691                     endem = re_End.match(lines[i])
692                     if endem:
693                         i += 1
694                         break
695                     i += 1
696             i += 1
697             continue
698
699         if format == 8:
700             # We want to scan for ams-type includes and, if we find them,
701             # add corresponding UseModule tags to the layout.
702             match = re_AMSMaths.match(lines[i])
703             if match:
704                 addstring("theorems-ams", usemodules)
705                 addstring("theorems-ams-extended", usemodules)
706                 addstring("theorems-sec", usemodules)
707                 lines.pop(i)
708                 continue
709             match = re_AMSMathsPlain.match(lines[i])
710             if match:
711                 addstring("theorems-starred", usemodules)
712                 lines.pop(i)
713                 continue
714             match = re_AMSMathsSeq.match(lines[i])
715             if match:
716                 addstring("theorems-ams", usemodules)
717                 addstring("theorems-ams-extended", usemodules)
718                 lines.pop(i)
719                 continue
720             i += 1
721             continue
722
723         # These just involved new features, not any changes to old ones
724         if format >= 5 and format <= 7:
725           i += 1
726           continue
727
728         if format == 4:
729             # Handle conversion to long CharStyle names
730             match = re_CharStyle.match(lines[i])
731             if match:
732                 lines[i] = "InsetLayout CharStyle:%s" % (match.group(3))
733                 i += 1
734                 lines.insert(i, "\tLyXType charstyle")
735                 i += 1
736                 lines.insert(i, "")
737                 lines[i] = "\tLabelString %s" % (match.group(3))
738             i += 1
739             continue
740
741         if format == 3:
742             # convert 'providesamsmath x',  'providesmakeidx x',  'providesnatbib x',  'providesurl x' to
743             #         'provides amsmath x', 'provides makeidx x', 'provides natbib x', 'provides url x'
744             # x is either 0 or 1
745             match = re_Provides.match(lines[i])
746             if match:
747                 lines[i] = "%sProvides %s%s%s" % (match.group(1), match.group(2).lower(),
748                                                   match.group(3), match.group(4))
749             i += 1
750             continue
751
752         if format == 2:
753             caption = []
754
755             # delete caption styles
756             match = re_Style.match(lines[i])
757             if match:
758                 style = string.lower(match.group(4))
759                 if style == "caption":
760                     del lines[i]
761                     while i < len(lines) and not re_End.match(lines[i]):
762                         caption.append(lines[i])
763                         del lines[i]
764                     if i == len(lines):
765                         error('Incomplete caption style.')
766                     else:
767                         del lines[i]
768                         continue
769
770             # delete undefinition of caption styles
771             match = re_NoStyle.match(lines[i])
772             if match:
773                 style = string.lower(match.group(4))
774                 if style == "caption":
775                     del lines[i]
776                     continue
777
778             # replace the CopyStyle statement with the definition of the real
779             # style. This may result in duplicate statements, but that is OK
780             # since the second one will overwrite the first one.
781             match = re_CopyStyle.match(lines[i])
782             if match:
783                 style = string.lower(match.group(4))
784                 if style == "caption":
785                     if len(caption) > 0:
786                         lines[i:i+1] = caption
787                     else:
788                         # FIXME: This style comes from an include file, we
789                         # should replace the real style and not this default.
790                         lines[i:i+1] = ['       Margin                First_Dynamic',
791                                         '       LatexType             Command',
792                                         '       LatexName             caption',
793                                         '       NeedProtect           1',
794                                         '       LabelSep              xx',
795                                         '       ParSkip               0.4',
796                                         '       TopSep                0.5',
797                                         '       Align                 Center',
798                                         '       AlignPossible         Center',
799                                         '       LabelType             Sensitive',
800                                         '       LabelString           "Senseless!"',
801                                         '       OptionalArgs          1',
802                                         '       LabelFont',
803                                         '         Series              Bold',
804                                         '       EndFont']
805
806             i += 1
807             continue
808
809         # Delete MaxCounter and remember the value of it
810         match = re_MaxCounter.match(lines[i])
811         if match:
812             level = match.group(4)
813             if string.lower(level) == "counter_chapter":
814                 maxcounter = 0
815             elif string.lower(level) == "counter_section":
816                 maxcounter = 1
817             elif string.lower(level) == "counter_subsection":
818                 maxcounter = 2
819             elif string.lower(level) == "counter_subsubsection":
820                 maxcounter = 3
821             elif string.lower(level) == "counter_paragraph":
822                 maxcounter = 4
823             elif string.lower(level) == "counter_subparagraph":
824                 maxcounter = 5
825             elif string.lower(level) == "counter_enumi":
826                 maxcounter = 6
827             elif string.lower(level) == "counter_enumii":
828                 maxcounter = 7
829             elif string.lower(level) == "counter_enumiii":
830                 maxcounter = 8
831             del lines[i]
832             continue
833
834         # Replace line
835         #
836         # LabelType Counter_EnumI
837         #
838         # with two lines
839         #
840         # LabelType Counter
841         # LabelCounter EnumI
842         #
843         match = re_LabelType.match(lines[i])
844         if match:
845             label = match.group(4)
846             # Remember indenting space for later reuse in added lines
847             space1 = match.group(1)
848             # Remember the line for adding the LabelCounter later.
849             # We can't do it here because it could shift latextype_line etc.
850             labeltype_line = i
851             if string.lower(label[:8]) == "counter_":
852                 counter = string.lower(label[8:])
853                 lines[i] = re_LabelType.sub(r'\1\2\3Counter', lines[i])
854
855         # Remember the LabelString line
856         match = re_LabelString.match(lines[i])
857         if match:
858             labelstring = match.group(4)
859             labelstring_line = i
860
861         # Remember the LabelStringAppendix line
862         match = re_LabelStringAppendix.match(lines[i])
863         if match:
864             labelstringappendix = match.group(4)
865             labelstringappendix_line = i
866
867         # Remember the LatexType line
868         match = re_LatexType.match(lines[i])
869         if match:
870             latextype = string.lower(match.group(4))
871             latextype_line = i
872
873         # Remember the TocLevel line
874         match = re_TocLevel.match(lines[i])
875         if match:
876             toclevel = string.lower(match.group(4))
877
878         # Reset variables at the beginning of a style definition
879         match = re_Style.match(lines[i])
880         if match:
881             style = string.lower(match.group(4))
882             counter = ""
883             toclevel = ""
884             label = ""
885             space1 = ""
886             labelstring = ""
887             labelstringappendix = ""
888             labelstring_line = -1
889             labelstringappendix_line = -1
890             labeltype_line = -1
891             latextype = ""
892             latextype_line = -1
893
894         if re_End.match(lines[i]):
895
896             # Add a line "LatexType Bib_Environment" if LabelType is Bibliography
897             # (or change the existing LatexType)
898             if string.lower(label) == "bibliography":
899                 if (latextype_line < 0):
900                     lines.insert(i, "%sLatexType Bib_Environment" % space1)
901                     i += 1
902                 else:
903                     lines[latextype_line] = re_LatexType.sub(r'\1\2\3Bib_Environment', lines[latextype_line])
904
905             # Change "LabelType Static" to "LabelType Itemize" for itemize environments
906             if latextype == "item_environment" and string.lower(label) == "static":
907                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Itemize', lines[labeltype_line])
908
909             # Change "LabelType Counter_EnumI" to "LabelType Enumerate" for enumerate environments
910             if latextype == "item_environment" and string.lower(label) == "counter_enumi":
911                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Enumerate', lines[labeltype_line])
912                 # Don't add the LabelCounter line later
913                 counter = ""
914
915             # Replace
916             #
917             # LabelString "Chapter"
918             #
919             # with
920             #
921             # LabelString "Chapter \arabic{chapter}"
922             #
923             # if this style has a counter. Ditto for LabelStringAppendix.
924             # This emulates the hardcoded article style numbering of 1.3
925             #
926             if counter != "":
927                 if style in counters:
928                     if labelstring_line < 0:
929                         lines.insert(i, '%sLabelString "%s"' % (space1, counters[style]))
930                         i += 1
931                     else:
932                         new_labelstring = concatenate_label(labelstring, counters[style])
933                         lines[labelstring_line] = re_LabelString.sub(
934                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
935                                 lines[labelstring_line])
936                 if style in appendixcounters:
937                     if labelstringappendix_line < 0:
938                         lines.insert(i, '%sLabelStringAppendix "%s"' % (space1, appendixcounters[style]))
939                         i += 1
940                     else:
941                         new_labelstring = concatenate_label(labelstring, appendixcounters[style])
942                         lines[labelstringappendix_line] = re_LabelStringAppendix.sub(
943                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
944                                 lines[labelstringappendix_line])
945
946                 # Now we can safely add the LabelCounter line
947                 lines.insert(labeltype_line + 1, "%sLabelCounter %s" % (space1, counter))
948                 i += 1
949
950             # Add the TocLevel setting for sectioning styles
951             if toclevel == "" and style in toclevels and maxcounter <= toclevels[style]:
952                 lines.insert(i, '%s\tTocLevel %d' % (space1, toclevels[style]))
953                 i += 1
954
955         i += 1
956
957     if only_comment:
958         lines.insert(i, "Format 2")
959     if usemodules:
960         i = formatline + 1
961         for mod in usemodules:
962             lines.insert(i, "UseModule " + mod)
963             i += 1
964
965     return format + 1
966
967
968 def main(argv):
969
970     # Open files
971     if len(argv) == 1:
972         source = sys.stdin
973         output = sys.stdout
974     elif len(argv) == 3:
975         source = open(argv[1], 'rb')
976         output = open(argv[2], 'wb')
977     else:
978         error(usage(argv[0]))
979
980     # Do the real work
981     lines = read(source)
982     format = 1
983     while (format < currentFormat):
984         format = convert(lines)
985     write(output, lines)
986
987     # Close files
988     if len(argv) == 3:
989         source.close()
990         output.close()
991
992     return 0
993
994
995 if __name__ == "__main__":
996     main(sys.argv)