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