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