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