]> git.lyx.org Git - lyx.git/blob - src/support/filetools.cpp
Fix layout bug. Pasting text into a cell tried to set Standard layout, because
[lyx.git] / src / support / filetools.cpp
1 /**
2  * \file filetools.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * parts Copyright 1985, 1990, 1993 Free Software Foundation, Inc.
7  *
8  * \author Ivan Schreter
9  * \author Dirk Niggemann
10  * \author Asger Alstrup
11  * \author Lars Gullik Bjønnes
12  * \author Jean-Marc Lasgouttes
13  * \author Angus Leeming
14  * \author John Levon
15  * \author Herbert Voß
16  *
17  * Full author contact details are available in file CREDITS.
18  *
19  * General path-mangling functions
20  */
21
22 #include <config.h>
23
24 #include "support/filetools.h"
25
26 #include "support/convert.h"
27 #include "support/debug.h"
28 #include "support/environment.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
31 #include "support/os.h"
32 #include "support/Package.h"
33 #include "support/Path.h"
34 #include "support/Systemcall.h"
35 #include "support/qstring_helpers.h"
36
37 #include <QDir>
38
39 #include "support/lassert.h"
40 #include <boost/regex.hpp>
41
42 #include <fcntl.h>
43
44 #include <cerrno>
45 #include <cstdlib>
46 #include <cstdio>
47
48 #include <utility>
49 #include <fstream>
50 #include <sstream>
51
52 using namespace std;
53
54 namespace lyx {
55 namespace support {
56
57 bool isLyXFilename(string const & filename)
58 {
59         return suffixIs(ascii_lowercase(filename), ".lyx");
60 }
61
62
63 bool isSGMLFilename(string const & filename)
64 {
65         return suffixIs(ascii_lowercase(filename), ".sgml");
66 }
67
68
69 bool isValidLaTeXFilename(string const & filename)
70 {
71         string const invalid_chars("#$%{}()[]\"^");
72         return filename.find_first_of(invalid_chars) == string::npos;
73 }
74
75
76 string const latex_path(string const & original_path,
77                 latex_path_extension extension,
78                 latex_path_dots dots)
79 {
80         // On cygwin, we may need windows or posix style paths.
81         string path = os::latex_path(original_path);
82         path = subst(path, "~", "\\string~");
83         if (path.find(' ') != string::npos) {
84                 // We can't use '"' because " is sometimes active (e.g. if
85                 // babel is loaded with the "german" option)
86                 if (extension == EXCLUDE_EXTENSION) {
87                         // ChangeExtension calls os::internal_path internally
88                         // so don't use it to remove the extension.
89                         string const ext = getExtension(path);
90                         string const base = ext.empty() ?
91                                 path :
92                                 path.substr(0, path.length() - ext.length() - 1);
93                         // ChangeExtension calls os::internal_path internally
94                         // so don't use it to re-add the extension.
95                         path = "\\string\"" + base + "\\string\"." + ext;
96                 } else {
97                         path = "\\string\"" + path + "\\string\"";
98                 }
99         }
100
101         return dots == ESCAPE_DOTS ? subst(path, ".", "\\lyxdot ") : path;
102 }
103
104
105 // Substitutes spaces with underscores in filename (and path)
106 FileName const makeLatexName(FileName const & file)
107 {
108         string name = file.onlyFileName();
109         string const path = file.onlyPath().absFilename() + "/";
110
111         // ok so we scan through the string twice, but who cares.
112         // FIXME: in Unicode time this will break for sure! There is
113         // a non-latin world out there...
114         string const keep = "abcdefghijklmnopqrstuvwxyz"
115                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
116                 "@!'()*+,-./0123456789:;<=>?[]`|";
117
118         string::size_type pos = 0;
119         while ((pos = name.find_first_not_of(keep, pos)) != string::npos)
120                 name[pos++] = '_';
121
122         FileName latex_name(path + name);
123         latex_name.changeExtension(".tex");
124         return latex_name;
125 }
126
127
128 string const quoteName(string const & name, quote_style style)
129 {
130         switch(style) {
131         case quote_shell:
132                 // This does not work for filenames containing " (windows)
133                 // or ' (all other OSes). This can't be changed easily, since
134                 // we would need to adapt the command line parser in
135                 // Forkedcall::generateChild. Therefore we don't pass user
136                 // filenames to child processes if possible. We store them in
137                 // a python script instead, where we don't have these
138                 // limitations.
139                 return (os::shell() == os::UNIX) ?
140                         '\'' + name + '\'':
141                         '"' + name + '"';
142         case quote_python:
143                 return "\"" + subst(subst(name, "\\", "\\\\"), "\"", "\\\"")
144                      + "\"";
145         }
146         // shut up stupid compiler
147         return string();
148 }
149
150
151 #if 0
152 // Uses a string of paths separated by ";"s to find a file to open.
153 // Can't cope with pathnames with a ';' in them. Returns full path to file.
154 // If path entry begins with $$LyX/, use system_lyxdir
155 // If path entry begins with $$User/, use user_lyxdir
156 // Example: "$$User/doc;$$LyX/doc"
157 FileName const fileOpenSearch(string const & path, string const & name,
158                              string const & ext)
159 {
160         FileName real_file;
161         string path_element;
162         bool notfound = true;
163         string tmppath = split(path, path_element, ';');
164
165         while (notfound && !path_element.empty()) {
166                 path_element = os::internal_path(path_element);
167                 if (!suffixIs(path_element, '/'))
168                         path_element += '/';
169                 path_element = subst(path_element, "$$LyX",
170                                      package().system_support().absFilename());
171                 path_element = subst(path_element, "$$User",
172                                      package().user_support().absFilename());
173
174                 real_file = fileSearch(path_element, name, ext);
175
176                 if (real_file.empty()) {
177                         do {
178                                 tmppath = split(tmppath, path_element, ';');
179                         } while (!tmppath.empty() && path_element.empty());
180                 } else {
181                         notfound = false;
182                 }
183         }
184         return real_file;
185 }
186 #endif
187
188
189 // Returns the real name of file name in directory path, with optional
190 // extension ext.
191 FileName const fileSearch(string const & path, string const & name,
192                           string const & ext, search_mode mode)
193 {
194         // if `name' is an absolute path, we ignore the setting of `path'
195         // Expand Environmentvariables in 'name'
196         string const tmpname = replaceEnvironmentPath(name);
197         FileName fullname(makeAbsPath(tmpname, path));
198         // search first without extension, then with it.
199         if (fullname.isReadableFile())
200                 return fullname;
201         if (ext.empty())
202                 // We are done.
203                 return mode == may_not_exist ? fullname : FileName();
204         // Only add the extension if it is not already the extension of
205         // fullname.
206         if (getExtension(fullname.absFilename()) != ext)
207                 fullname = FileName(addExtension(fullname.absFilename(), ext));
208         if (fullname.isReadableFile() || mode == may_not_exist)
209                 return fullname;
210         return FileName();
211 }
212
213
214 // Search the file name.ext in the subdirectory dir of
215 //   1) user_lyxdir
216 //   2) build_lyxdir (if not empty)
217 //   3) system_lyxdir
218 FileName const libFileSearch(string const & dir, string const & name,
219                            string const & ext)
220 {
221         FileName fullname = fileSearch(addPath(package().user_support().absFilename(), dir),
222                                      name, ext);
223         if (!fullname.empty())
224                 return fullname;
225
226         if (!package().build_support().empty())
227                 fullname = fileSearch(addPath(package().build_support().absFilename(), dir),
228                                       name, ext);
229         if (!fullname.empty())
230                 return fullname;
231
232         return fileSearch(addPath(package().system_support().absFilename(), dir), name, ext);
233 }
234
235
236 FileName const i18nLibFileSearch(string const & dir, string const & name,
237                   string const & ext)
238 {
239         /* The highest priority value is the `LANGUAGE' environment
240            variable. But we don't use the value if the currently
241            selected locale is the C locale. This is a GNU extension.
242
243            Otherwise, w use a trick to guess what support/gettext.has done:
244            each po file is able to tell us its name. (JMarc)
245         */
246
247         string lang = to_ascii(_("[[Replace with the code of your language]]"));
248         string const language = getEnv("LANGUAGE");
249         if (!lang.empty() && !language.empty())
250                 lang = language;
251
252         string l;
253         lang = split(lang, l, ':');
254         while (!l.empty()) {
255                 FileName tmp;
256                 // First try with the full name
257                 tmp = libFileSearch(addPath(dir, l), name, ext);
258                 if (!tmp.empty())
259                         return tmp;
260
261                 // Then the name without country code
262                 string const shortl = token(l, '_', 0);
263                 if (shortl != l) {
264                         tmp = libFileSearch(addPath(dir, shortl), name, ext);
265                         if (!tmp.empty())
266                                 return tmp;
267                 }
268
269 #if 1
270                 // For compatibility, to be removed later (JMarc)
271                 tmp = libFileSearch(dir, token(l, '_', 0) + '_' + name,
272                                     ext);
273                 if (!tmp.empty()) {
274                         lyxerr << "i18nLibFileSearch: File `" << tmp
275                                << "' has been found by the old method" <<endl;
276                         return tmp;
277                 }
278 #endif
279                 lang = split(lang, l, ':');
280         }
281
282         return libFileSearch(dir, name, ext);
283 }
284
285
286 string const libScriptSearch(string const & command_in, quote_style style)
287 {
288         static string const token_scriptpath = "$$s/";
289
290         string command = command_in;
291         // Find the starting position of "$$s/"
292         string::size_type const pos1 = command.find(token_scriptpath);
293         if (pos1 == string::npos)
294                 return command;
295         // Find the end of the "$$s/some_subdir/some_script" word within
296         // command. Assumes that the script name does not contain spaces.
297         string::size_type const start_script = pos1 + 4;
298         string::size_type const pos2 = command.find(' ', start_script);
299         string::size_type const size_script = pos2 == string::npos?
300                 (command.size() - start_script) : pos2 - start_script;
301
302         // Does this script file exist?
303         string const script =
304                 libFileSearch(".", command.substr(start_script, size_script)).absFilename();
305
306         if (script.empty()) {
307                 // Replace "$$s/" with ""
308                 command.erase(pos1, 4);
309         } else {
310                 // Replace "$$s/foo/some_script" with "<path to>/some_script".
311                 string::size_type const size_replace = size_script + 4;
312                 command.replace(pos1, size_replace, quoteName(script, style));
313         }
314
315         return command;
316 }
317
318
319 static FileName createTmpDir(FileName const & tempdir, string const & mask)
320 {
321         LYXERR(Debug::FILES, "createTmpDir: tempdir=`" << tempdir << "'\n"
322                 << "createTmpDir:    mask=`" << mask << '\'');
323
324         FileName const tmpfl = FileName::tempName(tempdir, mask);
325
326         if (tmpfl.empty() || !tmpfl.createDirectory(0700)) {
327                 LYXERR0("LyX could not create temporary directory in " << tempdir
328                         << "'");
329                 return FileName();
330         }
331
332         return tmpfl;
333 }
334
335
336 FileName const createLyXTmpDir(FileName const & deflt)
337 {
338         if (deflt.empty() || deflt == package().system_temp_dir())
339                 return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
340
341         if (deflt.createDirectory(0777)) 
342                 return deflt;
343
344         if (deflt.isDirWritable()) {
345                 // deflt could not be created because it
346                 // did exist already, so let's create our own
347                 // dir inside deflt.
348                 return createTmpDir(deflt, "lyx_tmpdir");
349         } else {
350                 // some other error occured.
351                 return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
352         }
353 }
354
355
356 // Strip filename from path name
357 string const onlyPath(string const & filename)
358 {
359         // If empty filename, return empty
360         if (filename.empty())
361                 return filename;
362
363         // Find last / or start of filename
364         size_t j = filename.rfind('/');
365         return j == string::npos ? "./" : filename.substr(0, j + 1);
366 }
367
368
369 // Convert relative path into absolute path based on a basepath.
370 // If relpath is absolute, just use that.
371 // If basepath is empty, use CWD as base.
372 // Note that basePath can be a relative path, in the sense that it may
373 // not begin with "/" (e.g.), but it should NOT contain such constructs
374 // as "/../".
375 // FIXME It might be nice if the code didn't simply assume that.
376 FileName const makeAbsPath(string const & relPath, string const & basePath)
377 {
378         FileName relative_path(relPath);
379         // checks for already absolute path
380         if (relative_path.isAbsolute())
381                 return relative_path;
382
383         // Copies given paths
384         string tempRel = os::internal_path(relPath);
385         // Since TempRel is NOT absolute, we can safely replace "//" with "/"
386         tempRel = subst(tempRel, "//", "/");
387
388         string tempBase;
389
390         FileName base_path(basePath);
391         if (base_path.isAbsolute())
392                 tempBase = basePath;
393         else
394                 tempBase = addPath(FileName::getcwd().absFilename(), basePath);
395
396         // Handle /./ at the end of the path
397         while (suffixIs(tempBase, "/./"))
398                 tempBase.erase(tempBase.length() - 2);
399
400         // processes relative path
401         string rTemp = tempRel;
402         string temp;
403
404         // Check for a leading "~"
405         // Split by first /
406         rTemp = split(rTemp, temp, '/');
407         if (temp == "~") {
408                 tempBase = package().home_dir().absFilename();
409                 tempRel = rTemp;
410         }
411
412         rTemp = tempRel;
413         while (!rTemp.empty()) {
414                 // Split by next /
415                 rTemp = split(rTemp, temp, '/');
416
417                 if (temp == ".") continue;
418                 if (temp == "..") {
419                         // Remove one level of TempBase
420                         if (tempBase.length() <= 1) {
421                                 //this is supposed to be an absolute path, so...
422                                 tempBase = "/";
423                                 continue;
424                         }
425                         //erase a trailing slash if there is one
426                         if (suffixIs(tempBase, "/"))
427                                 tempBase.erase(tempBase.length() - 1, string::npos);
428
429                         string::size_type i = tempBase.length() - 1;
430                         while (i > 0 && tempBase[i] != '/')
431                                 --i;
432                         if (i > 0)
433                                 tempBase.erase(i, string::npos);
434                         else
435                                 tempBase = '/';
436                 } else if (temp.empty() && !rTemp.empty()) {
437                                 tempBase = os::current_root() + rTemp;
438                                 rTemp.erase();
439                 } else {
440                         // Add this piece to TempBase
441                         if (!suffixIs(tempBase, '/'))
442                                 tempBase += '/';
443                         tempBase += temp;
444                 }
445         }
446
447         // returns absolute path
448         return FileName(tempBase);
449 }
450
451
452 // Correctly append filename to the pathname.
453 // If pathname is '.', then don't use pathname.
454 // Chops any path of filename.
455 string const addName(string const & path, string const & fname)
456 {
457         string const basename = onlyFilename(fname);
458         string buf;
459
460         if (path != "." && path != "./" && !path.empty()) {
461                 buf = os::internal_path(path);
462                 if (!suffixIs(path, '/'))
463                         buf += '/';
464         }
465
466         return buf + basename;
467 }
468
469
470 // Strips path from filename
471 string const onlyFilename(string const & fname)
472 {
473         if (fname.empty())
474                 return fname;
475
476         string::size_type j = fname.rfind('/');
477         if (j == string::npos) // no '/' in fname
478                 return fname;
479
480         // Strip to basename
481         return fname.substr(j + 1);
482 }
483
484
485 // Create absolute path. If impossible, don't do anything
486 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
487 string const expandPath(string const & path)
488 {
489         // checks for already absolute path
490         string rTemp = replaceEnvironmentPath(path);
491         FileName abs_path(rTemp);
492         if (abs_path.isAbsolute())
493                 return rTemp;
494
495         string temp;
496         string const copy = rTemp;
497
498         // Split by next /
499         rTemp = split(rTemp, temp, '/');
500
501         if (temp == ".")
502                 return FileName::getcwd().absFilename() + '/' + rTemp;
503
504         if (temp == "~")
505                 return package().home_dir().absFilename() + '/' + rTemp;
506
507         if (temp == "..")
508                 return makeAbsPath(copy).absFilename();
509
510         // Don't know how to handle this
511         return copy;
512 }
513
514
515 // Search the string for ${VAR} and $VAR and replace VAR using getenv.
516 string const replaceEnvironmentPath(string const & path)
517 {
518         // ${VAR} is defined as
519         // $\{[A-Za-z_][A-Za-z_0-9]*\}
520         static string const envvar_br = "[$]\\{([A-Za-z_][A-Za-z_0-9]*)\\}";
521
522         // $VAR is defined as:
523         // $\{[A-Za-z_][A-Za-z_0-9]*\}
524         static string const envvar = "[$]([A-Za-z_][A-Za-z_0-9]*)";
525
526         static boost::regex envvar_br_re("(.*)" + envvar_br + "(.*)");
527         static boost::regex envvar_re("(.*)" + envvar + "(.*)");
528         boost::smatch what;
529
530         string result = path;
531         while (1) {
532                 regex_match(result, what, envvar_br_re);
533                 if (!what[0].matched) {
534                         regex_match(result, what, envvar_re);
535                         if (!what[0].matched)
536                                 break;
537                 }
538                 result = what.str(1) + getEnv(what.str(2)) + what.str(3);
539         }
540         return result;
541 }
542
543
544 // Make relative path out of two absolute paths
545 docstring const makeRelPath(docstring const & abspath, docstring const & basepath)
546 // Makes relative path out of absolute path. If it is deeper than basepath,
547 // it's easy. If basepath and abspath share something (they are all deeper
548 // than some directory), it'll be rendered using ..'s. If they are completely
549 // different, then the absolute path will be used as relative path.
550 {
551         docstring::size_type const abslen = abspath.length();
552         docstring::size_type const baselen = basepath.length();
553
554         docstring::size_type i = os::common_path(abspath, basepath);
555
556         if (i == 0) {
557                 // actually no match - cannot make it relative
558                 return abspath;
559         }
560
561         // Count how many dirs there are in basepath above match
562         // and append as many '..''s into relpath
563         docstring buf;
564         docstring::size_type j = i;
565         while (j < baselen) {
566                 if (basepath[j] == '/') {
567                         if (j + 1 == baselen)
568                                 break;
569                         buf += "../";
570                 }
571                 ++j;
572         }
573
574         // Append relative stuff from common directory to abspath
575         if (abspath[i] == '/')
576                 ++i;
577         for (; i < abslen; ++i)
578                 buf += abspath[i];
579         // Remove trailing /
580         if (suffixIs(buf, '/'))
581                 buf.erase(buf.length() - 1);
582         // Substitute empty with .
583         if (buf.empty())
584                 buf = '.';
585         return buf;
586 }
587
588
589 // Append sub-directory(ies) to a path in an intelligent way
590 string const addPath(string const & path, string const & path_2)
591 {
592         string buf;
593         string const path2 = os::internal_path(path_2);
594
595         if (!path.empty() && path != "." && path != "./") {
596                 buf = os::internal_path(path);
597                 if (path[path.length() - 1] != '/')
598                         buf += '/';
599         }
600
601         if (!path2.empty()) {
602                 string::size_type const p2start = path2.find_first_not_of('/');
603                 string::size_type const p2end = path2.find_last_not_of('/');
604                 string const tmp = path2.substr(p2start, p2end - p2start + 1);
605                 buf += tmp + '/';
606         }
607         return buf;
608 }
609
610
611 string const changeExtension(string const & oldname, string const & extension)
612 {
613         string::size_type const last_slash = oldname.rfind('/');
614         string::size_type last_dot = oldname.rfind('.');
615         if (last_dot < last_slash && last_slash != string::npos)
616                 last_dot = string::npos;
617
618         string ext;
619         // Make sure the extension starts with a dot
620         if (!extension.empty() && extension[0] != '.')
621                 ext= '.' + extension;
622         else
623                 ext = extension;
624
625         return os::internal_path(oldname.substr(0, last_dot) + ext);
626 }
627
628
629 string const removeExtension(string const & name)
630 {
631         return changeExtension(name, string());
632 }
633
634
635 string const addExtension(string const & name, string const & extension)
636 {
637         if (!extension.empty() && extension[0] != '.')
638                 return name + '.' + extension;
639         return name + extension;
640 }
641
642
643 /// Return the extension of the file (not including the .)
644 string const getExtension(string const & name)
645 {
646         string::size_type const last_slash = name.rfind('/');
647         string::size_type const last_dot = name.rfind('.');
648         if (last_dot != string::npos &&
649             (last_slash == string::npos || last_dot > last_slash))
650                 return name.substr(last_dot + 1,
651                                    name.length() - (last_dot + 1));
652         else
653                 return string();
654 }
655
656
657 string const unzippedFileName(string const & zipped_file)
658 {
659         string const ext = getExtension(zipped_file);
660         if (ext == "gz" || ext == "z" || ext == "Z")
661                 return changeExtension(zipped_file, string());
662         return onlyPath(zipped_file) + "unzipped_" + onlyFilename(zipped_file);
663 }
664
665
666 FileName const unzipFile(FileName const & zipped_file, string const & unzipped_file)
667 {
668         FileName const tempfile = FileName(unzipped_file.empty() ?
669                 unzippedFileName(zipped_file.toFilesystemEncoding()) :
670                 unzipped_file);
671         // Run gunzip
672         string const command = "gunzip -c " +
673                 zipped_file.toFilesystemEncoding() + " > " +
674                 tempfile.toFilesystemEncoding();
675         Systemcall one;
676         one.startscript(Systemcall::Wait, command);
677         // test that command was executed successfully (anon)
678         // yes, please do. (Lgb)
679         return tempfile;
680 }
681
682
683 docstring const makeDisplayPath(string const & path, unsigned int threshold)
684 {
685         string str = path;
686
687         // If file is from LyXDir, display it as if it were relative.
688         string const system = package().system_support().absFilename();
689         if (prefixIs(str, system) && str != system)
690                 return from_utf8("[" + str.erase(0, system.length()) + "]");
691
692         // replace /home/blah with ~/
693         string const home = package().home_dir().absFilename();
694         if (!home.empty() && prefixIs(str, home))
695                 str = subst(str, home, "~");
696
697         if (str.length() <= threshold)
698                 return from_utf8(os::external_path(str));
699
700         string const prefix = ".../";
701         string temp;
702
703         while (str.length() > threshold)
704                 str = split(str, temp, '/');
705
706         // Did we shorten everything away?
707         if (str.empty()) {
708                 // Yes, filename itself is too long.
709                 // Pick the start and the end of the filename.
710                 str = onlyFilename(path);
711                 string const head = str.substr(0, threshold / 2 - 3);
712
713                 string::size_type len = str.length();
714                 string const tail =
715                         str.substr(len - threshold / 2 - 2, len - 1);
716                 str = head + "..." + tail;
717         }
718
719         return from_utf8(os::external_path(prefix + str));
720 }
721
722
723 bool readLink(FileName const & file, FileName & link)
724 {
725 #ifdef HAVE_READLINK
726         char linkbuffer[512];
727         // Should be PATH_MAX but that needs autconf support
728         string const encoded = file.toFilesystemEncoding();
729         int const nRead = ::readlink(encoded.c_str(),
730                                      linkbuffer, sizeof(linkbuffer) - 1);
731         if (nRead <= 0)
732                 return false;
733         linkbuffer[nRead] = '\0'; // terminator
734         link = makeAbsPath(linkbuffer, onlyPath(file.absFilename()));
735         return true;
736 #else
737         return false;
738 #endif
739 }
740
741
742 cmd_ret const runCommand(string const & cmd)
743 {
744         // FIXME: replace all calls to RunCommand with ForkedCall
745         // (if the output is not needed) or the code in ISpell.cpp
746         // (if the output is needed).
747
748         // One question is if we should use popen or
749         // create our own popen based on fork, exec, pipe
750         // of course the best would be to have a
751         // pstream (process stream), with the
752         // variants ipstream, opstream
753
754 #if defined (HAVE_POPEN)
755         FILE * inf = ::popen(cmd.c_str(), os::popen_read_mode());
756 #elif defined (HAVE__POPEN)
757         FILE * inf = ::_popen(cmd.c_str(), os::popen_read_mode());
758 #else
759 #error No popen() function.
760 #endif
761
762         // (Claus Hentschel) Check if popen was succesful ;-)
763         if (!inf) {
764                 lyxerr << "RunCommand:: could not start child process" << endl;
765                 return make_pair(-1, string());
766         }
767
768         string ret;
769         int c = fgetc(inf);
770         while (c != EOF) {
771                 ret += static_cast<char>(c);
772                 c = fgetc(inf);
773         }
774
775 #if defined (HAVE_PCLOSE)
776         int const pret = pclose(inf);
777 #elif defined (HAVE__PCLOSE)
778         int const pret = _pclose(inf);
779 #else
780 #error No pclose() function.
781 #endif
782
783         if (pret == -1)
784                 perror("RunCommand:: could not terminate child process");
785
786         return make_pair(pret, ret);
787 }
788
789
790 FileName const findtexfile(string const & fil, string const & /*format*/)
791 {
792         /* There is no problem to extend this function too use other
793            methods to look for files. It could be setup to look
794            in environment paths and also if wanted as a last resort
795            to a recursive find. One of the easier extensions would
796            perhaps be to use the LyX file lookup methods. But! I am
797            going to implement this until I see some demand for it.
798            Lgb
799         */
800
801         // If the file can be found directly, we just return a
802         // absolute path version of it.
803         FileName const absfile(makeAbsPath(fil));
804         if (absfile.exists())
805                 return absfile;
806
807         // Now we try to find it using kpsewhich.
808         // It seems from the kpsewhich manual page that it is safe to use
809         // kpsewhich without --format: "When the --format option is not
810         // given, the search path used when looking for a file is inferred
811         // from the name given, by looking for a known extension. If no
812         // known extension is found, the search path for TeX source files
813         // is used."
814         // However, we want to take advantage of the format sine almost all
815         // the different formats has environment variables that can be used
816         // to controll which paths to search. f.ex. bib looks in
817         // BIBINPUTS and TEXBIB. Small list follows:
818         // bib - BIBINPUTS, TEXBIB
819         // bst - BSTINPUTS
820         // graphic/figure - TEXPICTS, TEXINPUTS
821         // ist - TEXINDEXSTYLE, INDEXSTYLE
822         // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
823         // tex - TEXINPUTS
824         // tfm - TFMFONTS, TEXFONTS
825         // This means that to use kpsewhich in the best possible way we
826         // should help it by setting additional path in the approp. envir.var.
827         string const kpsecmd = "kpsewhich " + fil;
828
829         cmd_ret const c = runCommand(kpsecmd);
830
831         LYXERR(Debug::LATEX, "kpse status = " << c.first << '\n'
832                  << "kpse result = `" << rtrim(c.second, "\n\r") << '\'');
833         if (c.first != -1)
834                 return FileName(rtrim(to_utf8(from_filesystem8bit(c.second)), "\n\r"));
835         else
836                 return FileName();
837 }
838
839
840 void removeAutosaveFile(string const & filename)
841 {
842         string a = onlyPath(filename);
843         a += '#';
844         a += onlyFilename(filename);
845         a += '#';
846         FileName const autosave(a);
847         if (autosave.exists())
848                 autosave.removeFile();
849 }
850
851
852 void readBB_lyxerrMessage(FileName const & file, bool & zipped,
853         string const & message)
854 {
855         LYXERR(Debug::GRAPHICS, "[readBB_from_PSFile] " << message);
856         // FIXME: Why is this func deleting a file? (Lgb)
857         if (zipped)
858                 file.removeFile();
859 }
860
861
862 string const readBB_from_PSFile(FileName const & file)
863 {
864         // in a (e)ps-file it's an entry like %%BoundingBox:23 45 321 345
865         // It seems that every command in the header has an own line,
866         // getline() should work for all files.
867         // On the other hand some plot programs write the bb at the
868         // end of the file. Than we have in the header:
869         // %%BoundingBox: (atend)
870         // In this case we must check the end.
871         bool zipped = file.isZippedFile();
872         FileName const file_ = zipped ? unzipFile(file) : file;
873         string const format = file_.guessFormatFromContents();
874
875         if (format != "eps" && format != "ps") {
876                 readBB_lyxerrMessage(file_, zipped,"no(e)ps-format");
877                 return string();
878         }
879
880         static boost::regex bbox_re(
881                 "^%%BoundingBox:\\s*([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)");
882         ifstream is(file_.toFilesystemEncoding().c_str());
883         while (is) {
884                 string s;
885                 getline(is,s);
886                 boost::smatch what;
887                 if (regex_match(s, what, bbox_re)) {
888                         // Our callers expect the tokens in the string
889                         // separated by single spaces.
890                         // FIXME: change return type from string to something
891                         // sensible
892                         ostringstream os;
893                         os << what.str(1) << ' ' << what.str(2) << ' '
894                            << what.str(3) << ' ' << what.str(4);
895                         string const bb = os.str();
896                         readBB_lyxerrMessage(file_, zipped, bb);
897                         return bb;
898                 }
899         }
900         readBB_lyxerrMessage(file_, zipped, "no bb found");
901         return string();
902 }
903
904
905 int compare_timestamps(FileName const & file1, FileName const & file2)
906 {
907         // If the original is newer than the copy, then copy the original
908         // to the new directory.
909
910         int cmp = 0;
911         if (file1.exists() && file2.exists()) {
912                 double const tmp = difftime(file1.lastModified(), file2.lastModified());
913                 if (tmp != 0)
914                         cmp = tmp > 0 ? 1 : -1;
915
916         } else if (file1.exists()) {
917                 cmp = 1;
918         } else if (file2.exists()) {
919                 cmp = -1;
920         }
921
922         return cmp;
923 }
924
925
926 } //namespace support
927 } // namespace lyx