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