]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
5d9cd9426b2619093973cf42e88bc719b244c341
[lyx.git] / src / insets / InsetInclude.cpp
1 /**
2  * \file InsetInclude.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Richard Heck (conversion to InsetCommand)
8  * \author Bo Peng (embedding stuff)
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "InsetInclude.h"
16
17 #include "BaseClassList.h"
18 #include "Buffer.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
23 #include "Cursor.h"
24 #include "DispatchResult.h"
25 #include "Exporter.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "LaTeXFeatures.h"
29 #include "LyX.h"
30 #include "LyXRC.h"
31 #include "Lexer.h"
32 #include "MetricsInfo.h"
33 #include "OutputParams.h"
34 #include "TextClass.h"
35 #include "TocBackend.h"
36
37 #include "frontends/alert.h"
38 #include "frontends/Painter.h"
39
40 #include "graphics/PreviewImage.h"
41 #include "graphics/PreviewLoader.h"
42
43 #include "insets/RenderPreview.h"
44 #include "insets/InsetListingsParams.h"
45
46 #include "support/debug.h"
47 #include "support/docstream.h"
48 #include "support/ExceptionMessage.h"
49 #include "support/FileNameList.h"
50 #include "support/filetools.h"
51 #include "support/gettext.h"
52 #include "support/lstrings.h" // contains
53 #include "support/lyxalgo.h"
54 #include "support/convert.h"
55
56 #include <boost/bind.hpp>
57
58 using namespace std;
59 using namespace lyx::support;
60
61 namespace lyx {
62
63 namespace Alert = frontend::Alert;
64
65
66 namespace {
67
68 docstring const uniqueID()
69 {
70         static unsigned int seed = 1000;
71         return "file" + convert<docstring>(++seed);
72 }
73
74
75 /// the type of inclusion
76 enum Types {
77         INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
78 };
79
80
81 Types type(string const & s)
82 {
83         if (s == "input")
84                 return INPUT;
85         if (s == "verbatiminput")
86                 return VERB;
87         if (s == "verbatiminput*")
88                 return VERBAST;
89         if (s == "lstinputlisting")
90                 return LISTINGS;
91         if (s == "include")
92                 return INCLUDE;
93         return NONE;
94 }
95
96
97 Types type(InsetCommandParams const & params)
98 {
99         return type(params.getCmdName());
100 }
101
102
103 bool isListings(InsetCommandParams const & params)
104 {
105         return type(params) == LISTINGS;
106 }
107
108
109 bool isVerbatim(InsetCommandParams const & params)
110 {
111         Types const t = type(params);
112         return t == VERB || t == VERBAST;
113 }
114
115
116 bool isInputOrInclude(InsetCommandParams const & params)
117 {
118         Types const t = type(params);
119         return t == INPUT || t == INCLUDE;
120 }
121
122
123 FileName const masterFileName(Buffer const & buffer)
124 {
125         return buffer.masterBuffer()->fileName();
126 }
127
128
129 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
130
131
132 string const parentFilename(Buffer const & buffer)
133 {
134         return buffer.absFileName();
135 }
136
137
138 EmbeddedFile const includedFilename(Buffer const & buffer,
139                               InsetCommandParams const & params)
140 {
141         // it is not a good idea to create this EmbeddedFile object
142         // each time, but there seems to be no easy way around.
143         EmbeddedFile file(to_utf8(params["filename"]),
144                onlyPath(parentFilename(buffer)));
145         file.setEmbed(!params["embed"].empty());
146         file.enable(buffer.embedded(), &buffer);
147         return file;
148 }
149
150 } // namespace anon
151
152
153 InsetInclude::InsetInclude(InsetCommandParams const & p)
154         : InsetCommand(p, "include"), include_label(uniqueID()),
155           preview_(new RenderMonitoredPreview(this)), set_label_(false)
156 {
157         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
158 }
159
160
161 InsetInclude::InsetInclude(InsetInclude const & other)
162         : InsetCommand(other), include_label(other.include_label),
163           preview_(new RenderMonitoredPreview(this)), set_label_(false)
164 {
165         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
166 }
167
168
169 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
170 {
171         // FIXME
172         // This is only correct for the case of listings, but it'll do for now.
173         // In the other cases, this second parameter should just be empty.
174         static ParamInfo param_info_;
175         if (param_info_.empty()) {
176                 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
177                 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
178                 param_info_.add("embed", ParamInfo::LYX_INTERNAL);
179         }
180         return param_info_;
181 }
182
183
184 bool InsetInclude::isCompatibleCommand(string const & s)
185 {
186         return type(s) != NONE;
187 }
188
189
190 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
191 {
192         BOOST_ASSERT(&cur.buffer() == &buffer());
193         switch (cmd.action) {
194
195         case LFUN_INSET_MODIFY: {
196                 InsetCommandParams p(INCLUDE_CODE);
197                 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
198                 if (!p.getCmdName().empty()) {
199                         if (isListings(p)){
200                                 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
201                                 InsetListingsParams par_new(to_utf8(p["lstparams"]));
202                                 if (par_old.getParamValue("label") !=
203                                     par_new.getParamValue("label")
204                                     && !par_new.getParamValue("label").empty())
205                                         cur.bv().buffer().changeRefsIfUnique(
206                                                 from_utf8(par_old.getParamValue("label")),
207                                                 from_utf8(par_new.getParamValue("label")),
208                                                 REF_CODE);
209                         }
210                         try {
211                                 // the embed parameter passed back from the dialog
212                                 // is "true" or "false", we need to change it.
213                                 if (p["embed"] == _("false"))
214                                         p["embed"].clear();
215                                 else
216                                         p["embed"] = from_utf8(EmbeddedFile(to_utf8(p["filename"]),
217                                                 onlyPath(parentFilename(cur.buffer()))).inzipName());
218                                 // test parameter
219                                 includedFilename(cur.buffer(), p);
220                         } catch (ExceptionMessage const & message) {
221                                 Alert::error(message.title_, message.details_);
222                                 // do not set parameter if an error happens
223                                 break;
224                         }
225                         setParams(p);
226                         buffer().updateBibfilesCache();
227                 } else
228                         cur.noUpdate();
229                 break;
230         }
231
232         //pass everything else up the chain
233         default:
234                 InsetCommand::doDispatch(cur, cmd);
235                 break;
236         }
237 }
238
239
240 void InsetInclude::setParams(InsetCommandParams const & p)
241 {
242         InsetCommand::setParams(p);
243         set_label_ = false;
244
245         if (preview_->monitoring())
246                 preview_->stopMonitoring();
247
248         if (type(params()) == INPUT)
249                 add_preview(*preview_, *this, buffer());
250 }
251
252
253 Inset * InsetInclude::clone() const
254 {
255         return new InsetInclude(*this);
256 }
257
258
259 docstring InsetInclude::screenLabel() const
260 {
261         docstring temp;
262
263         switch (type(params())) {
264                 case INPUT:
265                         temp = buffer().B_("Input");
266                         break;
267                 case VERB:
268                         temp = buffer().B_("Verbatim Input");
269                         break;
270                 case VERBAST:
271                         temp = buffer().B_("Verbatim Input*");
272                         break;
273                 case INCLUDE:
274                         temp = buffer().B_("Include");
275                         break;
276                 case LISTINGS:
277                         temp = listings_label_;
278                         break;
279                 case NONE:
280                         BOOST_ASSERT(false);
281         }
282
283         temp += ": ";
284
285         if (params()["filename"].empty())
286                 temp += "???";
287         else
288                 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
289
290         if (!params()["embed"].empty())
291                 temp += _(" (embedded)");
292         return temp;
293 }
294
295
296 /// return the child buffer if the file is a LyX doc and is loaded
297 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
298 {
299         if (isVerbatim(params) || isListings(params))
300                 return 0;
301
302         string const included_file = includedFilename(buffer, params).absFilename();
303         if (!isLyXFilename(included_file))
304                 return 0;
305
306         Buffer * childBuffer = theBufferList().getBuffer(included_file);
307
308         // FIXME: recursive includes
309         return (childBuffer == &buffer) ? 0 : childBuffer;
310 }
311
312
313 /// return true if the file is or got loaded.
314 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
315 {
316         if (isVerbatim(params) || isListings(params))
317                 return 0;
318
319         string const parent_filename = parent.absFileName();
320         FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
321                            onlyPath(parent_filename));
322
323         if (!isLyXFilename(included_file.absFilename()))
324                 return 0;
325
326         Buffer * child = theBufferList().getBuffer(included_file.absFilename());
327         if (!child) {
328                 // the readonly flag can/will be wrong, not anymore I think.
329                 if (!included_file.exists())
330                         return 0;
331
332                 child = theBufferList().newBuffer(included_file.absFilename());
333                 if (!child)
334                         // Buffer creation is not possible.
335                         return 0;
336
337                 if (!child->loadLyXFile(included_file)) {
338                         //close the buffer we just opened
339                         theBufferList().release(child);
340                         return 0;
341                 }
342         }
343         child->setParent(&parent);
344         return child;
345 }
346
347
348 void resetParentBuffer(Buffer const * parent, InsetCommandParams const & params,
349         bool close_it)
350 {
351         if (isVerbatim(params) || isListings(params))
352                 return;
353
354         string const parent_filename = parent->absFileName();
355         FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
356                            onlyPath(parent_filename));
357
358         if (!isLyXFilename(included_file.absFilename()))
359                 return;
360
361         Buffer * child = theBufferList().getBuffer(included_file.absFilename());
362         // File not opened, nothing to close.
363         if (!child)
364                 return;
365
366         // Child document has a different parent, don't close it.
367         if (child->parent() != parent)
368                 return;
369
370         //close the buffer.
371         child->setParent(0);
372         if (close_it)
373                 theBufferList().release(child);
374         else
375                 updateLabels(*child);
376 }
377
378
379 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
380 {
381         string incfile = to_utf8(params()["filename"]);
382
383         // Do nothing if no file name has been specified
384         if (incfile.empty())
385                 return 0;
386
387         FileName const included_file =
388                 includedFilename(buffer(), params()).availableFile();
389
390         // Check we're not trying to include ourselves.
391         // FIXME RECURSIVE INCLUDE
392         // This isn't sufficient, as the inclusion could be downstream.
393         // But it'll have to do for now.
394         if (isInputOrInclude(params()) &&
395                 buffer().absFileName() == included_file.absFilename())
396         {
397                 Alert::error(_("Recursive input"),
398                                bformat(_("Attempted to include file %1$s in itself! "
399                                "Ignoring inclusion."), from_utf8(incfile)));
400                 return 0;
401         }
402
403         Buffer const * const masterBuffer = buffer().masterBuffer();
404
405         // if incfile is relative, make it relative to the master
406         // buffer directory.
407         if (!FileName(incfile).isAbsolute()) {
408                 // FIXME UNICODE
409                 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
410                                               from_utf8(masterBuffer->filePath())));
411         }
412
413         // write it to a file (so far the complete file)
414         string const exportfile = changeExtension(incfile, ".tex");
415         string const mangled =
416                 DocFileName(changeExtension(included_file.absFilename(),".tex")).
417                         mangledFilename();
418         FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
419
420         if (!runparams.nice)
421                 incfile = mangled;
422         else if (!isValidLaTeXFilename(incfile)) {
423                 frontend::Alert::warning(_("Invalid filename"),
424                                          _("The following filename is likely to cause trouble "
425                                            "when running the exported file through LaTeX: ") +
426                                             from_utf8(incfile));
427         }
428         LYXERR(Debug::LATEX, "incfile:" << incfile);
429         LYXERR(Debug::LATEX, "exportfile:" << exportfile);
430         LYXERR(Debug::LATEX, "writefile:" << writefile);
431
432         if (runparams.inComment || runparams.dryrun) {
433                 //Don't try to load or copy the file if we're
434                 //in a comment or doing a dryrun
435         } else if (isInputOrInclude(params()) &&
436                  isLyXFilename(included_file.absFilename())) {
437                 //if it's a LyX file and we're inputting or including,
438                 //try to load it so we can write the associated latex
439                 if (!loadIfNeeded(buffer(), params()))
440                         return false;
441
442                 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
443
444                 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
445                         // FIXME UNICODE
446                         docstring text = bformat(_("Included file `%1$s'\n"
447                                                 "has textclass `%2$s'\n"
448                                                              "while parent file has textclass `%3$s'."),
449                                               included_file.displayName(),
450                                               from_utf8(tmp->params().documentClass().name()),
451                                               from_utf8(masterBuffer->params().documentClass().name()));
452                         Alert::warning(_("Different textclasses"), text);
453                         //return 0;
454                 }
455
456                 // Make sure modules used in child are all included in master
457                 //FIXME It might be worth loading the children's modules into the master
458                 //over in BufferParams rather than doing this check.
459                 vector<string> const masterModules = masterBuffer->params().getModules();
460                 vector<string> const childModules = tmp->params().getModules();
461                 vector<string>::const_iterator it = childModules.begin();
462                 vector<string>::const_iterator end = childModules.end();
463                 for (; it != end; ++it) {
464                         string const module = *it;
465                         vector<string>::const_iterator found =
466                                 find(masterModules.begin(), masterModules.end(), module);
467                         if (found != masterModules.end()) {
468                                 docstring text = bformat(_("Included file `%1$s'\n"
469                                                         "uses module `%2$s'\n"
470                                                         "which is not used in parent file."),
471                                        included_file.displayName(), from_utf8(module));
472                                 Alert::warning(_("Module not found"), text);
473                         }
474                 }
475
476                 tmp->markDepClean(masterBuffer->temppath());
477
478 // FIXME: handle non existing files
479 // FIXME: Second argument is irrelevant!
480 // since only_body is true, makeLaTeXFile will not look at second
481 // argument. Should we set it to string(), or should makeLaTeXFile
482 // make use of it somehow? (JMarc 20031002)
483                 // The included file might be written in a different encoding
484                 Encoding const * const oldEnc = runparams.encoding;
485                 runparams.encoding = &tmp->params().encoding();
486                 tmp->makeLaTeXFile(writefile,
487                                    masterFileName(buffer()).onlyPath().absFilename(),
488                                    runparams, false);
489                 runparams.encoding = oldEnc;
490         } else {
491                 // In this case, it's not a LyX file, so we copy the file
492                 // to the temp dir, so that .aux files etc. are not created
493                 // in the original dir. Files included by this file will be
494                 // found via input@path, see ../Buffer.cpp.
495                 unsigned long const checksum_in  = included_file.checksum();
496                 unsigned long const checksum_out = writefile.checksum();
497
498                 if (checksum_in != checksum_out) {
499                         if (!included_file.copyTo(writefile)) {
500                                 // FIXME UNICODE
501                                 LYXERR(Debug::LATEX,
502                                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
503                                                                   "into the temporary directory."),
504                                                    from_utf8(included_file.absFilename()))));
505                                 return 0;
506                         }
507                 }
508         }
509
510         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
511                         "latex" : "pdflatex";
512         if (isVerbatim(params())) {
513                 incfile = latex_path(incfile);
514                 // FIXME UNICODE
515                 os << '\\' << from_ascii(params().getCmdName()) << '{'
516                    << from_utf8(incfile) << '}';
517         } else if (type(params()) == INPUT) {
518                 runparams.exportdata->addExternalFile(tex_format, writefile,
519                                                       exportfile);
520
521                 // \input wants file with extension (default is .tex)
522                 if (!isLyXFilename(included_file.absFilename())) {
523                         incfile = latex_path(incfile);
524                         // FIXME UNICODE
525                         os << '\\' << from_ascii(params().getCmdName())
526                            << '{' << from_utf8(incfile) << '}';
527                 } else {
528                 incfile = changeExtension(incfile, ".tex");
529                 incfile = latex_path(incfile);
530                         // FIXME UNICODE
531                         os << '\\' << from_ascii(params().getCmdName())
532                            << '{' << from_utf8(incfile) <<  '}';
533                 }
534         } else if (type(params()) == LISTINGS) {
535                 os << '\\' << from_ascii(params().getCmdName());
536                 string const opt = to_utf8(params()["lstparams"]);
537                 // opt is set in QInclude dialog and should have passed validation.
538                 InsetListingsParams params(opt);
539                 if (!params.params().empty())
540                         os << "[" << from_utf8(params.params()) << "]";
541                 os << '{'  << from_utf8(incfile) << '}';
542         } else {
543                 runparams.exportdata->addExternalFile(tex_format, writefile,
544                                                       exportfile);
545
546                 // \include don't want extension and demands that the
547                 // file really have .tex
548                 incfile = changeExtension(incfile, string());
549                 incfile = latex_path(incfile);
550                 // FIXME UNICODE
551                 os << '\\' << from_ascii(params().getCmdName()) << '{'
552                    << from_utf8(incfile) << '}';
553         }
554
555         return 0;
556 }
557
558
559 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
560 {
561         if (isVerbatim(params()) || isListings(params())) {
562                 os << '[' << screenLabel() << '\n';
563                 // FIXME: We don't know the encoding of the file, default to UTF-8.
564                 os << includedFilename(buffer(), params()).fileContents("UTF-8");
565                 os << "\n]";
566                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
567         } else {
568                 docstring const str = '[' + screenLabel() + ']';
569                 os << str;
570                 return str.size();
571         }
572 }
573
574
575 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
576 {
577         string incfile = to_utf8(params()["filename"]);
578
579         // Do nothing if no file name has been specified
580         if (incfile.empty())
581                 return 0;
582
583         string const included_file = includedFilename(buffer(), params()).absFilename();
584
585         // Check we're not trying to include ourselves.
586         // FIXME RECURSIVE INCLUDE
587         // This isn't sufficient, as the inclusion could be downstream.
588         // But it'll have to do for now.
589         if (buffer().absFileName() == included_file) {
590                 Alert::error(_("Recursive input"),
591                                bformat(_("Attempted to include file %1$s in itself! "
592                                "Ignoring inclusion."), from_utf8(incfile)));
593                 return 0;
594         }
595
596         // write it to a file (so far the complete file)
597         string const exportfile = changeExtension(incfile, ".sgml");
598         DocFileName writefile(changeExtension(included_file, ".sgml"));
599
600         if (loadIfNeeded(buffer(), params())) {
601                 Buffer * tmp = theBufferList().getBuffer(included_file);
602
603                 string const mangled = writefile.mangledFilename();
604                 writefile = makeAbsPath(mangled,
605                                         buffer().masterBuffer()->temppath());
606                 if (!runparams.nice)
607                         incfile = mangled;
608
609                 LYXERR(Debug::LATEX, "incfile:" << incfile);
610                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
611                 LYXERR(Debug::LATEX, "writefile:" << writefile);
612
613                 tmp->makeDocBookFile(writefile, runparams, true);
614         }
615
616         runparams.exportdata->addExternalFile("docbook", writefile,
617                                               exportfile);
618         runparams.exportdata->addExternalFile("docbook-xml", writefile,
619                                               exportfile);
620
621         if (isVerbatim(params()) || isListings(params())) {
622                 os << "<inlinegraphic fileref=\""
623                    << '&' << include_label << ';'
624                    << "\" format=\"linespecific\">";
625         } else
626                 os << '&' << include_label << ';';
627
628         return 0;
629 }
630
631
632 void InsetInclude::validate(LaTeXFeatures & features) const
633 {
634         string incfile = to_utf8(params()["filename"]);
635         string writefile;
636
637         BOOST_ASSERT(&buffer() == &features.buffer());
638
639         string const included_file =
640                 includedFilename(buffer(), params()).availableFile().absFilename();
641
642         if (isLyXFilename(included_file))
643                 writefile = changeExtension(included_file, ".sgml");
644         else
645                 writefile = included_file;
646
647         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
648                 incfile = DocFileName(writefile).mangledFilename();
649                 writefile = makeAbsPath(incfile,
650                                         buffer().masterBuffer()->temppath()).absFilename();
651         }
652
653         features.includeFile(include_label, writefile);
654
655         if (isVerbatim(params()))
656                 features.require("verbatim");
657         else if (isListings(params()))
658                 features.require("listings");
659
660         // Here we must do the fun stuff...
661         // Load the file in the include if it needs
662         // to be loaded:
663         if (loadIfNeeded(buffer(), params())) {
664                 // a file got loaded
665                 Buffer * const tmp = theBufferList().getBuffer(included_file);
666                 // make sure the buffer isn't us
667                 // FIXME RECURSIVE INCLUDES
668                 // This is not sufficient, as recursive includes could be
669                 // more than a file away. But it will do for now.
670                 if (tmp && tmp != &buffer()) {
671                         // We must temporarily change features.buffer,
672                         // otherwise it would always be the master buffer,
673                         // and nested includes would not work.
674                         features.setBuffer(*tmp);
675                         tmp->validate(features);
676                         features.setBuffer(buffer());
677                 }
678         }
679 }
680
681
682 void InsetInclude::getLabelList(vector<docstring> & list) const
683 {
684         if (isListings(params())) {
685                 InsetListingsParams p(to_utf8(params()["lstparams"]));
686                 string label = p.getParamValue("label");
687                 if (!label.empty())
688                         list.push_back(from_utf8(label));
689         }
690         else if (loadIfNeeded(buffer(), params())) {
691                 string const included_file = includedFilename(buffer(), params()).absFilename();
692                 Buffer * tmp = theBufferList().getBuffer(included_file);
693                 tmp->setParent(0);
694                 tmp->getLabelList(list);
695                 tmp->setParent(const_cast<Buffer *>(&buffer()));
696         }
697 }
698
699
700 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
701         InsetIterator const & /*di*/) const
702 {
703         if (loadIfNeeded(buffer(), params())) {
704                 string const included_file = includedFilename(buffer(), params()).absFilename();
705                 Buffer * tmp = theBufferList().getBuffer(included_file);
706                 //FIXME This is kind of a dirty hack and should be made reasonable.
707                 tmp->setParent(0);
708                 keys.fillWithBibKeys(tmp);
709                 tmp->setParent(&buffer());
710         }
711 }
712
713
714 void InsetInclude::updateBibfilesCache()
715 {
716         Buffer * const tmp = getChildBuffer(buffer(), params());
717         if (tmp) {
718                 tmp->setParent(0);
719                 tmp->updateBibfilesCache();
720                 tmp->setParent(&buffer());
721         }
722 }
723
724
725 EmbeddedFileList const &
726 InsetInclude::getBibfilesCache(Buffer const & buffer) const
727 {
728         Buffer * const tmp = getChildBuffer(buffer, params());
729         if (tmp) {
730                 tmp->setParent(0);
731                 EmbeddedFileList const & cache = tmp->getBibfilesCache();
732                 tmp->setParent(&buffer);
733                 return cache;
734         }
735         static EmbeddedFileList const empty;
736         return empty;
737 }
738
739
740 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
741 {
742         BOOST_ASSERT(mi.base.bv);
743
744         bool use_preview = false;
745         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
746                 graphics::PreviewImage const * pimage =
747                         preview_->getPreviewImage(mi.base.bv->buffer());
748                 use_preview = pimage && pimage->image();
749         }
750
751         if (use_preview) {
752                 preview_->metrics(mi, dim);
753         } else {
754                 if (!set_label_) {
755                         set_label_ = true;
756                         button_.update(screenLabel(), true);
757                 }
758                 button_.metrics(mi, dim);
759         }
760
761         Box b(0, dim.wid, -dim.asc, dim.des);
762         button_.setBox(b);
763 }
764
765
766 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
767 {
768         BOOST_ASSERT(pi.base.bv);
769
770         bool use_preview = false;
771         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
772                 graphics::PreviewImage const * pimage =
773                         preview_->getPreviewImage(pi.base.bv->buffer());
774                 use_preview = pimage && pimage->image();
775         }
776
777         if (use_preview)
778                 preview_->draw(pi, x, y);
779         else
780                 button_.draw(pi, x, y);
781 }
782
783
784 Inset::DisplayType InsetInclude::display() const
785 {
786         return type(params()) == INPUT ? Inline : AlignCenter;
787 }
788
789
790
791 //
792 // preview stuff
793 //
794
795 void InsetInclude::fileChanged() const
796 {
797         Buffer const * const buffer = updateFrontend();
798         if (!buffer)
799                 return;
800
801         preview_->removePreview(*buffer);
802         add_preview(*preview_.get(), *this, *buffer);
803         preview_->startLoading(*buffer);
804 }
805
806
807 namespace {
808
809 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
810 {
811         FileName const included_file = includedFilename(buffer, params);
812
813         return type(params) == INPUT && params.preview() &&
814                 included_file.isReadableFile();
815 }
816
817
818 docstring latexString(InsetInclude const & inset)
819 {
820         odocstringstream os;
821         // We don't need to set runparams.encoding since this will be done
822         // by latex() anyway.
823         OutputParams runparams(0);
824         runparams.flavor = OutputParams::LATEX;
825         inset.latex(os, runparams);
826
827         return os.str();
828 }
829
830
831 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
832                  Buffer const & buffer)
833 {
834         InsetCommandParams const & params = inset.params();
835         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
836             preview_wanted(params, buffer)) {
837                 renderer.setAbsFile(includedFilename(buffer, params));
838                 docstring const snippet = latexString(inset);
839                 renderer.addPreview(snippet, buffer);
840         }
841 }
842
843 } // namespace anon
844
845
846 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
847 {
848         Buffer const & buffer = ploader.buffer();
849         if (!preview_wanted(params(), buffer))
850                 return;
851         preview_->setAbsFile(includedFilename(buffer, params()));
852         docstring const snippet = latexString(*this);
853         preview_->addPreview(snippet, ploader);
854 }
855
856
857 void InsetInclude::addToToc(ParConstIterator const & cpit) const
858 {
859         if (isListings(params())) {
860                 InsetListingsParams p(to_utf8(params()["lstparams"]));
861                 string caption = p.getParamValue("caption");
862                 if (caption.empty())
863                         return;
864                 Toc & toc = buffer().tocBackend().toc("listing");
865                 docstring const str = convert<docstring>(toc.size() + 1)
866                         + ". " +  from_utf8(caption);
867                 ParConstIterator pit = cpit;
868                 pit.push_back(*this);
869                 toc.push_back(TocItem(pit, 0, str));
870                 return;
871         }
872         Buffer const * const childbuffer = getChildBuffer(buffer(), params());
873         if (!childbuffer)
874                 return;
875
876         TocList & toclist = buffer().tocBackend().tocs();
877         TocList const & childtoclist = childbuffer->tocBackend().tocs();
878         TocList::const_iterator it = childtoclist.begin();
879         TocList::const_iterator const end = childtoclist.end();
880         for(; it != end; ++it)
881                 toclist[it->first].insert(toclist[it->first].end(),
882                                 it->second.begin(), it->second.end());
883 }
884
885
886 void InsetInclude::updateLabels(ParIterator const &)
887 {
888         Buffer const * const childbuffer = getChildBuffer(buffer(), params());
889         if (childbuffer) {
890                 lyx::updateLabels(*childbuffer, true);
891                 return;
892         }
893         if (!isListings(params()))
894                 return;
895
896         InsetListingsParams const par(to_utf8(params()["lstparams"]));
897         if (par.getParamValue("caption").empty()) {
898                 listings_label_.clear();
899                 return;
900         }
901         Counters & counters = buffer().params().documentClass().counters();
902         docstring const cnt = from_ascii("listing");
903         listings_label_ = buffer().B_("Program Listing");
904         if (counters.hasCounter(cnt)) {
905                 counters.step(cnt);
906                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
907         }
908 }
909
910
911 void InsetInclude::registerEmbeddedFiles(EmbeddedFileList & files) const
912 {
913         files.registerFile(includedFilename(buffer(), params()), this, buffer());
914 }
915
916
917 void InsetInclude::updateEmbeddedFile(EmbeddedFile const & file)
918 {
919         InsetCommandParams p = params();
920         p["filename"] = from_utf8(file.outputFilename());
921         p["embed"] = file.embedded() ? from_utf8(file.inzipName()) : docstring();
922         setParams(p);
923 }
924
925
926 } // namespace lyx