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