]> git.lyx.org Git - lyx.git/blob - src/insets/ExternalSupport.cpp
InsetListings: change the interface of diaplay function and allow AlignLeft. Applied...
[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 "Exporter.h"
23 #include "Format.h"
24 #include "Mover.h"
25
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
34 #include <boost/filesystem/operations.hpp>
35
36 using std::endl;
37 using std::string;
38 using std::vector;
39
40 using boost::filesystem::is_directory;
41
42
43 namespace lyx {
44
45 using support::FileName;
46
47 namespace external {
48
49 Template const * getTemplatePtr(InsetExternalParams const & params)
50 {
51         TemplateManager const & etm = TemplateManager::get();
52         return etm.getTemplateByName(params.templatename());
53 }
54
55
56 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
57 {
58         formats.edit(buffer, params.filename,
59                      formats.getFormatFromFile(params.filename));
60 }
61
62
63 namespace {
64
65 string const subst_path(string const & input,
66                         string const & placeholder,
67                         string const & path,
68                         bool use_latex_path,
69                         support::latex_path_extension ext = support::PROTECT_EXTENSION,
70                         support::latex_path_dots dots = support::LEAVE_DOTS)
71 {
72         if (input.find(placeholder) == string::npos)
73                 return input;
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);
80 }
81
82 } // namespace anon
83
84
85 string const doSubstitution(InsetExternalParams const & params,
86                             Buffer const & buffer, string const & s,
87                             bool use_latex_path,
88                             bool external_in_tmpdir,
89                             Substitute what)
90 {
91         Buffer const * m_buffer = buffer.getMasterBuffer();
92         string const parentpath = external_in_tmpdir ?
93                 m_buffer->temppath() :
94                 buffer.filePath();
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();
101
102         string result = s;
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                 // FIXME UNICODE
110                 string relToMasterPath = support::onlyPath(
111                                 to_utf8(support::makeRelPath(from_utf8(absname),
112                                                              from_utf8(masterpath))));
113                 if (relToMasterPath == "./")
114                         relToMasterPath.clear();
115                 // FIXME UNICODE
116                 string relToParentPath = support::onlyPath(
117                                 to_utf8(support::makeRelPath(from_utf8(absname),
118                                                              from_utf8(parentpath))));
119                 if (relToParentPath == "./")
120                         relToParentPath.clear();
121
122                 result = subst_path(result, "$$FPath", filepath,
123                                     use_latex_path,
124                                     support::PROTECT_EXTENSION,
125                                     support::ESCAPE_DOTS);
126                 result = subst_path(result, "$$AbsPath", abspath,
127                                     use_latex_path,
128                                     support::PROTECT_EXTENSION,
129                                     support::ESCAPE_DOTS);
130                 result = subst_path(result, "$$RelPathMaster",
131                                     relToMasterPath, use_latex_path,
132                                     support::PROTECT_EXTENSION,
133                                     support::ESCAPE_DOTS);
134                 result = subst_path(result, "$$RelPathParent",
135                                     relToParentPath, use_latex_path,
136                                     support::PROTECT_EXTENSION,
137                                     support::ESCAPE_DOTS);
138                 if (support::absolutePath(filename)) {
139                         result = subst_path(result, "$$AbsOrRelPathMaster",
140                                             abspath, use_latex_path,
141                                             support::PROTECT_EXTENSION,
142                                             support::ESCAPE_DOTS);
143                         result = subst_path(result, "$$AbsOrRelPathParent",
144                                             abspath, use_latex_path,
145                                             support::PROTECT_EXTENSION,
146                                             support::ESCAPE_DOTS);
147                 } else {
148                         result = subst_path(result, "$$AbsOrRelPathMaster",
149                                             relToMasterPath, use_latex_path,
150                                             support::PROTECT_EXTENSION,
151                                             support::ESCAPE_DOTS);
152                         result = subst_path(result, "$$AbsOrRelPathParent",
153                                             relToParentPath, use_latex_path,
154                                             support::PROTECT_EXTENSION,
155                                             support::ESCAPE_DOTS);
156                 }
157         }
158
159         if (what == PATHS)
160                 return result;
161
162         result = subst_path(result, "$$FName", filename, use_latex_path,
163                             support::EXCLUDE_EXTENSION);
164         result = subst_path(result, "$$Basename", basename, use_latex_path,
165                             support::PROTECT_EXTENSION, support::ESCAPE_DOTS);
166         result = subst_path(result, "$$Extension",
167                         '.' + support::getExtension(filename), use_latex_path);
168         result = subst_path(result, "$$Tempname", params.tempname().absFilename(), use_latex_path);
169         result = subst_path(result, "$$Sysdir",
170                                 support::package().system_support().absFilename(), use_latex_path);
171
172         // Handle the $$Contents(filename) syntax
173         if (support::contains(result, "$$Contents(\"")) {
174                 // Since use_latex_path may be true we must extract the file
175                 // name from s instead of result and do the substitutions
176                 // again, this time with use_latex_path false.
177                 string::size_type const spos = s.find("$$Contents(\"");
178                 string::size_type const send = s.find("\")", spos);
179                 string const file_template = s.substr(spos + 12, send - (spos + 12));
180                 string const file = doSubstitution(params, buffer,
181                                                    file_template, false,
182                                                    external_in_tmpdir, what);
183                 string contents;
184
185                 FileName const absfile(
186                         support::makeAbsPath(file, m_buffer->temppath()));
187                 if (support::isFileReadable(absfile))
188                         contents = support::getFileContents(absfile);
189
190                 string::size_type const pos = result.find("$$Contents(\"");
191                 string::size_type const end = result.find("\")", pos);
192                 result.replace(pos, end + 2, contents);
193         }
194
195         return result;
196 }
197
198
199 namespace {
200
201 /** update the file represented by the template.
202     If \p external_in_tmpdir == true, then the generated file is
203     placed in the buffer's temporary directory.
204 */
205 void updateExternal(InsetExternalParams const & params,
206                     string const & format,
207                     Buffer const & buffer,
208                     ExportData & exportdata,
209                     bool external_in_tmpdir,
210                     bool dryrun)
211 {
212         Template const * const et_ptr = getTemplatePtr(params);
213         if (!et_ptr)
214                 return; // FAILURE
215         Template const & et = *et_ptr;
216
217         if (!et.automaticProduction)
218                 return; // NOT_NEEDED
219
220         Template::Formats::const_iterator cit = et.formats.find(format);
221         if (cit == et.formats.end())
222                 return; // FAILURE
223
224         Template::Format const & outputFormat = cit->second;
225         if (outputFormat.updateResult.empty())
226                 return; // NOT_NEEDED
227
228         string from_format = et.inputFormat;
229         if (from_format.empty())
230                 return; // NOT_NEEDED
231
232         if (from_format == "*") {
233                 if (params.filename.empty())
234                         return; // NOT_NEEDED
235
236                 // Try and ascertain the file format from its contents.
237                 from_format = formats.getFormatFromFile(params.filename);
238                 if (from_format.empty())
239                         return; // FAILURE
240
241         }
242
243         string const to_format = outputFormat.updateFormat;
244         if (to_format.empty())
245                 return; // NOT_NEEDED
246
247         // The master buffer. This is useful when there are multiple levels
248         // of include files
249         Buffer const * m_buffer = buffer.getMasterBuffer();
250
251         // We copy the source file to the temp dir and do the conversion
252         // there if necessary
253         FileName const temp_file(
254                 support::makeAbsPath(params.filename.mangledFilename(),
255                                      m_buffer->temppath()));
256         if (!params.filename.empty() && !is_directory(params.filename.toFilesystemEncoding())) {
257                 unsigned long const from_checksum = support::sum(params.filename);
258                 unsigned long const temp_checksum = support::sum(temp_file);
259
260                 if (from_checksum != temp_checksum) {
261                         Mover const & mover = getMover(from_format);
262                         if (!mover.copy(params.filename, temp_file)) {
263                                 LYXERR(Debug::EXTERNAL)
264                                         << "external::updateExternal. "
265                                         << "Unable to copy "
266                                         << params.filename << " to " << temp_file << endl;
267                                 return; // FAILURE
268                         }
269                 }
270         }
271
272         // the generated file (always in the temp dir)
273         string const to_file = doSubstitution(params, buffer,
274                                               outputFormat.updateResult,
275                                               false, true);
276         FileName const abs_to_file(
277                 support::makeAbsPath(to_file, m_buffer->temppath()));
278
279         if (!dryrun) {
280                 // Record the referenced files for the exporter.
281                 // The exporter will copy them to the export dir.
282                 typedef Template::Format::FileMap FileMap;
283                 FileMap::const_iterator rit  = outputFormat.referencedFiles.begin();
284                 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
285                 for (; rit != rend; ++rit) {
286                         vector<string>::const_iterator fit  = rit->second.begin();
287                         vector<string>::const_iterator fend = rit->second.end();
288                         for (; fit != fend; ++fit) {
289                                 FileName const source(support::makeAbsPath(
290                                                 doSubstitution(params, buffer, *fit,
291                                                                false, true),
292                                                 m_buffer->temppath()));
293                                 // The path of the referenced file is never the
294                                 // temp path, but the filename may be the mangled
295                                 // or the real name. Therefore we substitute the
296                                 // paths and names separately.
297                                 string file = support::subst(*fit, "$$FName",
298                                                 "$$FPath$$Basename$$Extension");
299                                 file = doSubstitution(params, buffer, file, false, false,
300                                                       PATHS);
301                                 file = doSubstitution(params, buffer, file,
302                                                       false, external_in_tmpdir,
303                                                       ALL_BUT_PATHS);
304                                 // if file is a relative name, it is interpreted
305                                 // relative to the master document.
306                                 exportdata.addExternalFile(rit->first, source, file);
307                         }
308                 }
309         }
310
311         // Do we need to perform the conversion?
312         // Yes if to_file does not exist or if from_file is newer than to_file
313         if (support::compare_timestamps(temp_file, abs_to_file) < 0)
314                 return; // SUCCESS
315
316         // FIXME (Abdel 12/08/06): Is there a need to show these errors?
317         ErrorList el;
318         bool const success =
319                 theConverters().convert(&buffer, temp_file, abs_to_file,
320                                    params.filename, from_format, to_format, el,
321                                    Converters::try_default | Converters::try_cache);
322
323         if (!success)
324                 LYXERR(Debug::EXTERNAL)
325                         << "external::updateExternal. "
326                         << "Unable to convert from "
327                         << from_format << " to " << to_format << endl;
328
329         // return success
330 }
331
332
333 string const substituteCommands(InsetExternalParams const & params,
334                                 string const & input, string const & format);
335
336 string const substituteOptions(InsetExternalParams const & params,
337                                string const & input, string const & format);
338
339 } // namespace anon
340
341
342 int writeExternal(InsetExternalParams const & params,
343                   string const & format,
344                   Buffer const & buffer, odocstream & os,
345                   ExportData & exportdata,
346                   bool external_in_tmpdir,
347                   bool dryrun)
348 {
349         Template const * const et_ptr = getTemplatePtr(params);
350         if (!et_ptr)
351                 return 0;
352         Template const & et = *et_ptr;
353
354         Template::Formats::const_iterator cit = et.formats.find(format);
355         if (cit == et.formats.end()) {
356                 LYXERR(Debug::EXTERNAL)
357                         << "External template format '" << format
358                         << "' not specified in template "
359                         << params.templatename() << endl;
360                 return 0;
361         }
362
363         if (!dryrun || support::contains(cit->second.product, "$$Contents"))
364                 updateExternal(params, format, buffer, exportdata,
365                                external_in_tmpdir, dryrun);
366
367         bool const use_latex_path = format == "LaTeX";
368         string str = doSubstitution(params, buffer, cit->second.product,
369                                     use_latex_path, external_in_tmpdir);
370         str = substituteCommands(params, str, format);
371         str = substituteOptions(params, str, format);
372         // FIXME UNICODE
373         os << from_utf8(str);
374         return int(lyx::count(str.begin(), str.end(),'\n'));
375 }
376
377 namespace {
378
379 // Empty template, specialised below.
380 template <typename TransformType>
381 string const substituteIt(string const &,
382                           TransformID,
383                           string const &,
384                           Template::Format const &,
385                           InsetExternalParams const &);
386
387
388 template <>
389 string const substituteIt<TransformCommand>(string const & input,
390                                             TransformID id,
391                                             string const & /* formatname */,
392                                             Template::Format const & format,
393                                             InsetExternalParams const & params)
394 {
395         typedef std::map<TransformID, TransformStore> Transformers;
396         Transformers::const_iterator it = format.command_transformers.find(id);
397         if (it == format.command_transformers.end())
398                 return input;
399
400         TransformStore const & store = it->second;
401
402         TransformCommand::ptr_type ptr;
403         if (id == Rotate)
404                 ptr = store.getCommandTransformer(params.rotationdata);
405         else if (id == Resize)
406                 ptr = store.getCommandTransformer(params.resizedata);
407
408         if (!ptr.get())
409                 return input;
410
411         string result =
412                 support::subst(input, ptr->front_placeholder(), ptr->front());
413         return support::subst(result, ptr->back_placeholder(),  ptr->back());
414 }
415
416
417 template <>
418 string const substituteIt<TransformOption>(string const & input,
419                                            TransformID id,
420                                            string const & fname,
421                                            Template::Format const & format,
422                                            InsetExternalParams const & params)
423 {
424         typedef std::map<TransformID, TransformStore> Transformers;
425         Transformers::const_iterator it = format.option_transformers.find(id);
426         if (it == format.option_transformers.end())
427                 return input;
428
429         TransformStore const & store = it->second;
430
431         TransformOption::ptr_type ptr;
432         switch (id) {
433         case Clip:
434                 ptr = store.getOptionTransformer(params.clipdata);
435                 break;
436         case Extra:
437                 ptr = store.getOptionTransformer(params.extradata.get(fname));
438                 break;
439         case Rotate:
440                 ptr = store.getOptionTransformer(params.rotationdata);
441                 break;
442         case Resize:
443                 ptr = store.getOptionTransformer(params.resizedata);
444                 break;
445         }
446
447         if (!ptr.get())
448                 return input;
449
450         return support::subst(input, ptr->placeholder(), ptr->option());
451 }
452
453
454 template <typename TransformerType>
455 string const transformIt(InsetExternalParams const & params,
456                          string const & s, string const & formatname)
457 {
458         Template const * const et = getTemplatePtr(params);
459         if (!et || et->transformIds.empty())
460                 return s;
461
462         Template::Formats::const_iterator fit = et->formats.find(formatname);
463         if (fit == et->formats.end())
464                 return s;
465
466         string result = s;
467         Template::Format const & format =  fit->second;
468
469         typedef vector<TransformID> TransformsIDs;
470         TransformsIDs::const_iterator it  = et->transformIds.begin();
471         TransformsIDs::const_iterator end = et->transformIds.end();
472         for (; it != end; ++it) {
473                 result = substituteIt<TransformerType>(result, *it, formatname,
474                                                        format, params);
475         }
476         return result;
477 }
478
479
480 string const substituteCommands(InsetExternalParams const & params,
481                                 string const & input, string const & format)
482 {
483         return transformIt<TransformCommand>(params, input, format);
484 }
485
486
487 string const substituteOption(InsetExternalParams const & params,
488                               string const & input, string const & format)
489 {
490         string opt = transformIt<TransformOption>(params, input, format);
491
492         if (format == "LaTeX" || format == "PDFLaTeX")
493                 return sanitizeLatexOption(opt);
494         if (format == "DocBook")
495                 return sanitizeDocBookOption(opt);
496         return opt;
497 }
498
499
500 string const substituteOptions(InsetExternalParams const & params,
501                                string const & input, string const & format)
502 {
503         string output = input;
504
505         Template const * const et = getTemplatePtr(params);
506         if (!et || et->transformIds.empty())
507                 return output;
508
509         Template::Formats::const_iterator fit = et->formats.find(format);
510         if (fit == et->formats.end() || fit->second.options.empty())
511                 return output;
512
513         typedef vector<Template::Option> Options;
514         Options const & options = fit->second.options;
515         Options::const_iterator it  = options.begin();
516         Options::const_iterator end = options.end();
517         for (; it != end; ++it) {
518                 string const opt = substituteOption(params, it->option, format);
519                 string const placeholder = "$$" + it->name;
520                 output = support::subst(output, placeholder, opt);
521         }
522
523         return output;
524 }
525
526 } // namespace anon
527
528 } // namespace external
529
530 } // namespace lyx