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, bool exclude_extension)
87 string path = subst(original_path, "\\", "/");
88 path = subst(path, "~", "\\string~");
89 if (path.find(' ') != string::npos)
90 // We can't use '"' because " is sometimes active (e.g. if
91 // babel is loaded with the "german" option)
92 if (exclude_extension) {
93 string const base = ChangeExtension(path, string());
94 string const ext = GetExtension(path);
95 // ChangeExtension calls os::internal_path internally
96 // so don't use it to re-add the extension.
97 path = "\\string\"" + base + "\\string\"." + ext;
99 path = "\\string\"" + path + "\\string\"";
104 // Substitutes spaces with underscores in filename (and path)
105 string const MakeLatexName(string const & file)
107 string name = OnlyFilename(file);
108 string const path = OnlyPath(file);
110 for (string::size_type i = 0; i < name.length(); ++i) {
111 name[i] &= 0x7f; // set 8th bit to 0
114 // ok so we scan through the string twice, but who cares.
115 string const keep("abcdefghijklmnopqrstuvwxyz"
116 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
117 "@!\"'()*+,-./0123456789:;<=>?[]`|");
119 string::size_type pos = 0;
120 while ((pos = name.find_first_not_of(keep, pos)) != string::npos) {
123 return AddName(path, name);
127 string const QuoteName(string const & name)
129 return (os::shell() == os::UNIX) ?
135 // Is a file readable ?
136 bool IsFileReadable(string const & path)
138 return fs::exists(path) && !fs::is_directory(path) && fs::is_readable(path);
142 //returns true: dir writeable
143 // false: not writeable
144 bool IsDirWriteable(string const & path)
146 lyxerr[Debug::FILES] << "IsDirWriteable: " << path << endl;
148 string const tmpfl(tempName(path, "lyxwritetest"));
158 // Uses a string of paths separated by ";"s to find a file to open.
159 // Can't cope with pathnames with a ';' in them. Returns full path to file.
160 // If path entry begins with $$LyX/, use system_lyxdir
161 // If path entry begins with $$User/, use user_lyxdir
162 // Example: "$$User/doc;$$LyX/doc"
163 string const FileOpenSearch(string const & path, string const & name,
168 bool notfound = true;
169 string tmppath = split(path, path_element, ';');
171 while (notfound && !path_element.empty()) {
172 path_element = os::internal_path(path_element);
173 if (!suffixIs(path_element, '/'))
175 path_element = subst(path_element, "$$LyX",
176 package().system_support());
177 path_element = subst(path_element, "$$User",
178 package().user_support());
180 real_file = FileSearch(path_element, name, ext);
182 if (real_file.empty()) {
184 tmppath = split(tmppath, path_element, ';');
185 } while (!tmppath.empty() && path_element.empty());
191 if (ext.empty() && notfound) {
192 real_file = FileOpenSearch(path, name, "exe");
193 if (notfound) real_file = FileOpenSearch(path, name, "cmd");
200 /// Returns a vector of all files in directory dir having extension ext.
201 vector<string> const DirList(string const & dir, string const & ext)
203 // EXCEPTIONS FIXME. Rewrite needed when we turn on exceptions. (Lgb)
204 vector<string> dirlist;
206 if (!(fs::exists(dir) && fs::is_directory(dir))) {
208 << "Directory \"" << dir
209 << "\" does not exist to DirList." << endl;
214 if (!ext.empty() && ext[0] != '.')
218 fs::directory_iterator dit(dir);
219 fs::directory_iterator end;
220 for (; dit != end; ++dit) {
221 string const & fil = dit->leaf();
222 if (suffixIs(fil, extension)) {
223 dirlist.push_back(fil);
230 // Returns the real name of file name in directory path, with optional
232 string const FileSearch(string const & path, string const & name,
235 // if `name' is an absolute path, we ignore the setting of `path'
236 // Expand Environmentvariables in 'name'
237 string const tmpname = ReplaceEnvironmentPath(name);
238 string fullname = MakeAbsPath(tmpname, path);
239 // search first without extension, then with it.
240 if (IsFileReadable(fullname))
242 else if (ext.empty())
244 else { // Is it not more reasonable to use ChangeExtension()? (SMiyata)
247 if (IsFileReadable(fullname))
255 // Search the file name.ext in the subdirectory dir of
257 // 2) build_lyxdir (if not empty)
259 string const LibFileSearch(string const & dir, string const & name,
262 string fullname = FileSearch(AddPath(package().user_support(), dir),
264 if (!fullname.empty())
267 if (!package().build_support().empty())
268 fullname = FileSearch(AddPath(package().build_support(), dir),
270 if (!fullname.empty())
273 return FileSearch(AddPath(package().system_support(), dir), name, ext);
278 i18nLibFileSearch(string const & dir, string const & name,
281 // the following comments are from intl/dcigettext.c. We try
282 // to mimick this behaviour here.
283 /* The highest priority value is the `LANGUAGE' environment
284 variable. But we don't use the value if the currently
285 selected locale is the C locale. This is a GNU extension. */
286 /* [Otherwise] We have to proceed with the POSIX methods of
287 looking to `LC_ALL', `LC_xxx', and `LANG'. */
289 string lang = getEnv("LC_ALL");
291 lang = getEnv("LC_MESSAGES");
293 lang = getEnv("LANG");
299 string const language = getEnv("LANGUAGE");
300 if (lang != "C" && lang != "POSIX" && !language.empty())
304 lang = split(lang, l, ':');
305 while (!l.empty() && l != "C" && l != "POSIX") {
306 string const tmp = LibFileSearch(dir,
307 token(l, '_', 0) + '_' + name,
311 lang = split(lang, l, ':');
314 return LibFileSearch(dir, name, ext);
318 string const LibScriptSearch(string const & command_in)
320 string const token_scriptpath("$$s/");
322 string command = command_in;
323 // Find the starting position of "$$s/"
324 string::size_type const pos1 = command.find(token_scriptpath);
325 if (pos1 == string::npos)
327 // Find the end of the "$$s/some_subdir/some_script" word within
328 // command. Assumes that the script name does not contain spaces.
329 string::size_type const start_script = pos1 + 4;
330 string::size_type const pos2 = command.find(' ', start_script);
331 string::size_type const size_script = pos2 == string::npos?
332 (command.size() - start_script) : pos2 - start_script;
334 // Does this script file exist?
335 string const script =
336 LibFileSearch(".", command.substr(start_script, size_script));
338 if (script.empty()) {
339 // Replace "$$s/" with ""
340 command.erase(pos1, 4);
342 // Replace "$$s/foo/some_script" with "<path to>/some_script".
343 string::size_type const size_replace = size_script + 4;
344 command.replace(pos1, size_replace, QuoteName(script));
353 string const createTmpDir(string const & tempdir, string const & mask)
356 << "createTmpDir: tempdir=`" << tempdir << "'\n"
357 << "createTmpDir: mask=`" << mask << '\'' << endl;
359 string const tmpfl(tempName(tempdir, mask));
360 // lyx::tempName actually creates a file to make sure that it
361 // stays unique. So we have to delete it before we can create
362 // a dir with the same name. Note also that we are not thread
363 // safe because of the gap between unlink and mkdir. (Lgb)
366 if (tmpfl.empty() || mkdir(tmpfl, 0700)) {
367 lyxerr << "LyX could not create the temporary directory '"
368 << tmpfl << "'" << endl;
372 return MakeAbsPath(tmpfl);
378 bool destroyDir(string const & tmpdir)
382 Path p(user_lyxdir());
384 return fs::remove_all(tmpdir) > 0;
388 string const createBufferTmpDir()
391 // We are in our own directory. Why bother to mangle name?
392 // In fact I wrote this code to circumvent a problematic behaviour
393 // (bug?) of EMX mkstemp().
395 package().temp_dir() + "/lyx_tmpbuf" +
396 convert<string>(count++);
398 if (mkdir(tmpfl, 0777)) {
399 lyxerr << "LyX could not create the temporary directory '"
400 << tmpfl << "'" << endl;
407 string const createLyXTmpDir(string const & deflt)
409 if (!deflt.empty() && deflt != "/tmp") {
410 if (mkdir(deflt, 0777)) {
412 Path p(package().user_support());
414 if (IsDirWriteable(deflt)) {
415 // deflt could not be created because it
416 // did exist already, so let's create our own
418 return createTmpDir(deflt, "lyx_tmpdir");
420 // some other error occured.
421 return createTmpDir("/tmp", "lyx_tmpdir");
427 Path p(package().user_support());
429 return createTmpDir("/tmp", "lyx_tmpdir");
434 bool createDirectory(string const & path, int permission)
436 string temp(rtrim(os::internal_path(path), "/"));
438 BOOST_ASSERT(!temp.empty());
440 if (mkdir(temp, permission))
447 // Strip filename from path name
448 string const OnlyPath(string const & Filename)
450 // If empty filename, return empty
451 if (Filename.empty()) return Filename;
453 // Find last / or start of filename
454 string::size_type j = Filename.rfind('/');
455 if (j == string::npos)
457 return Filename.substr(0, j + 1);
461 // Convert relative path into absolute path based on a basepath.
462 // If relpath is absolute, just use that.
463 // If basepath is empty, use CWD as base.
464 string const MakeAbsPath(string const & RelPath, string const & BasePath)
466 // checks for already absolute path
467 if (os::is_absolute_path(RelPath))
470 // Copies given paths
471 string TempRel(os::internal_path(RelPath));
472 // Since TempRel is NOT absolute, we can safely replace "//" with "/"
473 TempRel = subst(TempRel, "//", "/");
477 if (os::is_absolute_path(BasePath))
480 TempBase = AddPath(getcwd(), BasePath);
482 // Handle /./ at the end of the path
483 while (suffixIs(TempBase, "/./"))
484 TempBase.erase(TempBase.length() - 2);
486 // processes relative path
487 string RTemp(TempRel);
490 while (!RTemp.empty()) {
492 RTemp = split(RTemp, Temp, '/');
494 if (Temp == ".") continue;
496 // Remove one level of TempBase
497 string::difference_type i = TempBase.length() - 2;
500 while (i > 0 && TempBase[i] != '/') --i;
504 while (i > 2 && TempBase[i] != '/') --i;
507 TempBase.erase(i, string::npos);
510 } else if (Temp.empty() && !RTemp.empty()) {
511 TempBase = os::current_root() + RTemp;
514 // Add this piece to TempBase
515 if (!suffixIs(TempBase, '/'))
521 // returns absolute path
522 return os::internal_path(TempBase);
526 // Correctly append filename to the pathname.
527 // If pathname is '.', then don't use pathname.
528 // Chops any path of filename.
529 string const AddName(string const & path, string const & fname)
532 string const basename(OnlyFilename(fname));
536 if (path != "." && path != "./" && !path.empty()) {
537 buf = os::internal_path(path);
538 if (!suffixIs(path, '/'))
542 return buf + basename;
546 // Strips path from filename
547 string const OnlyFilename(string const & fname)
552 string::size_type j = fname.rfind('/');
553 if (j == string::npos) // no '/' in fname
557 return fname.substr(j + 1);
561 /// Returns true is path is absolute
562 bool AbsolutePath(string const & path)
564 return os::is_absolute_path(path);
569 // Create absolute path. If impossible, don't do anything
570 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
571 string const ExpandPath(string const & path)
573 // checks for already absolute path
574 string RTemp(ReplaceEnvironmentPath(path));
575 if (os::is_absolute_path(RTemp))
579 string const copy(RTemp);
582 RTemp = split(RTemp, Temp, '/');
585 return getcwd() + '/' + RTemp;
588 return package().home_dir() + '/' + RTemp;
591 return MakeAbsPath(copy);
593 // Don't know how to handle this
599 // Constracts path/../path
600 // Can't handle "../../" or "/../" (Asger)
601 // Also converts paths like /foo//bar ==> /foo/bar
602 string const NormalizePath(string const & path)
608 if (os::is_absolute_path(path))
611 // Make implicit current directory explicit
614 // Normalise paths like /foo//bar ==> /foo/bar
615 boost::RegEx regex("/{2,}");
616 RTemp = regex.Merge(RTemp, "/");
618 while (!RTemp.empty()) {
620 RTemp = split(RTemp, Temp, '/');
624 } else if (Temp == "..") {
625 // Remove one level of TempBase
626 string::difference_type i = TempBase.length() - 2;
627 while (i > 0 && TempBase[i] != '/')
629 if (i >= 0 && TempBase[i] == '/')
630 TempBase.erase(i + 1, string::npos);
634 TempBase += Temp + '/';
638 // returns absolute path
643 string const GetFileContents(string const & fname)
645 if (fs::exists(fname)) {
646 ifstream ifs(fname.c_str());
654 lyxerr << "LyX was not able to read file '" << fname << '\'' << endl;
659 // Search the string for ${VAR} and $VAR and replace VAR using getenv.
660 string const ReplaceEnvironmentPath(string const & path)
662 // ${VAR} is defined as
663 // $\{[A-Za-z_][A-Za-z_0-9]*\}
664 static string const envvar_br = "[$]\\{([A-Za-z_][A-Za-z_0-9]*)\\}";
666 // $VAR is defined as:
667 // $\{[A-Za-z_][A-Za-z_0-9]*\}
668 static string const envvar = "[$]([A-Za-z_][A-Za-z_0-9]*)";
670 static boost::regex envvar_br_re("(.*)" + envvar_br + "(.*)");
671 static boost::regex envvar_re("(.*)" + envvar + "(.*)");
674 string result = path;
676 regex_match(result, what, envvar_br_re);
677 if (!what[0].matched) {
678 regex_match(result, what, envvar_re);
679 if (!what[0].matched)
682 result = what.str(1) + getEnv(what.str(2)) + what.str(3);
688 // Make relative path out of two absolute paths
689 string const MakeRelPath(string const & abspath, string const & basepath)
690 // Makes relative path out of absolute path. If it is deeper than basepath,
691 // it's easy. If basepath and abspath share something (they are all deeper
692 // than some directory), it'll be rendered using ..'s. If they are completely
693 // different, then the absolute path will be used as relative path.
695 string::size_type const abslen = abspath.length();
696 string::size_type const baselen = basepath.length();
698 string::size_type i = os::common_path(abspath, basepath);
701 // actually no match - cannot make it relative
705 // Count how many dirs there are in basepath above match
706 // and append as many '..''s into relpath
708 string::size_type j = i;
709 while (j < baselen) {
710 if (basepath[j] == '/') {
711 if (j + 1 == baselen)
718 // Append relative stuff from common directory to abspath
719 if (abspath[i] == '/')
721 for (; i < abslen; ++i)
724 if (suffixIs(buf, '/'))
725 buf.erase(buf.length() - 1);
726 // Substitute empty with .
733 // Append sub-directory(ies) to a path in an intelligent way
734 string const AddPath(string const & path, string const & path_2)
737 string const path2 = os::internal_path(path_2);
739 if (!path.empty() && path != "." && path != "./") {
740 buf = os::internal_path(path);
741 if (path[path.length() - 1] != '/')
745 if (!path2.empty()) {
746 string::size_type const p2start = path2.find_first_not_of('/');
747 string::size_type const p2end = path2.find_last_not_of('/');
748 string const tmp = path2.substr(p2start, p2end - p2start + 1);
756 Change extension of oldname to extension.
757 Strips path off if no_path == true.
758 If no extension on oldname, just appends.
760 string const ChangeExtension(string const & oldname, string const & extension)
762 string::size_type const last_slash = oldname.rfind('/');
763 string::size_type last_dot = oldname.rfind('.');
764 if (last_dot < last_slash && last_slash != string::npos)
765 last_dot = string::npos;
768 // Make sure the extension starts with a dot
769 if (!extension.empty() && extension[0] != '.')
770 ext= '.' + extension;
774 return os::internal_path(oldname.substr(0, last_dot) + ext);
778 /// Return the extension of the file (not including the .)
779 string const GetExtension(string const & name)
781 string::size_type const last_slash = name.rfind('/');
782 string::size_type const last_dot = name.rfind('.');
783 if (last_dot != string::npos &&
784 (last_slash == string::npos || last_dot > last_slash))
785 return name.substr(last_dot + 1,
786 name.length() - (last_dot + 1));
792 // the different filetypes and what they contain in one of the first lines
793 // (dots are any characters). (Herbert 20020131)
796 // EPS %!PS-Adobe-3.0 EPSF...
803 // PBM P1... or P4 (B/W)
804 // PGM P2... or P5 (Grayscale)
805 // PPM P3... or P6 (color)
806 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
807 // SGI \001\332... (decimal 474)
809 // TIFF II... or MM...
811 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
812 // ...static char *...
813 // XWD \000\000\000\151 (0x00006900) decimal 105
815 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
816 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
817 // Z \037\235 UNIX compress
819 string const getFormatFromContents(string const & filename)
822 if (filename.empty() || !IsFileReadable(filename))
825 ifstream ifs(filename.c_str());
827 // Couldn't open file...
831 string const gzipStamp = "\037\213";
834 string const zipStamp = "PK";
837 string const compressStamp = "\037\235";
839 // Maximum strings to read
840 int const max_count = 50;
845 bool firstLine = true;
846 while ((count++ < max_count) && format.empty()) {
848 lyxerr[Debug::GRAPHICS]
849 << "filetools(getFormatFromContents)\n"
850 << "\tFile type not recognised before EOF!"
856 string const stamp = str.substr(0,2);
857 if (firstLine && str.size() >= 2) {
858 // at first we check for a zipped file, because this
859 // information is saved in the first bytes of the file!
860 // also some graphic formats which save the information
861 // in the first line, too.
862 if (prefixIs(str, gzipStamp)) {
865 } else if (stamp == zipStamp) {
868 } else if (stamp == compressStamp) {
872 } else if (stamp == "BM") {
875 } else if (stamp == "\001\332") {
879 // Don't need to use str.at(0), str.at(1) because
880 // we already know that str.size() >= 2
881 } else if (str[0] == 'P') {
897 } else if ((stamp == "II") || (stamp == "MM")) {
900 } else if (prefixIs(str,"%TGIF")) {
903 } else if (prefixIs(str,"#FIG")) {
906 } else if (prefixIs(str,"GIF")) {
909 } else if (str.size() > 3) {
910 int const c = ((str[0] << 24) & (str[1] << 16) &
911 (str[2] << 8) & str[3]);
922 else if (contains(str,"EPSF"))
923 // dummy, if we have wrong file description like
924 // %!PS-Adobe-2.0EPSF"
927 else if (contains(str,"Grace"))
930 else if (contains(str,"JFIF"))
933 else if (contains(str,"%PDF"))
936 else if (contains(str,"PNG"))
939 else if (contains(str,"%!PS-Adobe")) {
942 if (contains(str,"EPSF"))
948 else if (contains(str,"_bits[]"))
951 else if (contains(str,"XPM") || contains(str, "static char *"))
954 else if (contains(str,"BITPIX"))
958 if (!format.empty()) {
959 lyxerr[Debug::GRAPHICS]
960 << "Recognised Fileformat: " << format << endl;
964 lyxerr[Debug::GRAPHICS]
965 << "filetools(getFormatFromContents)\n"
966 << "\tCouldn't find a known format!\n";
971 /// check for zipped file
972 bool zippedFile(string const & name)
974 string const type = getFormatFromContents(name);
975 if (contains("gzip zip compress", type) && !type.empty())
981 string const unzippedFileName(string const & zipped_file)
983 string const ext = GetExtension(zipped_file);
984 if (ext == "gz" || ext == "z" || ext == "Z")
985 return ChangeExtension(zipped_file, string());
986 return "unzipped_" + zipped_file;
990 string const unzipFile(string const & zipped_file, string const & unzipped_file)
992 string const tempfile = unzipped_file.empty() ?
993 unzippedFileName(zipped_file) : unzipped_file;
995 string const command = "gunzip -c " + zipped_file + " > " + tempfile;
997 one.startscript(Systemcall::Wait, command);
998 // test that command was executed successfully (anon)
999 // yes, please do. (Lgb)
1004 string const MakeDisplayPath(string const & path, unsigned int threshold)
1008 string const home(package().home_dir());
1010 // replace /home/blah with ~/
1011 if (prefixIs(str, home))
1012 str = subst(str, home, "~");
1014 if (str.length() <= threshold)
1015 return os::external_path(str);
1017 string const prefix = ".../";
1020 while (str.length() > threshold)
1021 str = split(str, temp, '/');
1023 // Did we shorten everything away?
1025 // Yes, filename itself is too long.
1026 // Pick the start and the end of the filename.
1027 str = OnlyFilename(path);
1028 string const head = str.substr(0, threshold / 2 - 3);
1030 string::size_type len = str.length();
1032 str.substr(len - threshold / 2 - 2, len - 1);
1033 str = head + "..." + tail;
1036 return os::external_path(prefix + str);
1040 bool LyXReadLink(string const & file, string & link, bool resolve)
1042 #ifdef HAVE_READLINK
1043 char linkbuffer[512];
1044 // Should be PATH_MAX but that needs autconf support
1045 int const nRead = ::readlink(file.c_str(),
1046 linkbuffer, sizeof(linkbuffer) - 1);
1049 linkbuffer[nRead] = '\0'; // terminator
1051 link = MakeAbsPath(linkbuffer, OnlyPath(file));
1061 cmd_ret const RunCommand(string const & cmd)
1063 // FIXME: replace all calls to RunCommand with ForkedCall
1064 // (if the output is not needed) or the code in ispell.C
1065 // (if the output is needed).
1067 // One question is if we should use popen or
1068 // create our own popen based on fork, exec, pipe
1069 // of course the best would be to have a
1070 // pstream (process stream), with the
1071 // variants ipstream, opstream
1073 #if defined (HAVE_POPEN)
1074 FILE * inf = ::popen(cmd.c_str(), os::popen_read_mode());
1075 #elif defined (HAVE__POPEN)
1076 FILE * inf = ::_popen(cmd.c_str(), os::popen_read_mode());
1078 #error No popen() function.
1081 // (Claus Hentschel) Check if popen was succesful ;-)
1083 return make_pair(-1, string());
1084 lyxerr << "RunCommand:: could not start child process" << endl;
1090 ret += static_cast<char>(c);
1094 #if defined (HAVE_PCLOSE)
1095 int const pret = pclose(inf);
1096 #elif defined (HAVE__PCLOSE)
1097 int const pret = _pclose(inf);
1099 #error No pclose() function.
1103 perror("RunCommand:: could not terminate child process");
1105 return make_pair(pret, ret);
1109 string const findtexfile(string const & fil, string const & /*format*/)
1111 /* There is no problem to extend this function too use other
1112 methods to look for files. It could be setup to look
1113 in environment paths and also if wanted as a last resort
1114 to a recursive find. One of the easier extensions would
1115 perhaps be to use the LyX file lookup methods. But! I am
1116 going to implement this until I see some demand for it.
1120 // If the file can be found directly, we just return a
1121 // absolute path version of it.
1122 if (fs::exists(fil))
1123 return MakeAbsPath(fil);
1125 // No we try to find it using kpsewhich.
1126 // It seems from the kpsewhich manual page that it is safe to use
1127 // kpsewhich without --format: "When the --format option is not
1128 // given, the search path used when looking for a file is inferred
1129 // from the name given, by looking for a known extension. If no
1130 // known extension is found, the search path for TeX source files
1132 // However, we want to take advantage of the format sine almost all
1133 // the different formats has environment variables that can be used
1134 // to controll which paths to search. f.ex. bib looks in
1135 // BIBINPUTS and TEXBIB. Small list follows:
1136 // bib - BIBINPUTS, TEXBIB
1138 // graphic/figure - TEXPICTS, TEXINPUTS
1139 // ist - TEXINDEXSTYLE, INDEXSTYLE
1140 // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
1142 // tfm - TFMFONTS, TEXFONTS
1143 // This means that to use kpsewhich in the best possible way we
1144 // should help it by setting additional path in the approp. envir.var.
1145 string const kpsecmd = "kpsewhich " + fil;
1147 cmd_ret const c = RunCommand(kpsecmd);
1149 lyxerr[Debug::LATEX] << "kpse status = " << c.first << '\n'
1150 << "kpse result = `" << rtrim(c.second, "\n")
1153 return os::internal_path(rtrim(c.second, "\n\r"));
1159 void removeAutosaveFile(string const & filename)
1161 string a = OnlyPath(filename);
1163 a += OnlyFilename(filename);
1170 void readBB_lyxerrMessage(string const & file, bool & zipped,
1171 string const & message)
1173 lyxerr[Debug::GRAPHICS] << "[readBB_from_PSFile] "
1174 << message << std::endl;
1175 #ifdef WITH_WARNINGS
1176 #warning Why is this func deleting a file? (Lgb)
1183 string const readBB_from_PSFile(string const & file)
1185 // in a (e)ps-file it's an entry like %%BoundingBox:23 45 321 345
1186 // It seems that every command in the header has an own line,
1187 // getline() should work for all files.
1188 // On the other hand some plot programs write the bb at the
1189 // end of the file. Than we have in the header:
1190 // %%BoundingBox: (atend)
1191 // In this case we must check the end.
1192 bool zipped = zippedFile(file);
1193 string const file_ = zipped ?
1194 string(unzipFile(file)) : string(file);
1195 string const format = getFormatFromContents(file_);
1197 if (format != "eps" && format != "ps") {
1198 readBB_lyxerrMessage(file_, zipped,"no(e)ps-format");
1202 std::ifstream is(file_.c_str());
1206 if (contains(s,"%%BoundingBox:") && !contains(s,"atend")) {
1207 string const bb = ltrim(s.substr(14));
1208 readBB_lyxerrMessage(file_, zipped, bb);
1212 readBB_lyxerrMessage(file_, zipped, "no bb found");
1217 int compare_timestamps(string const & file1, string const & file2)
1219 BOOST_ASSERT(AbsolutePath(file1) && AbsolutePath(file2));
1221 // If the original is newer than the copy, then copy the original
1222 // to the new directory.
1225 if (fs::exists(file1) && fs::exists(file2)) {
1226 double const tmp = difftime(fs::last_write_time(file1),
1227 fs::last_write_time(file2));
1229 cmp = tmp > 0 ? 1 : -1;
1231 } else if (fs::exists(file1)) {
1233 } else if (fs::exists(file2)) {
1240 } //namespace support