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
24 #include "support/convert.h"
25 #include "support/environment.h"
26 #include "support/filetools.h"
27 #include "support/fs_extras.h"
28 #include "support/lstrings.h"
29 #include "support/lyxlib.h"
30 #include "support/os.h"
31 #include "support/package.h"
32 #include "support/path.h"
33 #include "support/systemcall.h"
35 // FIXME Interface violation
39 #include <boost/assert.hpp>
40 #include <boost/filesystem/operations.hpp>
41 #include <boost/regex.hpp>
54 #ifndef CXX_GLOBAL_CSTD
65 using std::ostringstream;
68 namespace fs = boost::filesystem;
73 bool isLyXFilename(string const & filename)
75 return suffixIs(ascii_lowercase(filename), ".lyx");
79 bool isSGMLFilename(string const & filename)
81 return suffixIs(ascii_lowercase(filename), ".sgml");
85 string const latex_path(string const & original_path,
86 latex_path_extension extension,
89 // On cygwin, we may need windows or posix style paths.
90 string path = os::latex_path(original_path);
91 path = subst(path, "~", "\\string~");
92 if (path.find(' ') != string::npos) {
93 // We can't use '"' because " is sometimes active (e.g. if
94 // babel is loaded with the "german" option)
95 if (extension == EXCLUDE_EXTENSION) {
96 // ChangeExtension calls os::internal_path internally
97 // so don't use it to remove the extension.
98 string const ext = getExtension(path);
99 string const base = ext.empty() ?
101 path.substr(0, path.length() - ext.length() - 1);
102 // ChangeExtension calls os::internal_path internally
103 // so don't use it to re-add the extension.
104 path = "\\string\"" + base + "\\string\"." + ext;
106 path = "\\string\"" + path + "\\string\"";
110 return dots == ESCAPE_DOTS ? subst(path, ".", "\\lyxdot ") : path;
114 // Substitutes spaces with underscores in filename (and path)
115 string const makeLatexName(string const & file)
117 string name = onlyFilename(file);
118 string const path = onlyPath(file);
120 for (string::size_type i = 0; i < name.length(); ++i)
121 name[i] &= 0x7f; // set 8th bit to 0
123 // ok so we scan through the string twice, but who cares.
124 string const keep = "abcdefghijklmnopqrstuvwxyz"
125 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
126 "@!\"'()*+,-./0123456789:;<=>?[]`|";
128 string::size_type pos = 0;
129 while ((pos = name.find_first_not_of(keep, pos)) != string::npos)
132 return addName(path, name);
136 string const quoteName(string const & name, quote_style style)
140 // This does not work for filenames containing " (windows)
141 // or ' (all other OSes). This can't be changed easily, since
142 // we would need to adapt the command line parser in
143 // Forkedcall::generateChild. Therefore we don't pass user
144 // filenames to child processes if possible. We store them in
145 // a python script instead, where we don't have these
147 return (os::shell() == os::UNIX) ?
151 return "\"" + subst(subst(name, "\\", "\\\\"), "\"", "\\\"")
154 // shut up stupid compiler
159 // Is a file readable ?
160 bool isFileReadable(string const & path)
162 return fs::exists(path) && !fs::is_directory(path) && fs::is_readable(path);
166 //returns true: dir writeable
167 // false: not writeable
168 bool isDirWriteable(string const & path)
170 lyxerr[Debug::FILES] << "isDirWriteable: " << path << endl;
172 string const tmpfl = tempName(path, "lyxwritetest");
182 // Uses a string of paths separated by ";"s to find a file to open.
183 // Can't cope with pathnames with a ';' in them. Returns full path to file.
184 // If path entry begins with $$LyX/, use system_lyxdir
185 // If path entry begins with $$User/, use user_lyxdir
186 // Example: "$$User/doc;$$LyX/doc"
187 string const fileOpenSearch(string const & path, string const & name,
192 bool notfound = true;
193 string tmppath = split(path, path_element, ';');
195 while (notfound && !path_element.empty()) {
196 path_element = os::internal_path(path_element);
197 if (!suffixIs(path_element, '/'))
199 path_element = subst(path_element, "$$LyX",
200 package().system_support());
201 path_element = subst(path_element, "$$User",
202 package().user_support());
204 real_file = fileSearch(path_element, name, ext);
206 if (real_file.empty()) {
208 tmppath = split(tmppath, path_element, ';');
209 } while (!tmppath.empty() && path_element.empty());
218 /// Returns a vector of all files in directory dir having extension ext.
219 vector<string> const dirList(string const & dir, string const & ext)
221 // EXCEPTIONS FIXME. Rewrite needed when we turn on exceptions. (Lgb)
222 vector<string> dirlist;
224 if (!(fs::exists(dir) && fs::is_directory(dir))) {
226 << "Directory \"" << dir
227 << "\" does not exist to DirList." << endl;
232 if (!ext.empty() && ext[0] != '.')
236 fs::directory_iterator dit(dir);
237 fs::directory_iterator end;
238 for (; dit != end; ++dit) {
239 string const & fil = dit->leaf();
240 if (suffixIs(fil, extension)) {
241 dirlist.push_back(fil);
248 // Returns the real name of file name in directory path, with optional
250 string const fileSearch(string const & path, string const & name,
253 // if `name' is an absolute path, we ignore the setting of `path'
254 // Expand Environmentvariables in 'name'
255 string const tmpname = replaceEnvironmentPath(name);
256 string fullname = makeAbsPath(tmpname, path);
257 // search first without extension, then with it.
258 if (isFileReadable(fullname))
262 // Is it not more reasonable to use ChangeExtension()? (SMiyata)
265 return isFileReadable(fullname) ? fullname : string();
269 // Search the file name.ext in the subdirectory dir of
271 // 2) build_lyxdir (if not empty)
273 string const libFileSearch(string const & dir, string const & name,
276 string fullname = fileSearch(addPath(package().user_support(), dir),
278 if (!fullname.empty())
281 if (!package().build_support().empty())
282 fullname = fileSearch(addPath(package().build_support(), dir),
284 if (!fullname.empty())
287 return fileSearch(addPath(package().system_support(), dir), name, ext);
291 string const i18nLibFileSearch(string const & dir, string const & name,
294 // the following comments are from intl/dcigettext.c. We try
295 // to mimick this behaviour here.
296 /* The highest priority value is the `LANGUAGE' environment
297 variable. But we don't use the value if the currently
298 selected locale is the C locale. This is a GNU extension. */
299 /* [Otherwise] We have to proceed with the POSIX methods of
300 looking to `LC_ALL', `LC_xxx', and `LANG'. */
302 string lang = getEnv("LC_ALL");
304 lang = getEnv("LC_MESSAGES");
306 lang = getEnv("LANG");
312 string const language = getEnv("LANGUAGE");
313 if (lang != "C" && lang != "POSIX" && !language.empty())
317 lang = split(lang, l, ':');
318 while (!l.empty() && l != "C" && l != "POSIX") {
319 string const tmp = libFileSearch(dir,
320 token(l, '_', 0) + '_' + name,
324 lang = split(lang, l, ':');
327 return libFileSearch(dir, name, ext);
331 string const libScriptSearch(string const & command_in, quote_style style)
333 static string const token_scriptpath = "$$s/";
335 string command = command_in;
336 // Find the starting position of "$$s/"
337 string::size_type const pos1 = command.find(token_scriptpath);
338 if (pos1 == string::npos)
340 // Find the end of the "$$s/some_subdir/some_script" word within
341 // command. Assumes that the script name does not contain spaces.
342 string::size_type const start_script = pos1 + 4;
343 string::size_type const pos2 = command.find(' ', start_script);
344 string::size_type const size_script = pos2 == string::npos?
345 (command.size() - start_script) : pos2 - start_script;
347 // Does this script file exist?
348 string const script =
349 libFileSearch(".", command.substr(start_script, size_script));
351 if (script.empty()) {
352 // Replace "$$s/" with ""
353 command.erase(pos1, 4);
355 // Replace "$$s/foo/some_script" with "<path to>/some_script".
356 string::size_type const size_replace = size_script + 4;
357 command.replace(pos1, size_replace, quoteName(script, style));
366 string const createTmpDir(string const & tempdir, string const & mask)
369 << "createTmpDir: tempdir=`" << tempdir << "'\n"
370 << "createTmpDir: mask=`" << mask << '\'' << endl;
372 string const tmpfl = tempName(tempdir, mask);
373 // lyx::tempName actually creates a file to make sure that it
374 // stays unique. So we have to delete it before we can create
375 // a dir with the same name. Note also that we are not thread
376 // safe because of the gap between unlink and mkdir. (Lgb)
379 if (tmpfl.empty() || mkdir(tmpfl, 0700)) {
380 lyxerr << "LyX could not create the temporary directory '"
381 << tmpfl << "'" << endl;
385 return makeAbsPath(tmpfl);
391 bool destroyDir(string const & tmpdir)
394 return fs::remove_all(tmpdir) > 0;
395 } catch (fs::filesystem_error const & fe){
396 lyxerr << "Could not delete " << tmpdir << ". (" << fe.what() << ")" << std::endl;
402 string const createBufferTmpDir()
405 // We are in our own directory. Why bother to mangle name?
406 // In fact I wrote this code to circumvent a problematic behaviour
407 // (bug?) of EMX mkstemp().
409 package().temp_dir() + "/lyx_tmpbuf" +
410 convert<string>(count++);
412 if (mkdir(tmpfl, 0777)) {
413 lyxerr << "LyX could not create the temporary directory '"
414 << tmpfl << "'" << endl;
421 string const createLyXTmpDir(string const & deflt)
423 if (!deflt.empty() && deflt != "/tmp") {
424 if (mkdir(deflt, 0777)) {
425 if (isDirWriteable(deflt)) {
426 // deflt could not be created because it
427 // did exist already, so let's create our own
429 return createTmpDir(deflt, "lyx_tmpdir");
431 // some other error occured.
432 return createTmpDir("/tmp", "lyx_tmpdir");
437 return createTmpDir("/tmp", "lyx_tmpdir");
442 bool createDirectory(string const & path, int permission)
444 string temp = rtrim(os::internal_path(path), "/");
445 BOOST_ASSERT(!temp.empty());
446 return mkdir(temp, permission) == 0;
450 // Strip filename from path name
451 string const onlyPath(string const & filename)
453 // If empty filename, return empty
454 if (filename.empty())
457 // Find last / or start of filename
458 string::size_type j = filename.rfind('/');
459 return j == string::npos ? "./" : filename.substr(0, j + 1);
463 // Convert relative path into absolute path based on a basepath.
464 // If relpath is absolute, just use that.
465 // If basepath is empty, use CWD as base.
466 string const makeAbsPath(string const & relPath, string const & basePath)
468 // checks for already absolute path
469 if (os::is_absolute_path(relPath))
472 // Copies given paths
473 string tempRel = os::internal_path(relPath);
474 // Since TempRel is NOT absolute, we can safely replace "//" with "/"
475 tempRel = subst(tempRel, "//", "/");
479 if (os::is_absolute_path(basePath))
482 tempBase = addPath(getcwd(), basePath);
484 // Handle /./ at the end of the path
485 while (suffixIs(tempBase, "/./"))
486 tempBase.erase(tempBase.length() - 2);
488 // processes relative path
489 string rTemp = tempRel;
492 while (!rTemp.empty()) {
494 rTemp = split(rTemp, temp, '/');
496 if (temp == ".") continue;
498 // Remove one level of TempBase
499 string::difference_type i = tempBase.length() - 2;
502 while (i > 0 && tempBase[i] != '/')
505 tempBase.erase(i, string::npos);
508 } else if (temp.empty() && !rTemp.empty()) {
509 tempBase = os::current_root() + rTemp;
512 // Add this piece to TempBase
513 if (!suffixIs(tempBase, '/'))
519 // returns absolute path
520 return os::internal_path(tempBase);
524 // Correctly append filename to the pathname.
525 // If pathname is '.', then don't use pathname.
526 // Chops any path of filename.
527 string const addName(string const & path, string const & fname)
529 string const basename = onlyFilename(fname);
532 if (path != "." && path != "./" && !path.empty()) {
533 buf = os::internal_path(path);
534 if (!suffixIs(path, '/'))
538 return buf + basename;
542 // Strips path from filename
543 string const onlyFilename(string const & fname)
548 string::size_type j = fname.rfind('/');
549 if (j == string::npos) // no '/' in fname
553 return fname.substr(j + 1);
557 /// Returns true is path is absolute
558 bool absolutePath(string const & path)
560 return os::is_absolute_path(path);
564 // Create absolute path. If impossible, don't do anything
565 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
566 string const expandPath(string const & path)
568 // checks for already absolute path
569 string rTemp = replaceEnvironmentPath(path);
570 if (os::is_absolute_path(rTemp))
574 string const copy = rTemp;
577 rTemp = split(rTemp, temp, '/');
580 return getcwd() + '/' + rTemp;
583 return package().home_dir() + '/' + rTemp;
586 return makeAbsPath(copy);
588 // Don't know how to handle this
593 // Normalize a path. Constracts path/../path
594 // Can't handle "../../" or "/../" (Asger)
595 // Also converts paths like /foo//bar ==> /foo/bar
596 string const normalizePath(string const & path)
598 // Normalize paths like /foo//bar ==> /foo/bar
599 static boost::regex regex("/{2,}");
600 string const tmppath = boost::regex_merge(path, regex, "/");
602 fs::path const npath = fs::path(tmppath, fs::no_check).normalize();
604 if (!npath.is_complete())
605 return "./" + npath.string() + '/';
607 return npath.string() + '/';
611 string const getFileContents(string const & fname)
613 if (fs::exists(fname)) {
614 ifstream ifs(fname.c_str());
622 lyxerr << "LyX was not able to read file '" << fname << '\'' << endl;
627 // Search the string for ${VAR} and $VAR and replace VAR using getenv.
628 string const replaceEnvironmentPath(string const & path)
630 // ${VAR} is defined as
631 // $\{[A-Za-z_][A-Za-z_0-9]*\}
632 static string const envvar_br = "[$]\\{([A-Za-z_][A-Za-z_0-9]*)\\}";
634 // $VAR is defined as:
635 // $\{[A-Za-z_][A-Za-z_0-9]*\}
636 static string const envvar = "[$]([A-Za-z_][A-Za-z_0-9]*)";
638 static boost::regex envvar_br_re("(.*)" + envvar_br + "(.*)");
639 static boost::regex envvar_re("(.*)" + envvar + "(.*)");
642 string result = path;
644 regex_match(result, what, envvar_br_re);
645 if (!what[0].matched) {
646 regex_match(result, what, envvar_re);
647 if (!what[0].matched)
650 result = what.str(1) + getEnv(what.str(2)) + what.str(3);
656 // Make relative path out of two absolute paths
657 string const makeRelPath(string const & abspath, string const & basepath)
658 // Makes relative path out of absolute path. If it is deeper than basepath,
659 // it's easy. If basepath and abspath share something (they are all deeper
660 // than some directory), it'll be rendered using ..'s. If they are completely
661 // different, then the absolute path will be used as relative path.
663 string::size_type const abslen = abspath.length();
664 string::size_type const baselen = basepath.length();
666 string::size_type i = os::common_path(abspath, basepath);
669 // actually no match - cannot make it relative
673 // Count how many dirs there are in basepath above match
674 // and append as many '..''s into relpath
676 string::size_type j = i;
677 while (j < baselen) {
678 if (basepath[j] == '/') {
679 if (j + 1 == baselen)
686 // Append relative stuff from common directory to abspath
687 if (abspath[i] == '/')
689 for (; i < abslen; ++i)
692 if (suffixIs(buf, '/'))
693 buf.erase(buf.length() - 1);
694 // Substitute empty with .
701 // Append sub-directory(ies) to a path in an intelligent way
702 string const addPath(string const & path, string const & path_2)
705 string const path2 = os::internal_path(path_2);
707 if (!path.empty() && path != "." && path != "./") {
708 buf = os::internal_path(path);
709 if (path[path.length() - 1] != '/')
713 if (!path2.empty()) {
714 string::size_type const p2start = path2.find_first_not_of('/');
715 string::size_type const p2end = path2.find_last_not_of('/');
716 string const tmp = path2.substr(p2start, p2end - p2start + 1);
724 Change extension of oldname to extension.
725 Strips path off if no_path == true.
726 If no extension on oldname, just appends.
728 string const changeExtension(string const & oldname, string const & extension)
730 string::size_type const last_slash = oldname.rfind('/');
731 string::size_type last_dot = oldname.rfind('.');
732 if (last_dot < last_slash && last_slash != string::npos)
733 last_dot = string::npos;
736 // Make sure the extension starts with a dot
737 if (!extension.empty() && extension[0] != '.')
738 ext= '.' + extension;
742 return os::internal_path(oldname.substr(0, last_dot) + ext);
746 string const removeExtension(string const & name)
748 return changeExtension(name, string());
752 /// Return the extension of the file (not including the .)
753 string const getExtension(string const & name)
755 string::size_type const last_slash = name.rfind('/');
756 string::size_type const last_dot = name.rfind('.');
757 if (last_dot != string::npos &&
758 (last_slash == string::npos || last_dot > last_slash))
759 return name.substr(last_dot + 1,
760 name.length() - (last_dot + 1));
766 // the different filetypes and what they contain in one of the first lines
767 // (dots are any characters). (Herbert 20020131)
770 // EPS %!PS-Adobe-3.0 EPSF...
777 // PBM P1... or P4 (B/W)
778 // PGM P2... or P5 (Grayscale)
779 // PPM P3... or P6 (color)
780 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
781 // SGI \001\332... (decimal 474)
783 // TIFF II... or MM...
785 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
786 // ...static char *...
787 // XWD \000\000\000\151 (0x00006900) decimal 105
789 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
790 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
791 // Z \037\235 UNIX compress
793 string const getFormatFromContents(string const & filename)
796 if (filename.empty() || !isFileReadable(filename))
799 ifstream ifs(filename.c_str());
801 // Couldn't open file...
805 static string const gzipStamp = "\037\213";
808 static string const zipStamp = "PK";
811 static string const compressStamp = "\037\235";
813 // Maximum strings to read
814 int const max_count = 50;
819 bool firstLine = true;
820 while ((count++ < max_count) && format.empty()) {
822 lyxerr[Debug::GRAPHICS]
823 << "filetools(getFormatFromContents)\n"
824 << "\tFile type not recognised before EOF!"
830 string const stamp = str.substr(0, 2);
831 if (firstLine && str.size() >= 2) {
832 // at first we check for a zipped file, because this
833 // information is saved in the first bytes of the file!
834 // also some graphic formats which save the information
835 // in the first line, too.
836 if (prefixIs(str, gzipStamp)) {
839 } else if (stamp == zipStamp) {
842 } else if (stamp == compressStamp) {
846 } else if (stamp == "BM") {
849 } else if (stamp == "\001\332") {
853 // Don't need to use str.at(0), str.at(1) because
854 // we already know that str.size() >= 2
855 } else if (str[0] == 'P') {
871 } else if ((stamp == "II") || (stamp == "MM")) {
874 } else if (prefixIs(str,"%TGIF")) {
877 } else if (prefixIs(str,"#FIG")) {
880 } else if (prefixIs(str,"GIF")) {
883 } else if (str.size() > 3) {
884 int const c = ((str[0] << 24) & (str[1] << 16) &
885 (str[2] << 8) & str[3]);
896 else if (contains(str,"EPSF"))
897 // dummy, if we have wrong file description like
898 // %!PS-Adobe-2.0EPSF"
901 else if (contains(str,"Grace"))
904 else if (contains(str,"JFIF"))
907 else if (contains(str,"%PDF"))
910 else if (contains(str,"PNG"))
913 else if (contains(str,"%!PS-Adobe")) {
916 if (contains(str,"EPSF"))
922 else if (contains(str,"_bits[]"))
925 else if (contains(str,"XPM") || contains(str, "static char *"))
928 else if (contains(str,"BITPIX"))
932 if (!format.empty()) {
933 lyxerr[Debug::GRAPHICS]
934 << "Recognised Fileformat: " << format << endl;
938 lyxerr[Debug::GRAPHICS]
939 << "filetools(getFormatFromContents)\n"
940 << "\tCouldn't find a known format!\n";
945 /// check for zipped file
946 bool zippedFile(string const & name)
948 string const type = getFormatFromContents(name);
949 if (contains("gzip zip compress", type) && !type.empty())
955 string const unzippedFileName(string const & zipped_file)
957 string const ext = getExtension(zipped_file);
958 if (ext == "gz" || ext == "z" || ext == "Z")
959 return changeExtension(zipped_file, string());
960 return "unzipped_" + zipped_file;
964 string const unzipFile(string const & zipped_file, string const & unzipped_file)
966 string const tempfile = unzipped_file.empty() ?
967 unzippedFileName(zipped_file) : unzipped_file;
969 string const command = "gunzip -c " + zipped_file + " > " + tempfile;
971 one.startscript(Systemcall::Wait, command);
972 // test that command was executed successfully (anon)
973 // yes, please do. (Lgb)
978 docstring const makeDisplayPath(string const & path, unsigned int threshold)
981 string const home = package().home_dir();
983 // replace /home/blah with ~/
984 if (!home.empty() && prefixIs(str, home))
985 str = subst(str, home, "~");
987 if (str.length() <= threshold)
988 return lyx::from_utf8(os::external_path(str));
990 string const prefix = ".../";
993 while (str.length() > threshold)
994 str = split(str, temp, '/');
996 // Did we shorten everything away?
998 // Yes, filename itself is too long.
999 // Pick the start and the end of the filename.
1000 str = onlyFilename(path);
1001 string const head = str.substr(0, threshold / 2 - 3);
1003 string::size_type len = str.length();
1005 str.substr(len - threshold / 2 - 2, len - 1);
1006 str = head + "..." + tail;
1009 return lyx::from_utf8(os::external_path(prefix + str));
1013 bool readLink(string const & file, string & link, bool resolve)
1015 #ifdef HAVE_READLINK
1016 char linkbuffer[512];
1017 // Should be PATH_MAX but that needs autconf support
1018 int const nRead = ::readlink(file.c_str(),
1019 linkbuffer, sizeof(linkbuffer) - 1);
1022 linkbuffer[nRead] = '\0'; // terminator
1024 link = makeAbsPath(linkbuffer, onlyPath(file));
1034 cmd_ret const runCommand(string const & cmd)
1036 // FIXME: replace all calls to RunCommand with ForkedCall
1037 // (if the output is not needed) or the code in ispell.C
1038 // (if the output is needed).
1040 // One question is if we should use popen or
1041 // create our own popen based on fork, exec, pipe
1042 // of course the best would be to have a
1043 // pstream (process stream), with the
1044 // variants ipstream, opstream
1046 #if defined (HAVE_POPEN)
1047 FILE * inf = ::popen(cmd.c_str(), os::popen_read_mode());
1048 #elif defined (HAVE__POPEN)
1049 FILE * inf = ::_popen(cmd.c_str(), os::popen_read_mode());
1051 #error No popen() function.
1054 // (Claus Hentschel) Check if popen was succesful ;-)
1056 lyxerr << "RunCommand:: could not start child process" << endl;
1057 return make_pair(-1, string());
1063 ret += static_cast<char>(c);
1067 #if defined (HAVE_PCLOSE)
1068 int const pret = pclose(inf);
1069 #elif defined (HAVE__PCLOSE)
1070 int const pret = _pclose(inf);
1072 #error No pclose() function.
1076 perror("RunCommand:: could not terminate child process");
1078 return make_pair(pret, ret);
1082 string const findtexfile(string const & fil, string const & /*format*/)
1084 /* There is no problem to extend this function too use other
1085 methods to look for files. It could be setup to look
1086 in environment paths and also if wanted as a last resort
1087 to a recursive find. One of the easier extensions would
1088 perhaps be to use the LyX file lookup methods. But! I am
1089 going to implement this until I see some demand for it.
1093 // If the file can be found directly, we just return a
1094 // absolute path version of it.
1095 if (fs::exists(fil))
1096 return makeAbsPath(fil);
1098 // No we try to find it using kpsewhich.
1099 // It seems from the kpsewhich manual page that it is safe to use
1100 // kpsewhich without --format: "When the --format option is not
1101 // given, the search path used when looking for a file is inferred
1102 // from the name given, by looking for a known extension. If no
1103 // known extension is found, the search path for TeX source files
1105 // However, we want to take advantage of the format sine almost all
1106 // the different formats has environment variables that can be used
1107 // to controll which paths to search. f.ex. bib looks in
1108 // BIBINPUTS and TEXBIB. Small list follows:
1109 // bib - BIBINPUTS, TEXBIB
1111 // graphic/figure - TEXPICTS, TEXINPUTS
1112 // ist - TEXINDEXSTYLE, INDEXSTYLE
1113 // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
1115 // tfm - TFMFONTS, TEXFONTS
1116 // This means that to use kpsewhich in the best possible way we
1117 // should help it by setting additional path in the approp. envir.var.
1118 string const kpsecmd = "kpsewhich " + fil;
1120 cmd_ret const c = runCommand(kpsecmd);
1122 lyxerr[Debug::LATEX] << "kpse status = " << c.first << '\n'
1123 << "kpse result = `" << rtrim(c.second, "\n")
1126 return os::internal_path(rtrim(c.second, "\n\r"));
1132 void removeAutosaveFile(string const & filename)
1134 string a = onlyPath(filename);
1136 a += onlyFilename(filename);
1143 void readBB_lyxerrMessage(string const & file, bool & zipped,
1144 string const & message)
1146 lyxerr[Debug::GRAPHICS] << "[readBB_from_PSFile] "
1147 << message << std::endl;
1148 #ifdef WITH_WARNINGS
1149 #warning Why is this func deleting a file? (Lgb)
1156 string const readBB_from_PSFile(string const & file)
1158 // in a (e)ps-file it's an entry like %%BoundingBox:23 45 321 345
1159 // It seems that every command in the header has an own line,
1160 // getline() should work for all files.
1161 // On the other hand some plot programs write the bb at the
1162 // end of the file. Than we have in the header:
1163 // %%BoundingBox: (atend)
1164 // In this case we must check the end.
1165 bool zipped = zippedFile(file);
1166 string const file_ = zipped ? unzipFile(file) : file;
1167 string const format = getFormatFromContents(file_);
1169 if (format != "eps" && format != "ps") {
1170 readBB_lyxerrMessage(file_, zipped,"no(e)ps-format");
1174 static boost::regex bbox_re(
1175 "^%%BoundingBox:\\s*([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)");
1176 std::ifstream is(file_.c_str());
1181 if (regex_match(s, what, bbox_re)) {
1182 // Our callers expect the tokens in the string
1183 // separated by single spaces.
1184 // FIXME: change return type from string to something
1187 os << what.str(1) << ' ' << what.str(2) << ' '
1188 << what.str(3) << ' ' << what.str(4);
1189 string const bb = os.str();
1190 readBB_lyxerrMessage(file_, zipped, bb);
1194 readBB_lyxerrMessage(file_, zipped, "no bb found");
1199 int compare_timestamps(string const & file1, string const & file2)
1201 BOOST_ASSERT(absolutePath(file1));
1202 BOOST_ASSERT(absolutePath(file2));
1204 // If the original is newer than the copy, then copy the original
1205 // to the new directory.
1208 if (fs::exists(file1) && fs::exists(file2)) {
1209 double const tmp = difftime(fs::last_write_time(file1),
1210 fs::last_write_time(file2));
1212 cmp = tmp > 0 ? 1 : -1;
1214 } else if (fs::exists(file1)) {
1216 } else if (fs::exists(file2)) {
1223 } //namespace support