]> git.lyx.org Git - lyx.git/blob - src/support/filetools.h
More requires --> required, for C++2a.
[lyx.git] / src / support / filetools.h
1 // -*- C++ -*-
2 /**
3  * \file filetools.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef LYX_FILETOOL_H
13 #define LYX_FILETOOL_H
14
15 #include "support/docstring.h"
16
17 #include <utility>
18 #include <string>
19 #include <set>
20
21 namespace lyx {
22 namespace support {
23
24 class FileName;
25
26 /// Record used temp file names
27 static std::set<std::string> tmp_names_;
28
29 /// Get a temporary file name.
30 /**
31 * The actual temp file (QTemporaryFile object) is immediately
32 * destroyed after the name has been generated, so a new file
33 * has to be created manually from the name.
34 * This is needed if the temp file has to be manually removed
35 * (e.g., when temp files are used as conversion target, and the initial
36 * file only serves as a placeholder), since QTemporaryFile objects
37 * cannot be manually removed at least on Windows (they are always
38 * kept open internally even after close()).
39 * In order to avoid race conditions due to duplicate names, we record
40 * all used temp file names.
41 * If you don't have to remove the temp file manually, use TempFile instead!
42 */
43 FileName const tempFileName(FileName, bool const dir = false);
44 /// Get temporary file name with custom path
45 FileName const tempFileName(FileName, std::string const &, bool const dir = false);
46 /// Get temporary file name with default path
47 FileName const tempFileName(std::string const &, bool const dir = false);
48
49 /// Remove and unregister a temporary file.
50 void removeTempFile(FileName const &);
51
52 /** Creates the global LyX temp dir.
53   \p deflt can be an existing directory name. In this case a new directory
54   inside \p deflt is created. If \p deflt does not exist yet, \p deflt is
55   created and used as the temporary directory.
56   \return the tmp dir name or string() if something went wrong.
57  */
58 FileName const createLyXTmpDir(FileName const & deflt);
59
60 #if 0
61 // FIXME unused. Should this be deleted or resurrected?
62 /** Find file by searching several directories.
63   Uses a string of paths separated by ";"s to find a file to open.
64     Can't cope with pathnames with a ';' in them. Returns full path to file.
65     If path entry begins with $$LyX/, use system_lyxdir.
66     If path entry begins with $$User/, use user_lyxdir.
67     Example: "$$User/doc;$$LyX/doc".
68 */
69 FileName const fileOpenSearch(std::string const & path,
70                                  std::string const & name,
71                                  std::string const & ext = std::string());
72 #endif
73
74 /// How to search files
75 enum search_mode {
76         /// The file must exist (return an empty file name otherwise)
77         must_exist,
78         /// Only do file name expansion, return the complete name even if
79         /// the file does not exist
80         may_not_exist,
81         /// The (image) file may be present with hi-dpi resolution -
82         /// the lookup checks for a file named "image" + "@2x" + ".ext" first.
83         /// If found it will return e.g. "image@2x.png" instead of "image.png".
84         /// Otherwise it will work as must_exist.
85         check_hidpi
86 };
87
88 /** Returns the real name of file name in directory path, with optional
89   extension ext.
90   The file is searched in the given path (unless it is an absolute
91   file name), first directly, and then with extension .ext (if given).
92   */
93 FileName const fileSearch(std::string const & path,
94                              std::string const & name,
95                              std::string const & ext = std::string(),
96                              search_mode mode = must_exist);
97
98 ///
99 bool isLyXFileName(std::string const & filename);
100
101 ///
102 bool isSGMLFileName(std::string const & filename);
103
104 /// check for characters in filenames not allowed by LaTeX
105 bool isValidLaTeXFileName(std::string const & filename);
106
107 /** check for characters in filenames that might lead to
108   problems when manually compiling the LaTeX export of LyX
109   and opening the result with some older DVI-viewers
110 */
111 bool isValidDVIFileName(std::string const & filename);
112
113 /// check whether the file has binary contents
114 bool isBinaryFile(FileName const & filename);
115
116 /** Returns the path of a library data file.
117     Search the file name.ext in the subdirectory dir of
118       -# user_lyxdir
119       -# build_lyxdir (if not empty)
120       -# system_lyxdir
121     The third parameter `ext' is optional.
122 */
123 FileName const libFileSearch(std::string const & dir,
124                                 std::string const & name,
125                                 std::string const & ext = std::string(),
126                                 search_mode mode = must_exist);
127
128 /** Same as libFileSearch(), but tries first to find an
129   internationalized version of the file by prepending $LANG_ to the
130   name
131   */
132 FileName const
133 i18nLibFileSearch(std::string const & dir,
134                   std::string const & name,
135                   std::string const & ext = std::string());
136
137 /** Same as libFileSearch(), but tries first to find a preferred
138   version of the file by appending the icon set name to the dir
139   */
140 FileName const
141 imageLibFileSearch(std::string & dir, std::string const & name,
142                    std::string const & ext = std::string(),
143                    search_mode mode = must_exist);
144
145 /// How to quote a filename
146 enum quote_style {
147         /** Quote for the (OS dependant) shell. This is needed for command
148             line arguments of subprocesses. */
149         quote_shell,
150         /** Quote a file name for the (OS dependant) shell. This is needed
151             for file names as command line arguments of subprocesses. */
152         quote_shell_filename,
153         /** Quote for python. Use this if you want to store a filename in a
154             python script. Example: \code
155             os << "infile = " << quoteName(filename) << '\\n';
156             \endcode This uses double quotes, so that you can also use this
157             to quote filenames as part of a string if the string is quoted
158             with single quotes. */
159         quote_python
160 };
161
162 /** Takes a command such as "python $$s/scripts/convertDefault.py file.in file.out"
163  *  and replaces "$$s/" with the path to the LyX support directory containing
164  *  this script. If the script is not found, "$$s/" is removed. Executing the
165  *  command will still fail, but the error message will make some sort of
166  *  sense ;-)
167  */
168 std::string const commandPrep(std::string const & command);
169
170 enum latex_path_extension {
171         PROTECT_EXTENSION,
172         EXCLUDE_EXTENSION
173 };
174
175 enum latex_path_dots {
176         LEAVE_DOTS,
177         ESCAPE_DOTS
178 };
179
180 /** @param path a file path in internal_path format. Ie, directories
181  *  are indicated by '/', not by '\'.
182  *
183  *  Manipulates @c path into a form suitable for inclusion in a LaTeX
184  *  document.
185  *  If @c path contains LaTeX special characters, these are escaped.
186  *  Eg, '~' -> '\\string~'
187  *  If @c path contains spaces, then the returned path is enclosed in
188  *  "-quotes. This last fix will lead to successful compiliation of the
189  *  LaTeX file only if a sufficiently modern LaTeX compiler is used.
190  *  If @c ext == EXCLUDE_EXTENSION the extension is left outside the quotes.
191  *  This is needed for pdfeTeX, Version 3.141592-1.21a-2.2 (Web2C 7.5.4)
192  *  (format=pdflatex 2005.4.11) in combination with
193  *  pdftex.def 2002/06/19 v0.03k graphics/color for pdftex:
194  *  It does not recognize the file extension if it is inside the quotes.
195  *  If @c dots == ESCAPE_DOTS dots in the filename are replaced by
196  *  "\\lyxdot ". This is needed for the \\includegraphics command if the
197  *  automatic format selection is used.
198  */
199 std::string const latex_path(std::string const & path,
200                 latex_path_extension extension = PROTECT_EXTENSION,
201                 latex_path_dots dots = LEAVE_DOTS);
202
203 /// Substitutes active latex characters with underscores in filename
204 FileName const makeLatexName(FileName const & file);
205
206 /** Put the name in quotes suitable for the current shell or python,
207     depending on \p style. */
208 std::string const quoteName(std::string const & file, quote_style style = quote_shell);
209
210 /// Add a filename to a path. Any path from filename is stripped first.
211 std::string const addName(std::string const & path, std::string const & fname);
212
213 /// Append sub-directory(ies) to path in an intelligent way
214 std::string const addPath(std::string const & path, std::string const & path2);
215
216 /** Change extension of oldname to extension.
217  If oldname does not have an extension, it is appended.
218  If the extension is empty, any extension is removed from the name.
219  */
220 std::string const
221 changeExtension(std::string const & oldname, std::string const & extension);
222
223 /// Remove the extension from \p name
224 std::string const removeExtension(std::string const & name);
225
226 /** Add the extension \p ext to \p name.
227  Use this instead of changeExtension if you know that \p name is without
228  extension, because changeExtension would wrongly interpret \p name if it
229  contains a dot.
230  */
231 std::string const
232 addExtension(std::string const & name, std::string const & extension);
233
234 /// Return the extension of the file (not including the .)
235 std::string const getExtension(std::string const & name);
236
237 /** \return the name that LyX will give to the unzipped file \p zipped_file
238   if the second argument of unzipFile() is empty.
239  */
240 std::string const unzippedFileName(std::string const & zipped_file);
241
242 /** Unzip \p zipped_file.
243   The unzipped file is named \p unzipped_file if \p unzipped_file is not
244   empty, and unzippedFileName(\p zipped_file) otherwise.
245   Will overwrite an already existing unzipped file without warning.
246  */
247 FileName const unzipFile(FileName const & zipped_file,
248                          std::string const & unzipped_file = std::string());
249
250 /** Convert relative path into absolute path based on a basepath.
251   If relpath is absolute, just use that.
252   If basepath doesn't exist use CWD.
253   */
254 FileName const makeAbsPath(std::string const & RelPath = std::string(),
255                               std::string const & BasePath = std::string());
256
257 /** Creates a nice compact path for displaying. The parameter
258   threshold, if given, specifies the maximal length of the path.
259   */
260 docstring const
261 makeDisplayPath(std::string const & path, unsigned int threshold = 1000);
262
263 /** Makes relative path out of absolute path.
264   If it is deeper than basepath,
265   it's easy. If basepath and abspath share something (they are all deeper
266   than some directory), it'll be rendered using ..'s. If they are completely
267   different, then the absolute path will be used as relative path
268   WARNING: the absolute path and base path must really be absolute paths!!!
269   */
270 docstring const
271 makeRelPath(docstring const & abspath, docstring const & basepath);
272
273 /// Strip filename from path name
274 std::string const onlyPath(std::string const & fname);
275
276 /// Strips path from filename
277 std::string const onlyFileName(std::string const & fname);
278
279 /** Check and Replace Environmentvariables ${NAME} in Path.
280     Replaces all occurrences of these, if they are found in the
281     environment.
282     Variables are defined by Var := '${' [a-zA-Z_][a-zA-Z_0-9]* '}'
283 */
284 std::string const replaceEnvironmentPath(std::string const & path);
285
286 /**
287    Return a string to be used as a prefix to a command for setting the
288    environment of the TeX engine with respect to the paths \p path and \p lpath.
289  */
290 std::string latexEnvCmdPrefix(std::string const &path, std::string const & lpath);
291
292 /** Replace all references to a current directory (a lonely '.' or
293     the prefix "./") in \c pathlist with \c path. Also prefixes
294     all non-absolute paths with \c path.
295 */
296 std::string const replaceCurdirPath(std::string const & path, std::string const & pathlist);
297
298 /** Set \c link to the path \c file points to as a symbolic link.
299     \return true if successful.
300  */
301 bool readLink(FileName const & file, FileName & link);
302
303 /**
304  * Search a TeX file in all locations the latex compiler would search it,
305  * with the help of kpsewhich.
306  * The current working directory must be set correctly, so that relative
307  * names work.
308  * \param fil The filename to search
309  * \param format The file format as used by kpsewhich, e.g. "bib", "bst" etc.
310  */
311 FileName const findtexfile(std::string const & fil,
312                                                    std::string const & format,
313                                                    bool const onlykpse = false);
314
315 /** \param file1, file2 the two files to be compared. Must have absolute paths.
316  *  \returns 1 if \c file1 has a more recent timestamp than \c file2,
317  *           0 if their timestamps are the same,
318  *          -1 if \c file2 has a more recent timestamp than \c file1.
319  *  If one of the files does not exist, the return value indicates the file
320  *  which does exist. Eg, if \c file1 exists but \c file2 does not, return 1.
321  */
322 int compare_timestamps(FileName const & file1, FileName const & file2);
323
324 /// \param lfuns: true if we're converting lfuns, false if prefs
325 bool prefs2prefs(FileName const & filename, FileName const & tempfile,
326                  bool lfuns);
327
328 /// Does file \p file need to be updated by configure.py?
329 bool configFileNeedsUpdate(std::string const & file);
330
331 typedef std::pair<int, std::string> cmd_ret;
332
333 cmd_ret const runCommand(std::string const & cmd);
334
335 int fileLock(const char * lock_file);
336 void fileUnlock(int fd, const char * lock_file);
337
338 } // namespace support
339 } // namespace lyx
340
341
342
343 #endif