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