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