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"
21 #include "ErrorList.h"
26 #include "frontends/alert.h"
28 #include "support/debug.h"
29 #include "support/filetools.h"
30 #include "support/gettext.h"
31 #include "support/lstrings.h"
32 #include "support/lyxalgo.h"
33 #include "support/lyxlib.h"
34 #include "support/os.h"
35 #include "support/Package.h"
40 using namespace lyx::support;
45 Template const * getTemplatePtr(InsetExternalParams const & params)
47 TemplateManager const & etm = TemplateManager::get();
48 return etm.getTemplateByName(params.templatename());
52 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
54 formats.edit(buffer, params.filename,
55 formats.getFormatFromFile(params.filename));
61 string const subst_path(string const & input,
62 string const & placeholder,
65 latex_path_extension ext = PROTECT_EXTENSION,
66 latex_path_dots dots = LEAVE_DOTS)
68 if (input.find(placeholder) == string::npos)
70 // Don't use external_path here when use_latex_path is false, as the
71 // path will be compared with another one in internal style later
72 // in Converters::move.
73 string const path2 = use_latex_path ?
74 latex_path(path, ext, dots) : path;
75 return subst(input, placeholder, path2);
81 string const doSubstitution(InsetExternalParams const & params,
82 Buffer const & buffer, string const & s,
84 bool external_in_tmpdir,
87 Buffer const * masterBuffer = buffer.masterBuffer();
88 string const parentpath = external_in_tmpdir ?
89 masterBuffer->temppath() :
91 string const filename = external_in_tmpdir ?
92 params.filename.mangledFilename() :
93 params.filename.outputFilename(parentpath);
94 string const basename = changeExtension(
95 onlyFilename(filename), string());
96 string const absname = makeAbsPath(filename, parentpath).absFilename();
99 if (what != ALL_BUT_PATHS) {
100 string const filepath = onlyPath(filename);
101 string const abspath = onlyPath(absname);
102 string const masterpath = external_in_tmpdir ?
103 masterBuffer->temppath() :
104 masterBuffer->filePath();
106 string relToMasterPath = onlyPath(
107 to_utf8(makeRelPath(from_utf8(absname),
108 from_utf8(masterpath))));
109 if (relToMasterPath == "./")
110 relToMasterPath.clear();
112 string relToParentPath = onlyPath(
113 to_utf8(makeRelPath(from_utf8(absname),
114 from_utf8(parentpath))));
115 if (relToParentPath == "./")
116 relToParentPath.clear();
118 result = subst_path(result, "$$FPath", filepath,
122 result = subst_path(result, "$$AbsPath", abspath,
126 result = subst_path(result, "$$RelPathMaster",
127 relToMasterPath, use_latex_path,
130 result = subst_path(result, "$$RelPathParent",
131 relToParentPath, use_latex_path,
134 if (absolutePath(filename)) {
135 result = subst_path(result, "$$AbsOrRelPathMaster",
136 abspath, use_latex_path,
139 result = subst_path(result, "$$AbsOrRelPathParent",
140 abspath, use_latex_path,
144 result = subst_path(result, "$$AbsOrRelPathMaster",
145 relToMasterPath, use_latex_path,
148 result = subst_path(result, "$$AbsOrRelPathParent",
149 relToParentPath, use_latex_path,
158 result = subst_path(result, "$$FName", filename, use_latex_path,
160 result = subst_path(result, "$$Basename", basename, use_latex_path,
161 PROTECT_EXTENSION, ESCAPE_DOTS);
162 result = subst_path(result, "$$Extension",
163 '.' + getExtension(filename), use_latex_path);
164 result = subst_path(result, "$$Tempname", params.tempname().absFilename(), use_latex_path);
165 result = subst_path(result, "$$Sysdir",
166 package().system_support().absFilename(), use_latex_path);
168 // Handle the $$Contents(filename) syntax
169 if (contains(result, "$$Contents(\"")) {
170 // Since use_latex_path may be true we must extract the file
171 // name from s instead of result and do the substitutions
172 // again, this time with use_latex_path false.
173 size_t const spos = s.find("$$Contents(\"");
174 size_t const send = s.find("\")", spos);
175 string const file_template = s.substr(spos + 12, send - (spos + 12));
176 string const file = doSubstitution(params, buffer,
177 file_template, false,
178 external_in_tmpdir, what);
181 FileName const absfile(
182 makeAbsPath(file, masterBuffer->temppath()));
183 if (absfile.isReadableFile())
185 contents = to_utf8(absfile.fileContents("UTF-8"));
187 size_t const pos = result.find("$$Contents(\"");
188 size_t const end = result.find("\")", pos);
189 result.replace(pos, end + 2, contents);
198 /** update the file represented by the template.
199 If \p external_in_tmpdir == true, then the generated file is
200 placed in the buffer's temporary directory.
202 void updateExternal(InsetExternalParams const & params,
203 string const & format,
204 Buffer const & buffer,
205 ExportData & exportdata,
206 bool external_in_tmpdir,
209 Template const * const et_ptr = getTemplatePtr(params);
212 Template const & et = *et_ptr;
214 if (!et.automaticProduction)
215 return; // NOT_NEEDED
217 Template::Formats::const_iterator cit = et.formats.find(format);
218 if (cit == et.formats.end())
221 Template::Format const & outputFormat = cit->second;
222 if (outputFormat.updateResult.empty())
223 return; // NOT_NEEDED
225 string from_format = et.inputFormat;
226 if (from_format.empty())
227 return; // NOT_NEEDED
229 if (from_format == "*") {
230 if (params.filename.empty())
231 return; // NOT_NEEDED
233 // Try and ascertain the file format from its contents.
234 from_format = formats.getFormatFromFile(params.filename);
235 if (from_format.empty())
239 string const to_format = outputFormat.updateFormat;
240 if (to_format.empty())
241 return; // NOT_NEEDED
243 // The master buffer. This is useful when there are multiple levels
245 Buffer const * masterBuffer = buffer.masterBuffer();
247 // We copy the source file to the temp dir and do the conversion
248 // there if necessary
249 FileName const temp_file(
250 makeAbsPath(params.filename.mangledFilename(),
251 masterBuffer->temppath()));
252 if (!params.filename.empty() && !params.filename.isDirectory()) {
253 unsigned long const from_checksum = params.filename.checksum();
254 unsigned long const temp_checksum = temp_file.checksum();
256 if (from_checksum != temp_checksum) {
257 Mover const & mover = getMover(from_format);
258 if (!mover.copy(params.filename, temp_file)) {
259 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
260 << "Unable to copy " << params.filename << " to " << temp_file);
266 // the generated file (always in the temp dir)
267 string const to_file = doSubstitution(params, buffer,
268 outputFormat.updateResult,
270 FileName const abs_to_file(
271 makeAbsPath(to_file, masterBuffer->temppath()));
274 // Record the referenced files for the exporter.
275 // The exporter will copy them to the export dir.
276 typedef Template::Format::FileMap FileMap;
277 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
278 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
279 for (; rit != rend; ++rit) {
280 vector<string>::const_iterator fit = rit->second.begin();
281 vector<string>::const_iterator fend = rit->second.end();
282 for (; fit != fend; ++fit) {
283 FileName const source(makeAbsPath(
284 doSubstitution(params, buffer, *fit,
286 masterBuffer->temppath()));
287 // The path of the referenced file is never the
288 // temp path, but the filename may be the mangled
289 // or the real name. Therefore we substitute the
290 // paths and names separately.
291 string file = subst(*fit, "$$FName",
292 "$$FPath$$Basename$$Extension");
293 file = doSubstitution(params, buffer, file, false, false,
295 file = doSubstitution(params, buffer, file,
296 false, external_in_tmpdir,
298 // if file is a relative name, it is interpreted
299 // relative to the master document.
300 exportdata.addExternalFile(rit->first, source, file);
305 // Do we need to perform the conversion?
306 // Yes if to_file does not exist or if from_file is newer than to_file
307 if (compare_timestamps(temp_file, abs_to_file) < 0)
310 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
313 theConverters().convert(&buffer, temp_file, abs_to_file,
314 params.filename, from_format, to_format, el,
315 Converters::try_default | Converters::try_cache);
318 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
319 << "Unable to convert from " << from_format << " to " << to_format);
326 string const substituteCommands(InsetExternalParams const & params,
327 string const & input, string const & format);
329 string const substituteOptions(InsetExternalParams const & params,
330 string const & input, string const & format);
335 int writeExternal(InsetExternalParams const & params,
336 string const & format,
337 Buffer const & buffer, odocstream & os,
338 ExportData & exportdata,
339 bool external_in_tmpdir,
342 Template const * const et_ptr = getTemplatePtr(params);
345 Template const & et = *et_ptr;
347 Template::Formats::const_iterator cit = et.formats.find(format);
348 if (cit == et.formats.end()) {
349 LYXERR(Debug::EXTERNAL, "External template format '" << format
350 << "' not specified in template " << params.templatename());
354 if (!dryrun || contains(cit->second.product, "$$Contents"))
355 updateExternal(params, format, buffer, exportdata,
356 external_in_tmpdir, dryrun);
358 bool const use_latex_path = format == "LaTeX";
359 string str = doSubstitution(params, buffer, cit->second.product,
360 use_latex_path, external_in_tmpdir);
362 string const absname = makeAbsPath(
363 params.filename.outputFilename(buffer.filePath()), buffer.filePath()).absFilename();
365 if (!external_in_tmpdir && !isValidLaTeXFilename(absname)) {
366 lyx::frontend::Alert::warning(_("Invalid filename"),
367 _("The following filename is likely to cause trouble "
368 "when running the exported file through LaTeX: ") +
372 str = substituteCommands(params, str, format);
373 str = substituteOptions(params, str, format);
375 os << from_utf8(str);
376 return int(count(str.begin(), str.end(),'\n'));
381 // Empty template, specialised below.
382 template <typename TransformType>
383 string const substituteIt(string const &,
386 Template::Format const &,
387 InsetExternalParams const &);
391 string const substituteIt<TransformCommand>(string const & input,
393 string const & /* formatname */,
394 Template::Format const & format,
395 InsetExternalParams const & params)
397 typedef map<TransformID, TransformStore> Transformers;
398 Transformers::const_iterator it = format.command_transformers.find(id);
399 if (it == format.command_transformers.end())
402 TransformStore const & store = it->second;
404 TransformCommand::ptr_type ptr;
406 ptr = store.getCommandTransformer(params.rotationdata);
407 else if (id == Resize)
408 ptr = store.getCommandTransformer(params.resizedata);
414 subst(input, ptr->front_placeholder(), ptr->front());
415 return subst(result, ptr->back_placeholder(), ptr->back());
420 string const substituteIt<TransformOption>(string const & input,
422 string const & fname,
423 Template::Format const & format,
424 InsetExternalParams const & params)
426 typedef map<TransformID, TransformStore> Transformers;
427 Transformers::const_iterator it = format.option_transformers.find(id);
428 if (it == format.option_transformers.end())
431 TransformStore const & store = it->second;
433 TransformOption::ptr_type ptr;
436 ptr = store.getOptionTransformer(params.clipdata);
439 ptr = store.getOptionTransformer(params.extradata.get(fname));
442 ptr = store.getOptionTransformer(params.rotationdata);
445 ptr = store.getOptionTransformer(params.resizedata);
452 return subst(input, ptr->placeholder(), ptr->option());
456 template <typename TransformerType>
457 string const transformIt(InsetExternalParams const & params,
458 string const & s, string const & formatname)
460 Template const * const et = getTemplatePtr(params);
461 if (!et || et->transformIds.empty())
464 Template::Formats::const_iterator fit = et->formats.find(formatname);
465 if (fit == et->formats.end())
469 Template::Format const & format = fit->second;
471 typedef vector<TransformID> TransformsIDs;
472 TransformsIDs::const_iterator it = et->transformIds.begin();
473 TransformsIDs::const_iterator end = et->transformIds.end();
474 for (; it != end; ++it) {
475 result = substituteIt<TransformerType>(result, *it, formatname,
482 string const substituteCommands(InsetExternalParams const & params,
483 string const & input, string const & format)
485 return transformIt<TransformCommand>(params, input, format);
489 string const substituteOption(InsetExternalParams const & params,
490 string const & input, string const & format)
492 string opt = transformIt<TransformOption>(params, input, format);
494 if (format == "LaTeX" || format == "PDFLaTeX")
495 return sanitizeLatexOption(opt);
496 if (format == "DocBook")
497 return sanitizeDocBookOption(opt);
502 string const substituteOptions(InsetExternalParams const & params,
503 string const & input, string const & format)
505 string output = input;
507 Template const * const et = getTemplatePtr(params);
508 if (!et || et->transformIds.empty())
511 Template::Formats::const_iterator fit = et->formats.find(format);
512 if (fit == et->formats.end() || fit->second.options.empty())
515 typedef vector<Template::Option> Options;
516 Options const & options = fit->second.options;
517 Options::const_iterator it = options.begin();
518 Options::const_iterator end = options.end();
519 for (; it != end; ++it) {
520 string const opt = substituteOption(params, it->option, format);
521 string const placeholder = "$$" + it->name;
522 output = subst(output, placeholder, opt);
530 } // namespace external