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