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