3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * parts Copyright 1985, 1990, 1993 Free Software Foundation, Inc.
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
17 * Full author contact details are available in file CREDITS.
19 * General path-mangling functions
26 #include "support/filetools.h"
28 #include "support/debug.h"
29 #include "support/environment.h"
30 #include "support/gettext.h"
31 #include "support/lstrings.h"
32 #include "support/os.h"
33 #include "support/Package.h"
34 #include "support/Path.h"
35 #include "support/Systemcall.h"
36 #include "support/qstring_helpers.h"
40 #include "support/lassert.h"
41 #include "support/regex.h"
66 bool isLyXFileName(string const & filename)
68 return suffixIs(ascii_lowercase(filename), ".lyx");
72 bool isSGMLFileName(string const & filename)
74 return suffixIs(ascii_lowercase(filename), ".sgml");
78 bool isValidLaTeXFileName(string const & filename)
80 string const invalid_chars("#%\"");
81 return filename.find_first_of(invalid_chars) == string::npos;
85 bool isValidDVIFileName(string const & filename)
87 string const invalid_chars("${}()[]^");
88 return filename.find_first_of(invalid_chars) == string::npos;
92 string const latex_path(string const & original_path,
93 latex_path_extension extension,
96 // On cygwin, we may need windows or posix style paths.
97 string path = os::latex_path(original_path);
98 path = subst(path, "~", "\\string~");
99 if (path.find(' ') != string::npos) {
100 // We can't use '"' because " is sometimes active (e.g. if
101 // babel is loaded with the "german" option)
102 if (extension == EXCLUDE_EXTENSION) {
103 // changeExtension calls os::internal_path internally
104 // so don't use it to remove the extension.
105 string const ext = getExtension(path);
106 string const base = ext.empty() ?
108 path.substr(0, path.length() - ext.length() - 1);
109 // changeExtension calls os::internal_path internally
110 // so don't use it to re-add the extension.
111 path = "\\string\"" + base + "\\string\"." + ext;
113 path = "\\string\"" + path + "\\string\"";
117 if (dots != ESCAPE_DOTS)
120 // Replace dots with the lyxdot macro, but only in the file name,
121 // not the directory part.
122 // addName etc call os::internal_path internally
123 // so don't use them for path manipulation
124 // The directory separator is always '/' for LaTeX.
125 string::size_type pos = path.rfind('/');
126 if (pos == string::npos)
127 return subst(path, ".", "\\lyxdot ");
128 return path.substr(0, pos) + subst(path.substr(pos), ".", "\\lyxdot ");
132 // Substitutes spaces with underscores in filename (and path)
133 FileName const makeLatexName(FileName const & file)
135 string name = file.onlyFileName();
136 string const path = file.onlyPath().absFileName() + "/";
138 // ok so we scan through the string twice, but who cares.
139 // FIXME: in Unicode time this will break for sure! There is
140 // a non-latin world out there...
141 string const keep = "abcdefghijklmnopqrstuvwxyz"
142 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
143 "@!'()*+,-./0123456789:;<=>?[]`|";
145 string::size_type pos = 0;
146 while ((pos = name.find_first_not_of(keep, pos)) != string::npos)
149 FileName latex_name(path + name);
150 latex_name.changeExtension(".tex");
155 string const quoteName(string const & name, quote_style style)
159 // This does not work on native Windows for filenames
160 // containing the following characters < > : " / \ | ? *
161 // Moreover, it can't be made to work, as, according to
162 // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx
163 // those are reserved characters, and thus are forbidden.
164 // Please, also note that the command-line parser in
165 // ForkedCall::generateChild cannot deal with filenames
166 // containing " or ', therefore we don't pass user filenames
167 // to child processes if possible. We store them in a python
168 // script instead, where we don't have these limitations.
170 return (os::shell() == os::UNIX) ?
171 '\'' + subst(name, "'", "\'\\\'\'") + '\'' :
174 // According to the QProcess parser, a single double
175 // quote is represented by three consecutive ones.
176 // Here we simply escape the double quote and let our
177 // simple parser in Systemcall.cpp do the substitution.
178 return '"' + subst(name, "\"", "\\\"") + '"';
181 return "\"" + subst(subst(name, "\\", "\\\\"), "\"", "\\\"")
184 // shut up stupid compiler
190 // Uses a string of paths separated by ";"s to find a file to open.
191 // Can't cope with pathnames with a ';' in them. Returns full path to file.
192 // If path entry begins with $$LyX/, use system_lyxdir
193 // If path entry begins with $$User/, use user_lyxdir
194 // Example: "$$User/doc;$$LyX/doc"
195 FileName const fileOpenSearch(string const & path, string const & name,
200 bool notfound = true;
201 string tmppath = split(path, path_element, ';');
203 while (notfound && !path_element.empty()) {
204 path_element = os::internal_path(path_element);
205 if (!suffixIs(path_element, '/'))
207 path_element = subst(path_element, "$$LyX",
208 package().system_support().absFileName());
209 path_element = subst(path_element, "$$User",
210 package().user_support().absFileName());
212 real_file = fileSearch(path_element, name, ext);
214 if (real_file.empty()) {
216 tmppath = split(tmppath, path_element, ';');
217 } while (!tmppath.empty() && path_element.empty());
227 // Returns the real name of file name in directory path, with optional
229 FileName const fileSearch(string const & path, string const & name,
230 string const & ext, search_mode mode)
232 // if `name' is an absolute path, we ignore the setting of `path'
233 // Expand Environmentvariables in 'name'
234 string const tmpname = replaceEnvironmentPath(name);
235 FileName fullname(makeAbsPath(tmpname, path));
236 // search first without extension, then with it.
237 if (fullname.isReadableFile())
241 return mode == may_not_exist ? fullname : FileName();
242 // Only add the extension if it is not already the extension of
244 if (getExtension(fullname.absFileName()) != ext)
245 fullname = FileName(addExtension(fullname.absFileName(), ext));
246 if (fullname.isReadableFile() || mode == may_not_exist)
252 // Search the file name.ext in the subdirectory dir of
254 // 2) build_lyxdir (if not empty)
256 FileName const libFileSearch(string const & dir, string const & name,
259 FileName fullname = fileSearch(addPath(package().user_support().absFileName(), dir),
261 if (!fullname.empty())
264 if (!package().build_support().empty())
265 fullname = fileSearch(addPath(package().build_support().absFileName(), dir),
267 if (!fullname.empty())
270 return fileSearch(addPath(package().system_support().absFileName(), dir), name, ext);
274 FileName const i18nLibFileSearch(string const & dir, string const & name,
277 /* The highest priority value is the `LANGUAGE' environment
278 variable. But we don't use the value if the currently
279 selected locale is the C locale. This is a GNU extension.
281 Otherwise, w use a trick to guess what support/gettext.has done:
282 each po file is able to tell us its name. (JMarc)
285 string lang = to_ascii(_(languageTestString()));
286 string const language = getEnv("LANGUAGE");
287 if (!lang.empty() && !language.empty())
291 lang = split(lang, l, ':');
294 // First try with the full name
295 tmp = libFileSearch(addPath(dir, l), name, ext);
299 // Then the name without country code
300 string const shortl = token(l, '_', 0);
302 tmp = libFileSearch(addPath(dir, shortl), name, ext);
308 // For compatibility, to be removed later (JMarc)
309 tmp = libFileSearch(dir, token(l, '_', 0) + '_' + name,
312 lyxerr << "i18nLibFileSearch: File `" << tmp
313 << "' has been found by the old method" <<endl;
317 lang = split(lang, l, ':');
320 return libFileSearch(dir, name, ext);
324 FileName const imageLibFileSearch(string & dir, string const & name,
327 if (!lyx::lyxrc.icon_set.empty()) {
328 string const imagedir = addPath(dir, lyx::lyxrc.icon_set);
329 FileName const fn = libFileSearch(imagedir, name, ext);
335 return libFileSearch(dir, name, ext);
339 string const libScriptSearch(string const & command_in, quote_style style)
341 static string const token_scriptpath = "$$s/";
343 string command = command_in;
344 // Find the starting position of "$$s/"
345 string::size_type const pos1 = command.find(token_scriptpath);
346 if (pos1 == string::npos)
348 // Find the end of the "$$s/some_subdir/some_script" word within
349 // command. Assumes that the script name does not contain spaces.
350 string::size_type const start_script = pos1 + 4;
351 string::size_type const pos2 = command.find(' ', start_script);
352 string::size_type const size_script = pos2 == string::npos?
353 (command.size() - start_script) : pos2 - start_script;
355 // Does this script file exist?
356 string const script =
357 libFileSearch(".", command.substr(start_script, size_script)).absFileName();
359 if (script.empty()) {
360 // Replace "$$s/" with ""
361 command.erase(pos1, 4);
363 // Replace "$$s/foo/some_script" with "<path to>/some_script".
364 string::size_type const size_replace = size_script + 4;
365 command.replace(pos1, size_replace, quoteName(script, style));
372 static FileName createTmpDir(FileName const & tempdir, string const & mask)
374 LYXERR(Debug::FILES, "createTmpDir: tempdir=`" << tempdir << "'\n"
375 << "createTmpDir: mask=`" << mask << '\'');
377 FileName const tmpfl = FileName::tempName(tempdir, mask);
379 if (tmpfl.empty() || !tmpfl.createDirectory(0700)) {
380 LYXERR0("LyX could not create temporary directory in " << tempdir
389 FileName const createLyXTmpDir(FileName const & deflt)
391 if (deflt.empty() || deflt == package().system_temp_dir())
392 return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
394 if (deflt.createDirectory(0777))
397 if (deflt.isDirWritable()) {
398 // deflt could not be created because it
399 // did exist already, so let's create our own
401 return createTmpDir(deflt, "lyx_tmpdir");
403 // some other error occured.
404 return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
409 // Strip filename from path name
410 string const onlyPath(string const & filename)
412 // If empty filename, return empty
413 if (filename.empty())
416 // Find last / or start of filename
417 size_t j = filename.rfind('/');
418 return j == string::npos ? "./" : filename.substr(0, j + 1);
422 // Convert relative path into absolute path based on a basepath.
423 // If relpath is absolute, just use that.
424 // If basepath is empty, use CWD as base.
425 // Note that basePath can be a relative path, in the sense that it may
426 // not begin with "/" (e.g.), but it should NOT contain such constructs
428 // FIXME It might be nice if the code didn't simply assume that.
429 FileName const makeAbsPath(string const & relPath, string const & basePath)
431 // checks for already absolute path
432 if (FileName::isAbsolute(relPath))
433 return FileName(relPath);
435 // Copies given paths
436 string tempRel = os::internal_path(relPath);
437 // Since TempRel is NOT absolute, we can safely replace "//" with "/"
438 tempRel = subst(tempRel, "//", "/");
442 if (FileName::isAbsolute(basePath))
445 tempBase = addPath(FileName::getcwd().absFileName(), basePath);
447 // Handle /./ at the end of the path
448 while (suffixIs(tempBase, "/./"))
449 tempBase.erase(tempBase.length() - 2);
451 // processes relative path
452 string rTemp = tempRel;
455 // Check for a leading "~"
457 rTemp = split(rTemp, temp, '/');
459 tempBase = Package::get_home_dir().absFileName();
464 while (!rTemp.empty()) {
466 rTemp = split(rTemp, temp, '/');
468 if (temp == ".") continue;
470 // Remove one level of TempBase
471 if (tempBase.length() <= 1) {
472 //this is supposed to be an absolute path, so...
476 //erase a trailing slash if there is one
477 if (suffixIs(tempBase, "/"))
478 tempBase.erase(tempBase.length() - 1, string::npos);
480 string::size_type i = tempBase.length() - 1;
481 while (i > 0 && tempBase[i] != '/')
484 tempBase.erase(i, string::npos);
487 } else if (temp.empty() && !rTemp.empty()) {
488 tempBase = os::current_root() + rTemp;
491 // Add this piece to TempBase
492 if (!suffixIs(tempBase, '/'))
498 // returns absolute path
499 return FileName(tempBase);
503 // Correctly append filename to the pathname.
504 // If pathname is '.', then don't use pathname.
505 // Chops any path of filename.
506 string const addName(string const & path, string const & fname)
508 string const basename = onlyFileName(fname);
511 if (path != "." && path != "./" && !path.empty()) {
512 buf = os::internal_path(path);
513 if (!suffixIs(path, '/'))
517 return buf + basename;
521 // Strips path from filename
522 string const onlyFileName(string const & fname)
527 string::size_type j = fname.rfind('/');
528 if (j == string::npos) // no '/' in fname
532 return fname.substr(j + 1);
536 // Create absolute path. If impossible, don't do anything
537 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
538 string const expandPath(string const & path)
540 // checks for already absolute path
541 string rTemp = replaceEnvironmentPath(path);
542 if (FileName::isAbsolute(rTemp))
546 string const copy = rTemp;
549 rTemp = split(rTemp, temp, '/');
552 return FileName::getcwd().absFileName() + '/' + rTemp;
555 return Package::get_home_dir().absFileName() + '/' + rTemp;
558 return makeAbsPath(copy).absFileName();
560 // Don't know how to handle this
565 // Search the string for ${VAR} and $VAR and replace VAR using getenv.
566 string const replaceEnvironmentPath(string const & path)
568 // ${VAR} is defined as
569 // $\{[A-Za-z_][A-Za-z_0-9]*\}
570 static string const envvar_br = "[$]\\{([A-Za-z_][A-Za-z_0-9]*)\\}";
572 // $VAR is defined as:
573 // $[A-Za-z_][A-Za-z_0-9]*
574 static string const envvar = "[$]([A-Za-z_][A-Za-z_0-9]*)";
576 static regex envvar_br_re("(.*)" + envvar_br + "(.*)");
577 static regex envvar_re("(.*)" + envvar + "(.*)");
578 string result = path;
581 if (!regex_match(result, what, envvar_br_re)) {
582 if (!regex_match(result, what, envvar_re))
585 string env_var = getEnv(what.str(2));
586 result = what.str(1) + env_var + what.str(3);
592 // Return a command prefix for setting the environment of the TeX engine.
593 string latexEnvCmdPrefix(string const & path)
595 if (path.empty() || lyxrc.texinputs_prefix.empty())
598 string const texinputs_prefix = os::latex_path_list(
599 replaceCurdirPath(path, lyxrc.texinputs_prefix));
600 string const sep = string(1, os::path_separator(os::TEXENGINE));
601 string const texinputs = getEnv("TEXINPUTS");
603 if (os::shell() == os::UNIX)
604 return "env TEXINPUTS=\"." + sep + texinputs_prefix
605 + sep + texinputs + "\" ";
607 return "cmd /d /c set TEXINPUTS=." + sep + texinputs_prefix
608 + sep + texinputs + "&";
612 // Replace current directory in all elements of a path list with a given path.
613 string const replaceCurdirPath(string const & path, string const & pathlist)
615 string const oldpathlist = replaceEnvironmentPath(pathlist);
616 char const sep = os::path_separator();
619 for (size_t i = 0, k = 0; i != string::npos; k = i) {
620 i = oldpathlist.find(sep, i);
621 string p = oldpathlist.substr(k, i - k);
622 if (FileName::isAbsolute(p)) {
628 } else if (prefixIs(p, "./")) {
630 while (p[offset] == '/')
633 newpathlist += addPath(path, p.substr(offset));
634 if (suffixIs(p, "//"))
637 if (i != string::npos) {
639 // Stop here if the last element is empty
640 if (++i == oldpathlist.length())
648 // Make relative path out of two absolute paths
649 docstring const makeRelPath(docstring const & abspath, docstring const & basepath)
650 // Makes relative path out of absolute path. If it is deeper than basepath,
651 // it's easy. If basepath and abspath share something (they are all deeper
652 // than some directory), it'll be rendered using ..'s. If they are completely
653 // different, then the absolute path will be used as relative path.
655 docstring::size_type const abslen = abspath.length();
656 docstring::size_type const baselen = basepath.length();
658 docstring::size_type i = os::common_path(abspath, basepath);
661 // actually no match - cannot make it relative
665 // Count how many dirs there are in basepath above match
666 // and append as many '..''s into relpath
668 docstring::size_type j = i;
669 while (j < baselen) {
670 if (basepath[j] == '/') {
671 if (j + 1 == baselen)
678 // Append relative stuff from common directory to abspath
679 if (abspath[i] == '/')
681 for (; i < abslen; ++i)
684 if (suffixIs(buf, '/'))
685 buf.erase(buf.length() - 1);
686 // Substitute empty with .
693 // Append sub-directory(ies) to a path in an intelligent way
694 string const addPath(string const & path, string const & path_2)
697 string const path2 = os::internal_path(path_2);
699 if (!path.empty() && path != "." && path != "./") {
700 buf = os::internal_path(path);
701 if (path[path.length() - 1] != '/')
705 if (!path2.empty()) {
706 string::size_type const p2start = path2.find_first_not_of('/');
707 string::size_type const p2end = path2.find_last_not_of('/');
708 string const tmp = path2.substr(p2start, p2end - p2start + 1);
715 string const changeExtension(string const & oldname, string const & extension)
717 string::size_type const last_slash = oldname.rfind('/');
718 string::size_type last_dot = oldname.rfind('.');
719 if (last_dot < last_slash && last_slash != string::npos)
720 last_dot = string::npos;
723 // Make sure the extension starts with a dot
724 if (!extension.empty() && extension[0] != '.')
725 ext= '.' + extension;
729 return os::internal_path(oldname.substr(0, last_dot) + ext);
733 string const removeExtension(string const & name)
735 return changeExtension(name, string());
739 string const addExtension(string const & name, string const & extension)
741 if (!extension.empty() && extension[0] != '.')
742 return name + '.' + extension;
743 return name + extension;
747 /// Return the extension of the file (not including the .)
748 string const getExtension(string const & name)
750 string::size_type const last_slash = name.rfind('/');
751 string::size_type const last_dot = name.rfind('.');
752 if (last_dot != string::npos &&
753 (last_slash == string::npos || last_dot > last_slash))
754 return name.substr(last_dot + 1,
755 name.length() - (last_dot + 1));
761 string const unzippedFileName(string const & zipped_file)
763 string const ext = getExtension(zipped_file);
764 if (ext == "gz" || ext == "z" || ext == "Z")
765 return changeExtension(zipped_file, string());
766 return onlyPath(zipped_file) + "unzipped_" + onlyFileName(zipped_file);
770 FileName const unzipFile(FileName const & zipped_file, string const & unzipped_file)
772 FileName const tempfile = FileName(unzipped_file.empty() ?
773 unzippedFileName(zipped_file.toFilesystemEncoding()) :
776 string const command = "gunzip -c " +
777 zipped_file.toFilesystemEncoding() + " > " +
778 tempfile.toFilesystemEncoding();
780 one.startscript(Systemcall::Wait, command);
781 // test that command was executed successfully (anon)
782 // yes, please do. (Lgb)
787 docstring const makeDisplayPath(string const & path, unsigned int threshold)
791 // If file is from LyXDir, display it as if it were relative.
792 string const system = package().system_support().absFileName();
793 if (prefixIs(str, system) && str != system)
794 return from_utf8("[" + str.erase(0, system.length()) + "]");
796 // replace /home/blah with ~/
797 string const home = Package::get_home_dir().absFileName();
798 if (!home.empty() && prefixIs(str, home))
799 str = subst(str, home, "~");
801 if (str.length() <= threshold)
802 return from_utf8(os::external_path(str));
804 string const prefix = ".../";
805 docstring dstr = from_utf8(str);
808 while (dstr.length() > threshold)
809 dstr = split(dstr, temp, '/');
811 // Did we shorten everything away?
813 // Yes, filename itself is too long.
814 // Pick the start and the end of the filename.
815 dstr = from_utf8(onlyFileName(path));
816 docstring const head = dstr.substr(0, threshold / 2 - 3);
818 docstring::size_type len = dstr.length();
819 docstring const tail =
820 dstr.substr(len - threshold / 2 - 2, len - 1);
821 dstr = head + from_ascii("...") + tail;
824 return from_utf8(os::external_path(prefix + to_utf8(dstr)));
829 bool readLink(FileName const & file, FileName & link)
831 string const encoded = file.toFilesystemEncoding();
832 #ifdef HAVE_DEF_PATH_MAX
833 char linkbuffer[PATH_MAX + 1];
834 int const nRead = ::readlink(encoded.c_str(),
835 linkbuffer, sizeof(linkbuffer) - 1);
838 linkbuffer[nRead] = '\0'; // terminator
840 vector<char> buf(1024);
844 nRead = ::readlink(encoded.c_str(), &buf[0], buf.size() - 1);
848 if (nRead < buf.size() - 1) {
851 buf.resize(buf.size() * 2);
853 buf[nRead] = '\0'; // terminator
854 const char * linkbuffer = &buf[0];
856 link = makeAbsPath(linkbuffer, onlyPath(file.absFileName()));
860 bool readLink(FileName const &, FileName &)
867 cmd_ret const runCommand(string const & cmd)
869 // FIXME: replace all calls to RunCommand with ForkedCall
870 // (if the output is not needed) or the code in ISpell.cpp
871 // (if the output is needed).
873 // One question is if we should use popen or
874 // create our own popen based on fork, exec, pipe
875 // of course the best would be to have a
876 // pstream (process stream), with the
877 // variants ipstream, opstream
882 PROCESS_INFORMATION process;
883 SECURITY_ATTRIBUTES security;
886 bool err2out = false;
888 string const infile = trim(split(cmd, command, '<'), " \"");
889 command = rtrim(command);
890 if (suffixIs(command, "2>&1")) {
891 command = rtrim(command, "2>&1");
894 string const cmdarg = "/d /c " + command;
895 string const comspec = getEnv("COMSPEC");
897 security.nLength = sizeof(SECURITY_ATTRIBUTES);
898 security.bInheritHandle = TRUE;
899 security.lpSecurityDescriptor = NULL;
901 if (CreatePipe(&in, &out, &security, 0)) {
902 memset(&startup, 0, sizeof(STARTUPINFO));
903 memset(&process, 0, sizeof(PROCESS_INFORMATION));
905 startup.cb = sizeof(STARTUPINFO);
906 startup.dwFlags = STARTF_USESTDHANDLES;
908 startup.hStdError = err2out ? out : GetStdHandle(STD_ERROR_HANDLE);
909 startup.hStdInput = infile.empty()
910 ? GetStdHandle(STD_INPUT_HANDLE)
911 : CreateFile(infile.c_str(), GENERIC_READ,
912 FILE_SHARE_READ, &security, OPEN_EXISTING,
913 FILE_ATTRIBUTE_NORMAL, NULL);
914 startup.hStdOutput = out;
916 if (startup.hStdInput != INVALID_HANDLE_VALUE &&
917 CreateProcess(comspec.c_str(), (LPTSTR)cmdarg.c_str(),
918 &security, &security, TRUE, CREATE_NO_WINDOW,
919 0, 0, &startup, &process)) {
921 CloseHandle(process.hThread);
922 fno = _open_osfhandle((long)in, _O_RDONLY);
924 inf = _fdopen(fno, "r");
927 #elif defined (HAVE_POPEN)
928 FILE * inf = ::popen(cmd.c_str(), os::popen_read_mode());
929 #elif defined (HAVE__POPEN)
930 FILE * inf = ::_popen(cmd.c_str(), os::popen_read_mode());
932 #error No popen() function.
935 // (Claus Hentschel) Check if popen was successful ;-)
937 lyxerr << "RunCommand:: could not start child process" << endl;
938 return make_pair(-1, string());
944 ret += static_cast<char>(c);
949 WaitForSingleObject(process.hProcess, INFINITE);
951 CloseHandle(startup.hStdInput);
952 CloseHandle(process.hProcess);
953 int const pret = fclose(inf);
954 #elif defined (HAVE_PCLOSE)
955 int const pret = pclose(inf);
956 #elif defined (HAVE__PCLOSE)
957 int const pret = _pclose(inf);
959 #error No pclose() function.
963 perror("RunCommand:: could not terminate child process");
965 return make_pair(pret, ret);
969 FileName const findtexfile(string const & fil, string const & /*format*/)
971 /* There is no problem to extend this function too use other
972 methods to look for files. It could be setup to look
973 in environment paths and also if wanted as a last resort
974 to a recursive find. One of the easier extensions would
975 perhaps be to use the LyX file lookup methods. But! I am
976 going to implement this until I see some demand for it.
980 // If the file can be found directly, we just return a
981 // absolute path version of it.
982 FileName const absfile(makeAbsPath(fil));
983 if (absfile.exists())
986 // Now we try to find it using kpsewhich.
987 // It seems from the kpsewhich manual page that it is safe to use
988 // kpsewhich without --format: "When the --format option is not
989 // given, the search path used when looking for a file is inferred
990 // from the name given, by looking for a known extension. If no
991 // known extension is found, the search path for TeX source files
993 // However, we want to take advantage of the format sine almost all
994 // the different formats has environment variables that can be used
995 // to controll which paths to search. f.ex. bib looks in
996 // BIBINPUTS and TEXBIB. Small list follows:
997 // bib - BIBINPUTS, TEXBIB
999 // graphic/figure - TEXPICTS, TEXINPUTS
1000 // ist - TEXINDEXSTYLE, INDEXSTYLE
1001 // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
1003 // tfm - TFMFONTS, TEXFONTS
1004 // This means that to use kpsewhich in the best possible way we
1005 // should help it by setting additional path in the approp. envir.var.
1006 string const kpsecmd = "kpsewhich " + fil;
1008 cmd_ret const c = runCommand(kpsecmd);
1010 LYXERR(Debug::LATEX, "kpse status = " << c.first << '\n'
1011 << "kpse result = `" << rtrim(c.second, "\n\r") << '\'');
1013 return FileName(rtrim(to_utf8(from_filesystem8bit(c.second)), "\n\r"));
1019 int compare_timestamps(FileName const & file1, FileName const & file2)
1021 // If the original is newer than the copy, then copy the original
1022 // to the new directory.
1025 if (file1.exists() && file2.exists()) {
1026 double const tmp = difftime(file1.lastModified(), file2.lastModified());
1028 cmp = tmp > 0 ? 1 : -1;
1030 } else if (file1.exists()) {
1032 } else if (file2.exists()) {
1040 bool prefs2prefs(FileName const & filename, FileName const & tempfile, bool lfuns)
1042 FileName const script = libFileSearch("scripts", "prefs2prefs.py");
1043 if (script.empty()) {
1044 LYXERR0("Could not find bind file conversion "
1045 "script prefs2prefs.py.");
1049 ostringstream command;
1050 command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
1051 << ' ' << (lfuns ? "-l" : "-p") << ' '
1052 << quoteName(filename.toFilesystemEncoding())
1053 << ' ' << quoteName(tempfile.toFilesystemEncoding());
1054 string const command_str = command.str();
1056 LYXERR(Debug::FILES, "Running `" << command_str << '\'');
1058 cmd_ret const ret = runCommand(command_str);
1059 if (ret.first != 0) {
1060 LYXERR0("Could not run file conversion script prefs2prefs.py.");
1067 } //namespace support