]> git.lyx.org Git - lyx.git/blob - src/insets/ExternalSupport.cpp
Fix Bug 3947: BibTeX allows parentheses in the key (even if the whole entry is delimi...
[lyx.git] / src / insets / ExternalSupport.cpp
1 /**
2  * \file ExternalSupport.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup Nielsen
7  * \author Angus Leeming
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "ExternalSupport.h"
15 #include "ExternalTemplate.h"
16 #include "ExternalTransforms.h"
17 #include "InsetExternal.h"
18
19 #include "Buffer.h"
20 #include "Converter.h"
21 #include "debug.h"
22 #include "gettext.h"
23 #include "ErrorList.h"
24 #include "Exporter.h"
25 #include "Format.h"
26 #include "Mover.h"
27
28 #include "frontends/alert.h"
29
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"
37
38 #include <boost/filesystem/operations.hpp>
39
40 using std::endl;
41 using std::string;
42 using std::vector;
43
44 using boost::filesystem::is_directory;
45
46
47 namespace lyx {
48
49 using support::FileName;
50 using support::isValidLaTeXFilename;
51
52 namespace external {
53
54 Template const * getTemplatePtr(InsetExternalParams const & params)
55 {
56         TemplateManager const & etm = TemplateManager::get();
57         return etm.getTemplateByName(params.templatename());
58 }
59
60
61 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
62 {
63         formats.edit(buffer, params.filename,
64                      formats.getFormatFromFile(params.filename));
65 }
66
67
68 namespace {
69
70 string const subst_path(string const & input,
71                         string const & placeholder,
72                         string const & path,
73                         bool use_latex_path,
74                         support::latex_path_extension ext = support::PROTECT_EXTENSION,
75                         support::latex_path_dots dots = support::LEAVE_DOTS)
76 {
77         if (input.find(placeholder) == string::npos)
78                 return input;
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);
85 }
86
87 } // namespace anon
88
89
90 string const doSubstitution(InsetExternalParams const & params,
91                             Buffer const & buffer, string const & s,
92                             bool use_latex_path,
93                             bool external_in_tmpdir,
94                             Substitute what)
95 {
96         Buffer const * m_buffer = buffer.getMasterBuffer();
97         string const parentpath = external_in_tmpdir ?
98                 m_buffer->temppath() :
99                 buffer.filePath();
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();
106
107         string result = s;
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();
114                 // FIXME UNICODE
115                 string relToMasterPath = support::onlyPath(
116                                 to_utf8(support::makeRelPath(from_utf8(absname),
117                                                              from_utf8(masterpath))));
118                 if (relToMasterPath == "./")
119                         relToMasterPath.clear();
120                 // FIXME UNICODE
121                 string relToParentPath = support::onlyPath(
122                                 to_utf8(support::makeRelPath(from_utf8(absname),
123                                                              from_utf8(parentpath))));
124                 if (relToParentPath == "./")
125                         relToParentPath.clear();
126
127                 result = subst_path(result, "$$FPath", filepath,
128                                     use_latex_path,
129                                     support::PROTECT_EXTENSION,
130                                     support::ESCAPE_DOTS);
131                 result = subst_path(result, "$$AbsPath", abspath,
132                                     use_latex_path,
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);
152                 } else {
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);
161                 }
162         }
163
164         if (what == PATHS)
165                 return result;
166
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);
176
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);
188                 string contents;
189
190                 FileName const absfile(
191                         support::makeAbsPath(file, m_buffer->temppath()));
192                 if (support::isFileReadable(absfile))
193                         contents = support::getFileContents(absfile);
194
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);
198         }
199
200         return result;
201 }
202
203
204 namespace {
205
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.
209 */
210 void updateExternal(InsetExternalParams const & params,
211                     string const & format,
212                     Buffer const & buffer,
213                     ExportData & exportdata,
214                     bool external_in_tmpdir,
215                     bool dryrun)
216 {
217         Template const * const et_ptr = getTemplatePtr(params);
218         if (!et_ptr)
219                 return; // FAILURE
220         Template const & et = *et_ptr;
221
222         if (!et.automaticProduction)
223                 return; // NOT_NEEDED
224
225         Template::Formats::const_iterator cit = et.formats.find(format);
226         if (cit == et.formats.end())
227                 return; // FAILURE
228
229         Template::Format const & outputFormat = cit->second;
230         if (outputFormat.updateResult.empty())
231                 return; // NOT_NEEDED
232
233         string from_format = et.inputFormat;
234         if (from_format.empty())
235                 return; // NOT_NEEDED
236
237         if (from_format == "*") {
238                 if (params.filename.empty())
239                         return; // NOT_NEEDED
240
241                 // Try and ascertain the file format from its contents.
242                 from_format = formats.getFormatFromFile(params.filename);
243                 if (from_format.empty())
244                         return; // FAILURE
245
246         }
247
248         string const to_format = outputFormat.updateFormat;
249         if (to_format.empty())
250                 return; // NOT_NEEDED
251
252         // The master buffer. This is useful when there are multiple levels
253         // of include files
254         Buffer const * m_buffer = buffer.getMasterBuffer();
255
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);
264
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. "
270                                         << "Unable to copy "
271                                         << params.filename << " to " << temp_file << endl;
272                                 return; // FAILURE
273                         }
274                 }
275         }
276
277         // the generated file (always in the temp dir)
278         string const to_file = doSubstitution(params, buffer,
279                                               outputFormat.updateResult,
280                                               false, true);
281         FileName const abs_to_file(
282                 support::makeAbsPath(to_file, m_buffer->temppath()));
283
284         if (!dryrun) {
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,
296                                                                false, true),
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,
305                                                       PATHS);
306                                 file = doSubstitution(params, buffer, file,
307                                                       false, external_in_tmpdir,
308                                                       ALL_BUT_PATHS);
309                                 // if file is a relative name, it is interpreted
310                                 // relative to the master document.
311                                 exportdata.addExternalFile(rit->first, source, file);
312                         }
313                 }
314         }
315
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)
319                 return; // SUCCESS
320
321         // FIXME (Abdel 12/08/06): Is there a need to show these errors?
322         ErrorList el;
323         bool const success =
324                 theConverters().convert(&buffer, temp_file, abs_to_file,
325                                    params.filename, from_format, to_format, el,
326                                    Converters::try_default | Converters::try_cache);
327
328         if (!success)
329                 LYXERR(Debug::EXTERNAL)
330                         << "external::updateExternal. "
331                         << "Unable to convert from "
332                         << from_format << " to " << to_format << endl;
333
334         // return success
335 }
336
337
338 string const substituteCommands(InsetExternalParams const & params,
339                                 string const & input, string const & format);
340
341 string const substituteOptions(InsetExternalParams const & params,
342                                string const & input, string const & format);
343
344 } // namespace anon
345
346
347 int writeExternal(InsetExternalParams const & params,
348                   string const & format,
349                   Buffer const & buffer, odocstream & os,
350                   ExportData & exportdata,
351                   bool external_in_tmpdir,
352                   bool dryrun)
353 {
354         Template const * const et_ptr = getTemplatePtr(params);
355         if (!et_ptr)
356                 return 0;
357         Template const & et = *et_ptr;
358
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;
365                 return 0;
366         }
367
368         if (!dryrun || support::contains(cit->second.product, "$$Contents"))
369                 updateExternal(params, format, buffer, exportdata,
370                                external_in_tmpdir, dryrun);
371
372         bool const use_latex_path = format == "LaTeX";
373         string str = doSubstitution(params, buffer, cit->second.product,
374                                     use_latex_path, external_in_tmpdir);
375
376         string const absname = support::makeAbsPath(
377                 params.filename.outputFilename(buffer.filePath()), buffer.filePath()).absFilename();
378
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: ") +
383                                               from_utf8(absname));
384         }
385
386         str = substituteCommands(params, str, format);
387         str = substituteOptions(params, str, format);
388         // FIXME UNICODE
389         os << from_utf8(str);
390         return int(lyx::count(str.begin(), str.end(),'\n'));
391 }
392
393 namespace {
394
395 // Empty template, specialised below.
396 template <typename TransformType>
397 string const substituteIt(string const &,
398                           TransformID,
399                           string const &,
400                           Template::Format const &,
401                           InsetExternalParams const &);
402
403
404 template <>
405 string const substituteIt<TransformCommand>(string const & input,
406                                             TransformID id,
407                                             string const & /* formatname */,
408                                             Template::Format const & format,
409                                             InsetExternalParams const & params)
410 {
411         typedef std::map<TransformID, TransformStore> Transformers;
412         Transformers::const_iterator it = format.command_transformers.find(id);
413         if (it == format.command_transformers.end())
414                 return input;
415
416         TransformStore const & store = it->second;
417
418         TransformCommand::ptr_type ptr;
419         if (id == Rotate)
420                 ptr = store.getCommandTransformer(params.rotationdata);
421         else if (id == Resize)
422                 ptr = store.getCommandTransformer(params.resizedata);
423
424         if (!ptr.get())
425                 return input;
426
427         string result =
428                 support::subst(input, ptr->front_placeholder(), ptr->front());
429         return support::subst(result, ptr->back_placeholder(),  ptr->back());
430 }
431
432
433 template <>
434 string const substituteIt<TransformOption>(string const & input,
435                                            TransformID id,
436                                            string const & fname,
437                                            Template::Format const & format,
438                                            InsetExternalParams const & params)
439 {
440         typedef std::map<TransformID, TransformStore> Transformers;
441         Transformers::const_iterator it = format.option_transformers.find(id);
442         if (it == format.option_transformers.end())
443                 return input;
444
445         TransformStore const & store = it->second;
446
447         TransformOption::ptr_type ptr;
448         switch (id) {
449         case Clip:
450                 ptr = store.getOptionTransformer(params.clipdata);
451                 break;
452         case Extra:
453                 ptr = store.getOptionTransformer(params.extradata.get(fname));
454                 break;
455         case Rotate:
456                 ptr = store.getOptionTransformer(params.rotationdata);
457                 break;
458         case Resize:
459                 ptr = store.getOptionTransformer(params.resizedata);
460                 break;
461         }
462
463         if (!ptr.get())
464                 return input;
465
466         return support::subst(input, ptr->placeholder(), ptr->option());
467 }
468
469
470 template <typename TransformerType>
471 string const transformIt(InsetExternalParams const & params,
472                          string const & s, string const & formatname)
473 {
474         Template const * const et = getTemplatePtr(params);
475         if (!et || et->transformIds.empty())
476                 return s;
477
478         Template::Formats::const_iterator fit = et->formats.find(formatname);
479         if (fit == et->formats.end())
480                 return s;
481
482         string result = s;
483         Template::Format const & format =  fit->second;
484
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,
490                                                        format, params);
491         }
492         return result;
493 }
494
495
496 string const substituteCommands(InsetExternalParams const & params,
497                                 string const & input, string const & format)
498 {
499         return transformIt<TransformCommand>(params, input, format);
500 }
501
502
503 string const substituteOption(InsetExternalParams const & params,
504                               string const & input, string const & format)
505 {
506         string opt = transformIt<TransformOption>(params, input, format);
507
508         if (format == "LaTeX" || format == "PDFLaTeX")
509                 return sanitizeLatexOption(opt);
510         if (format == "DocBook")
511                 return sanitizeDocBookOption(opt);
512         return opt;
513 }
514
515
516 string const substituteOptions(InsetExternalParams const & params,
517                                string const & input, string const & format)
518 {
519         string output = input;
520
521         Template const * const et = getTemplatePtr(params);
522         if (!et || et->transformIds.empty())
523                 return output;
524
525         Template::Formats::const_iterator fit = et->formats.find(format);
526         if (fit == et->formats.end() || fit->second.options.empty())
527                 return output;
528
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);
537         }
538
539         return output;
540 }
541
542 } // namespace anon
543
544 } // namespace external
545
546 } // namespace lyx