2 # -*- coding: utf-8 -*-
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
8 # \author Angus Leeming
11 # Full author contact details are available in file CREDITS
14 # fig_copy.py <from file> <to file>
16 # This script will copy an XFIG .fig file "$1" to "$2". In the process,
17 # it will modify the contents of the .fig file so that the names of any
18 # picture files that are stored as relative paths are replaced
19 # with the absolute path.
21 import os, sys, locale
23 if len(sys.argv) != 3:
24 print >> sys.stderr, "Usage: fig_copy.py <from file> <to file>"
27 language, output_encoding = locale.getdefaultlocale()
28 if output_encoding == None:
29 output_encoding = 'latin1'
31 from_file = unicode(sys.argv[1], 'utf8').encode(output_encoding)
32 to_file = unicode(sys.argv[2], 'utf8').encode(output_encoding)
34 if not os.path.isfile(from_file):
35 print >> sys.stderr, "Unable to read", from_file
38 from_dir = os.path.split(os.path.realpath(from_file))[0]
39 to_dir = os.path.split(os.path.realpath(to_file))[0]
41 # The work is trivial if "to" and "from" are in the same directory.
42 if from_dir == to_dir:
45 shutil.copy(from_file, to_file)
50 # Ok, they're in different directories. The .fig file must be modified.
53 # We're looking for a line of text that defines an entry of
54 # type '2' (a polyline), subtype '5' (an external picture file).
55 # The line has 14 other data fields.
56 patternline = re.compile(r'^\s*2\s+5(\s+[0-9.+-]+){14}\s*$')
57 emptyline = re.compile(r'^\s*$')
58 commentline = re.compile(r'^\s*#.*$')
59 # we allow space in path name
60 figureline = re.compile(r'^(\s*[01]\s*)(\S[\S ]*)(\s*)$')
62 input = open(from_file, 'r')
63 output = open(to_file, 'w')
65 # path in the fig is relative to this path
69 for line in input.xreadlines():
70 if found and not emptyline.match(line) and not commentline.match(line):
71 # The contents of the final line containing the file name
72 # are ' X <file name>', where X = 0 or 1.
73 # We extract filename and replace it with the absolute filename.
74 (pre, path, post) = figureline.match(line).groups()
75 line = pre + os.path.realpath(path) + post
77 elif patternline.match(line):
79 print >> output, line,