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