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