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