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