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