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"
34 #include <boost/filesystem/operations.hpp>
40 using boost::filesystem::is_directory;
45 using support::FileName;
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 formats.edit(buffer, params.filename,
59 formats.getFormatFromFile(params.filename));
65 string const subst_path(string const & input,
66 string const & placeholder,
69 support::latex_path_extension ext = support::PROTECT_EXTENSION,
70 support::latex_path_dots dots = support::LEAVE_DOTS)
72 if (input.find(placeholder) == string::npos)
74 // Don't use external_path here when use_latex_path is false, as the
75 // path will be compared with another one in internal style later
76 // in Converters::move.
77 string const path2 = use_latex_path ?
78 support::latex_path(path, ext, dots) : path;
79 return support::subst(input, placeholder, path2);
85 string const doSubstitution(InsetExternalParams const & params,
86 Buffer const & buffer, string const & s,
88 bool external_in_tmpdir,
91 Buffer const * m_buffer = buffer.getMasterBuffer();
92 string const parentpath = external_in_tmpdir ?
93 m_buffer->temppath() :
95 string const filename = external_in_tmpdir ?
96 params.filename.mangledFilename() :
97 params.filename.outputFilename(parentpath);
98 string const basename = support::changeExtension(
99 support::onlyFilename(filename), string());
100 string const absname = support::makeAbsPath(filename, parentpath).absFilename();
103 if (what != ALL_BUT_PATHS) {
104 string const filepath = support::onlyPath(filename);
105 string const abspath = support::onlyPath(absname);
106 string const masterpath = external_in_tmpdir ?
107 m_buffer->temppath() :
108 m_buffer->filePath();
109 string relToMasterPath = support::onlyPath(
110 support::makeRelPath(absname, masterpath));
111 if (relToMasterPath == "./")
112 relToMasterPath.clear();
113 string relToParentPath = support::onlyPath(
114 support::makeRelPath(absname, parentpath));
115 if (relToParentPath == "./")
116 relToParentPath.clear();
118 result = subst_path(result, "$$FPath", filepath,
120 support::PROTECT_EXTENSION,
121 support::ESCAPE_DOTS);
122 result = subst_path(result, "$$AbsPath", abspath,
124 support::PROTECT_EXTENSION,
125 support::ESCAPE_DOTS);
126 result = subst_path(result, "$$RelPathMaster",
127 relToMasterPath, use_latex_path,
128 support::PROTECT_EXTENSION,
129 support::ESCAPE_DOTS);
130 result = subst_path(result, "$$RelPathParent",
131 relToParentPath, use_latex_path,
132 support::PROTECT_EXTENSION,
133 support::ESCAPE_DOTS);
134 if (support::absolutePath(filename)) {
135 result = subst_path(result, "$$AbsOrRelPathMaster",
136 abspath, use_latex_path,
137 support::PROTECT_EXTENSION,
138 support::ESCAPE_DOTS);
139 result = subst_path(result, "$$AbsOrRelPathParent",
140 abspath, use_latex_path,
141 support::PROTECT_EXTENSION,
142 support::ESCAPE_DOTS);
144 result = subst_path(result, "$$AbsOrRelPathMaster",
145 relToMasterPath, use_latex_path,
146 support::PROTECT_EXTENSION,
147 support::ESCAPE_DOTS);
148 result = subst_path(result, "$$AbsOrRelPathParent",
149 relToParentPath, use_latex_path,
150 support::PROTECT_EXTENSION,
151 support::ESCAPE_DOTS);
158 result = subst_path(result, "$$FName", filename, use_latex_path,
159 support::EXCLUDE_EXTENSION);
160 result = subst_path(result, "$$Basename", basename, use_latex_path,
161 support::PROTECT_EXTENSION, support::ESCAPE_DOTS);
162 result = subst_path(result, "$$Extension",
163 '.' + support::getExtension(filename), use_latex_path);
164 result = subst_path(result, "$$Tempname", params.tempname().absFilename(), use_latex_path);
165 result = subst_path(result, "$$Sysdir",
166 support::package().system_support(), use_latex_path);
168 // Handle the $$Contents(filename) syntax
169 if (support::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 string::size_type const spos = s.find("$$Contents(\"");
174 string::size_type 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 support::makeAbsPath(file, m_buffer->temppath()));
183 if (support::isFileReadable(absfile))
184 contents = support::getFileContents(absfile);
186 string::size_type const pos = result.find("$$Contents(\"");
187 string::size_type const end = result.find("\")", pos);
188 result.replace(pos, end + 2, contents);
197 /** update the file represented by the template.
198 If \p external_in_tmpdir == true, then the generated file is
199 placed in the buffer's temporary directory.
201 void updateExternal(InsetExternalParams const & params,
202 string const & format,
203 Buffer const & buffer,
204 ExportData & exportdata,
205 bool external_in_tmpdir,
208 Template const * const et_ptr = getTemplatePtr(params);
211 Template const & et = *et_ptr;
213 if (!et.automaticProduction)
214 return; // NOT_NEEDED
216 Template::Formats::const_iterator cit = et.formats.find(format);
217 if (cit == et.formats.end())
220 Template::Format const & outputFormat = cit->second;
221 if (outputFormat.updateResult.empty())
222 return; // NOT_NEEDED
224 string from_format = et.inputFormat;
225 if (from_format.empty())
226 return; // NOT_NEEDED
228 if (from_format == "*") {
229 if (params.filename.empty())
230 return; // NOT_NEEDED
232 // Try and ascertain the file format from its contents.
233 from_format = formats.getFormatFromFile(params.filename);
234 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 * m_buffer = buffer.getMasterBuffer();
247 // We copy the source file to the temp dir and do the conversion
248 // there if necessary
249 FileName const temp_file(
250 support::makeAbsPath(params.filename.mangledFilename(),
251 m_buffer->temppath()));
252 if (!params.filename.empty() && !is_directory(params.filename.toFilesystemEncoding())) {
253 unsigned long const from_checksum = support::sum(params.filename);
254 unsigned long const temp_checksum = support::sum(temp_file);
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]
260 << "external::updateExternal. "
262 << params.filename << " to " << temp_file << endl;
268 // the generated file (always in the temp dir)
269 string const to_file = doSubstitution(params, buffer,
270 outputFormat.updateResult,
272 FileName const abs_to_file(
273 support::makeAbsPath(to_file, m_buffer->temppath()));
276 // Record the referenced files for the exporter.
277 // The exporter will copy them to the export dir.
278 typedef Template::Format::FileMap FileMap;
279 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
280 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
281 for (; rit != rend; ++rit) {
282 vector<string>::const_iterator fit = rit->second.begin();
283 vector<string>::const_iterator fend = rit->second.end();
284 for (; fit != fend; ++fit) {
285 FileName const source(support::makeAbsPath(
286 doSubstitution(params, buffer, *fit,
288 m_buffer->temppath()));
289 // The path of the referenced file is never the
290 // temp path, but the filename may be the mangled
291 // or the real name. Therefore we substitute the
292 // paths and names separately.
293 string file = support::subst(*fit, "$$FName",
294 "$$FPath$$Basename$$Extension");
295 file = doSubstitution(params, buffer, file, false, false,
297 file = doSubstitution(params, buffer, file,
298 false, external_in_tmpdir,
300 // if file is a relative name, it is interpreted
301 // relative to the master document.
302 exportdata.addExternalFile(rit->first, source, file);
307 // Do we need to perform the conversion?
308 // Yes if to_file does not exist or if from_file is newer than to_file
309 if (support::compare_timestamps(temp_file, abs_to_file) < 0)
312 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
315 theConverters().convert(&buffer, temp_file, abs_to_file,
316 params.filename, from_format, to_format, el,
317 Converters::try_default | Converters::try_cache);
320 lyxerr[Debug::EXTERNAL]
321 << "external::updateExternal. "
322 << "Unable to convert from "
323 << from_format << " to " << to_format << endl;
329 string const substituteCommands(InsetExternalParams const & params,
330 string const & input, string const & format);
332 string const substituteOptions(InsetExternalParams const & params,
333 string const & input, string const & format);
338 int writeExternal(InsetExternalParams const & params,
339 string const & format,
340 Buffer const & buffer, odocstream & os,
341 ExportData & exportdata,
342 bool external_in_tmpdir,
345 Template const * const et_ptr = getTemplatePtr(params);
348 Template const & et = *et_ptr;
350 Template::Formats::const_iterator cit = et.formats.find(format);
351 if (cit == et.formats.end()) {
352 lyxerr[Debug::EXTERNAL]
353 << "External template format '" << format
354 << "' not specified in template "
355 << params.templatename() << endl;
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);
366 str = substituteCommands(params, str, format);
367 str = substituteOptions(params, str, format);
369 os << from_utf8(str);
370 return int(lyx::count(str.begin(), str.end(),'\n'));
375 // Empty template, specialised below.
376 template <typename TransformType>
377 string const substituteIt(string const &,
380 Template::Format const &,
381 InsetExternalParams const &);
385 string const substituteIt<TransformCommand>(string const & input,
387 string const & /* formatname */,
388 Template::Format const & format,
389 InsetExternalParams const & params)
391 typedef std::map<TransformID, TransformStore> Transformers;
392 Transformers::const_iterator it = format.command_transformers.find(id);
393 if (it == format.command_transformers.end())
396 TransformStore const & store = it->second;
398 TransformCommand::ptr_type ptr;
400 ptr = store.getCommandTransformer(params.rotationdata);
401 else if (id == Resize)
402 ptr = store.getCommandTransformer(params.resizedata);
408 support::subst(input, ptr->front_placeholder(), ptr->front());
409 return support::subst(result, ptr->back_placeholder(), ptr->back());
414 string const substituteIt<TransformOption>(string const & input,
416 string const & fname,
417 Template::Format const & format,
418 InsetExternalParams const & params)
420 typedef std::map<TransformID, TransformStore> Transformers;
421 Transformers::const_iterator it = format.option_transformers.find(id);
422 if (it == format.option_transformers.end())
425 TransformStore const & store = it->second;
427 TransformOption::ptr_type ptr;
430 ptr = store.getOptionTransformer(params.clipdata);
433 ptr = store.getOptionTransformer(params.extradata.get(fname));
436 ptr = store.getOptionTransformer(params.rotationdata);
439 ptr = store.getOptionTransformer(params.resizedata);
446 return support::subst(input, ptr->placeholder(), ptr->option());
450 template <typename TransformerType>
451 string const transformIt(InsetExternalParams const & params,
452 string const & s, string const & formatname)
454 Template const * const et = getTemplatePtr(params);
455 if (!et || et->transformIds.empty())
458 Template::Formats::const_iterator fit = et->formats.find(formatname);
459 if (fit == et->formats.end())
463 Template::Format const & format = fit->second;
465 typedef vector<TransformID> TransformsIDs;
466 TransformsIDs::const_iterator it = et->transformIds.begin();
467 TransformsIDs::const_iterator end = et->transformIds.end();
468 for (; it != end; ++it) {
469 result = substituteIt<TransformerType>(result, *it, formatname,
476 string const substituteCommands(InsetExternalParams const & params,
477 string const & input, string const & format)
479 return transformIt<TransformCommand>(params, input, format);
483 string const substituteOption(InsetExternalParams const & params,
484 string const & input, string const & format)
486 string opt = transformIt<TransformOption>(params, input, format);
488 if (format == "LaTeX" || format == "PDFLaTeX")
489 return sanitizeLatexOption(opt);
490 if (format == "DocBook")
491 return sanitizeDocBookOption(opt);
496 string const substituteOptions(InsetExternalParams const & params,
497 string const & input, string const & format)
499 string output = input;
501 Template const * const et = getTemplatePtr(params);
502 if (!et || et->transformIds.empty())
505 Template::Formats::const_iterator fit = et->formats.find(format);
506 if (fit == et->formats.end() || fit->second.options.empty())
509 typedef vector<Template::Option> Options;
510 Options const & options = fit->second.options;
511 Options::const_iterator it = options.begin();
512 Options::const_iterator end = options.end();
513 for (; it != end; ++it) {
514 string const opt = substituteOption(params, it->option, format);
515 string const placeholder = "$$" + it->name;
516 output = support::subst(output, placeholder, opt);
524 } // namespace external