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, "external::updateExternal. "
266 << "Unable to copy " << params.filename << " to " << temp_file);
272 // the generated file (always in the temp dir)
273 string const to_file = doSubstitution(params, buffer,
274 outputFormat.updateResult,
276 FileName const abs_to_file(
277 support::makeAbsPath(to_file, masterBuffer->temppath()));
280 // Record the referenced files for the exporter.
281 // The exporter will copy them to the export dir.
282 typedef Template::Format::FileMap FileMap;
283 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
284 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
285 for (; rit != rend; ++rit) {
286 vector<string>::const_iterator fit = rit->second.begin();
287 vector<string>::const_iterator fend = rit->second.end();
288 for (; fit != fend; ++fit) {
289 FileName const source(support::makeAbsPath(
290 doSubstitution(params, buffer, *fit,
292 masterBuffer->temppath()));
293 // The path of the referenced file is never the
294 // temp path, but the filename may be the mangled
295 // or the real name. Therefore we substitute the
296 // paths and names separately.
297 string file = support::subst(*fit, "$$FName",
298 "$$FPath$$Basename$$Extension");
299 file = doSubstitution(params, buffer, file, false, false,
301 file = doSubstitution(params, buffer, file,
302 false, external_in_tmpdir,
304 // if file is a relative name, it is interpreted
305 // relative to the master document.
306 exportdata.addExternalFile(rit->first, source, file);
311 // Do we need to perform the conversion?
312 // Yes if to_file does not exist or if from_file is newer than to_file
313 if (support::compare_timestamps(temp_file, abs_to_file) < 0)
316 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
319 theConverters().convert(&buffer, temp_file, abs_to_file,
320 params.filename, from_format, to_format, el,
321 Converters::try_default | Converters::try_cache);
324 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
325 << "Unable to convert from " << from_format << " to " << to_format);
332 string const substituteCommands(InsetExternalParams const & params,
333 string const & input, string const & format);
335 string const substituteOptions(InsetExternalParams const & params,
336 string const & input, string const & format);
341 int writeExternal(InsetExternalParams const & params,
342 string const & format,
343 Buffer const & buffer, odocstream & os,
344 ExportData & exportdata,
345 bool external_in_tmpdir,
348 Template const * const et_ptr = getTemplatePtr(params);
351 Template const & et = *et_ptr;
353 Template::Formats::const_iterator cit = et.formats.find(format);
354 if (cit == et.formats.end()) {
355 LYXERR(Debug::EXTERNAL, "External template format '" << format
356 << "' not specified in template " << params.templatename());
360 if (!dryrun || support::contains(cit->second.product, "$$Contents"))
361 updateExternal(params, format, buffer, exportdata,
362 external_in_tmpdir, dryrun);
364 bool const use_latex_path = format == "LaTeX";
365 string str = doSubstitution(params, buffer, cit->second.product,
366 use_latex_path, external_in_tmpdir);
368 string const absname = support::makeAbsPath(
369 params.filename.outputFilename(buffer.filePath()), buffer.filePath()).absFilename();
371 if (!external_in_tmpdir && !isValidLaTeXFilename(absname)) {
372 lyx::frontend::Alert::warning(_("Invalid filename"),
373 _("The following filename is likely to cause trouble "
374 "when running the exported file through LaTeX: ") +
378 str = substituteCommands(params, str, format);
379 str = substituteOptions(params, str, format);
381 os << from_utf8(str);
382 return int(std::count(str.begin(), str.end(),'\n'));
387 // Empty template, specialised below.
388 template <typename TransformType>
389 string const substituteIt(string const &,
392 Template::Format const &,
393 InsetExternalParams const &);
397 string const substituteIt<TransformCommand>(string const & input,
399 string const & /* formatname */,
400 Template::Format const & format,
401 InsetExternalParams const & params)
403 typedef std::map<TransformID, TransformStore> Transformers;
404 Transformers::const_iterator it = format.command_transformers.find(id);
405 if (it == format.command_transformers.end())
408 TransformStore const & store = it->second;
410 TransformCommand::ptr_type ptr;
412 ptr = store.getCommandTransformer(params.rotationdata);
413 else if (id == Resize)
414 ptr = store.getCommandTransformer(params.resizedata);
420 support::subst(input, ptr->front_placeholder(), ptr->front());
421 return support::subst(result, ptr->back_placeholder(), ptr->back());
426 string const substituteIt<TransformOption>(string const & input,
428 string const & fname,
429 Template::Format const & format,
430 InsetExternalParams const & params)
432 typedef std::map<TransformID, TransformStore> Transformers;
433 Transformers::const_iterator it = format.option_transformers.find(id);
434 if (it == format.option_transformers.end())
437 TransformStore const & store = it->second;
439 TransformOption::ptr_type ptr;
442 ptr = store.getOptionTransformer(params.clipdata);
445 ptr = store.getOptionTransformer(params.extradata.get(fname));
448 ptr = store.getOptionTransformer(params.rotationdata);
451 ptr = store.getOptionTransformer(params.resizedata);
458 return support::subst(input, ptr->placeholder(), ptr->option());
462 template <typename TransformerType>
463 string const transformIt(InsetExternalParams const & params,
464 string const & s, string const & formatname)
466 Template const * const et = getTemplatePtr(params);
467 if (!et || et->transformIds.empty())
470 Template::Formats::const_iterator fit = et->formats.find(formatname);
471 if (fit == et->formats.end())
475 Template::Format const & format = fit->second;
477 typedef vector<TransformID> TransformsIDs;
478 TransformsIDs::const_iterator it = et->transformIds.begin();
479 TransformsIDs::const_iterator end = et->transformIds.end();
480 for (; it != end; ++it) {
481 result = substituteIt<TransformerType>(result, *it, formatname,
488 string const substituteCommands(InsetExternalParams const & params,
489 string const & input, string const & format)
491 return transformIt<TransformCommand>(params, input, format);
495 string const substituteOption(InsetExternalParams const & params,
496 string const & input, string const & format)
498 string opt = transformIt<TransformOption>(params, input, format);
500 if (format == "LaTeX" || format == "PDFLaTeX")
501 return sanitizeLatexOption(opt);
502 if (format == "DocBook")
503 return sanitizeDocBookOption(opt);
508 string const substituteOptions(InsetExternalParams const & params,
509 string const & input, string const & format)
511 string output = input;
513 Template const * const et = getTemplatePtr(params);
514 if (!et || et->transformIds.empty())
517 Template::Formats::const_iterator fit = et->formats.find(format);
518 if (fit == et->formats.end() || fit->second.options.empty())
521 typedef vector<Template::Option> Options;
522 Options const & options = fit->second.options;
523 Options::const_iterator it = options.begin();
524 Options::const_iterator end = options.end();
525 for (; it != end; ++it) {
526 string const opt = substituteOption(params, it->option, format);
527 string const placeholder = "$$" + it->name;
528 output = support::subst(output, placeholder, opt);
536 } // namespace external