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