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