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