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