]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
do what the FIXME suggested
[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 docstring InsetInclude::screenLabel() const
254 {
255         docstring temp;
256
257         switch (type(params())) {
258                 case INPUT:
259                         temp = buffer().B_("Input");
260                         break;
261                 case VERB:
262                         temp = buffer().B_("Verbatim Input");
263                         break;
264                 case VERBAST:
265                         temp = buffer().B_("Verbatim Input*");
266                         break;
267                 case INCLUDE:
268                         temp = buffer().B_("Include");
269                         break;
270                 case LISTINGS:
271                         temp = listings_label_;
272                         break;
273                 case NONE:
274                         BOOST_ASSERT(false);
275         }
276
277         temp += ": ";
278
279         if (params()["filename"].empty())
280                 temp += "???";
281         else
282                 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
283
284         if (!params()["embed"].empty())
285                 temp += _(" (embedded)");
286         return temp;
287 }
288
289
290 /// return the child buffer if the file is a LyX doc and is loaded
291 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
292 {
293         if (isVerbatim(params) || isListings(params))
294                 return 0;
295
296         string const included_file = includedFilename(buffer, params).absFilename();
297         if (!isLyXFilename(included_file))
298                 return 0;
299
300         Buffer * childBuffer = theBufferList().getBuffer(included_file);
301
302         // FIXME: recursive includes
303         return (childBuffer == &buffer) ? 0 : childBuffer;
304 }
305
306
307 /// return true if the file is or got loaded.
308 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
309 {
310         if (isVerbatim(params) || isListings(params))
311                 return 0;
312
313         string const parent_filename = parent.absFileName();
314         FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
315                            onlyPath(parent_filename));
316
317         if (!isLyXFilename(included_file.absFilename()))
318                 return 0;
319
320         Buffer * child = theBufferList().getBuffer(included_file.absFilename());
321         if (!child) {
322                 // the readonly flag can/will be wrong, not anymore I think.
323                 if (!included_file.exists())
324                         return 0;
325
326                 child = theBufferList().newBuffer(included_file.absFilename());
327                 if (!child)
328                         // Buffer creation is not possible.
329                         return 0;
330
331                 if (!child->loadLyXFile(included_file)) {
332                         //close the buffer we just opened
333                         theBufferList().release(child);
334                         return 0;
335                 }
336         }
337         child->setParent(&parent);
338         return child;
339 }
340
341
342 void resetParentBuffer(Buffer const * parent, InsetCommandParams const & params,
343         bool close_it)
344 {
345         if (isVerbatim(params) || isListings(params))
346                 return;
347
348         string const parent_filename = parent->absFileName();
349         FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
350                            onlyPath(parent_filename));
351
352         if (!isLyXFilename(included_file.absFilename()))
353                 return;
354
355         Buffer * child = theBufferList().getBuffer(included_file.absFilename());
356         // File not opened, nothing to close.
357         if (!child)
358                 return;
359
360         // Child document has a different parent, don't close it.
361         if (child->parent() != parent)
362                 return;
363
364         //close the buffer.
365         child->setParent(0);
366         if (close_it)
367                 theBufferList().release(child);
368         else
369                 updateLabels(*child);
370 }
371
372
373 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
374 {
375         string incfile = to_utf8(params()["filename"]);
376
377         // Do nothing if no file name has been specified
378         if (incfile.empty())
379                 return 0;
380
381         FileName const included_file =
382                 includedFilename(buffer(), params()).availableFile();
383
384         // Check we're not trying to include ourselves.
385         // FIXME RECURSIVE INCLUDE
386         // This isn't sufficient, as the inclusion could be downstream.
387         // But it'll have to do for now.
388         if (isInputOrInclude(params()) &&
389                 buffer().absFileName() == included_file.absFilename())
390         {
391                 Alert::error(_("Recursive input"),
392                                bformat(_("Attempted to include file %1$s in itself! "
393                                "Ignoring inclusion."), from_utf8(incfile)));
394                 return 0;
395         }
396
397         Buffer const * const masterBuffer = buffer().masterBuffer();
398
399         // if incfile is relative, make it relative to the master
400         // buffer directory.
401         if (!FileName(incfile).isAbsolute()) {
402                 // FIXME UNICODE
403                 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
404                                               from_utf8(masterBuffer->filePath())));
405         }
406
407         // write it to a file (so far the complete file)
408         string const exportfile = changeExtension(incfile, ".tex");
409         string const mangled =
410                 DocFileName(changeExtension(included_file.absFilename(),".tex")).
411                         mangledFilename();
412         FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
413
414         if (!runparams.nice)
415                 incfile = mangled;
416         else if (!isValidLaTeXFilename(incfile)) {
417                 frontend::Alert::warning(_("Invalid filename"),
418                                          _("The following filename is likely to cause trouble "
419                                            "when running the exported file through LaTeX: ") +
420                                             from_utf8(incfile));
421         }
422         LYXERR(Debug::LATEX, "incfile:" << incfile);
423         LYXERR(Debug::LATEX, "exportfile:" << exportfile);
424         LYXERR(Debug::LATEX, "writefile:" << writefile);
425
426         if (runparams.inComment || runparams.dryrun) {
427                 //Don't try to load or copy the file if we're
428                 //in a comment or doing a dryrun
429         } else if (isInputOrInclude(params()) &&
430                  isLyXFilename(included_file.absFilename())) {
431                 //if it's a LyX file and we're inputting or including,
432                 //try to load it so we can write the associated latex
433                 if (!loadIfNeeded(buffer(), params()))
434                         return false;
435
436                 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
437
438                 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
439                         // FIXME UNICODE
440                         docstring text = bformat(_("Included file `%1$s'\n"
441                                                 "has textclass `%2$s'\n"
442                                                              "while parent file has textclass `%3$s'."),
443                                               included_file.displayName(),
444                                               from_utf8(tmp->params().documentClass().name()),
445                                               from_utf8(masterBuffer->params().documentClass().name()));
446                         Alert::warning(_("Different textclasses"), text);
447                         //return 0;
448                 }
449
450                 // Make sure modules used in child are all included in master
451                 //FIXME It might be worth loading the children's modules into the master
452                 //over in BufferParams rather than doing this check.
453                 vector<string> const masterModules = masterBuffer->params().getModules();
454                 vector<string> const childModules = tmp->params().getModules();
455                 vector<string>::const_iterator it = childModules.begin();
456                 vector<string>::const_iterator end = childModules.end();
457                 for (; it != end; ++it) {
458                         string const module = *it;
459                         vector<string>::const_iterator found =
460                                 find(masterModules.begin(), masterModules.end(), module);
461                         if (found != masterModules.end()) {
462                                 docstring text = bformat(_("Included file `%1$s'\n"
463                                                         "uses module `%2$s'\n"
464                                                         "which is not used in parent file."),
465                                        included_file.displayName(), from_utf8(module));
466                                 Alert::warning(_("Module not found"), text);
467                         }
468                 }
469
470                 tmp->markDepClean(masterBuffer->temppath());
471
472 // FIXME: handle non existing files
473 // FIXME: Second argument is irrelevant!
474 // since only_body is true, makeLaTeXFile will not look at second
475 // argument. Should we set it to string(), or should makeLaTeXFile
476 // make use of it somehow? (JMarc 20031002)
477                 // The included file might be written in a different encoding
478                 Encoding const * const oldEnc = runparams.encoding;
479                 runparams.encoding = &tmp->params().encoding();
480                 tmp->makeLaTeXFile(writefile,
481                                    masterFileName(buffer()).onlyPath().absFilename(),
482                                    runparams, false);
483                 runparams.encoding = oldEnc;
484         } else {
485                 // In this case, it's not a LyX file, so we copy the file
486                 // to the temp dir, so that .aux files etc. are not created
487                 // in the original dir. Files included by this file will be
488                 // found via input@path, see ../Buffer.cpp.
489                 unsigned long const checksum_in  = included_file.checksum();
490                 unsigned long const checksum_out = writefile.checksum();
491
492                 if (checksum_in != checksum_out) {
493                         if (!included_file.copyTo(writefile)) {
494                                 // FIXME UNICODE
495                                 LYXERR(Debug::LATEX,
496                                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
497                                                                   "into the temporary directory."),
498                                                    from_utf8(included_file.absFilename()))));
499                                 return 0;
500                         }
501                 }
502         }
503
504         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
505                         "latex" : "pdflatex";
506         if (isVerbatim(params())) {
507                 incfile = latex_path(incfile);
508                 // FIXME UNICODE
509                 os << '\\' << from_ascii(params().getCmdName()) << '{'
510                    << from_utf8(incfile) << '}';
511         } else if (type(params()) == INPUT) {
512                 runparams.exportdata->addExternalFile(tex_format, writefile,
513                                                       exportfile);
514
515                 // \input wants file with extension (default is .tex)
516                 if (!isLyXFilename(included_file.absFilename())) {
517                         incfile = latex_path(incfile);
518                         // FIXME UNICODE
519                         os << '\\' << from_ascii(params().getCmdName())
520                            << '{' << from_utf8(incfile) << '}';
521                 } else {
522                 incfile = changeExtension(incfile, ".tex");
523                 incfile = latex_path(incfile);
524                         // FIXME UNICODE
525                         os << '\\' << from_ascii(params().getCmdName())
526                            << '{' << from_utf8(incfile) <<  '}';
527                 }
528         } else if (type(params()) == LISTINGS) {
529                 os << '\\' << from_ascii(params().getCmdName());
530                 string const opt = to_utf8(params()["lstparams"]);
531                 // opt is set in QInclude dialog and should have passed validation.
532                 InsetListingsParams params(opt);
533                 if (!params.params().empty())
534                         os << "[" << from_utf8(params.params()) << "]";
535                 os << '{'  << from_utf8(incfile) << '}';
536         } else {
537                 runparams.exportdata->addExternalFile(tex_format, writefile,
538                                                       exportfile);
539
540                 // \include don't want extension and demands that the
541                 // file really have .tex
542                 incfile = changeExtension(incfile, string());
543                 incfile = latex_path(incfile);
544                 // FIXME UNICODE
545                 os << '\\' << from_ascii(params().getCmdName()) << '{'
546                    << from_utf8(incfile) << '}';
547         }
548
549         return 0;
550 }
551
552
553 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
554 {
555         if (isVerbatim(params()) || isListings(params())) {
556                 os << '[' << screenLabel() << '\n';
557                 // FIXME: We don't know the encoding of the file, default to UTF-8.
558                 os << includedFilename(buffer(), params()).fileContents("UTF-8");
559                 os << "\n]";
560                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
561         } else {
562                 docstring const str = '[' + screenLabel() + ']';
563                 os << str;
564                 return str.size();
565         }
566 }
567
568
569 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
570 {
571         string incfile = to_utf8(params()["filename"]);
572
573         // Do nothing if no file name has been specified
574         if (incfile.empty())
575                 return 0;
576
577         string const included_file = includedFilename(buffer(), params()).absFilename();
578
579         // Check we're not trying to include ourselves.
580         // FIXME RECURSIVE INCLUDE
581         // This isn't sufficient, as the inclusion could be downstream.
582         // But it'll have to do for now.
583         if (buffer().absFileName() == included_file) {
584                 Alert::error(_("Recursive input"),
585                                bformat(_("Attempted to include file %1$s in itself! "
586                                "Ignoring inclusion."), from_utf8(incfile)));
587                 return 0;
588         }
589
590         // write it to a file (so far the complete file)
591         string const exportfile = changeExtension(incfile, ".sgml");
592         DocFileName writefile(changeExtension(included_file, ".sgml"));
593
594         if (loadIfNeeded(buffer(), params())) {
595                 Buffer * tmp = theBufferList().getBuffer(included_file);
596
597                 string const mangled = writefile.mangledFilename();
598                 writefile = makeAbsPath(mangled,
599                                         buffer().masterBuffer()->temppath());
600                 if (!runparams.nice)
601                         incfile = mangled;
602
603                 LYXERR(Debug::LATEX, "incfile:" << incfile);
604                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
605                 LYXERR(Debug::LATEX, "writefile:" << writefile);
606
607                 tmp->makeDocBookFile(writefile, runparams, true);
608         }
609
610         runparams.exportdata->addExternalFile("docbook", writefile,
611                                               exportfile);
612         runparams.exportdata->addExternalFile("docbook-xml", writefile,
613                                               exportfile);
614
615         if (isVerbatim(params()) || isListings(params())) {
616                 os << "<inlinegraphic fileref=\""
617                    << '&' << include_label << ';'
618                    << "\" format=\"linespecific\">";
619         } else
620                 os << '&' << include_label << ';';
621
622         return 0;
623 }
624
625
626 void InsetInclude::validate(LaTeXFeatures & features) const
627 {
628         string incfile = to_utf8(params()["filename"]);
629         string writefile;
630
631         BOOST_ASSERT(&buffer() == &features.buffer());
632
633         string const included_file =
634                 includedFilename(buffer(), params()).availableFile().absFilename();
635
636         if (isLyXFilename(included_file))
637                 writefile = changeExtension(included_file, ".sgml");
638         else
639                 writefile = included_file;
640
641         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
642                 incfile = DocFileName(writefile).mangledFilename();
643                 writefile = makeAbsPath(incfile,
644                                         buffer().masterBuffer()->temppath()).absFilename();
645         }
646
647         features.includeFile(include_label, writefile);
648
649         if (isVerbatim(params()))
650                 features.require("verbatim");
651         else if (isListings(params()))
652                 features.require("listings");
653
654         // Here we must do the fun stuff...
655         // Load the file in the include if it needs
656         // to be loaded:
657         if (loadIfNeeded(buffer(), params())) {
658                 // a file got loaded
659                 Buffer * const tmp = theBufferList().getBuffer(included_file);
660                 // make sure the buffer isn't us
661                 // FIXME RECURSIVE INCLUDES
662                 // This is not sufficient, as recursive includes could be
663                 // more than a file away. But it will do for now.
664                 if (tmp && tmp != &buffer()) {
665                         // We must temporarily change features.buffer,
666                         // otherwise it would always be the master buffer,
667                         // and nested includes would not work.
668                         features.setBuffer(*tmp);
669                         tmp->validate(features);
670                         features.setBuffer(buffer());
671                 }
672         }
673 }
674
675
676 void InsetInclude::getLabelList(vector<docstring> & list) const
677 {
678         if (isListings(params())) {
679                 InsetListingsParams p(to_utf8(params()["lstparams"]));
680                 string label = p.getParamValue("label");
681                 if (!label.empty())
682                         list.push_back(from_utf8(label));
683         }
684         else if (loadIfNeeded(buffer(), params())) {
685                 string const included_file = includedFilename(buffer(), params()).absFilename();
686                 Buffer * tmp = theBufferList().getBuffer(included_file);
687                 tmp->setParent(0);
688                 tmp->getLabelList(list);
689                 tmp->setParent(const_cast<Buffer *>(&buffer()));
690         }
691 }
692
693
694 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
695         InsetIterator const & /*di*/) const
696 {
697         if (loadIfNeeded(buffer(), params())) {
698                 string const included_file = includedFilename(buffer(), params()).absFilename();
699                 Buffer * tmp = theBufferList().getBuffer(included_file);
700                 //FIXME This is kind of a dirty hack and should be made reasonable.
701                 tmp->setParent(0);
702                 keys.fillWithBibKeys(tmp);
703                 tmp->setParent(&buffer());
704         }
705 }
706
707
708 void InsetInclude::updateBibfilesCache()
709 {
710         Buffer * const tmp = getChildBuffer(buffer(), params());
711         if (tmp) {
712                 tmp->setParent(0);
713                 tmp->updateBibfilesCache();
714                 tmp->setParent(&buffer());
715         }
716 }
717
718
719 EmbeddedFileList const &
720 InsetInclude::getBibfilesCache(Buffer const & buffer) const
721 {
722         Buffer * const tmp = getChildBuffer(buffer, params());
723         if (tmp) {
724                 tmp->setParent(0);
725                 EmbeddedFileList const & cache = tmp->getBibfilesCache();
726                 tmp->setParent(&buffer);
727                 return cache;
728         }
729         static EmbeddedFileList const empty;
730         return empty;
731 }
732
733
734 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
735 {
736         BOOST_ASSERT(mi.base.bv);
737
738         bool use_preview = false;
739         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
740                 graphics::PreviewImage const * pimage =
741                         preview_->getPreviewImage(mi.base.bv->buffer());
742                 use_preview = pimage && pimage->image();
743         }
744
745         if (use_preview) {
746                 preview_->metrics(mi, dim);
747         } else {
748                 if (!set_label_) {
749                         set_label_ = true;
750                         button_.update(screenLabel(), true);
751                 }
752                 button_.metrics(mi, dim);
753         }
754
755         Box b(0, dim.wid, -dim.asc, dim.des);
756         button_.setBox(b);
757 }
758
759
760 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
761 {
762         BOOST_ASSERT(pi.base.bv);
763
764         bool use_preview = false;
765         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
766                 graphics::PreviewImage const * pimage =
767                         preview_->getPreviewImage(pi.base.bv->buffer());
768                 use_preview = pimage && pimage->image();
769         }
770
771         if (use_preview)
772                 preview_->draw(pi, x, y);
773         else
774                 button_.draw(pi, x, y);
775 }
776
777
778 Inset::DisplayType InsetInclude::display() const
779 {
780         return type(params()) == INPUT ? Inline : AlignCenter;
781 }
782
783
784
785 //
786 // preview stuff
787 //
788
789 void InsetInclude::fileChanged() const
790 {
791         Buffer const * const buffer = updateFrontend();
792         if (!buffer)
793                 return;
794
795         preview_->removePreview(*buffer);
796         add_preview(*preview_.get(), *this, *buffer);
797         preview_->startLoading(*buffer);
798 }
799
800
801 namespace {
802
803 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
804 {
805         FileName const included_file = includedFilename(buffer, params);
806
807         return type(params) == INPUT && params.preview() &&
808                 included_file.isReadableFile();
809 }
810
811
812 docstring latexString(InsetInclude const & inset)
813 {
814         odocstringstream os;
815         // We don't need to set runparams.encoding since this will be done
816         // by latex() anyway.
817         OutputParams runparams(0);
818         runparams.flavor = OutputParams::LATEX;
819         inset.latex(os, runparams);
820
821         return os.str();
822 }
823
824
825 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
826                  Buffer const & buffer)
827 {
828         InsetCommandParams const & params = inset.params();
829         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
830             preview_wanted(params, buffer)) {
831                 renderer.setAbsFile(includedFilename(buffer, params));
832                 docstring const snippet = latexString(inset);
833                 renderer.addPreview(snippet, buffer);
834         }
835 }
836
837 } // namespace anon
838
839
840 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
841 {
842         Buffer const & buffer = ploader.buffer();
843         if (!preview_wanted(params(), buffer))
844                 return;
845         preview_->setAbsFile(includedFilename(buffer, params()));
846         docstring const snippet = latexString(*this);
847         preview_->addPreview(snippet, ploader);
848 }
849
850
851 void InsetInclude::addToToc(ParConstIterator const & cpit) const
852 {
853         if (isListings(params())) {
854                 InsetListingsParams p(to_utf8(params()["lstparams"]));
855                 string caption = p.getParamValue("caption");
856                 if (caption.empty())
857                         return;
858                 Toc & toc = buffer().tocBackend().toc("listing");
859                 docstring const str = convert<docstring>(toc.size() + 1)
860                         + ". " +  from_utf8(caption);
861                 ParConstIterator pit = cpit;
862                 pit.push_back(*this);
863                 toc.push_back(TocItem(pit, 0, str));
864                 return;
865         }
866         Buffer const * const childbuffer = getChildBuffer(buffer(), params());
867         if (!childbuffer)
868                 return;
869
870         TocList & toclist = buffer().tocBackend().tocs();
871         TocList const & childtoclist = childbuffer->tocBackend().tocs();
872         TocList::const_iterator it = childtoclist.begin();
873         TocList::const_iterator const end = childtoclist.end();
874         for(; it != end; ++it)
875                 toclist[it->first].insert(toclist[it->first].end(),
876                                 it->second.begin(), it->second.end());
877 }
878
879
880 void InsetInclude::updateLabels(ParIterator const &)
881 {
882         Buffer const * const childbuffer = getChildBuffer(buffer(), params());
883         if (childbuffer) {
884                 lyx::updateLabels(*childbuffer, true);
885                 return;
886         }
887         if (!isListings(params()))
888                 return;
889
890         InsetListingsParams const par(to_utf8(params()["lstparams"]));
891         if (par.getParamValue("caption").empty()) {
892                 listings_label_.clear();
893                 return;
894         }
895         Counters & counters = buffer().params().documentClass().counters();
896         docstring const cnt = from_ascii("listing");
897         listings_label_ = buffer().B_("Program Listing");
898         if (counters.hasCounter(cnt)) {
899                 counters.step(cnt);
900                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
901         }
902 }
903
904
905 void InsetInclude::registerEmbeddedFiles(EmbeddedFileList & files) const
906 {
907         files.registerFile(includedFilename(buffer(), params()), this, buffer());
908 }
909
910
911 void InsetInclude::updateEmbeddedFile(EmbeddedFile const & file)
912 {
913         InsetCommandParams p = params();
914         p["filename"] = from_utf8(file.outputFilename());
915         p["embed"] = file.embedded() ? from_utf8(file.inzipName()) : docstring();
916         setParams(p);
917 }
918
919
920 } // namespace lyx