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