]> git.lyx.org Git - lyx.git/blob - lib/scripts/layout2layout.py
e018f43a974a8d0a2d9a9027d4baa3a0ba45485b
[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.
89
90 # Do not forget to document format change in Customization
91 # Manual (section "Declaring a new text class").
92
93 # You might also want to consider running the
94 # development/tools/updatelayouts.sh script to update all
95 # layout files to the new format.
96
97 currentFormat = 24
98
99
100 def usage(prog_name):
101     return ("Usage: %s inputfile outputfile\n" % prog_name +
102             "or     %s <inputfile >outputfile" % prog_name)
103
104
105 def error(message):
106     sys.stderr.write(message + '\n')
107     sys.exit(1)
108
109
110 def trim_bom(line):
111     " Remove byte order mark."
112     if line[0:3] == "\357\273\277":
113         return line[3:]
114     else:
115         return line
116
117
118 def read(source):
119     " Read input file and strip lineendings."
120     lines = source.read().splitlines()
121     lines[0] = trim_bom(lines[0])
122     return lines
123
124
125 def write(output, lines):
126     " Write output file with native lineendings."
127     output.write(os.linesep.join(lines) + os.linesep)
128
129
130 # Concatenates old and new in an intelligent way:
131 # If old is wrapped in ", they are stripped. The result is wrapped in ".
132 def concatenate_label(old, new):
133     # Don't use strip as long as we support python 1.5.2
134     if old[0] == '"':
135         return old[0:-1] + new + '"'
136     else:
137         return '"' + old + new + '"'
138
139 # appends a string to a list unless it's already there
140 def addstring(s, l):
141     if l.count(s) > 0:
142         return
143     l.append(s)
144
145
146 def convert(lines):
147     " Convert to new format."
148     re_Comment = re.compile(r'^(\s*)#')
149     re_Counter = re.compile(r'\s*Counter\s*', re.IGNORECASE)
150     re_Name = re.compile(r'\s*Name\s+(\S+)\s*', re.IGNORECASE)
151     re_UseMod = re.compile(r'^\s*UseModule\s+(.*)', re.IGNORECASE)
152     re_Empty = re.compile(r'^(\s*)$')
153     re_Format = re.compile(r'^(\s*)(Format)(\s+)(\S+)', re.IGNORECASE)
154     re_Preamble = re.compile(r'^(\s*)Preamble', re.IGNORECASE)
155     re_EndPreamble = re.compile(r'^(\s*)EndPreamble', re.IGNORECASE)
156     re_LangPreamble = re.compile(r'^(\s*)LangPreamble', re.IGNORECASE)
157     re_EndLangPreamble = re.compile(r'^(\s*)EndLangPreamble', re.IGNORECASE)
158     re_BabelPreamble = re.compile(r'^(\s*)BabelPreamble', re.IGNORECASE)
159     re_EndBabelPreamble = re.compile(r'^(\s*)EndBabelPreamble', re.IGNORECASE)
160     re_MaxCounter = re.compile(r'^(\s*)(MaxCounter)(\s+)(\S+)', re.IGNORECASE)
161     re_LabelType = re.compile(r'^(\s*)(LabelType)(\s+)(\S+)', re.IGNORECASE)
162     re_LabelString = re.compile(r'^(\s*)(LabelString)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
163     re_LabelStringAppendix = re.compile(r'^(\s*)(LabelStringAppendix)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
164     re_LatexType = re.compile(r'^(\s*)(LatexType)(\s+)(\S+)', re.IGNORECASE)
165     re_Style = re.compile(r'^(\s*)(Style)(\s+)(\S+)', re.IGNORECASE)
166     re_CopyStyle = re.compile(r'^(\s*)(CopyStyle)(\s+)(\S+)', re.IGNORECASE)
167     re_NoStyle = re.compile(r'^(\s*)(NoStyle)(\s+)(\S+)', re.IGNORECASE)
168     re_End = re.compile(r'^(\s*)(End)(\s*)$', re.IGNORECASE)
169     re_Provides = re.compile(r'^(\s*)Provides(\S+)(\s+)(\S+)', re.IGNORECASE)
170     re_CharStyle = re.compile(r'^(\s*)CharStyle(\s+)(\S+)$', re.IGNORECASE)
171     re_AMSMaths = re.compile(r'^\s*Input ams(?:math|def)s.inc\s*')
172     re_AMSMathsPlain = re.compile(r'^\s*Input amsmaths-plain.inc\s*')
173     re_AMSMathsSeq = re.compile(r'^\s*Input amsmaths-seq.inc\s*')
174     re_TocLevel = re.compile(r'^(\s*)(TocLevel)(\s+)(\S+)', re.IGNORECASE)
175     re_I18nPreamble = re.compile(r'^(\s*)I18nPreamble', re.IGNORECASE)
176     re_EndI18nPreamble = re.compile(r'^(\s*)EndI18nPreamble', re.IGNORECASE)
177     re_Builtin = re.compile(r'^(\s*)LaTeXBuiltin\s+(\w*)', re.IGNORECASE)
178     re_True = re.compile(r'^\s*(?:true|1)\s*$', re.IGNORECASE)
179
180     # counters for sectioning styles (hardcoded in 1.3)
181     counters = {"part"          : "\\Roman{part}",
182                 "chapter"       : "\\arabic{chapter}",
183                 "section"       : "\\arabic{section}",
184                 "subsection"    : "\\arabic{section}.\\arabic{subsection}",
185                 "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
186                 "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
187                 "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
188
189     # counters for sectioning styles in appendix (hardcoded in 1.3)
190     appendixcounters = {"chapter"       : "\\Alph{chapter}",
191                         "section"       : "\\Alph{section}",
192                         "subsection"    : "\\arabic{section}.\\arabic{subsection}",
193                         "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
194                         "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
195                         "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
196
197     # Value of TocLevel for sectioning styles
198     toclevels = {"part"          : 0,
199                  "chapter"       : 0,
200                  "section"       : 1,
201                  "subsection"    : 2,
202                  "subsubsection" : 3,
203                  "paragraph"     : 4,
204                  "subparagraph"  : 5}
205
206     i = 0
207     only_comment = 1
208     counter = ""
209     toclevel = ""
210     label = ""
211     labelstring = ""
212     labelstringappendix = ""
213     space1 = ""
214     labelstring_line = -1
215     labelstringappendix_line = -1
216     labeltype_line = -1
217     latextype = ""
218     latextype_line = -1
219     style = ""
220     maxcounter = 0
221     format = 1
222     formatline = 0
223     usemodules = []
224
225     while i < len(lines):
226         # Skip comments and empty lines
227         if re_Comment.match(lines[i]) or re_Empty.match(lines[i]):
228             i += 1
229             continue
230
231         # insert file format if not already there
232         if (only_comment):
233             match = re_Format.match(lines[i])
234             if match:
235                 formatline = i
236                 format = int(match.group(4))
237                 if format > 1 and format < currentFormat:
238                     lines[i] = "Format %d" % (format + 1)
239                     only_comment = 0
240                 elif format == currentFormat:
241                     # nothing to do
242                     return format
243                 else:
244                     error('Cannot convert file format %s' % format)
245             else:
246                 lines.insert(i, "Format 2")
247                 only_comment = 0
248                 continue
249
250         # Don't get confused by LaTeX code
251         if re_Preamble.match(lines[i]):
252             i += 1
253             while i < len(lines) and not re_EndPreamble.match(lines[i]):
254                 i += 1
255             continue
256         if re_LangPreamble.match(lines[i]):
257             i += 1
258             while i < len(lines) and not re_EndLangPreamble.match(lines[i]):
259                 i += 1
260             continue
261         if re_BabelPreamble.match(lines[i]):
262             i += 1
263             while i < len(lines) and not re_EndBabelPreamble.match(lines[i]):
264                 i += 1
265             continue
266
267         if format == 23:
268           match = re_Builtin.match(lines[i])
269           if match:
270             ws = match.group(1)
271             arg = match.group(2)
272             newarg = ""
273             if re_True.match(arg):
274               newarg = "false"
275             else:
276               newarg = "true"
277             lines[i] = ws + "NeedsFloatPkg " + newarg
278               
279           
280         # This just involved new features, not any changes to old ones
281         if format >= 14 and format <= 22:
282           i += 1
283           continue
284
285         # Rename I18NPreamble to BabelPreamble
286         if format == 13:
287             match = re_I18nPreamble.match(lines[i])
288             if match:
289                 lines[i] = match.group(1) + "BabelPreamble"
290                 i += 1
291                 match = re_EndI18nPreamble.match(lines[i])
292                 while i < len(lines) and not match:
293                     i += 1
294                     match = re_EndI18nPreamble.match(lines[i])
295                 lines[i] = match.group(1) + "EndBabelPreamble"
296                 i += 1
297                 continue
298
299         # These just involved new features, not any changes to old ones
300         if format == 11 or format == 12:
301           i += 1
302           continue
303
304         if format == 10:
305             match = re_UseMod.match(lines[i])
306             if match:
307                 module = match.group(1)
308                 lines[i] = "DefaultModule " + module
309             i += 1
310             continue
311
312         if format == 9:
313             match = re_Counter.match(lines[i])
314             if match:
315                 counterline = i
316                 i += 1
317                 while i < len(lines):
318                     namem = re_Name.match(lines[i])
319                     if namem:
320                         name = namem.group(1)
321                         lines.pop(i)
322                         lines[counterline] = "Counter %s" % name
323                         # we don't need to increment i
324                         continue
325                     endem = re_End.match(lines[i])
326                     if endem:
327                         i += 1
328                         break
329                     i += 1
330             i += 1
331             continue
332
333         if format == 8:
334             # We want to scan for ams-type includes and, if we find them,
335             # add corresponding UseModule tags to the layout.
336             match = re_AMSMaths.match(lines[i])
337             if match:
338                 addstring("theorems-ams", usemodules)
339                 addstring("theorems-ams-extended", usemodules)
340                 addstring("theorems-sec", usemodules)
341                 lines.pop(i)
342                 continue
343             match = re_AMSMathsPlain.match(lines[i])
344             if match:
345                 addstring("theorems-starred", usemodules)
346                 lines.pop(i)
347                 continue
348             match = re_AMSMathsSeq.match(lines[i])
349             if match:
350                 addstring("theorems-ams", usemodules)
351                 addstring("theorems-ams-extended", usemodules)
352                 lines.pop(i)
353                 continue
354             i += 1
355             continue
356
357         # These just involved new features, not any changes to old ones
358         if format >= 5 and format <= 7:
359           i += 1
360           continue
361
362         if format == 4:
363             # Handle conversion to long CharStyle names
364             match = re_CharStyle.match(lines[i])
365             if match:
366                 lines[i] = "InsetLayout CharStyle:%s" % (match.group(3))
367                 i += 1
368                 lines.insert(i, "\tLyXType charstyle")
369                 i += 1
370                 lines.insert(i, "")
371                 lines[i] = "\tLabelString %s" % (match.group(3))
372             i += 1
373             continue
374
375         if format == 3:
376             # convert 'providesamsmath x',  'providesmakeidx x',  'providesnatbib x',  'providesurl x' to
377             #         'provides amsmath x', 'provides makeidx x', 'provides natbib x', 'provides url x'
378             # x is either 0 or 1
379             match = re_Provides.match(lines[i])
380             if match:
381                 lines[i] = "%sProvides %s%s%s" % (match.group(1), match.group(2).lower(),
382                                                   match.group(3), match.group(4))
383             i += 1
384             continue
385
386         if format == 2:
387             caption = []
388
389             # delete caption styles
390             match = re_Style.match(lines[i])
391             if match:
392                 style = string.lower(match.group(4))
393                 if style == "caption":
394                     del lines[i]
395                     while i < len(lines) and not re_End.match(lines[i]):
396                         caption.append(lines[i])
397                         del lines[i]
398                     if i == len(lines):
399                         error('Incomplete caption style.')
400                     else:
401                         del lines[i]
402                         continue
403
404             # delete undefinition of caption styles
405             match = re_NoStyle.match(lines[i])
406             if match:
407                 style = string.lower(match.group(4))
408                 if style == "caption":
409                     del lines[i]
410                     continue
411
412             # replace the CopyStyle statement with the definition of the real
413             # style. This may result in duplicate statements, but that is OK
414             # since the second one will overwrite the first one.
415             match = re_CopyStyle.match(lines[i])
416             if match:
417                 style = string.lower(match.group(4))
418                 if style == "caption":
419                     if len(caption) > 0:
420                         lines[i:i+1] = caption
421                     else:
422                         # FIXME: This style comes from an include file, we
423                         # should replace the real style and not this default.
424                         lines[i:i+1] = ['       Margin                First_Dynamic',
425                                         '       LatexType             Command',
426                                         '       LatexName             caption',
427                                         '       NeedProtect           1',
428                                         '       LabelSep              xx',
429                                         '       ParSkip               0.4',
430                                         '       TopSep                0.5',
431                                         '       Align                 Center',
432                                         '       AlignPossible         Center',
433                                         '       LabelType             Sensitive',
434                                         '       LabelString           "Senseless!"',
435                                         '       OptionalArgs          1',
436                                         '       LabelFont',
437                                         '         Series              Bold',
438                                         '       EndFont']
439
440             i += 1
441             continue
442
443         # Delete MaxCounter and remember the value of it
444         match = re_MaxCounter.match(lines[i])
445         if match:
446             level = match.group(4)
447             if string.lower(level) == "counter_chapter":
448                 maxcounter = 0
449             elif string.lower(level) == "counter_section":
450                 maxcounter = 1
451             elif string.lower(level) == "counter_subsection":
452                 maxcounter = 2
453             elif string.lower(level) == "counter_subsubsection":
454                 maxcounter = 3
455             elif string.lower(level) == "counter_paragraph":
456                 maxcounter = 4
457             elif string.lower(level) == "counter_subparagraph":
458                 maxcounter = 5
459             elif string.lower(level) == "counter_enumi":
460                 maxcounter = 6
461             elif string.lower(level) == "counter_enumii":
462                 maxcounter = 7
463             elif string.lower(level) == "counter_enumiii":
464                 maxcounter = 8
465             del lines[i]
466             continue
467
468         # Replace line
469         #
470         # LabelType Counter_EnumI
471         #
472         # with two lines
473         #
474         # LabelType Counter
475         # LabelCounter EnumI
476         #
477         match = re_LabelType.match(lines[i])
478         if match:
479             label = match.group(4)
480             # Remember indenting space for later reuse in added lines
481             space1 = match.group(1)
482             # Remember the line for adding the LabelCounter later.
483             # We can't do it here because it could shift latextype_line etc.
484             labeltype_line = i
485             if string.lower(label[:8]) == "counter_":
486                 counter = string.lower(label[8:])
487                 lines[i] = re_LabelType.sub(r'\1\2\3Counter', lines[i])
488
489         # Remember the LabelString line
490         match = re_LabelString.match(lines[i])
491         if match:
492             labelstring = match.group(4)
493             labelstring_line = i
494
495         # Remember the LabelStringAppendix line
496         match = re_LabelStringAppendix.match(lines[i])
497         if match:
498             labelstringappendix = match.group(4)
499             labelstringappendix_line = i
500
501         # Remember the LatexType line
502         match = re_LatexType.match(lines[i])
503         if match:
504             latextype = string.lower(match.group(4))
505             latextype_line = i
506
507         # Remember the TocLevel line
508         match = re_TocLevel.match(lines[i])
509         if match:
510             toclevel = string.lower(match.group(4))
511
512         # Reset variables at the beginning of a style definition
513         match = re_Style.match(lines[i])
514         if match:
515             style = string.lower(match.group(4))
516             counter = ""
517             toclevel = ""
518             label = ""
519             space1 = ""
520             labelstring = ""
521             labelstringappendix = ""
522             labelstring_line = -1
523             labelstringappendix_line = -1
524             labeltype_line = -1
525             latextype = ""
526             latextype_line = -1
527
528         if re_End.match(lines[i]):
529
530             # Add a line "LatexType Bib_Environment" if LabelType is Bibliography
531             # (or change the existing LatexType)
532             if string.lower(label) == "bibliography":
533                 if (latextype_line < 0):
534                     lines.insert(i, "%sLatexType Bib_Environment" % space1)
535                     i += 1
536                 else:
537                     lines[latextype_line] = re_LatexType.sub(r'\1\2\3Bib_Environment', lines[latextype_line])
538
539             # Change "LabelType Static" to "LabelType Itemize" for itemize environments
540             if latextype == "item_environment" and string.lower(label) == "static":
541                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Itemize', lines[labeltype_line])
542
543             # Change "LabelType Counter_EnumI" to "LabelType Enumerate" for enumerate environments
544             if latextype == "item_environment" and string.lower(label) == "counter_enumi":
545                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Enumerate', lines[labeltype_line])
546                 # Don't add the LabelCounter line later
547                 counter = ""
548
549             # Replace
550             #
551             # LabelString "Chapter"
552             #
553             # with
554             #
555             # LabelString "Chapter \arabic{chapter}"
556             #
557             # if this style has a counter. Ditto for LabelStringAppendix.
558             # This emulates the hardcoded article style numbering of 1.3
559             #
560             if counter != "":
561                 if counters.has_key(style):
562                     if labelstring_line < 0:
563                         lines.insert(i, '%sLabelString "%s"' % (space1, counters[style]))
564                         i += 1
565                     else:
566                         new_labelstring = concatenate_label(labelstring, counters[style])
567                         lines[labelstring_line] = re_LabelString.sub(
568                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
569                                 lines[labelstring_line])
570                 if appendixcounters.has_key(style):
571                     if labelstringappendix_line < 0:
572                         lines.insert(i, '%sLabelStringAppendix "%s"' % (space1, appendixcounters[style]))
573                         i += 1
574                     else:
575                         new_labelstring = concatenate_label(labelstring, appendixcounters[style])
576                         lines[labelstringappendix_line] = re_LabelStringAppendix.sub(
577                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
578                                 lines[labelstringappendix_line])
579
580                 # Now we can safely add the LabelCounter line
581                 lines.insert(labeltype_line + 1, "%sLabelCounter %s" % (space1, counter))
582                 i += 1
583
584             # Add the TocLevel setting for sectioning styles
585             if toclevel == "" and toclevels.has_key(style) and maxcounter <= toclevels[style]:
586                 lines.insert(i, '%s\tTocLevel %d' % (space1, toclevels[style]))
587                 i += 1
588
589         i += 1
590
591     if usemodules:
592         i = formatline + 1
593         for mod in usemodules:
594             lines.insert(i, "UseModule " + mod)
595             i += 1
596
597     return format + 1
598
599
600 def main(argv):
601
602     # Open files
603     if len(argv) == 1:
604         source = sys.stdin
605         output = sys.stdout
606     elif len(argv) == 3:
607         source = open(argv[1], 'rb')
608         output = open(argv[2], 'wb')
609     else:
610         error(usage(argv[0]))
611
612     # Do the real work
613     lines = read(source)
614     format = 1
615     while (format < currentFormat):
616         format = convert(lines)
617     write(output, lines)
618
619     # Close files
620     if len(argv) == 3:
621         source.close()
622         output.close()
623
624     return 0
625
626
627 if __name__ == "__main__":
628     main(sys.argv)