2 * \file ExternalSupport.C
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"
26 #include "support/filetools.h"
27 #include "support/forkedcall.h"
28 #include "support/lstrings.h"
29 #include "support/lyxalgo.h"
30 #include "support/lyxlib.h"
31 #include "support/os.h"
32 #include "support/package.h"
33 #include "support/path.h"
35 #include "support/std_ostream.h"
37 namespace support = lyx::support;
49 Template const * getTemplatePtr(InsetExternalParams const & params)
51 TemplateManager const & etm = TemplateManager::get();
52 return etm.getTemplateByName(params.templatename());
56 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
58 string const file_with_path = params.filename.absFilename();
59 formats.edit(buffer, file_with_path,
60 formats.getFormatFromFile(file_with_path));
66 string const subst_path(string const & input,
67 string const & placeholder,
71 if (input.find(placeholder) == string::npos)
73 string const path2 = use_latex_path ?
74 support::latex_path(path) : support::os::external_path(path);
75 return support::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 * m_buffer = buffer.getMasterBuffer();
88 string const parentpath = external_in_tmpdir ?
89 m_buffer->temppath() :
91 string const filename = external_in_tmpdir ?
92 params.filename.mangledFilename() :
93 params.filename.outputFilename(parentpath);
94 string const basename = support::ChangeExtension(
95 support::OnlyFilename(filename), string());
96 string const absname = support::MakeAbsPath(filename, parentpath);
99 if (what != ALL_BUT_PATHS) {
100 string const filepath = support::OnlyPath(filename);
101 string const abspath = support::OnlyPath(absname);
102 string const masterpath = external_in_tmpdir ?
103 m_buffer->temppath() :
104 m_buffer->filePath();
105 string relToMasterPath = support::OnlyPath(
106 support::MakeRelPath(absname, masterpath));
107 if (relToMasterPath == "./")
108 relToMasterPath.clear();
109 string relToParentPath = support::OnlyPath(
110 support::MakeRelPath(absname, parentpath));
111 if (relToParentPath == "./")
112 relToParentPath.clear();
114 result = subst_path(result, "$$FPath", filepath, use_latex_path);
115 result = subst_path(result, "$$AbsPath", abspath, use_latex_path);
116 result = subst_path(result, "$$RelPathMaster",
117 relToMasterPath, use_latex_path);
118 result = subst_path(result, "$$RelPathParent",
119 relToParentPath, use_latex_path);
120 if (support::AbsolutePath(filename)) {
121 result = subst_path(result, "$$AbsOrRelPathMaster",
122 abspath, use_latex_path);
123 result = subst_path(result, "$$AbsOrRelPathParent",
124 abspath, use_latex_path);
126 result = subst_path(result, "$$AbsOrRelPathMaster",
127 relToMasterPath, use_latex_path);
128 result = subst_path(result, "$$AbsOrRelPathParent",
129 relToParentPath, use_latex_path);
136 result = subst_path(result, "$$FName", filename, use_latex_path);
137 result = subst_path(result, "$$Basename", basename, use_latex_path);
138 result = subst_path(result, "$$Extension",
139 '.' + support::GetExtension(filename), use_latex_path);
140 result = subst_path(result, "$$Tempname", params.tempname(), use_latex_path);
141 result = subst_path(result, "$$Sysdir",
142 support::package().system_support(), use_latex_path);
144 // Handle the $$Contents(filename) syntax
145 if (support::contains(result, "$$Contents(\"")) {
147 string::size_type const pos = result.find("$$Contents(\"");
148 string::size_type const end = result.find("\")", pos);
149 string const file = result.substr(pos + 12, end - (pos + 12));
152 string const filepath = support::IsFileReadable(file) ?
153 buffer.filePath() : m_buffer->temppath();
154 support::Path p(filepath);
156 if (support::IsFileReadable(file))
157 contents = support::GetFileContents(file);
159 result = support::subst(result,
160 ("$$Contents(\"" + file + "\")").c_str(),
170 /** update the file represented by the template.
171 If \p external_in_tmpdir == true, then the generated file is
172 placed in the buffer's temporary directory.
174 void updateExternal(InsetExternalParams const & params,
175 string const & format,
176 Buffer const & buffer,
177 ExportData & exportdata,
178 bool external_in_tmpdir)
180 Template const * const et_ptr = getTemplatePtr(params);
183 Template const & et = *et_ptr;
185 if (!et.automaticProduction)
186 return; // NOT_NEEDED
188 Template::Formats::const_iterator cit = et.formats.find(format);
189 if (cit == et.formats.end())
192 Template::Format const & outputFormat = cit->second;
193 if (outputFormat.updateResult.empty())
194 return; // NOT_NEEDED
196 string from_format = et.inputFormat;
197 if (from_format.empty())
198 return; // NOT_NEEDED
200 string abs_from_file = params.filename.absFilename();
202 if (from_format == "*") {
203 if (abs_from_file.empty())
204 return; // NOT_NEEDED
206 // Try and ascertain the file format from its contents.
207 from_format = formats.getFormatFromFile(abs_from_file);
208 if (from_format.empty())
213 string const to_format = outputFormat.updateFormat;
214 if (to_format.empty())
215 return; // NOT_NEEDED
217 if (!converters.isReachable(from_format, to_format)) {
218 lyxerr[Debug::EXTERNAL]
219 << "external::updateExternal. "
220 << "Unable to convert from "
221 << from_format << " to " << to_format << endl;
225 // The master buffer. This is useful when there are multiple levels
227 Buffer const * m_buffer = buffer.getMasterBuffer();
229 // We copy the source file to the temp dir and do the conversion
230 // there if necessary
231 string const temp_file =
232 support::MakeAbsPath(params.filename.mangledFilename(),
233 m_buffer->temppath());
234 if (!abs_from_file.empty()) {
235 unsigned long const from_checksum = support::sum(abs_from_file);
236 unsigned long const temp_checksum = support::sum(temp_file);
238 if (from_checksum != temp_checksum) {
239 Mover const & mover = movers(from_format);
240 if (!mover.copy(abs_from_file, temp_file)) {
241 lyxerr[Debug::EXTERNAL]
242 << "external::updateExternal. "
244 << abs_from_file << " to " << temp_file << endl;
250 // the generated file (always in the temp dir)
251 string const to_file = doSubstitution(params, buffer,
252 outputFormat.updateResult,
254 string const abs_to_file =
255 support::MakeAbsPath(to_file, m_buffer->temppath());
257 // Record the referenced files for the exporter.
258 // The exporter will copy them to the export dir.
259 typedef Template::Format::FileMap FileMap;
260 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
261 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
262 for (; rit != rend; ++rit) {
263 vector<string>::const_iterator fit = rit->second.begin();
264 vector<string>::const_iterator fend = rit->second.end();
265 for (; fit != fend; ++fit) {
266 string const source = support::MakeAbsPath(
267 doSubstitution(params, buffer, *fit,
269 m_buffer->temppath());
270 // The path of the referenced file is never the
271 // temp path, but the filename may be the mangled
272 // or the real name. Therefore we substitute the
273 // paths and names separately.
274 string file = support::subst(*fit, "$$FName",
275 "$$FPath$$Basename$$Extension");
276 file = doSubstitution(params, buffer, file, false, false,
278 file = doSubstitution(params, buffer, file,
279 false, external_in_tmpdir,
281 // if file is a relative name, it is interpreted
282 // relative to the master document.
283 exportdata.addExternalFile(rit->first, source, file);
287 // Do we need to perform the conversion?
288 // Yes if to_file does not exist or if from_file is newer than to_file
289 if (support::compare_timestamps(temp_file, abs_to_file) < 0)
291 string const to_file_base =
292 support::ChangeExtension(to_file, string());
293 /* bool const success = */
294 converters.convert(&buffer, temp_file, to_file_base,
295 from_format, to_format, true);
300 string const substituteCommands(InsetExternalParams const & params,
301 string const & input, string const & format);
303 string const substituteOptions(InsetExternalParams const & params,
304 string const & input, string const & format);
309 int writeExternal(InsetExternalParams const & params,
310 string const & format,
311 Buffer const & buffer, ostream & os,
312 ExportData & exportdata,
313 bool external_in_tmpdir)
315 Template const * const et_ptr = getTemplatePtr(params);
318 Template const & et = *et_ptr;
320 Template::Formats::const_iterator cit = et.formats.find(format);
321 if (cit == et.formats.end()) {
322 lyxerr[Debug::EXTERNAL]
323 << "External template format '" << format
324 << "' not specified in template "
325 << params.templatename() << endl;
329 updateExternal(params, format, buffer, exportdata, external_in_tmpdir);
331 bool const use_latex_path = format == "LaTeX";
332 string str = doSubstitution(params, buffer, cit->second.product,
333 use_latex_path, external_in_tmpdir);
334 str = substituteCommands(params, str, format);
335 str = substituteOptions(params, str, format);
337 return int(lyx::count(str.begin(), str.end(),'\n'));
342 // Empty template, specialised below.
343 template <typename TransformType>
344 string const substituteIt(string const &,
347 Template::Format const &,
348 InsetExternalParams const &);
352 string const substituteIt<TransformCommand>(string const & input,
354 string const & /* formatname */,
355 Template::Format const & format,
356 InsetExternalParams const & params)
358 typedef std::map<TransformID, TransformStore> Transformers;
359 Transformers::const_iterator it = format.command_transformers.find(id);
360 if (it == format.command_transformers.end())
363 TransformStore const & store = it->second;
365 TransformCommand::ptr_type ptr;
367 ptr = store.getCommandTransformer(params.rotationdata);
368 else if (id == Resize)
369 ptr = store.getCommandTransformer(params.resizedata);
375 support::subst(input, ptr->front_placeholder(), ptr->front());
376 return support::subst(result, ptr->back_placeholder(), ptr->back());
381 string const substituteIt<TransformOption>(string const & input,
383 string const & fname,
384 Template::Format const & format,
385 InsetExternalParams const & params)
387 typedef std::map<TransformID, TransformStore> Transformers;
388 Transformers::const_iterator it = format.option_transformers.find(id);
389 if (it == format.option_transformers.end())
392 TransformStore const & store = it->second;
394 TransformOption::ptr_type ptr;
397 ptr = store.getOptionTransformer(params.clipdata);
400 ptr = store.getOptionTransformer(params.extradata.get(fname));
403 ptr = store.getOptionTransformer(params.rotationdata);
406 ptr = store.getOptionTransformer(params.resizedata);
413 return support::subst(input, ptr->placeholder(), ptr->option());
417 template <typename TransformerType>
418 string const transformIt(InsetExternalParams const & params,
419 string const & s, string const & formatname)
421 Template const * const et = getTemplatePtr(params);
422 if (!et || et->transformIds.empty())
425 Template::Formats::const_iterator fit = et->formats.find(formatname);
426 if (fit == et->formats.end())
430 Template::Format const & format = fit->second;
432 typedef vector<TransformID> TransformsIDs;
433 TransformsIDs::const_iterator it = et->transformIds.begin();
434 TransformsIDs::const_iterator end = et->transformIds.end();
435 for (; it != end; ++it) {
436 result = substituteIt<TransformerType>(result, *it, formatname,
443 string const substituteCommands(InsetExternalParams const & params,
444 string const & input, string const & format)
446 return transformIt<TransformCommand>(params, input, format);
450 string const substituteOption(InsetExternalParams const & params,
451 string const & input, string const & format)
453 string opt = transformIt<TransformOption>(params, input, format);
455 if (format == "LaTeX" || format == "PDFLaTeX")
456 return sanitizeLatexOption(opt);
457 if (format == "DocBook")
458 return sanitizeDocBookOption(opt);
459 if (format == "LinuxDoc")
460 return sanitizeLinuxDocOption(opt);
465 string const substituteOptions(InsetExternalParams const & params,
466 string const & input, string const & format)
468 string output = input;
470 Template const * const et = getTemplatePtr(params);
471 if (!et || et->transformIds.empty())
474 Template::Formats::const_iterator fit = et->formats.find(format);
475 if (fit == et->formats.end() || fit->second.options.empty())
478 typedef vector<Template::Option> Options;
479 Options const & options = fit->second.options;
480 Options::const_iterator it = options.begin();
481 Options::const_iterator end = options.end();
482 for (; it != end; ++it) {
483 string const opt = substituteOption(params, it->option, format);
484 string const placeholder = "$$" + it->name;
485 output = support::subst(output, placeholder, opt);
493 } // namespace external