2 * \file ExternalSupport.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup Nielsen
7 * \author Angus Leeming
9 * Full author contact details are available in file CREDITS.
14 #include "ExternalSupport.h"
15 #include "ExternalTemplate.h"
16 #include "ExternalTransforms.h"
17 #include "InsetExternal.h"
20 #include "Converter.h"
23 #include "ErrorList.h"
28 #include "frontends/alert.h"
30 #include "support/filetools.h"
31 #include "support/Forkedcall.h"
32 #include "support/lstrings.h"
33 #include "support/lyxalgo.h"
34 #include "support/lyxlib.h"
35 #include "support/os.h"
36 #include "support/Package.h"
38 #include <boost/filesystem/operations.hpp>
46 using boost::filesystem::is_directory;
51 using support::FileName;
52 using support::isValidLaTeXFilename;
56 Template const * getTemplatePtr(InsetExternalParams const & params)
58 TemplateManager const & etm = TemplateManager::get();
59 return etm.getTemplateByName(params.templatename());
63 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
65 formats.edit(buffer, params.filename,
66 formats.getFormatFromFile(params.filename));
72 string const subst_path(string const & input,
73 string const & placeholder,
76 support::latex_path_extension ext = support::PROTECT_EXTENSION,
77 support::latex_path_dots dots = support::LEAVE_DOTS)
79 if (input.find(placeholder) == string::npos)
81 // Don't use external_path here when use_latex_path is false, as the
82 // path will be compared with another one in internal style later
83 // in Converters::move.
84 string const path2 = use_latex_path ?
85 support::latex_path(path, ext, dots) : path;
86 return support::subst(input, placeholder, path2);
92 string const doSubstitution(InsetExternalParams const & params,
93 Buffer const & buffer, string const & s,
95 bool external_in_tmpdir,
98 Buffer const * m_buffer = buffer.getMasterBuffer();
99 string const parentpath = external_in_tmpdir ?
100 m_buffer->temppath() :
102 string const filename = external_in_tmpdir ?
103 params.filename.mangledFilename() :
104 params.filename.outputFilename(parentpath);
105 string const basename = support::changeExtension(
106 support::onlyFilename(filename), string());
107 string const absname = support::makeAbsPath(filename, parentpath).absFilename();
110 if (what != ALL_BUT_PATHS) {
111 string const filepath = support::onlyPath(filename);
112 string const abspath = support::onlyPath(absname);
113 string const masterpath = external_in_tmpdir ?
114 m_buffer->temppath() :
115 m_buffer->filePath();
117 string relToMasterPath = support::onlyPath(
118 to_utf8(support::makeRelPath(from_utf8(absname),
119 from_utf8(masterpath))));
120 if (relToMasterPath == "./")
121 relToMasterPath.clear();
123 string relToParentPath = support::onlyPath(
124 to_utf8(support::makeRelPath(from_utf8(absname),
125 from_utf8(parentpath))));
126 if (relToParentPath == "./")
127 relToParentPath.clear();
129 result = subst_path(result, "$$FPath", filepath,
131 support::PROTECT_EXTENSION,
132 support::ESCAPE_DOTS);
133 result = subst_path(result, "$$AbsPath", abspath,
135 support::PROTECT_EXTENSION,
136 support::ESCAPE_DOTS);
137 result = subst_path(result, "$$RelPathMaster",
138 relToMasterPath, use_latex_path,
139 support::PROTECT_EXTENSION,
140 support::ESCAPE_DOTS);
141 result = subst_path(result, "$$RelPathParent",
142 relToParentPath, use_latex_path,
143 support::PROTECT_EXTENSION,
144 support::ESCAPE_DOTS);
145 if (support::absolutePath(filename)) {
146 result = subst_path(result, "$$AbsOrRelPathMaster",
147 abspath, use_latex_path,
148 support::PROTECT_EXTENSION,
149 support::ESCAPE_DOTS);
150 result = subst_path(result, "$$AbsOrRelPathParent",
151 abspath, use_latex_path,
152 support::PROTECT_EXTENSION,
153 support::ESCAPE_DOTS);
155 result = subst_path(result, "$$AbsOrRelPathMaster",
156 relToMasterPath, use_latex_path,
157 support::PROTECT_EXTENSION,
158 support::ESCAPE_DOTS);
159 result = subst_path(result, "$$AbsOrRelPathParent",
160 relToParentPath, use_latex_path,
161 support::PROTECT_EXTENSION,
162 support::ESCAPE_DOTS);
169 result = subst_path(result, "$$FName", filename, use_latex_path,
170 support::EXCLUDE_EXTENSION);
171 result = subst_path(result, "$$Basename", basename, use_latex_path,
172 support::PROTECT_EXTENSION, support::ESCAPE_DOTS);
173 result = subst_path(result, "$$Extension",
174 '.' + support::getExtension(filename), use_latex_path);
175 result = subst_path(result, "$$Tempname", params.tempname().absFilename(), use_latex_path);
176 result = subst_path(result, "$$Sysdir",
177 support::package().system_support().absFilename(), use_latex_path);
179 // Handle the $$Contents(filename) syntax
180 if (support::contains(result, "$$Contents(\"")) {
181 // Since use_latex_path may be true we must extract the file
182 // name from s instead of result and do the substitutions
183 // again, this time with use_latex_path false.
184 string::size_type const spos = s.find("$$Contents(\"");
185 string::size_type const send = s.find("\")", spos);
186 string const file_template = s.substr(spos + 12, send - (spos + 12));
187 string const file = doSubstitution(params, buffer,
188 file_template, false,
189 external_in_tmpdir, what);
192 FileName const absfile(
193 support::makeAbsPath(file, m_buffer->temppath()));
194 if (support::isFileReadable(absfile))
195 contents = support::getFileContents(absfile);
197 string::size_type const pos = result.find("$$Contents(\"");
198 string::size_type const end = result.find("\")", pos);
199 result.replace(pos, end + 2, contents);
208 /** update the file represented by the template.
209 If \p external_in_tmpdir == true, then the generated file is
210 placed in the buffer's temporary directory.
212 void updateExternal(InsetExternalParams const & params,
213 string const & format,
214 Buffer const & buffer,
215 ExportData & exportdata,
216 bool external_in_tmpdir,
219 Template const * const et_ptr = getTemplatePtr(params);
222 Template const & et = *et_ptr;
224 if (!et.automaticProduction)
225 return; // NOT_NEEDED
227 Template::Formats::const_iterator cit = et.formats.find(format);
228 if (cit == et.formats.end())
231 Template::Format const & outputFormat = cit->second;
232 if (outputFormat.updateResult.empty())
233 return; // NOT_NEEDED
235 string from_format = et.inputFormat;
236 if (from_format.empty())
237 return; // NOT_NEEDED
239 if (from_format == "*") {
240 if (params.filename.empty())
241 return; // NOT_NEEDED
243 // Try and ascertain the file format from its contents.
244 from_format = formats.getFormatFromFile(params.filename);
245 if (from_format.empty())
250 string const to_format = outputFormat.updateFormat;
251 if (to_format.empty())
252 return; // NOT_NEEDED
254 // The master buffer. This is useful when there are multiple levels
256 Buffer const * m_buffer = buffer.getMasterBuffer();
258 // We copy the source file to the temp dir and do the conversion
259 // there if necessary
260 FileName const temp_file(
261 support::makeAbsPath(params.filename.mangledFilename(),
262 m_buffer->temppath()));
263 if (!params.filename.empty() && !is_directory(params.filename.toFilesystemEncoding())) {
264 unsigned long const from_checksum = support::sum(params.filename);
265 unsigned long const temp_checksum = support::sum(temp_file);
267 if (from_checksum != temp_checksum) {
268 Mover const & mover = getMover(from_format);
269 if (!mover.copy(params.filename, temp_file)) {
270 LYXERR(Debug::EXTERNAL)
271 << "external::updateExternal. "
273 << params.filename << " to " << temp_file << endl;
279 // the generated file (always in the temp dir)
280 string const to_file = doSubstitution(params, buffer,
281 outputFormat.updateResult,
283 FileName const abs_to_file(
284 support::makeAbsPath(to_file, m_buffer->temppath()));
287 // Record the referenced files for the exporter.
288 // The exporter will copy them to the export dir.
289 typedef Template::Format::FileMap FileMap;
290 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
291 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
292 for (; rit != rend; ++rit) {
293 vector<string>::const_iterator fit = rit->second.begin();
294 vector<string>::const_iterator fend = rit->second.end();
295 for (; fit != fend; ++fit) {
296 FileName const source(support::makeAbsPath(
297 doSubstitution(params, buffer, *fit,
299 m_buffer->temppath()));
300 // The path of the referenced file is never the
301 // temp path, but the filename may be the mangled
302 // or the real name. Therefore we substitute the
303 // paths and names separately.
304 string file = support::subst(*fit, "$$FName",
305 "$$FPath$$Basename$$Extension");
306 file = doSubstitution(params, buffer, file, false, false,
308 file = doSubstitution(params, buffer, file,
309 false, external_in_tmpdir,
311 // if file is a relative name, it is interpreted
312 // relative to the master document.
313 exportdata.addExternalFile(rit->first, source, file);
318 // Do we need to perform the conversion?
319 // Yes if to_file does not exist or if from_file is newer than to_file
320 if (support::compare_timestamps(temp_file, abs_to_file) < 0)
323 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
326 theConverters().convert(&buffer, temp_file, abs_to_file,
327 params.filename, from_format, to_format, el,
328 Converters::try_default | Converters::try_cache);
331 LYXERR(Debug::EXTERNAL)
332 << "external::updateExternal. "
333 << "Unable to convert from "
334 << from_format << " to " << to_format << endl;
341 string const substituteCommands(InsetExternalParams const & params,
342 string const & input, string const & format);
344 string const substituteOptions(InsetExternalParams const & params,
345 string const & input, string const & format);
350 int writeExternal(InsetExternalParams const & params,
351 string const & format,
352 Buffer const & buffer, odocstream & os,
353 ExportData & exportdata,
354 bool external_in_tmpdir,
357 Template const * const et_ptr = getTemplatePtr(params);
360 Template const & et = *et_ptr;
362 Template::Formats::const_iterator cit = et.formats.find(format);
363 if (cit == et.formats.end()) {
364 LYXERR(Debug::EXTERNAL)
365 << "External template format '" << format
366 << "' not specified in template "
367 << params.templatename() << endl;
371 if (!dryrun || support::contains(cit->second.product, "$$Contents"))
372 updateExternal(params, format, buffer, exportdata,
373 external_in_tmpdir, dryrun);
375 bool const use_latex_path = format == "LaTeX";
376 string str = doSubstitution(params, buffer, cit->second.product,
377 use_latex_path, external_in_tmpdir);
379 string const absname = support::makeAbsPath(
380 params.filename.outputFilename(buffer.filePath()), buffer.filePath()).absFilename();
382 if (!external_in_tmpdir && !isValidLaTeXFilename(absname)) {
383 lyx::frontend::Alert::warning(_("Invalid filename"),
384 _("The following filename is likely to cause trouble "
385 "when running the exported file through LaTeX: ") +
389 str = substituteCommands(params, str, format);
390 str = substituteOptions(params, str, format);
392 os << from_utf8(str);
393 return int(std::count(str.begin(), str.end(),'\n'));
398 // Empty template, specialised below.
399 template <typename TransformType>
400 string const substituteIt(string const &,
403 Template::Format const &,
404 InsetExternalParams const &);
408 string const substituteIt<TransformCommand>(string const & input,
410 string const & /* formatname */,
411 Template::Format const & format,
412 InsetExternalParams const & params)
414 typedef std::map<TransformID, TransformStore> Transformers;
415 Transformers::const_iterator it = format.command_transformers.find(id);
416 if (it == format.command_transformers.end())
419 TransformStore const & store = it->second;
421 TransformCommand::ptr_type ptr;
423 ptr = store.getCommandTransformer(params.rotationdata);
424 else if (id == Resize)
425 ptr = store.getCommandTransformer(params.resizedata);
431 support::subst(input, ptr->front_placeholder(), ptr->front());
432 return support::subst(result, ptr->back_placeholder(), ptr->back());
437 string const substituteIt<TransformOption>(string const & input,
439 string const & fname,
440 Template::Format const & format,
441 InsetExternalParams const & params)
443 typedef std::map<TransformID, TransformStore> Transformers;
444 Transformers::const_iterator it = format.option_transformers.find(id);
445 if (it == format.option_transformers.end())
448 TransformStore const & store = it->second;
450 TransformOption::ptr_type ptr;
453 ptr = store.getOptionTransformer(params.clipdata);
456 ptr = store.getOptionTransformer(params.extradata.get(fname));
459 ptr = store.getOptionTransformer(params.rotationdata);
462 ptr = store.getOptionTransformer(params.resizedata);
469 return support::subst(input, ptr->placeholder(), ptr->option());
473 template <typename TransformerType>
474 string const transformIt(InsetExternalParams const & params,
475 string const & s, string const & formatname)
477 Template const * const et = getTemplatePtr(params);
478 if (!et || et->transformIds.empty())
481 Template::Formats::const_iterator fit = et->formats.find(formatname);
482 if (fit == et->formats.end())
486 Template::Format const & format = fit->second;
488 typedef vector<TransformID> TransformsIDs;
489 TransformsIDs::const_iterator it = et->transformIds.begin();
490 TransformsIDs::const_iterator end = et->transformIds.end();
491 for (; it != end; ++it) {
492 result = substituteIt<TransformerType>(result, *it, formatname,
499 string const substituteCommands(InsetExternalParams const & params,
500 string const & input, string const & format)
502 return transformIt<TransformCommand>(params, input, format);
506 string const substituteOption(InsetExternalParams const & params,
507 string const & input, string const & format)
509 string opt = transformIt<TransformOption>(params, input, format);
511 if (format == "LaTeX" || format == "PDFLaTeX")
512 return sanitizeLatexOption(opt);
513 if (format == "DocBook")
514 return sanitizeDocBookOption(opt);
519 string const substituteOptions(InsetExternalParams const & params,
520 string const & input, string const & format)
522 string output = input;
524 Template const * const et = getTemplatePtr(params);
525 if (!et || et->transformIds.empty())
528 Template::Formats::const_iterator fit = et->formats.find(format);
529 if (fit == et->formats.end() || fit->second.options.empty())
532 typedef vector<Template::Option> Options;
533 Options const & options = fit->second.options;
534 Options::const_iterator it = options.begin();
535 Options::const_iterator end = options.end();
536 for (; it != end; ++it) {
537 string const opt = substituteOption(params, it->option, format);
538 string const placeholder = "$$" + it->name;
539 output = support::subst(output, placeholder, opt);
547 } // namespace external