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"
46 using support::FileName;
47 using support::isValidLaTeXFilename;
51 Template const * getTemplatePtr(InsetExternalParams const & params)
53 TemplateManager const & etm = TemplateManager::get();
54 return etm.getTemplateByName(params.templatename());
58 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
60 formats.edit(buffer, params.filename,
61 formats.getFormatFromFile(params.filename));
67 string const subst_path(string const & input,
68 string const & placeholder,
71 support::latex_path_extension ext = support::PROTECT_EXTENSION,
72 support::latex_path_dots dots = support::LEAVE_DOTS)
74 if (input.find(placeholder) == string::npos)
76 // Don't use external_path here when use_latex_path is false, as the
77 // path will be compared with another one in internal style later
78 // in Converters::move.
79 string const path2 = use_latex_path ?
80 support::latex_path(path, ext, dots) : path;
81 return support::subst(input, placeholder, path2);
87 string const doSubstitution(InsetExternalParams const & params,
88 Buffer const & buffer, string const & s,
90 bool external_in_tmpdir,
93 Buffer const * masterBuffer = buffer.masterBuffer();
94 string const parentpath = external_in_tmpdir ?
95 masterBuffer->temppath() :
97 string const filename = external_in_tmpdir ?
98 params.filename.mangledFilename() :
99 params.filename.outputFilename(parentpath);
100 string const basename = support::changeExtension(
101 support::onlyFilename(filename), string());
102 string const absname = support::makeAbsPath(filename, parentpath).absFilename();
105 if (what != ALL_BUT_PATHS) {
106 string const filepath = support::onlyPath(filename);
107 string const abspath = support::onlyPath(absname);
108 string const masterpath = external_in_tmpdir ?
109 masterBuffer->temppath() :
110 masterBuffer->filePath();
112 string relToMasterPath = support::onlyPath(
113 to_utf8(support::makeRelPath(from_utf8(absname),
114 from_utf8(masterpath))));
115 if (relToMasterPath == "./")
116 relToMasterPath.clear();
118 string relToParentPath = support::onlyPath(
119 to_utf8(support::makeRelPath(from_utf8(absname),
120 from_utf8(parentpath))));
121 if (relToParentPath == "./")
122 relToParentPath.clear();
124 result = subst_path(result, "$$FPath", filepath,
126 support::PROTECT_EXTENSION,
127 support::ESCAPE_DOTS);
128 result = subst_path(result, "$$AbsPath", abspath,
130 support::PROTECT_EXTENSION,
131 support::ESCAPE_DOTS);
132 result = subst_path(result, "$$RelPathMaster",
133 relToMasterPath, use_latex_path,
134 support::PROTECT_EXTENSION,
135 support::ESCAPE_DOTS);
136 result = subst_path(result, "$$RelPathParent",
137 relToParentPath, use_latex_path,
138 support::PROTECT_EXTENSION,
139 support::ESCAPE_DOTS);
140 if (support::absolutePath(filename)) {
141 result = subst_path(result, "$$AbsOrRelPathMaster",
142 abspath, use_latex_path,
143 support::PROTECT_EXTENSION,
144 support::ESCAPE_DOTS);
145 result = subst_path(result, "$$AbsOrRelPathParent",
146 abspath, use_latex_path,
147 support::PROTECT_EXTENSION,
148 support::ESCAPE_DOTS);
150 result = subst_path(result, "$$AbsOrRelPathMaster",
151 relToMasterPath, use_latex_path,
152 support::PROTECT_EXTENSION,
153 support::ESCAPE_DOTS);
154 result = subst_path(result, "$$AbsOrRelPathParent",
155 relToParentPath, use_latex_path,
156 support::PROTECT_EXTENSION,
157 support::ESCAPE_DOTS);
164 result = subst_path(result, "$$FName", filename, use_latex_path,
165 support::EXCLUDE_EXTENSION);
166 result = subst_path(result, "$$Basename", basename, use_latex_path,
167 support::PROTECT_EXTENSION, support::ESCAPE_DOTS);
168 result = subst_path(result, "$$Extension",
169 '.' + support::getExtension(filename), use_latex_path);
170 result = subst_path(result, "$$Tempname", params.tempname().absFilename(), use_latex_path);
171 result = subst_path(result, "$$Sysdir",
172 support::package().system_support().absFilename(), use_latex_path);
174 // Handle the $$Contents(filename) syntax
175 if (support::contains(result, "$$Contents(\"")) {
176 // Since use_latex_path may be true we must extract the file
177 // name from s instead of result and do the substitutions
178 // again, this time with use_latex_path false.
179 size_t const spos = s.find("$$Contents(\"");
180 size_t const send = s.find("\")", spos);
181 string const file_template = s.substr(spos + 12, send - (spos + 12));
182 string const file = doSubstitution(params, buffer,
183 file_template, false,
184 external_in_tmpdir, what);
187 FileName const absfile(
188 support::makeAbsPath(file, masterBuffer->temppath()));
189 if (absfile.isReadableFile())
190 contents = absfile.fileContents();
192 size_t const pos = result.find("$$Contents(\"");
193 size_t const end = result.find("\")", pos);
194 result.replace(pos, end + 2, contents);
203 /** update the file represented by the template.
204 If \p external_in_tmpdir == true, then the generated file is
205 placed in the buffer's temporary directory.
207 void updateExternal(InsetExternalParams const & params,
208 string const & format,
209 Buffer const & buffer,
210 ExportData & exportdata,
211 bool external_in_tmpdir,
214 Template const * const et_ptr = getTemplatePtr(params);
217 Template const & et = *et_ptr;
219 if (!et.automaticProduction)
220 return; // NOT_NEEDED
222 Template::Formats::const_iterator cit = et.formats.find(format);
223 if (cit == et.formats.end())
226 Template::Format const & outputFormat = cit->second;
227 if (outputFormat.updateResult.empty())
228 return; // NOT_NEEDED
230 string from_format = et.inputFormat;
231 if (from_format.empty())
232 return; // NOT_NEEDED
234 if (from_format == "*") {
235 if (params.filename.empty())
236 return; // NOT_NEEDED
238 // Try and ascertain the file format from its contents.
239 from_format = formats.getFormatFromFile(params.filename);
240 if (from_format.empty())
244 string const to_format = outputFormat.updateFormat;
245 if (to_format.empty())
246 return; // NOT_NEEDED
248 // The master buffer. This is useful when there are multiple levels
250 Buffer const * masterBuffer = buffer.masterBuffer();
252 // We copy the source file to the temp dir and do the conversion
253 // there if necessary
254 FileName const temp_file(
255 support::makeAbsPath(params.filename.mangledFilename(),
256 masterBuffer->temppath()));
257 if (!params.filename.empty() && !params.filename.isDirectory()) {
258 unsigned long const from_checksum = params.filename.checksum();
259 unsigned long const temp_checksum = temp_file.checksum();
261 if (from_checksum != temp_checksum) {
262 Mover const & mover = getMover(from_format);
263 if (!mover.copy(params.filename, temp_file)) {
264 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
265 << "Unable to copy " << params.filename << " to " << temp_file);
271 // the generated file (always in the temp dir)
272 string const to_file = doSubstitution(params, buffer,
273 outputFormat.updateResult,
275 FileName const abs_to_file(
276 support::makeAbsPath(to_file, masterBuffer->temppath()));
279 // Record the referenced files for the exporter.
280 // The exporter will copy them to the export dir.
281 typedef Template::Format::FileMap FileMap;
282 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
283 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
284 for (; rit != rend; ++rit) {
285 vector<string>::const_iterator fit = rit->second.begin();
286 vector<string>::const_iterator fend = rit->second.end();
287 for (; fit != fend; ++fit) {
288 FileName const source(support::makeAbsPath(
289 doSubstitution(params, buffer, *fit,
291 masterBuffer->temppath()));
292 // The path of the referenced file is never the
293 // temp path, but the filename may be the mangled
294 // or the real name. Therefore we substitute the
295 // paths and names separately.
296 string file = support::subst(*fit, "$$FName",
297 "$$FPath$$Basename$$Extension");
298 file = doSubstitution(params, buffer, file, false, false,
300 file = doSubstitution(params, buffer, file,
301 false, external_in_tmpdir,
303 // if file is a relative name, it is interpreted
304 // relative to the master document.
305 exportdata.addExternalFile(rit->first, source, file);
310 // Do we need to perform the conversion?
311 // Yes if to_file does not exist or if from_file is newer than to_file
312 if (support::compare_timestamps(temp_file, abs_to_file) < 0)
315 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
318 theConverters().convert(&buffer, temp_file, abs_to_file,
319 params.filename, from_format, to_format, el,
320 Converters::try_default | Converters::try_cache);
323 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
324 << "Unable to convert from " << from_format << " to " << to_format);
331 string const substituteCommands(InsetExternalParams const & params,
332 string const & input, string const & format);
334 string const substituteOptions(InsetExternalParams const & params,
335 string const & input, string const & format);
340 int writeExternal(InsetExternalParams const & params,
341 string const & format,
342 Buffer const & buffer, odocstream & os,
343 ExportData & exportdata,
344 bool external_in_tmpdir,
347 Template const * const et_ptr = getTemplatePtr(params);
350 Template const & et = *et_ptr;
352 Template::Formats::const_iterator cit = et.formats.find(format);
353 if (cit == et.formats.end()) {
354 LYXERR(Debug::EXTERNAL, "External template format '" << format
355 << "' not specified in template " << params.templatename());
359 if (!dryrun || support::contains(cit->second.product, "$$Contents"))
360 updateExternal(params, format, buffer, exportdata,
361 external_in_tmpdir, dryrun);
363 bool const use_latex_path = format == "LaTeX";
364 string str = doSubstitution(params, buffer, cit->second.product,
365 use_latex_path, external_in_tmpdir);
367 string const absname = support::makeAbsPath(
368 params.filename.outputFilename(buffer.filePath()), buffer.filePath()).absFilename();
370 if (!external_in_tmpdir && !isValidLaTeXFilename(absname)) {
371 lyx::frontend::Alert::warning(_("Invalid filename"),
372 _("The following filename is likely to cause trouble "
373 "when running the exported file through LaTeX: ") +
377 str = substituteCommands(params, str, format);
378 str = substituteOptions(params, str, format);
380 os << from_utf8(str);
381 return int(std::count(str.begin(), str.end(),'\n'));
386 // Empty template, specialised below.
387 template <typename TransformType>
388 string const substituteIt(string const &,
391 Template::Format const &,
392 InsetExternalParams const &);
396 string const substituteIt<TransformCommand>(string const & input,
398 string const & /* formatname */,
399 Template::Format const & format,
400 InsetExternalParams const & params)
402 typedef std::map<TransformID, TransformStore> Transformers;
403 Transformers::const_iterator it = format.command_transformers.find(id);
404 if (it == format.command_transformers.end())
407 TransformStore const & store = it->second;
409 TransformCommand::ptr_type ptr;
411 ptr = store.getCommandTransformer(params.rotationdata);
412 else if (id == Resize)
413 ptr = store.getCommandTransformer(params.resizedata);
419 support::subst(input, ptr->front_placeholder(), ptr->front());
420 return support::subst(result, ptr->back_placeholder(), ptr->back());
425 string const substituteIt<TransformOption>(string const & input,
427 string const & fname,
428 Template::Format const & format,
429 InsetExternalParams const & params)
431 typedef std::map<TransformID, TransformStore> Transformers;
432 Transformers::const_iterator it = format.option_transformers.find(id);
433 if (it == format.option_transformers.end())
436 TransformStore const & store = it->second;
438 TransformOption::ptr_type ptr;
441 ptr = store.getOptionTransformer(params.clipdata);
444 ptr = store.getOptionTransformer(params.extradata.get(fname));
447 ptr = store.getOptionTransformer(params.rotationdata);
450 ptr = store.getOptionTransformer(params.resizedata);
457 return support::subst(input, ptr->placeholder(), ptr->option());
461 template <typename TransformerType>
462 string const transformIt(InsetExternalParams const & params,
463 string const & s, string const & formatname)
465 Template const * const et = getTemplatePtr(params);
466 if (!et || et->transformIds.empty())
469 Template::Formats::const_iterator fit = et->formats.find(formatname);
470 if (fit == et->formats.end())
474 Template::Format const & format = fit->second;
476 typedef vector<TransformID> TransformsIDs;
477 TransformsIDs::const_iterator it = et->transformIds.begin();
478 TransformsIDs::const_iterator end = et->transformIds.end();
479 for (; it != end; ++it) {
480 result = substituteIt<TransformerType>(result, *it, formatname,
487 string const substituteCommands(InsetExternalParams const & params,
488 string const & input, string const & format)
490 return transformIt<TransformCommand>(params, input, format);
494 string const substituteOption(InsetExternalParams const & params,
495 string const & input, string const & format)
497 string opt = transformIt<TransformOption>(params, input, format);
499 if (format == "LaTeX" || format == "PDFLaTeX")
500 return sanitizeLatexOption(opt);
501 if (format == "DocBook")
502 return sanitizeDocBookOption(opt);
507 string const substituteOptions(InsetExternalParams const & params,
508 string const & input, string const & format)
510 string output = input;
512 Template const * const et = getTemplatePtr(params);
513 if (!et || et->transformIds.empty())
516 Template::Formats::const_iterator fit = et->formats.find(format);
517 if (fit == et->formats.end() || fit->second.options.empty())
520 typedef vector<Template::Option> Options;
521 Options const & options = fit->second.options;
522 Options::const_iterator it = options.begin();
523 Options::const_iterator end = options.end();
524 for (; it != end; ++it) {
525 string const opt = substituteOption(params, it->option, format);
526 string const placeholder = "$$" + it->name;
527 output = support::subst(output, placeholder, opt);
535 } // namespace external