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"
38 #include <boost/filesystem/operations.hpp>
44 using boost::filesystem::is_directory;
49 using support::FileName;
50 using support::isValidLaTeXFilename;
54 Template const * getTemplatePtr(InsetExternalParams const & params)
56 TemplateManager const & etm = TemplateManager::get();
57 return etm.getTemplateByName(params.templatename());
61 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
63 formats.edit(buffer, params.filename,
64 formats.getFormatFromFile(params.filename));
70 string const subst_path(string const & input,
71 string const & placeholder,
74 support::latex_path_extension ext = support::PROTECT_EXTENSION,
75 support::latex_path_dots dots = support::LEAVE_DOTS)
77 if (input.find(placeholder) == string::npos)
79 // Don't use external_path here when use_latex_path is false, as the
80 // path will be compared with another one in internal style later
81 // in Converters::move.
82 string const path2 = use_latex_path ?
83 support::latex_path(path, ext, dots) : path;
84 return support::subst(input, placeholder, path2);
90 string const doSubstitution(InsetExternalParams const & params,
91 Buffer const & buffer, string const & s,
93 bool external_in_tmpdir,
96 Buffer const * m_buffer = buffer.getMasterBuffer();
97 string const parentpath = external_in_tmpdir ?
98 m_buffer->temppath() :
100 string const filename = external_in_tmpdir ?
101 params.filename.mangledFilename() :
102 params.filename.outputFilename(parentpath);
103 string const basename = support::changeExtension(
104 support::onlyFilename(filename), string());
105 string const absname = support::makeAbsPath(filename, parentpath).absFilename();
108 if (what != ALL_BUT_PATHS) {
109 string const filepath = support::onlyPath(filename);
110 string const abspath = support::onlyPath(absname);
111 string const masterpath = external_in_tmpdir ?
112 m_buffer->temppath() :
113 m_buffer->filePath();
115 string relToMasterPath = support::onlyPath(
116 to_utf8(support::makeRelPath(from_utf8(absname),
117 from_utf8(masterpath))));
118 if (relToMasterPath == "./")
119 relToMasterPath.clear();
121 string relToParentPath = support::onlyPath(
122 to_utf8(support::makeRelPath(from_utf8(absname),
123 from_utf8(parentpath))));
124 if (relToParentPath == "./")
125 relToParentPath.clear();
127 result = subst_path(result, "$$FPath", filepath,
129 support::PROTECT_EXTENSION,
130 support::ESCAPE_DOTS);
131 result = subst_path(result, "$$AbsPath", abspath,
133 support::PROTECT_EXTENSION,
134 support::ESCAPE_DOTS);
135 result = subst_path(result, "$$RelPathMaster",
136 relToMasterPath, use_latex_path,
137 support::PROTECT_EXTENSION,
138 support::ESCAPE_DOTS);
139 result = subst_path(result, "$$RelPathParent",
140 relToParentPath, use_latex_path,
141 support::PROTECT_EXTENSION,
142 support::ESCAPE_DOTS);
143 if (support::absolutePath(filename)) {
144 result = subst_path(result, "$$AbsOrRelPathMaster",
145 abspath, use_latex_path,
146 support::PROTECT_EXTENSION,
147 support::ESCAPE_DOTS);
148 result = subst_path(result, "$$AbsOrRelPathParent",
149 abspath, use_latex_path,
150 support::PROTECT_EXTENSION,
151 support::ESCAPE_DOTS);
153 result = subst_path(result, "$$AbsOrRelPathMaster",
154 relToMasterPath, use_latex_path,
155 support::PROTECT_EXTENSION,
156 support::ESCAPE_DOTS);
157 result = subst_path(result, "$$AbsOrRelPathParent",
158 relToParentPath, use_latex_path,
159 support::PROTECT_EXTENSION,
160 support::ESCAPE_DOTS);
167 result = subst_path(result, "$$FName", filename, use_latex_path,
168 support::EXCLUDE_EXTENSION);
169 result = subst_path(result, "$$Basename", basename, use_latex_path,
170 support::PROTECT_EXTENSION, support::ESCAPE_DOTS);
171 result = subst_path(result, "$$Extension",
172 '.' + support::getExtension(filename), use_latex_path);
173 result = subst_path(result, "$$Tempname", params.tempname().absFilename(), use_latex_path);
174 result = subst_path(result, "$$Sysdir",
175 support::package().system_support().absFilename(), use_latex_path);
177 // Handle the $$Contents(filename) syntax
178 if (support::contains(result, "$$Contents(\"")) {
179 // Since use_latex_path may be true we must extract the file
180 // name from s instead of result and do the substitutions
181 // again, this time with use_latex_path false.
182 string::size_type const spos = s.find("$$Contents(\"");
183 string::size_type const send = s.find("\")", spos);
184 string const file_template = s.substr(spos + 12, send - (spos + 12));
185 string const file = doSubstitution(params, buffer,
186 file_template, false,
187 external_in_tmpdir, what);
190 FileName const absfile(
191 support::makeAbsPath(file, m_buffer->temppath()));
192 if (support::isFileReadable(absfile))
193 contents = support::getFileContents(absfile);
195 string::size_type const pos = result.find("$$Contents(\"");
196 string::size_type const end = result.find("\")", pos);
197 result.replace(pos, end + 2, contents);
206 /** update the file represented by the template.
207 If \p external_in_tmpdir == true, then the generated file is
208 placed in the buffer's temporary directory.
210 void updateExternal(InsetExternalParams const & params,
211 string const & format,
212 Buffer const & buffer,
213 ExportData & exportdata,
214 bool external_in_tmpdir,
217 Template const * const et_ptr = getTemplatePtr(params);
220 Template const & et = *et_ptr;
222 if (!et.automaticProduction)
223 return; // NOT_NEEDED
225 Template::Formats::const_iterator cit = et.formats.find(format);
226 if (cit == et.formats.end())
229 Template::Format const & outputFormat = cit->second;
230 if (outputFormat.updateResult.empty())
231 return; // NOT_NEEDED
233 string from_format = et.inputFormat;
234 if (from_format.empty())
235 return; // NOT_NEEDED
237 if (from_format == "*") {
238 if (params.filename.empty())
239 return; // NOT_NEEDED
241 // Try and ascertain the file format from its contents.
242 from_format = formats.getFormatFromFile(params.filename);
243 if (from_format.empty())
248 string const to_format = outputFormat.updateFormat;
249 if (to_format.empty())
250 return; // NOT_NEEDED
252 // The master buffer. This is useful when there are multiple levels
254 Buffer const * m_buffer = buffer.getMasterBuffer();
256 // We copy the source file to the temp dir and do the conversion
257 // there if necessary
258 FileName const temp_file(
259 support::makeAbsPath(params.filename.mangledFilename(),
260 m_buffer->temppath()));
261 if (!params.filename.empty() && !is_directory(params.filename.toFilesystemEncoding())) {
262 unsigned long const from_checksum = support::sum(params.filename);
263 unsigned long const temp_checksum = support::sum(temp_file);
265 if (from_checksum != temp_checksum) {
266 Mover const & mover = getMover(from_format);
267 if (!mover.copy(params.filename, temp_file)) {
268 LYXERR(Debug::EXTERNAL)
269 << "external::updateExternal. "
271 << params.filename << " to " << temp_file << endl;
277 // the generated file (always in the temp dir)
278 string const to_file = doSubstitution(params, buffer,
279 outputFormat.updateResult,
281 FileName const abs_to_file(
282 support::makeAbsPath(to_file, m_buffer->temppath()));
285 // Record the referenced files for the exporter.
286 // The exporter will copy them to the export dir.
287 typedef Template::Format::FileMap FileMap;
288 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
289 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
290 for (; rit != rend; ++rit) {
291 vector<string>::const_iterator fit = rit->second.begin();
292 vector<string>::const_iterator fend = rit->second.end();
293 for (; fit != fend; ++fit) {
294 FileName const source(support::makeAbsPath(
295 doSubstitution(params, buffer, *fit,
297 m_buffer->temppath()));
298 // The path of the referenced file is never the
299 // temp path, but the filename may be the mangled
300 // or the real name. Therefore we substitute the
301 // paths and names separately.
302 string file = support::subst(*fit, "$$FName",
303 "$$FPath$$Basename$$Extension");
304 file = doSubstitution(params, buffer, file, false, false,
306 file = doSubstitution(params, buffer, file,
307 false, external_in_tmpdir,
309 // if file is a relative name, it is interpreted
310 // relative to the master document.
311 exportdata.addExternalFile(rit->first, source, file);
316 // Do we need to perform the conversion?
317 // Yes if to_file does not exist or if from_file is newer than to_file
318 if (support::compare_timestamps(temp_file, abs_to_file) < 0)
321 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
324 theConverters().convert(&buffer, temp_file, abs_to_file,
325 params.filename, from_format, to_format, el,
326 Converters::try_default | Converters::try_cache);
329 LYXERR(Debug::EXTERNAL)
330 << "external::updateExternal. "
331 << "Unable to convert from "
332 << from_format << " to " << to_format << endl;
338 string const substituteCommands(InsetExternalParams const & params,
339 string const & input, string const & format);
341 string const substituteOptions(InsetExternalParams const & params,
342 string const & input, string const & format);
347 int writeExternal(InsetExternalParams const & params,
348 string const & format,
349 Buffer const & buffer, odocstream & os,
350 ExportData & exportdata,
351 bool external_in_tmpdir,
354 Template const * const et_ptr = getTemplatePtr(params);
357 Template const & et = *et_ptr;
359 Template::Formats::const_iterator cit = et.formats.find(format);
360 if (cit == et.formats.end()) {
361 LYXERR(Debug::EXTERNAL)
362 << "External template format '" << format
363 << "' not specified in template "
364 << params.templatename() << endl;
368 if (!dryrun || support::contains(cit->second.product, "$$Contents"))
369 updateExternal(params, format, buffer, exportdata,
370 external_in_tmpdir, dryrun);
372 bool const use_latex_path = format == "LaTeX";
373 string str = doSubstitution(params, buffer, cit->second.product,
374 use_latex_path, external_in_tmpdir);
376 string const absname = support::makeAbsPath(
377 params.filename.outputFilename(buffer.filePath()), buffer.filePath()).absFilename();
379 if (!external_in_tmpdir && !isValidLaTeXFilename(absname)) {
380 lyx::frontend::Alert::warning(_("Invalid filename"),
381 _("The following filename is likely to cause trouble "
382 "when running the exported file through LaTeX: ") +
386 str = substituteCommands(params, str, format);
387 str = substituteOptions(params, str, format);
389 os << from_utf8(str);
390 return int(lyx::count(str.begin(), str.end(),'\n'));
395 // Empty template, specialised below.
396 template <typename TransformType>
397 string const substituteIt(string const &,
400 Template::Format const &,
401 InsetExternalParams const &);
405 string const substituteIt<TransformCommand>(string const & input,
407 string const & /* formatname */,
408 Template::Format const & format,
409 InsetExternalParams const & params)
411 typedef std::map<TransformID, TransformStore> Transformers;
412 Transformers::const_iterator it = format.command_transformers.find(id);
413 if (it == format.command_transformers.end())
416 TransformStore const & store = it->second;
418 TransformCommand::ptr_type ptr;
420 ptr = store.getCommandTransformer(params.rotationdata);
421 else if (id == Resize)
422 ptr = store.getCommandTransformer(params.resizedata);
428 support::subst(input, ptr->front_placeholder(), ptr->front());
429 return support::subst(result, ptr->back_placeholder(), ptr->back());
434 string const substituteIt<TransformOption>(string const & input,
436 string const & fname,
437 Template::Format const & format,
438 InsetExternalParams const & params)
440 typedef std::map<TransformID, TransformStore> Transformers;
441 Transformers::const_iterator it = format.option_transformers.find(id);
442 if (it == format.option_transformers.end())
445 TransformStore const & store = it->second;
447 TransformOption::ptr_type ptr;
450 ptr = store.getOptionTransformer(params.clipdata);
453 ptr = store.getOptionTransformer(params.extradata.get(fname));
456 ptr = store.getOptionTransformer(params.rotationdata);
459 ptr = store.getOptionTransformer(params.resizedata);
466 return support::subst(input, ptr->placeholder(), ptr->option());
470 template <typename TransformerType>
471 string const transformIt(InsetExternalParams const & params,
472 string const & s, string const & formatname)
474 Template const * const et = getTemplatePtr(params);
475 if (!et || et->transformIds.empty())
478 Template::Formats::const_iterator fit = et->formats.find(formatname);
479 if (fit == et->formats.end())
483 Template::Format const & format = fit->second;
485 typedef vector<TransformID> TransformsIDs;
486 TransformsIDs::const_iterator it = et->transformIds.begin();
487 TransformsIDs::const_iterator end = et->transformIds.end();
488 for (; it != end; ++it) {
489 result = substituteIt<TransformerType>(result, *it, formatname,
496 string const substituteCommands(InsetExternalParams const & params,
497 string const & input, string const & format)
499 return transformIt<TransformCommand>(params, input, format);
503 string const substituteOption(InsetExternalParams const & params,
504 string const & input, string const & format)
506 string opt = transformIt<TransformOption>(params, input, format);
508 if (format == "LaTeX" || format == "PDFLaTeX")
509 return sanitizeLatexOption(opt);
510 if (format == "DocBook")
511 return sanitizeDocBookOption(opt);
516 string const substituteOptions(InsetExternalParams const & params,
517 string const & input, string const & format)
519 string output = input;
521 Template const * const et = getTemplatePtr(params);
522 if (!et || et->transformIds.empty())
525 Template::Formats::const_iterator fit = et->formats.find(format);
526 if (fit == et->formats.end() || fit->second.options.empty())
529 typedef vector<Template::Option> Options;
530 Options const & options = fit->second.options;
531 Options::const_iterator it = options.begin();
532 Options::const_iterator end = options.end();
533 for (; it != end; ++it) {
534 string const opt = substituteOption(params, it->option, format);
535 string const placeholder = "$$" + it->name;
536 output = support::subst(output, placeholder, opt);
544 } // namespace external