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/filetools.h"
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"
39 #include "support/lassert.h"
40 #include <boost/regex.hpp>
57 bool isLyXFilename(string const & filename)
59 return suffixIs(ascii_lowercase(filename), ".lyx");
63 bool isSGMLFilename(string const & filename)
65 return suffixIs(ascii_lowercase(filename), ".sgml");
69 bool isValidLaTeXFilename(string const & filename)
71 string const invalid_chars("#$%{}()[]\"^");
72 return filename.find_first_of(invalid_chars) == string::npos;
76 string const latex_path(string const & original_path,
77 latex_path_extension extension,
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() ?
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;
97 path = "\\string\"" + path + "\\string\"";
101 return dots == ESCAPE_DOTS ? subst(path, ".", "\\lyxdot ") : path;
105 // Substitutes spaces with underscores in filename (and path)
106 FileName const makeLatexName(FileName const & file)
108 string name = file.onlyFileName();
109 string const path = file.onlyPath().absFilename() + "/";
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:;<=>?[]`|";
118 string::size_type pos = 0;
119 while ((pos = name.find_first_not_of(keep, pos)) != string::npos)
122 FileName latex_name(path + name);
123 latex_name.changeExtension(".tex");
128 string const quoteName(string const & name, quote_style style)
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
139 return (os::shell() == os::UNIX) ?
143 return "\"" + subst(subst(name, "\\", "\\\\"), "\"", "\\\"")
146 // shut up stupid compiler
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,
162 bool notfound = true;
163 string tmppath = split(path, path_element, ';');
165 while (notfound && !path_element.empty()) {
166 path_element = os::internal_path(path_element);
167 if (!suffixIs(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());
174 real_file = fileSearch(path_element, name, ext);
176 if (real_file.empty()) {
178 tmppath = split(tmppath, path_element, ';');
179 } while (!tmppath.empty() && path_element.empty());
189 // Returns the real name of file name in directory path, with optional
191 FileName const fileSearch(string const & path, string const & name,
192 string const & ext, search_mode mode)
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())
203 return mode == may_not_exist ? fullname : FileName();
204 // Only add the extension if it is not already the extension of
206 if (getExtension(fullname.absFilename()) != ext)
207 fullname = FileName(addExtension(fullname.absFilename(), ext));
208 if (fullname.isReadableFile() || mode == may_not_exist)
214 // Search the file name.ext in the subdirectory dir of
216 // 2) build_lyxdir (if not empty)
218 FileName const libFileSearch(string const & dir, string const & name,
221 FileName fullname = fileSearch(addPath(package().user_support().absFilename(), dir),
223 if (!fullname.empty())
226 if (!package().build_support().empty())
227 fullname = fileSearch(addPath(package().build_support().absFilename(), dir),
229 if (!fullname.empty())
232 return fileSearch(addPath(package().system_support().absFilename(), dir), name, ext);
236 FileName const i18nLibFileSearch(string const & dir, string const & name,
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.
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)
247 string lang = to_ascii(_("[[Replace with the code of your language]]"));
248 string const language = getEnv("LANGUAGE");
249 if (!lang.empty() && !language.empty())
253 lang = split(lang, l, ':');
256 // First try with the full name
257 tmp = libFileSearch(addPath(dir, l), name, ext);
261 // Then the name without country code
262 string const shortl = token(l, '_', 0);
264 tmp = libFileSearch(addPath(dir, shortl), name, ext);
270 // For compatibility, to be removed later (JMarc)
271 tmp = libFileSearch(dir, token(l, '_', 0) + '_' + name,
274 lyxerr << "i18nLibFileSearch: File `" << tmp
275 << "' has been found by the old method" <<endl;
279 lang = split(lang, l, ':');
282 return libFileSearch(dir, name, ext);
286 string const libScriptSearch(string const & command_in, quote_style style)
288 static string const token_scriptpath = "$$s/";
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)
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;
302 // Does this script file exist?
303 string const script =
304 libFileSearch(".", command.substr(start_script, size_script)).absFilename();
306 if (script.empty()) {
307 // Replace "$$s/" with ""
308 command.erase(pos1, 4);
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));
319 static FileName createTmpDir(FileName const & tempdir, string const & mask)
321 LYXERR(Debug::FILES, "createTmpDir: tempdir=`" << tempdir << "'\n"
322 << "createTmpDir: mask=`" << mask << '\'');
324 string const tmp_dir = tempdir.absFilename() + "/" + mask;
325 FileName const tmpfl = FileName::tempName(tmp_dir);
327 if (tmpfl.empty() || !tmpfl.createDirectory(0700)) {
328 LYXERR0("LyX could not create the temporary directory '" << tmp_dir
337 FileName const createLyXTmpDir(FileName const & deflt)
339 if (deflt.empty() || deflt == package().system_temp_dir())
340 return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
342 if (deflt.createDirectory(0777))
345 if (deflt.isDirWritable()) {
346 // deflt could not be created because it
347 // did exist already, so let's create our own
349 return createTmpDir(deflt, "lyx_tmpdir");
351 // some other error occured.
352 return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
357 // Strip filename from path name
358 string const onlyPath(string const & filename)
360 // If empty filename, return empty
361 if (filename.empty())
364 // Find last / or start of filename
365 size_t j = filename.rfind('/');
366 return j == string::npos ? "./" : filename.substr(0, j + 1);
370 // Convert relative path into absolute path based on a basepath.
371 // If relpath is absolute, just use that.
372 // If basepath is empty, use CWD as base.
373 // Note that basePath can be a relative path, in the sense that it may
374 // not begin with "/" (e.g.), but it should NOT contain such constructs
376 // FIXME It might be nice if the code didn't simply assume that.
377 FileName const makeAbsPath(string const & relPath, string const & basePath)
379 FileName relative_path(relPath);
380 // checks for already absolute path
381 if (relative_path.isAbsolute())
382 return relative_path;
384 // Copies given paths
385 string tempRel = os::internal_path(relPath);
386 // Since TempRel is NOT absolute, we can safely replace "//" with "/"
387 tempRel = subst(tempRel, "//", "/");
391 FileName base_path(basePath);
392 if (base_path.isAbsolute())
395 tempBase = addPath(FileName::getcwd().absFilename(), basePath);
397 // Handle /./ at the end of the path
398 while (suffixIs(tempBase, "/./"))
399 tempBase.erase(tempBase.length() - 2);
401 // processes relative path
402 string rTemp = tempRel;
405 // Check for a leading "~"
407 rTemp = split(rTemp, temp, '/');
409 tempBase = package().home_dir().absFilename();
414 while (!rTemp.empty()) {
416 rTemp = split(rTemp, temp, '/');
418 if (temp == ".") continue;
420 // Remove one level of TempBase
421 if (tempBase.length() <= 1) {
422 //this is supposed to be an absolute path, so...
426 //erase a trailing slash if there is one
427 if (suffixIs(tempBase, "/"))
428 tempBase.erase(tempBase.length() - 1, string::npos);
430 string::size_type i = tempBase.length() - 1;
431 while (i > 0 && tempBase[i] != '/')
434 tempBase.erase(i, string::npos);
437 } else if (temp.empty() && !rTemp.empty()) {
438 tempBase = os::current_root() + rTemp;
441 // Add this piece to TempBase
442 if (!suffixIs(tempBase, '/'))
448 // returns absolute path
449 return FileName(tempBase);
453 // Correctly append filename to the pathname.
454 // If pathname is '.', then don't use pathname.
455 // Chops any path of filename.
456 string const addName(string const & path, string const & fname)
458 string const basename = onlyFilename(fname);
461 if (path != "." && path != "./" && !path.empty()) {
462 buf = os::internal_path(path);
463 if (!suffixIs(path, '/'))
467 return buf + basename;
471 // Strips path from filename
472 string const onlyFilename(string const & fname)
477 string::size_type j = fname.rfind('/');
478 if (j == string::npos) // no '/' in fname
482 return fname.substr(j + 1);
486 // Create absolute path. If impossible, don't do anything
487 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
488 string const expandPath(string const & path)
490 // checks for already absolute path
491 string rTemp = replaceEnvironmentPath(path);
492 FileName abs_path(rTemp);
493 if (abs_path.isAbsolute())
497 string const copy = rTemp;
500 rTemp = split(rTemp, temp, '/');
503 return FileName::getcwd().absFilename() + '/' + rTemp;
506 return package().home_dir().absFilename() + '/' + rTemp;
509 return makeAbsPath(copy).absFilename();
511 // Don't know how to handle this
516 // Search the string for ${VAR} and $VAR and replace VAR using getenv.
517 string const replaceEnvironmentPath(string const & path)
519 // ${VAR} is defined as
520 // $\{[A-Za-z_][A-Za-z_0-9]*\}
521 static string const envvar_br = "[$]\\{([A-Za-z_][A-Za-z_0-9]*)\\}";
523 // $VAR is defined as:
524 // $\{[A-Za-z_][A-Za-z_0-9]*\}
525 static string const envvar = "[$]([A-Za-z_][A-Za-z_0-9]*)";
527 static boost::regex envvar_br_re("(.*)" + envvar_br + "(.*)");
528 static boost::regex envvar_re("(.*)" + envvar + "(.*)");
531 string result = path;
533 regex_match(result, what, envvar_br_re);
534 if (!what[0].matched) {
535 regex_match(result, what, envvar_re);
536 if (!what[0].matched)
539 result = what.str(1) + getEnv(what.str(2)) + what.str(3);
545 // Make relative path out of two absolute paths
546 docstring const makeRelPath(docstring const & abspath, docstring const & basepath)
547 // Makes relative path out of absolute path. If it is deeper than basepath,
548 // it's easy. If basepath and abspath share something (they are all deeper
549 // than some directory), it'll be rendered using ..'s. If they are completely
550 // different, then the absolute path will be used as relative path.
552 docstring::size_type const abslen = abspath.length();
553 docstring::size_type const baselen = basepath.length();
555 docstring::size_type i = os::common_path(abspath, basepath);
558 // actually no match - cannot make it relative
562 // Count how many dirs there are in basepath above match
563 // and append as many '..''s into relpath
565 docstring::size_type j = i;
566 while (j < baselen) {
567 if (basepath[j] == '/') {
568 if (j + 1 == baselen)
575 // Append relative stuff from common directory to abspath
576 if (abspath[i] == '/')
578 for (; i < abslen; ++i)
581 if (suffixIs(buf, '/'))
582 buf.erase(buf.length() - 1);
583 // Substitute empty with .
590 // Append sub-directory(ies) to a path in an intelligent way
591 string const addPath(string const & path, string const & path_2)
594 string const path2 = os::internal_path(path_2);
596 if (!path.empty() && path != "." && path != "./") {
597 buf = os::internal_path(path);
598 if (path[path.length() - 1] != '/')
602 if (!path2.empty()) {
603 string::size_type const p2start = path2.find_first_not_of('/');
604 string::size_type const p2end = path2.find_last_not_of('/');
605 string const tmp = path2.substr(p2start, p2end - p2start + 1);
612 string const changeExtension(string const & oldname, string const & extension)
614 string::size_type const last_slash = oldname.rfind('/');
615 string::size_type last_dot = oldname.rfind('.');
616 if (last_dot < last_slash && last_slash != string::npos)
617 last_dot = string::npos;
620 // Make sure the extension starts with a dot
621 if (!extension.empty() && extension[0] != '.')
622 ext= '.' + extension;
626 return os::internal_path(oldname.substr(0, last_dot) + ext);
630 string const removeExtension(string const & name)
632 return changeExtension(name, string());
636 string const addExtension(string const & name, string const & extension)
638 if (!extension.empty() && extension[0] != '.')
639 return name + '.' + extension;
640 return name + extension;
644 /// Return the extension of the file (not including the .)
645 string const getExtension(string const & name)
647 string::size_type const last_slash = name.rfind('/');
648 string::size_type const last_dot = name.rfind('.');
649 if (last_dot != string::npos &&
650 (last_slash == string::npos || last_dot > last_slash))
651 return name.substr(last_dot + 1,
652 name.length() - (last_dot + 1));
658 string const unzippedFileName(string const & zipped_file)
660 string const ext = getExtension(zipped_file);
661 if (ext == "gz" || ext == "z" || ext == "Z")
662 return changeExtension(zipped_file, string());
663 return onlyPath(zipped_file) + "unzipped_" + onlyFilename(zipped_file);
667 FileName const unzipFile(FileName const & zipped_file, string const & unzipped_file)
669 FileName const tempfile = FileName(unzipped_file.empty() ?
670 unzippedFileName(zipped_file.toFilesystemEncoding()) :
673 string const command = "gunzip -c " +
674 zipped_file.toFilesystemEncoding() + " > " +
675 tempfile.toFilesystemEncoding();
677 one.startscript(Systemcall::Wait, command);
678 // test that command was executed successfully (anon)
679 // yes, please do. (Lgb)
684 docstring const makeDisplayPath(string const & path, unsigned int threshold)
688 // If file is from LyXDir, display it as if it were relative.
689 string const system = package().system_support().absFilename();
690 if (prefixIs(str, system) && str != system)
691 return from_utf8("[" + str.erase(0, system.length()) + "]");
693 // replace /home/blah with ~/
694 string const home = package().home_dir().absFilename();
695 if (!home.empty() && prefixIs(str, home))
696 str = subst(str, home, "~");
698 if (str.length() <= threshold)
699 return from_utf8(os::external_path(str));
701 string const prefix = ".../";
704 while (str.length() > threshold)
705 str = split(str, temp, '/');
707 // Did we shorten everything away?
709 // Yes, filename itself is too long.
710 // Pick the start and the end of the filename.
711 str = onlyFilename(path);
712 string const head = str.substr(0, threshold / 2 - 3);
714 string::size_type len = str.length();
716 str.substr(len - threshold / 2 - 2, len - 1);
717 str = head + "..." + tail;
720 return from_utf8(os::external_path(prefix + str));
724 bool readLink(FileName const & file, FileName & link)
727 char linkbuffer[512];
728 // Should be PATH_MAX but that needs autconf support
729 string const encoded = file.toFilesystemEncoding();
730 int const nRead = ::readlink(encoded.c_str(),
731 linkbuffer, sizeof(linkbuffer) - 1);
734 linkbuffer[nRead] = '\0'; // terminator
735 link = makeAbsPath(linkbuffer, onlyPath(file.absFilename()));
743 cmd_ret const runCommand(string const & cmd)
745 // FIXME: replace all calls to RunCommand with ForkedCall
746 // (if the output is not needed) or the code in ISpell.cpp
747 // (if the output is needed).
749 // One question is if we should use popen or
750 // create our own popen based on fork, exec, pipe
751 // of course the best would be to have a
752 // pstream (process stream), with the
753 // variants ipstream, opstream
755 #if defined (HAVE_POPEN)
756 FILE * inf = ::popen(cmd.c_str(), os::popen_read_mode());
757 #elif defined (HAVE__POPEN)
758 FILE * inf = ::_popen(cmd.c_str(), os::popen_read_mode());
760 #error No popen() function.
763 // (Claus Hentschel) Check if popen was succesful ;-)
765 lyxerr << "RunCommand:: could not start child process" << endl;
766 return make_pair(-1, string());
772 ret += static_cast<char>(c);
776 #if defined (HAVE_PCLOSE)
777 int const pret = pclose(inf);
778 #elif defined (HAVE__PCLOSE)
779 int const pret = _pclose(inf);
781 #error No pclose() function.
785 perror("RunCommand:: could not terminate child process");
787 return make_pair(pret, ret);
791 FileName const findtexfile(string const & fil, string const & /*format*/)
793 /* There is no problem to extend this function too use other
794 methods to look for files. It could be setup to look
795 in environment paths and also if wanted as a last resort
796 to a recursive find. One of the easier extensions would
797 perhaps be to use the LyX file lookup methods. But! I am
798 going to implement this until I see some demand for it.
802 // If the file can be found directly, we just return a
803 // absolute path version of it.
804 FileName const absfile(makeAbsPath(fil));
805 if (absfile.exists())
808 // Now we try to find it using kpsewhich.
809 // It seems from the kpsewhich manual page that it is safe to use
810 // kpsewhich without --format: "When the --format option is not
811 // given, the search path used when looking for a file is inferred
812 // from the name given, by looking for a known extension. If no
813 // known extension is found, the search path for TeX source files
815 // However, we want to take advantage of the format sine almost all
816 // the different formats has environment variables that can be used
817 // to controll which paths to search. f.ex. bib looks in
818 // BIBINPUTS and TEXBIB. Small list follows:
819 // bib - BIBINPUTS, TEXBIB
821 // graphic/figure - TEXPICTS, TEXINPUTS
822 // ist - TEXINDEXSTYLE, INDEXSTYLE
823 // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
825 // tfm - TFMFONTS, TEXFONTS
826 // This means that to use kpsewhich in the best possible way we
827 // should help it by setting additional path in the approp. envir.var.
828 string const kpsecmd = "kpsewhich " + fil;
830 cmd_ret const c = runCommand(kpsecmd);
832 LYXERR(Debug::LATEX, "kpse status = " << c.first << '\n'
833 << "kpse result = `" << rtrim(c.second, "\n\r") << '\'');
835 return FileName(rtrim(to_utf8(from_filesystem8bit(c.second)), "\n\r"));
841 void removeAutosaveFile(string const & filename)
843 string a = onlyPath(filename);
845 a += onlyFilename(filename);
847 FileName const autosave(a);
848 if (autosave.exists())
849 autosave.removeFile();
853 void readBB_lyxerrMessage(FileName const & file, bool & zipped,
854 string const & message)
856 LYXERR(Debug::GRAPHICS, "[readBB_from_PSFile] " << message);
857 // FIXME: Why is this func deleting a file? (Lgb)
863 string const readBB_from_PSFile(FileName const & file)
865 // in a (e)ps-file it's an entry like %%BoundingBox:23 45 321 345
866 // It seems that every command in the header has an own line,
867 // getline() should work for all files.
868 // On the other hand some plot programs write the bb at the
869 // end of the file. Than we have in the header:
870 // %%BoundingBox: (atend)
871 // In this case we must check the end.
872 bool zipped = file.isZippedFile();
873 FileName const file_ = zipped ? unzipFile(file) : file;
874 string const format = file_.guessFormatFromContents();
876 if (format != "eps" && format != "ps") {
877 readBB_lyxerrMessage(file_, zipped,"no(e)ps-format");
881 static boost::regex bbox_re(
882 "^%%BoundingBox:\\s*([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)");
883 ifstream is(file_.toFilesystemEncoding().c_str());
888 if (regex_match(s, what, bbox_re)) {
889 // Our callers expect the tokens in the string
890 // separated by single spaces.
891 // FIXME: change return type from string to something
894 os << what.str(1) << ' ' << what.str(2) << ' '
895 << what.str(3) << ' ' << what.str(4);
896 string const bb = os.str();
897 readBB_lyxerrMessage(file_, zipped, bb);
901 readBB_lyxerrMessage(file_, zipped, "no bb found");
906 int compare_timestamps(FileName const & file1, FileName const & file2)
908 // If the original is newer than the copy, then copy the original
909 // to the new directory.
912 if (file1.exists() && file2.exists()) {
913 double const tmp = difftime(file1.lastModified(), file2.lastModified());
915 cmp = tmp > 0 ? 1 : -1;
917 } else if (file1.exists()) {
919 } else if (file2.exists()) {
927 } //namespace support