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