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"
47 using support::FileName;
48 using support::isValidLaTeXFilename;
52 Template const * getTemplatePtr(InsetExternalParams const & params)
54 TemplateManager const & etm = TemplateManager::get();
55 return etm.getTemplateByName(params.templatename());
59 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
61 formats.edit(buffer, params.filename,
62 formats.getFormatFromFile(params.filename));
68 string const subst_path(string const & input,
69 string const & placeholder,
72 support::latex_path_extension ext = support::PROTECT_EXTENSION,
73 support::latex_path_dots dots = support::LEAVE_DOTS)
75 if (input.find(placeholder) == string::npos)
77 // Don't use external_path here when use_latex_path is false, as the
78 // path will be compared with another one in internal style later
79 // in Converters::move.
80 string const path2 = use_latex_path ?
81 support::latex_path(path, ext, dots) : path;
82 return support::subst(input, placeholder, path2);
88 string const doSubstitution(InsetExternalParams const & params,
89 Buffer const & buffer, string const & s,
91 bool external_in_tmpdir,
94 Buffer const * m_buffer = buffer.getMasterBuffer();
95 string const parentpath = external_in_tmpdir ?
96 m_buffer->temppath() :
98 string const filename = external_in_tmpdir ?
99 params.filename.mangledFilename() :
100 params.filename.outputFilename(parentpath);
101 string const basename = support::changeExtension(
102 support::onlyFilename(filename), string());
103 string const absname = support::makeAbsPath(filename, parentpath).absFilename();
106 if (what != ALL_BUT_PATHS) {
107 string const filepath = support::onlyPath(filename);
108 string const abspath = support::onlyPath(absname);
109 string const masterpath = external_in_tmpdir ?
110 m_buffer->temppath() :
111 m_buffer->filePath();
113 string relToMasterPath = support::onlyPath(
114 to_utf8(support::makeRelPath(from_utf8(absname),
115 from_utf8(masterpath))));
116 if (relToMasterPath == "./")
117 relToMasterPath.clear();
119 string relToParentPath = support::onlyPath(
120 to_utf8(support::makeRelPath(from_utf8(absname),
121 from_utf8(parentpath))));
122 if (relToParentPath == "./")
123 relToParentPath.clear();
125 result = subst_path(result, "$$FPath", filepath,
127 support::PROTECT_EXTENSION,
128 support::ESCAPE_DOTS);
129 result = subst_path(result, "$$AbsPath", abspath,
131 support::PROTECT_EXTENSION,
132 support::ESCAPE_DOTS);
133 result = subst_path(result, "$$RelPathMaster",
134 relToMasterPath, use_latex_path,
135 support::PROTECT_EXTENSION,
136 support::ESCAPE_DOTS);
137 result = subst_path(result, "$$RelPathParent",
138 relToParentPath, use_latex_path,
139 support::PROTECT_EXTENSION,
140 support::ESCAPE_DOTS);
141 if (support::absolutePath(filename)) {
142 result = subst_path(result, "$$AbsOrRelPathMaster",
143 abspath, use_latex_path,
144 support::PROTECT_EXTENSION,
145 support::ESCAPE_DOTS);
146 result = subst_path(result, "$$AbsOrRelPathParent",
147 abspath, use_latex_path,
148 support::PROTECT_EXTENSION,
149 support::ESCAPE_DOTS);
151 result = subst_path(result, "$$AbsOrRelPathMaster",
152 relToMasterPath, use_latex_path,
153 support::PROTECT_EXTENSION,
154 support::ESCAPE_DOTS);
155 result = subst_path(result, "$$AbsOrRelPathParent",
156 relToParentPath, use_latex_path,
157 support::PROTECT_EXTENSION,
158 support::ESCAPE_DOTS);
165 result = subst_path(result, "$$FName", filename, use_latex_path,
166 support::EXCLUDE_EXTENSION);
167 result = subst_path(result, "$$Basename", basename, use_latex_path,
168 support::PROTECT_EXTENSION, support::ESCAPE_DOTS);
169 result = subst_path(result, "$$Extension",
170 '.' + support::getExtension(filename), use_latex_path);
171 result = subst_path(result, "$$Tempname", params.tempname().absFilename(), use_latex_path);
172 result = subst_path(result, "$$Sysdir",
173 support::package().system_support().absFilename(), use_latex_path);
175 // Handle the $$Contents(filename) syntax
176 if (support::contains(result, "$$Contents(\"")) {
177 // Since use_latex_path may be true we must extract the file
178 // name from s instead of result and do the substitutions
179 // again, this time with use_latex_path false.
180 string::size_type const spos = s.find("$$Contents(\"");
181 string::size_type const send = s.find("\")", spos);
182 string const file_template = s.substr(spos + 12, send - (spos + 12));
183 string const file = doSubstitution(params, buffer,
184 file_template, false,
185 external_in_tmpdir, what);
188 FileName const absfile(
189 support::makeAbsPath(file, m_buffer->temppath()));
190 if (absfile.isFileReadable())
191 contents = support::getFileContents(absfile);
193 string::size_type const pos = result.find("$$Contents(\"");
194 string::size_type const end = result.find("\")", pos);
195 result.replace(pos, end + 2, contents);
204 /** update the file represented by the template.
205 If \p external_in_tmpdir == true, then the generated file is
206 placed in the buffer's temporary directory.
208 void updateExternal(InsetExternalParams const & params,
209 string const & format,
210 Buffer const & buffer,
211 ExportData & exportdata,
212 bool external_in_tmpdir,
215 Template const * const et_ptr = getTemplatePtr(params);
218 Template const & et = *et_ptr;
220 if (!et.automaticProduction)
221 return; // NOT_NEEDED
223 Template::Formats::const_iterator cit = et.formats.find(format);
224 if (cit == et.formats.end())
227 Template::Format const & outputFormat = cit->second;
228 if (outputFormat.updateResult.empty())
229 return; // NOT_NEEDED
231 string from_format = et.inputFormat;
232 if (from_format.empty())
233 return; // NOT_NEEDED
235 if (from_format == "*") {
236 if (params.filename.empty())
237 return; // NOT_NEEDED
239 // Try and ascertain the file format from its contents.
240 from_format = formats.getFormatFromFile(params.filename);
241 if (from_format.empty())
246 string const to_format = outputFormat.updateFormat;
247 if (to_format.empty())
248 return; // NOT_NEEDED
250 // The master buffer. This is useful when there are multiple levels
252 Buffer const * m_buffer = buffer.getMasterBuffer();
254 // We copy the source file to the temp dir and do the conversion
255 // there if necessary
256 FileName const temp_file(
257 support::makeAbsPath(params.filename.mangledFilename(),
258 m_buffer->temppath()));
259 if (!params.filename.empty() && !params.filename.isDirectory()) {
260 unsigned long const from_checksum = support::sum(params.filename);
261 unsigned long const temp_checksum = support::sum(temp_file);
263 if (from_checksum != temp_checksum) {
264 Mover const & mover = getMover(from_format);
265 if (!mover.copy(params.filename, temp_file)) {
266 LYXERR(Debug::EXTERNAL)
267 << "external::updateExternal. "
269 << params.filename << " to " << temp_file << endl;
275 // the generated file (always in the temp dir)
276 string const to_file = doSubstitution(params, buffer,
277 outputFormat.updateResult,
279 FileName const abs_to_file(
280 support::makeAbsPath(to_file, m_buffer->temppath()));
283 // Record the referenced files for the exporter.
284 // The exporter will copy them to the export dir.
285 typedef Template::Format::FileMap FileMap;
286 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
287 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
288 for (; rit != rend; ++rit) {
289 vector<string>::const_iterator fit = rit->second.begin();
290 vector<string>::const_iterator fend = rit->second.end();
291 for (; fit != fend; ++fit) {
292 FileName const source(support::makeAbsPath(
293 doSubstitution(params, buffer, *fit,
295 m_buffer->temppath()));
296 // The path of the referenced file is never the
297 // temp path, but the filename may be the mangled
298 // or the real name. Therefore we substitute the
299 // paths and names separately.
300 string file = support::subst(*fit, "$$FName",
301 "$$FPath$$Basename$$Extension");
302 file = doSubstitution(params, buffer, file, false, false,
304 file = doSubstitution(params, buffer, file,
305 false, external_in_tmpdir,
307 // if file is a relative name, it is interpreted
308 // relative to the master document.
309 exportdata.addExternalFile(rit->first, source, file);
314 // Do we need to perform the conversion?
315 // Yes if to_file does not exist or if from_file is newer than to_file
316 if (support::compare_timestamps(temp_file, abs_to_file) < 0)
319 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
322 theConverters().convert(&buffer, temp_file, abs_to_file,
323 params.filename, from_format, to_format, el,
324 Converters::try_default | Converters::try_cache);
327 LYXERR(Debug::EXTERNAL)
328 << "external::updateExternal. "
329 << "Unable to convert from "
330 << from_format << " to " << to_format << endl;
337 string const substituteCommands(InsetExternalParams const & params,
338 string const & input, string const & format);
340 string const substituteOptions(InsetExternalParams const & params,
341 string const & input, string const & format);
346 int writeExternal(InsetExternalParams const & params,
347 string const & format,
348 Buffer const & buffer, odocstream & os,
349 ExportData & exportdata,
350 bool external_in_tmpdir,
353 Template const * const et_ptr = getTemplatePtr(params);
356 Template const & et = *et_ptr;
358 Template::Formats::const_iterator cit = et.formats.find(format);
359 if (cit == et.formats.end()) {
360 LYXERR(Debug::EXTERNAL)
361 << "External template format '" << format
362 << "' not specified in template "
363 << params.templatename() << endl;
367 if (!dryrun || support::contains(cit->second.product, "$$Contents"))
368 updateExternal(params, format, buffer, exportdata,
369 external_in_tmpdir, dryrun);
371 bool const use_latex_path = format == "LaTeX";
372 string str = doSubstitution(params, buffer, cit->second.product,
373 use_latex_path, external_in_tmpdir);
375 string const absname = support::makeAbsPath(
376 params.filename.outputFilename(buffer.filePath()), buffer.filePath()).absFilename();
378 if (!external_in_tmpdir && !isValidLaTeXFilename(absname)) {
379 lyx::frontend::Alert::warning(_("Invalid filename"),
380 _("The following filename is likely to cause trouble "
381 "when running the exported file through LaTeX: ") +
385 str = substituteCommands(params, str, format);
386 str = substituteOptions(params, str, format);
388 os << from_utf8(str);
389 return int(std::count(str.begin(), str.end(),'\n'));
394 // Empty template, specialised below.
395 template <typename TransformType>
396 string const substituteIt(string const &,
399 Template::Format const &,
400 InsetExternalParams const &);
404 string const substituteIt<TransformCommand>(string const & input,
406 string const & /* formatname */,
407 Template::Format const & format,
408 InsetExternalParams const & params)
410 typedef std::map<TransformID, TransformStore> Transformers;
411 Transformers::const_iterator it = format.command_transformers.find(id);
412 if (it == format.command_transformers.end())
415 TransformStore const & store = it->second;
417 TransformCommand::ptr_type ptr;
419 ptr = store.getCommandTransformer(params.rotationdata);
420 else if (id == Resize)
421 ptr = store.getCommandTransformer(params.resizedata);
427 support::subst(input, ptr->front_placeholder(), ptr->front());
428 return support::subst(result, ptr->back_placeholder(), ptr->back());
433 string const substituteIt<TransformOption>(string const & input,
435 string const & fname,
436 Template::Format const & format,
437 InsetExternalParams const & params)
439 typedef std::map<TransformID, TransformStore> Transformers;
440 Transformers::const_iterator it = format.option_transformers.find(id);
441 if (it == format.option_transformers.end())
444 TransformStore const & store = it->second;
446 TransformOption::ptr_type ptr;
449 ptr = store.getOptionTransformer(params.clipdata);
452 ptr = store.getOptionTransformer(params.extradata.get(fname));
455 ptr = store.getOptionTransformer(params.rotationdata);
458 ptr = store.getOptionTransformer(params.resizedata);
465 return support::subst(input, ptr->placeholder(), ptr->option());
469 template <typename TransformerType>
470 string const transformIt(InsetExternalParams const & params,
471 string const & s, string const & formatname)
473 Template const * const et = getTemplatePtr(params);
474 if (!et || et->transformIds.empty())
477 Template::Formats::const_iterator fit = et->formats.find(formatname);
478 if (fit == et->formats.end())
482 Template::Format const & format = fit->second;
484 typedef vector<TransformID> TransformsIDs;
485 TransformsIDs::const_iterator it = et->transformIds.begin();
486 TransformsIDs::const_iterator end = et->transformIds.end();
487 for (; it != end; ++it) {
488 result = substituteIt<TransformerType>(result, *it, formatname,
495 string const substituteCommands(InsetExternalParams const & params,
496 string const & input, string const & format)
498 return transformIt<TransformCommand>(params, input, format);
502 string const substituteOption(InsetExternalParams const & params,
503 string const & input, string const & format)
505 string opt = transformIt<TransformOption>(params, input, format);
507 if (format == "LaTeX" || format == "PDFLaTeX")
508 return sanitizeLatexOption(opt);
509 if (format == "DocBook")
510 return sanitizeDocBookOption(opt);
515 string const substituteOptions(InsetExternalParams const & params,
516 string const & input, string const & format)
518 string output = input;
520 Template const * const et = getTemplatePtr(params);
521 if (!et || et->transformIds.empty())
524 Template::Formats::const_iterator fit = et->formats.find(format);
525 if (fit == et->formats.end() || fit->second.options.empty())
528 typedef vector<Template::Option> Options;
529 Options const & options = fit->second.options;
530 Options::const_iterator it = options.begin();
531 Options::const_iterator end = options.end();
532 for (; it != end; ++it) {
533 string const opt = substituteOption(params, it->option, format);
534 string const placeholder = "$$" + it->name;
535 output = support::subst(output, placeholder, opt);
543 } // namespace external