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