]> git.lyx.org Git - features.git/blob - src/insets/InsetInclude.cpp
Fix warning.
[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  *
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() const
369 {
370         Buffer * childBuffer = loadIfNeeded(); 
371
372         // FIXME: recursive includes
373         return (childBuffer == &buffer()) ? 0 : childBuffer;
374 }
375
376
377 Buffer * InsetInclude::loadIfNeeded() const
378 {
379         // Don't try to load it again if we failed before.
380         if (failedtoload_)
381                 return 0;
382
383         // Use cached Buffer if possible.
384         if (child_buffer_ != 0) {
385                 if (theBufferList().isLoaded(child_buffer_))
386                         return child_buffer_;
387                 // Buffer vanished, so invalidate cache and try to reload.
388                 child_buffer_ = 0;
389         }
390
391         InsetCommandParams const & p = params();
392         if (isVerbatim(p) || isListings(p))
393                 return 0;
394
395         string const parent_filename = buffer().absFileName();
396         FileName const included_file = 
397                 makeAbsPath(to_utf8(p["filename"]), onlyPath(parent_filename));
398
399         if (!isLyXFilename(included_file.absFilename()))
400                 return 0;
401
402         Buffer * child = theBufferList().getBuffer(included_file);
403         if (!child) {
404                 // the readonly flag can/will be wrong, not anymore I think.
405                 if (!included_file.exists())
406                         return 0;
407
408                 child = theBufferList().newBuffer(included_file.absFilename());
409                 if (!child)
410                         // Buffer creation is not possible.
411                         return 0;
412
413                 if (!child->loadLyXFile(included_file)) {
414                         failedtoload_ = true;
415                         //close the buffer we just opened
416                         theBufferList().release(child);
417                         return 0;
418                 }
419         
420                 if (!child->errorList("Parse").empty()) {
421                         // FIXME: Do something.
422                 }
423         }
424         child->setParent(&buffer());
425         // Cache the child buffer.
426         child_buffer_ = child;
427         return child;
428 }
429
430
431 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
432 {
433         string incfile = to_utf8(params()["filename"]);
434
435         // Do nothing if no file name has been specified
436         if (incfile.empty())
437                 return 0;
438
439         FileName const included_file = includedFilename(buffer(), params());
440
441         // Check we're not trying to include ourselves.
442         // FIXME RECURSIVE INCLUDE
443         // This isn't sufficient, as the inclusion could be downstream.
444         // But it'll have to do for now.
445         if (isInputOrInclude(params()) &&
446                 buffer().absFileName() == included_file.absFilename())
447         {
448                 Alert::error(_("Recursive input"),
449                                bformat(_("Attempted to include file %1$s in itself! "
450                                "Ignoring inclusion."), from_utf8(incfile)));
451                 return 0;
452         }
453
454         Buffer const * const masterBuffer = buffer().masterBuffer();
455
456         // if incfile is relative, make it relative to the master
457         // buffer directory.
458         if (!FileName::isAbsolute(incfile)) {
459                 // FIXME UNICODE
460                 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
461                                               from_utf8(masterBuffer->filePath())));
462         }
463
464         // write it to a file (so far the complete file)
465         string exportfile;
466         string mangled;
467         // bug 5681
468         if (type(params()) == LISTINGS) {
469                 exportfile = incfile;
470                 mangled = DocFileName(included_file).mangledFilename();
471         } else {
472                 exportfile = changeExtension(incfile, ".tex");
473                 mangled = DocFileName(changeExtension(included_file.absFilename(), ".tex")).
474                         mangledFilename();
475         }
476
477         FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
478
479         if (!runparams.nice)
480                 incfile = mangled;
481         else if (!isValidLaTeXFilename(incfile)) {
482                 frontend::Alert::warning(_("Invalid filename"),
483                                          _("The following filename is likely to cause trouble "
484                                            "when running the exported file through LaTeX: ") +
485                                             from_utf8(incfile));
486         }
487         LYXERR(Debug::LATEX, "incfile:" << incfile);
488         LYXERR(Debug::LATEX, "exportfile:" << exportfile);
489         LYXERR(Debug::LATEX, "writefile:" << writefile);
490
491         if (runparams.inComment || runparams.dryrun) {
492                 //Don't try to load or copy the file if we're
493                 //in a comment or doing a dryrun
494         } else if (isInputOrInclude(params()) &&
495                  isLyXFilename(included_file.absFilename())) {
496                 //if it's a LyX file and we're inputting or including,
497                 //try to load it so we can write the associated latex
498                 if (!loadIfNeeded())
499                         return false;
500
501                 Buffer * tmp = theBufferList().getBuffer(included_file);
502
503                 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
504                         // FIXME UNICODE
505                         docstring text = bformat(_("Included file `%1$s'\n"
506                                 "has textclass `%2$s'\n"
507                                 "while parent file has textclass `%3$s'."),
508                                 included_file.displayName(),
509                                 from_utf8(tmp->params().documentClass().name()),
510                                 from_utf8(masterBuffer->params().documentClass().name()));
511                         Alert::warning(_("Different textclasses"), text, true);
512                 }
513
514                 // Make sure modules used in child are all included in master
515                 // FIXME It might be worth loading the children's modules into the master
516                 // over in BufferParams rather than doing this check.
517                 LayoutModuleList const masterModules = masterBuffer->params().getModules();
518                 LayoutModuleList const childModules = tmp->params().getModules();
519                 LayoutModuleList::const_iterator it = childModules.begin();
520                 LayoutModuleList::const_iterator end = childModules.end();
521                 for (; it != end; ++it) {
522                         string const module = *it;
523                         LayoutModuleList::const_iterator found =
524                                 find(masterModules.begin(), masterModules.end(), module);
525                         if (found == masterModules.end()) {
526                                 docstring text = bformat(_("Included file `%1$s'\n"
527                                         "uses module `%2$s'\n"
528                                         "which is not used in parent file."),
529                                         included_file.displayName(), from_utf8(module));
530                                 Alert::warning(_("Module not found"), text);
531                         }
532                 }
533
534                 tmp->markDepClean(masterBuffer->temppath());
535
536                 // FIXME: handle non existing files
537                 // FIXME: Second argument is irrelevant!
538                 // since only_body is true, makeLaTeXFile will not look at second
539                 // argument. Should we set it to string(), or should makeLaTeXFile
540                 // make use of it somehow? (JMarc 20031002)
541                 // The included file might be written in a different encoding
542                 Encoding const * const oldEnc = runparams.encoding;
543                 runparams.encoding = &tmp->params().encoding();
544                 tmp->makeLaTeXFile(writefile,
545                                    masterFileName(buffer()).onlyPath().absFilename(),
546                                    runparams, false);
547                 runparams.encoding = oldEnc;
548         } else {
549                 // In this case, it's not a LyX file, so we copy the file
550                 // to the temp dir, so that .aux files etc. are not created
551                 // in the original dir. Files included by this file will be
552                 // found via input@path, see ../Buffer.cpp.
553                 unsigned long const checksum_in  = included_file.checksum();
554                 unsigned long const checksum_out = writefile.checksum();
555
556                 if (checksum_in != checksum_out) {
557                         if (!included_file.copyTo(writefile)) {
558                                 // FIXME UNICODE
559                                 LYXERR(Debug::LATEX,
560                                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
561                                                                   "into the temporary directory."),
562                                                    from_utf8(included_file.absFilename()))));
563                                 return 0;
564                         }
565                 }
566         }
567
568         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
569                         "latex" : "pdflatex";
570         switch (type(params())) {
571         case VERB:
572         case VERBAST: {
573                 incfile = latex_path(incfile);
574                 // FIXME UNICODE
575                 os << '\\' << from_ascii(params().getCmdName()) << '{'
576                    << from_utf8(incfile) << '}';
577                 break;
578         } 
579         case INPUT: {
580                 runparams.exportdata->addExternalFile(tex_format, writefile,
581                                                       exportfile);
582
583                 // \input wants file with extension (default is .tex)
584                 if (!isLyXFilename(included_file.absFilename())) {
585                         incfile = latex_path(incfile);
586                         // FIXME UNICODE
587                         os << '\\' << from_ascii(params().getCmdName())
588                            << '{' << from_utf8(incfile) << '}';
589                 } else {
590                 incfile = changeExtension(incfile, ".tex");
591                 incfile = latex_path(incfile);
592                         // FIXME UNICODE
593                         os << '\\' << from_ascii(params().getCmdName())
594                            << '{' << from_utf8(incfile) <<  '}';
595                 }
596                 break;
597         } 
598         case LISTINGS: {
599                 os << '\\' << from_ascii(params().getCmdName());
600                 string const opt = to_utf8(params()["lstparams"]);
601                 // opt is set in QInclude dialog and should have passed validation.
602                 InsetListingsParams params(opt);
603                 if (!params.params().empty())
604                         os << "[" << from_utf8(params.params()) << "]";
605                 os << '{'  << from_utf8(incfile) << '}';
606                 break;
607         } 
608         case INCLUDE: {
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                 break;
620         }
621         case NONE:
622                 break;
623         }
624
625         return 0;
626 }
627
628
629 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
630 {
631         if (isVerbatim(params()) || isListings(params())) {
632                 os << '[' << screenLabel() << '\n';
633                 // FIXME: We don't know the encoding of the file, default to UTF-8.
634                 os << includedFilename(buffer(), params()).fileContents("UTF-8");
635                 os << "\n]";
636                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
637         } else {
638                 docstring const str = '[' + screenLabel() + ']';
639                 os << str;
640                 return str.size();
641         }
642 }
643
644
645 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
646 {
647         string incfile = to_utf8(params()["filename"]);
648
649         // Do nothing if no file name has been specified
650         if (incfile.empty())
651                 return 0;
652
653         string const included_file = includedFilename(buffer(), params()).absFilename();
654
655         // Check we're not trying to include ourselves.
656         // FIXME RECURSIVE INCLUDE
657         // This isn't sufficient, as the inclusion could be downstream.
658         // But it'll have to do for now.
659         if (buffer().absFileName() == included_file) {
660                 Alert::error(_("Recursive input"),
661                                bformat(_("Attempted to include file %1$s in itself! "
662                                "Ignoring inclusion."), from_utf8(incfile)));
663                 return 0;
664         }
665
666         // write it to a file (so far the complete file)
667         string const exportfile = changeExtension(incfile, ".sgml");
668         DocFileName writefile(changeExtension(included_file, ".sgml"));
669
670         if (loadIfNeeded()) {
671                 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
672
673                 string const mangled = writefile.mangledFilename();
674                 writefile = makeAbsPath(mangled,
675                                         buffer().masterBuffer()->temppath());
676                 if (!runparams.nice)
677                         incfile = mangled;
678
679                 LYXERR(Debug::LATEX, "incfile:" << incfile);
680                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
681                 LYXERR(Debug::LATEX, "writefile:" << writefile);
682
683                 tmp->makeDocBookFile(writefile, runparams, true);
684         }
685
686         runparams.exportdata->addExternalFile("docbook", writefile,
687                                               exportfile);
688         runparams.exportdata->addExternalFile("docbook-xml", writefile,
689                                               exportfile);
690
691         if (isVerbatim(params()) || isListings(params())) {
692                 os << "<inlinegraphic fileref=\""
693                    << '&' << include_label << ';'
694                    << "\" format=\"linespecific\">";
695         } else
696                 os << '&' << include_label << ';';
697
698         return 0;
699 }
700
701
702 void InsetInclude::validate(LaTeXFeatures & features) const
703 {
704         string incfile = to_utf8(params()["filename"]);
705         string writefile;
706
707         LASSERT(&buffer() == &features.buffer(), /**/);
708
709         string const included_file =
710                 includedFilename(buffer(), params()).absFilename();
711
712         if (isLyXFilename(included_file))
713                 writefile = changeExtension(included_file, ".sgml");
714         else
715                 writefile = included_file;
716
717         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
718                 incfile = DocFileName(writefile).mangledFilename();
719                 writefile = makeAbsPath(incfile,
720                                         buffer().masterBuffer()->temppath()).absFilename();
721         }
722
723         features.includeFile(include_label, writefile);
724
725         if (isVerbatim(params()))
726                 features.require("verbatim");
727         else if (isListings(params()))
728                 features.require("listings");
729
730         // Here we must do the fun stuff...
731         // Load the file in the include if it needs
732         // to be loaded:
733         if (loadIfNeeded()) {
734                 // a file got loaded
735                 Buffer * const tmp = theBufferList().getBuffer(FileName(included_file));
736                 // make sure the buffer isn't us
737                 // FIXME RECURSIVE INCLUDES
738                 // This is not sufficient, as recursive includes could be
739                 // more than a file away. But it will do for now.
740                 if (tmp && tmp != &buffer()) {
741                         // We must temporarily change features.buffer,
742                         // otherwise it would always be the master buffer,
743                         // and nested includes would not work.
744                         features.setBuffer(*tmp);
745                         tmp->validate(features);
746                         features.setBuffer(buffer());
747                 }
748         }
749 }
750
751
752 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
753         InsetIterator const & /*di*/) const
754 {
755         if (loadIfNeeded()) {
756                 string const included_file = includedFilename(buffer(), params()).absFilename();
757                 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
758                 BiblioInfo const & newkeys = tmp->localBibInfo();
759                 keys.mergeBiblioInfo(newkeys);
760         }
761 }
762
763
764 void InsetInclude::updateBibfilesCache()
765 {
766         Buffer const * const child = getChildBuffer();
767         if (child)
768                 child->updateBibfilesCache(Buffer::UpdateChildOnly);
769 }
770
771
772 support::FileNameList const &
773         InsetInclude::getBibfilesCache() const
774 {
775         Buffer const * const child = getChildBuffer();
776         if (child)
777                 return child->getBibfilesCache(Buffer::UpdateChildOnly);
778
779         static support::FileNameList const empty;
780         return empty;
781 }
782
783
784 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
785 {
786         LASSERT(mi.base.bv, /**/);
787
788         bool use_preview = false;
789         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
790                 graphics::PreviewImage const * pimage =
791                         preview_->getPreviewImage(mi.base.bv->buffer());
792                 use_preview = pimage && pimage->image();
793         }
794
795         if (use_preview) {
796                 preview_->metrics(mi, dim);
797         } else {
798                 if (!set_label_) {
799                         set_label_ = true;
800                         button_.update(screenLabel(), true);
801                 }
802                 button_.metrics(mi, dim);
803         }
804
805         Box b(0, dim.wid, -dim.asc, dim.des);
806         button_.setBox(b);
807 }
808
809
810 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
811 {
812         LASSERT(pi.base.bv, /**/);
813
814         bool use_preview = false;
815         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
816                 graphics::PreviewImage const * pimage =
817                         preview_->getPreviewImage(pi.base.bv->buffer());
818                 use_preview = pimage && pimage->image();
819         }
820
821         if (use_preview)
822                 preview_->draw(pi, x, y);
823         else
824                 button_.draw(pi, x, y);
825 }
826
827
828 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
829 {
830         return from_ascii("context-include");
831 }
832
833
834 Inset::DisplayType InsetInclude::display() const
835 {
836         return type(params()) == INPUT ? Inline : AlignCenter;
837 }
838
839
840
841 //
842 // preview stuff
843 //
844
845 void InsetInclude::fileChanged() const
846 {
847         Buffer const * const buffer = updateFrontend();
848         if (!buffer)
849                 return;
850
851         preview_->removePreview(*buffer);
852         add_preview(*preview_.get(), *this, *buffer);
853         preview_->startLoading(*buffer);
854 }
855
856
857 namespace {
858
859 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
860 {
861         FileName const included_file = includedFilename(buffer, params);
862
863         return type(params) == INPUT && params.preview() &&
864                 included_file.isReadableFile();
865 }
866
867
868 docstring latexString(InsetInclude const & inset)
869 {
870         odocstringstream os;
871         // We don't need to set runparams.encoding since this will be done
872         // by latex() anyway.
873         OutputParams runparams(0);
874         runparams.flavor = OutputParams::LATEX;
875         inset.latex(os, runparams);
876
877         return os.str();
878 }
879
880
881 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
882                  Buffer const & buffer)
883 {
884         InsetCommandParams const & params = inset.params();
885         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
886             preview_wanted(params, buffer)) {
887                 renderer.setAbsFile(includedFilename(buffer, params));
888                 docstring const snippet = latexString(inset);
889                 renderer.addPreview(snippet, buffer);
890         }
891 }
892
893 } // namespace anon
894
895
896 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
897 {
898         Buffer const & buffer = ploader.buffer();
899         if (!preview_wanted(params(), buffer))
900                 return;
901         preview_->setAbsFile(includedFilename(buffer, params()));
902         docstring const snippet = latexString(*this);
903         preview_->addPreview(snippet, ploader);
904 }
905
906
907 void InsetInclude::addToToc(DocIterator const & cpit)
908 {
909         TocBackend & backend = buffer().tocBackend();
910
911         if (isListings(params())) {
912                 if (label_)
913                         label_->addToToc(cpit);
914
915                 InsetListingsParams p(to_utf8(params()["lstparams"]));
916                 string caption = p.getParamValue("caption");
917                 if (caption.empty())
918                         return;
919                 Toc & toc = backend.toc("listing");
920                 docstring str = convert<docstring>(toc.size() + 1)
921                         + ". " +  from_utf8(caption);
922                 DocIterator pit = cpit;
923                 toc.push_back(TocItem(pit, 0, str));
924                 return;
925         }
926         Buffer const * const childbuffer = getChildBuffer();
927         if (!childbuffer)
928                 return;
929
930         Toc & toc = backend.toc("child");
931         docstring str = childbuffer->fileName().displayName();
932         toc.push_back(TocItem(cpit, 0, str));
933
934         TocList & toclist = backend.tocs();
935         childbuffer->tocBackend().update();
936         TocList const & childtoclist = childbuffer->tocBackend().tocs();
937         TocList::const_iterator it = childtoclist.begin();
938         TocList::const_iterator const end = childtoclist.end();
939         for(; it != end; ++it)
940                 toclist[it->first].insert(toclist[it->first].end(),
941                         it->second.begin(), it->second.end());
942 }
943
944
945 void InsetInclude::updateCommand()
946 {
947         if (!label_)
948                 return;
949
950         docstring old_label = label_->getParam("name");
951         label_->updateCommand(old_label, false);
952         // the label might have been adapted (duplicate)
953         docstring new_label = label_->getParam("name");
954         if (old_label == new_label)
955                 return;
956
957         // update listings parameters...
958         InsetCommandParams p(INCLUDE_CODE);
959         p = params();
960         InsetListingsParams par(to_utf8(params()["lstparams"]));
961         par.addParam("label", "{" + to_utf8(new_label) + "}", true);
962         p["lstparams"] = from_utf8(par.params());
963         setParams(p);   
964 }
965
966 void InsetInclude::updateLabels(ParIterator const & it)
967 {
968         Buffer const * const childbuffer = getChildBuffer();
969         if (childbuffer) {
970                 childbuffer->updateLabels(Buffer::UpdateChildOnly);
971                 return;
972         }
973         if (!isListings(params()))
974                 return;
975
976         if (label_)
977                 label_->updateLabels(it);
978
979         InsetListingsParams const par(to_utf8(params()["lstparams"]));
980         if (par.getParamValue("caption").empty()) {
981                 listings_label_ = buffer().B_("Program Listing");
982                 return;
983         }
984         Buffer const & master = *buffer().masterBuffer();
985         Counters & counters = master.params().documentClass().counters();
986         docstring const cnt = from_ascii("listing");
987         listings_label_ = master.B_("Program Listing");
988         if (counters.hasCounter(cnt)) {
989                 counters.step(cnt);
990                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
991         }
992 }
993
994
995 } // namespace lyx