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 * masterBuffer = buffer.masterBuffer();
95 string const parentpath = external_in_tmpdir ?
96 masterBuffer->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 masterBuffer->temppath() :
111 masterBuffer->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 size_t const spos = s.find("$$Contents(\"");
181 size_t 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, masterBuffer->temppath()));
190 if (absfile.isFileReadable())
191 contents = absfile.fileContents();
193 size_t const pos = result.find("$$Contents(\"");
194 size_t 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())
245 string const to_format = outputFormat.updateFormat;
246 if (to_format.empty())
247 return; // NOT_NEEDED
249 // The master buffer. This is useful when there are multiple levels
251 Buffer const * masterBuffer = buffer.masterBuffer();
253 // We copy the source file to the temp dir and do the conversion
254 // there if necessary
255 FileName const temp_file(
256 support::makeAbsPath(params.filename.mangledFilename(),
257 masterBuffer->temppath()));
258 if (!params.filename.empty() && !params.filename.isDirectory()) {
259 unsigned long const from_checksum = support::sum(params.filename);
260 unsigned long const temp_checksum = support::sum(temp_file);
262 if (from_checksum != temp_checksum) {
263 Mover const & mover = getMover(from_format);
264 if (!mover.copy(params.filename, temp_file)) {
265 LYXERR(Debug::EXTERNAL)
266 << "external::updateExternal. "
268 << params.filename << " to " << temp_file << endl;
274 // the generated file (always in the temp dir)
275 string const to_file = doSubstitution(params, buffer,
276 outputFormat.updateResult,
278 FileName const abs_to_file(
279 support::makeAbsPath(to_file, masterBuffer->temppath()));
282 // Record the referenced files for the exporter.
283 // The exporter will copy them to the export dir.
284 typedef Template::Format::FileMap FileMap;
285 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
286 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
287 for (; rit != rend; ++rit) {
288 vector<string>::const_iterator fit = rit->second.begin();
289 vector<string>::const_iterator fend = rit->second.end();
290 for (; fit != fend; ++fit) {
291 FileName const source(support::makeAbsPath(
292 doSubstitution(params, buffer, *fit,
294 masterBuffer->temppath()));
295 // The path of the referenced file is never the
296 // temp path, but the filename may be the mangled
297 // or the real name. Therefore we substitute the
298 // paths and names separately.
299 string file = support::subst(*fit, "$$FName",
300 "$$FPath$$Basename$$Extension");
301 file = doSubstitution(params, buffer, file, false, false,
303 file = doSubstitution(params, buffer, file,
304 false, external_in_tmpdir,
306 // if file is a relative name, it is interpreted
307 // relative to the master document.
308 exportdata.addExternalFile(rit->first, source, file);
313 // Do we need to perform the conversion?
314 // Yes if to_file does not exist or if from_file is newer than to_file
315 if (support::compare_timestamps(temp_file, abs_to_file) < 0)
318 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
321 theConverters().convert(&buffer, temp_file, abs_to_file,
322 params.filename, from_format, to_format, el,
323 Converters::try_default | Converters::try_cache);
326 LYXERR(Debug::EXTERNAL)
327 << "external::updateExternal. "
328 << "Unable to convert from "
329 << from_format << " to " << to_format << endl;
336 string const substituteCommands(InsetExternalParams const & params,
337 string const & input, string const & format);
339 string const substituteOptions(InsetExternalParams const & params,
340 string const & input, string const & format);
345 int writeExternal(InsetExternalParams const & params,
346 string const & format,
347 Buffer const & buffer, odocstream & os,
348 ExportData & exportdata,
349 bool external_in_tmpdir,
352 Template const * const et_ptr = getTemplatePtr(params);
355 Template const & et = *et_ptr;
357 Template::Formats::const_iterator cit = et.formats.find(format);
358 if (cit == et.formats.end()) {
359 LYXERR(Debug::EXTERNAL)
360 << "External template format '" << format
361 << "' not specified in template "
362 << params.templatename() << endl;
366 if (!dryrun || support::contains(cit->second.product, "$$Contents"))
367 updateExternal(params, format, buffer, exportdata,
368 external_in_tmpdir, dryrun);
370 bool const use_latex_path = format == "LaTeX";
371 string str = doSubstitution(params, buffer, cit->second.product,
372 use_latex_path, external_in_tmpdir);
374 string const absname = support::makeAbsPath(
375 params.filename.outputFilename(buffer.filePath()), buffer.filePath()).absFilename();
377 if (!external_in_tmpdir && !isValidLaTeXFilename(absname)) {
378 lyx::frontend::Alert::warning(_("Invalid filename"),
379 _("The following filename is likely to cause trouble "
380 "when running the exported file through LaTeX: ") +
384 str = substituteCommands(params, str, format);
385 str = substituteOptions(params, str, format);
387 os << from_utf8(str);
388 return int(std::count(str.begin(), str.end(),'\n'));
393 // Empty template, specialised below.
394 template <typename TransformType>
395 string const substituteIt(string const &,
398 Template::Format const &,
399 InsetExternalParams const &);
403 string const substituteIt<TransformCommand>(string const & input,
405 string const & /* formatname */,
406 Template::Format const & format,
407 InsetExternalParams const & params)
409 typedef std::map<TransformID, TransformStore> Transformers;
410 Transformers::const_iterator it = format.command_transformers.find(id);
411 if (it == format.command_transformers.end())
414 TransformStore const & store = it->second;
416 TransformCommand::ptr_type ptr;
418 ptr = store.getCommandTransformer(params.rotationdata);
419 else if (id == Resize)
420 ptr = store.getCommandTransformer(params.resizedata);
426 support::subst(input, ptr->front_placeholder(), ptr->front());
427 return support::subst(result, ptr->back_placeholder(), ptr->back());
432 string const substituteIt<TransformOption>(string const & input,
434 string const & fname,
435 Template::Format const & format,
436 InsetExternalParams const & params)
438 typedef std::map<TransformID, TransformStore> Transformers;
439 Transformers::const_iterator it = format.option_transformers.find(id);
440 if (it == format.option_transformers.end())
443 TransformStore const & store = it->second;
445 TransformOption::ptr_type ptr;
448 ptr = store.getOptionTransformer(params.clipdata);
451 ptr = store.getOptionTransformer(params.extradata.get(fname));
454 ptr = store.getOptionTransformer(params.rotationdata);
457 ptr = store.getOptionTransformer(params.resizedata);
464 return support::subst(input, ptr->placeholder(), ptr->option());
468 template <typename TransformerType>
469 string const transformIt(InsetExternalParams const & params,
470 string const & s, string const & formatname)
472 Template const * const et = getTemplatePtr(params);
473 if (!et || et->transformIds.empty())
476 Template::Formats::const_iterator fit = et->formats.find(formatname);
477 if (fit == et->formats.end())
481 Template::Format const & format = fit->second;
483 typedef vector<TransformID> TransformsIDs;
484 TransformsIDs::const_iterator it = et->transformIds.begin();
485 TransformsIDs::const_iterator end = et->transformIds.end();
486 for (; it != end; ++it) {
487 result = substituteIt<TransformerType>(result, *it, formatname,
494 string const substituteCommands(InsetExternalParams const & params,
495 string const & input, string const & format)
497 return transformIt<TransformCommand>(params, input, format);
501 string const substituteOption(InsetExternalParams const & params,
502 string const & input, string const & format)
504 string opt = transformIt<TransformOption>(params, input, format);
506 if (format == "LaTeX" || format == "PDFLaTeX")
507 return sanitizeLatexOption(opt);
508 if (format == "DocBook")
509 return sanitizeDocBookOption(opt);
514 string const substituteOptions(InsetExternalParams const & params,
515 string const & input, string const & format)
517 string output = input;
519 Template const * const et = getTemplatePtr(params);
520 if (!et || et->transformIds.empty())
523 Template::Formats::const_iterator fit = et->formats.find(format);
524 if (fit == et->formats.end() || fit->second.options.empty())
527 typedef vector<Template::Option> Options;
528 Options const & options = fit->second.options;
529 Options::const_iterator it = options.begin();
530 Options::const_iterator end = options.end();
531 for (; it != end; ++it) {
532 string const opt = substituteOption(params, it->option, format);
533 string const placeholder = "$$" + it->name;
534 output = support::subst(output, placeholder, opt);
542 } // namespace external