]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
Get InsetCollapsable working, at least to some extent.
[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() 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         if (isVerbatim(params())) {
571                 incfile = latex_path(incfile);
572                 // FIXME UNICODE
573                 os << '\\' << from_ascii(params().getCmdName()) << '{'
574                    << from_utf8(incfile) << '}';
575         } else if (type(params()) == INPUT) {
576                 runparams.exportdata->addExternalFile(tex_format, writefile,
577                                                       exportfile);
578
579                 // \input wants file with extension (default is .tex)
580                 if (!isLyXFilename(included_file.absFilename())) {
581                         incfile = latex_path(incfile);
582                         // FIXME UNICODE
583                         os << '\\' << from_ascii(params().getCmdName())
584                            << '{' << from_utf8(incfile) << '}';
585                 } else {
586                 incfile = changeExtension(incfile, ".tex");
587                 incfile = latex_path(incfile);
588                         // FIXME UNICODE
589                         os << '\\' << from_ascii(params().getCmdName())
590                            << '{' << from_utf8(incfile) <<  '}';
591                 }
592         } else if (type(params()) == LISTINGS) {
593                 os << '\\' << from_ascii(params().getCmdName());
594                 string const opt = to_utf8(params()["lstparams"]);
595                 // opt is set in QInclude dialog and should have passed validation.
596                 InsetListingsParams params(opt);
597                 if (!params.params().empty())
598                         os << "[" << from_utf8(params.params()) << "]";
599                 os << '{'  << from_utf8(incfile) << '}';
600         } else {
601                 runparams.exportdata->addExternalFile(tex_format, writefile,
602                                                       exportfile);
603
604                 // \include don't want extension and demands that the
605                 // file really have .tex
606                 incfile = changeExtension(incfile, string());
607                 incfile = latex_path(incfile);
608                 // FIXME UNICODE
609                 os << '\\' << from_ascii(params().getCmdName()) << '{'
610                    << from_utf8(incfile) << '}';
611         }
612
613         return 0;
614 }
615
616
617 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
618 {
619         if (isVerbatim(params()) || isListings(params())) {
620                 os << '[' << screenLabel() << '\n';
621                 // FIXME: We don't know the encoding of the file, default to UTF-8.
622                 os << includedFilename(buffer(), params()).fileContents("UTF-8");
623                 os << "\n]";
624                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
625         } else {
626                 docstring const str = '[' + screenLabel() + ']';
627                 os << str;
628                 return str.size();
629         }
630 }
631
632
633 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
634 {
635         string incfile = to_utf8(params()["filename"]);
636
637         // Do nothing if no file name has been specified
638         if (incfile.empty())
639                 return 0;
640
641         string const included_file = includedFilename(buffer(), params()).absFilename();
642
643         // Check we're not trying to include ourselves.
644         // FIXME RECURSIVE INCLUDE
645         // This isn't sufficient, as the inclusion could be downstream.
646         // But it'll have to do for now.
647         if (buffer().absFileName() == included_file) {
648                 Alert::error(_("Recursive input"),
649                                bformat(_("Attempted to include file %1$s in itself! "
650                                "Ignoring inclusion."), from_utf8(incfile)));
651                 return 0;
652         }
653
654         // write it to a file (so far the complete file)
655         string const exportfile = changeExtension(incfile, ".sgml");
656         DocFileName writefile(changeExtension(included_file, ".sgml"));
657
658         if (loadIfNeeded()) {
659                 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
660
661                 string const mangled = writefile.mangledFilename();
662                 writefile = makeAbsPath(mangled,
663                                         buffer().masterBuffer()->temppath());
664                 if (!runparams.nice)
665                         incfile = mangled;
666
667                 LYXERR(Debug::LATEX, "incfile:" << incfile);
668                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
669                 LYXERR(Debug::LATEX, "writefile:" << writefile);
670
671                 tmp->makeDocBookFile(writefile, runparams, true);
672         }
673
674         runparams.exportdata->addExternalFile("docbook", writefile,
675                                               exportfile);
676         runparams.exportdata->addExternalFile("docbook-xml", writefile,
677                                               exportfile);
678
679         if (isVerbatim(params()) || isListings(params())) {
680                 os << "<inlinegraphic fileref=\""
681                    << '&' << include_label << ';'
682                    << "\" format=\"linespecific\">";
683         } else
684                 os << '&' << include_label << ';';
685
686         return 0;
687 }
688
689
690 void InsetInclude::validate(LaTeXFeatures & features) const
691 {
692         string incfile = to_utf8(params()["filename"]);
693         string writefile;
694
695         LASSERT(&buffer() == &features.buffer(), /**/);
696
697         string const included_file =
698                 includedFilename(buffer(), params()).absFilename();
699
700         if (isLyXFilename(included_file))
701                 writefile = changeExtension(included_file, ".sgml");
702         else
703                 writefile = included_file;
704
705         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
706                 incfile = DocFileName(writefile).mangledFilename();
707                 writefile = makeAbsPath(incfile,
708                                         buffer().masterBuffer()->temppath()).absFilename();
709         }
710
711         features.includeFile(include_label, writefile);
712
713         if (isVerbatim(params()))
714                 features.require("verbatim");
715         else if (isListings(params()))
716                 features.require("listings");
717
718         // Here we must do the fun stuff...
719         // Load the file in the include if it needs
720         // to be loaded:
721         if (loadIfNeeded()) {
722                 // a file got loaded
723                 Buffer * const tmp = theBufferList().getBuffer(FileName(included_file));
724                 // make sure the buffer isn't us
725                 // FIXME RECURSIVE INCLUDES
726                 // This is not sufficient, as recursive includes could be
727                 // more than a file away. But it will do for now.
728                 if (tmp && tmp != &buffer()) {
729                         // We must temporarily change features.buffer,
730                         // otherwise it would always be the master buffer,
731                         // and nested includes would not work.
732                         features.setBuffer(*tmp);
733                         tmp->validate(features);
734                         features.setBuffer(buffer());
735                 }
736         }
737 }
738
739
740 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
741         InsetIterator const & /*di*/) const
742 {
743         if (loadIfNeeded()) {
744                 string const included_file = includedFilename(buffer(), params()).absFilename();
745                 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
746                 BiblioInfo const & newkeys = tmp->localBibInfo();
747                 keys.mergeBiblioInfo(newkeys);
748         }
749 }
750
751
752 void InsetInclude::updateBibfilesCache()
753 {
754         Buffer const * const child = getChildBuffer();
755         if (child)
756                 child->updateBibfilesCache(Buffer::UpdateChildOnly);
757 }
758
759
760 support::FileNameList const &
761         InsetInclude::getBibfilesCache() const
762 {
763         Buffer const * const child = getChildBuffer();
764         if (child)
765                 return child->getBibfilesCache(Buffer::UpdateChildOnly);
766
767         static support::FileNameList const empty;
768         return empty;
769 }
770
771
772 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
773 {
774         LASSERT(mi.base.bv, /**/);
775
776         bool use_preview = false;
777         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
778                 graphics::PreviewImage const * pimage =
779                         preview_->getPreviewImage(mi.base.bv->buffer());
780                 use_preview = pimage && pimage->image();
781         }
782
783         if (use_preview) {
784                 preview_->metrics(mi, dim);
785         } else {
786                 if (!set_label_) {
787                         set_label_ = true;
788                         button_.update(screenLabel(), true);
789                 }
790                 button_.metrics(mi, dim);
791         }
792
793         Box b(0, dim.wid, -dim.asc, dim.des);
794         button_.setBox(b);
795 }
796
797
798 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
799 {
800         LASSERT(pi.base.bv, /**/);
801
802         bool use_preview = false;
803         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
804                 graphics::PreviewImage const * pimage =
805                         preview_->getPreviewImage(pi.base.bv->buffer());
806                 use_preview = pimage && pimage->image();
807         }
808
809         if (use_preview)
810                 preview_->draw(pi, x, y);
811         else
812                 button_.draw(pi, x, y);
813 }
814
815
816 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
817 {
818         return from_ascii("context-include");
819 }
820
821
822 Inset::DisplayType InsetInclude::display() const
823 {
824         return type(params()) == INPUT ? Inline : AlignCenter;
825 }
826
827
828
829 //
830 // preview stuff
831 //
832
833 void InsetInclude::fileChanged() const
834 {
835         Buffer const * const buffer = updateFrontend();
836         if (!buffer)
837                 return;
838
839         preview_->removePreview(*buffer);
840         add_preview(*preview_.get(), *this, *buffer);
841         preview_->startLoading(*buffer);
842 }
843
844
845 namespace {
846
847 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
848 {
849         FileName const included_file = includedFilename(buffer, params);
850
851         return type(params) == INPUT && params.preview() &&
852                 included_file.isReadableFile();
853 }
854
855
856 docstring latexString(InsetInclude const & inset)
857 {
858         odocstringstream os;
859         // We don't need to set runparams.encoding since this will be done
860         // by latex() anyway.
861         OutputParams runparams(0);
862         runparams.flavor = OutputParams::LATEX;
863         inset.latex(os, runparams);
864
865         return os.str();
866 }
867
868
869 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
870                  Buffer const & buffer)
871 {
872         InsetCommandParams const & params = inset.params();
873         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
874             preview_wanted(params, buffer)) {
875                 renderer.setAbsFile(includedFilename(buffer, params));
876                 docstring const snippet = latexString(inset);
877                 renderer.addPreview(snippet, buffer);
878         }
879 }
880
881 } // namespace anon
882
883
884 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
885 {
886         Buffer const & buffer = ploader.buffer();
887         if (!preview_wanted(params(), buffer))
888                 return;
889         preview_->setAbsFile(includedFilename(buffer, params()));
890         docstring const snippet = latexString(*this);
891         preview_->addPreview(snippet, ploader);
892 }
893
894
895 void InsetInclude::addToToc(DocIterator const & cpit)
896 {
897         TocBackend & backend = buffer().tocBackend();
898
899         if (isListings(params())) {
900                 if (label_)
901                         label_->addToToc(cpit);
902
903                 InsetListingsParams p(to_utf8(params()["lstparams"]));
904                 string caption = p.getParamValue("caption");
905                 if (caption.empty())
906                         return;
907                 Toc & toc = backend.toc("listing");
908                 docstring str = convert<docstring>(toc.size() + 1)
909                         + ". " +  from_utf8(caption);
910                 DocIterator pit = cpit;
911                 toc.push_back(TocItem(pit, 0, str));
912                 return;
913         }
914         Buffer const * const childbuffer = getChildBuffer();
915         if (!childbuffer)
916                 return;
917
918         Toc & toc = backend.toc("child");
919         docstring str = childbuffer->fileName().displayName();
920         toc.push_back(TocItem(cpit, 0, str));
921
922         TocList & toclist = backend.tocs();
923         childbuffer->tocBackend().update();
924         TocList const & childtoclist = childbuffer->tocBackend().tocs();
925         TocList::const_iterator it = childtoclist.begin();
926         TocList::const_iterator const end = childtoclist.end();
927         for(; it != end; ++it)
928                 toclist[it->first].insert(toclist[it->first].end(),
929                         it->second.begin(), it->second.end());
930 }
931
932
933 void InsetInclude::updateCommand()
934 {
935         if (!label_)
936                 return;
937
938         docstring old_label = label_->getParam("name");
939         label_->updateCommand(old_label, false);
940         // the label might have been adapted (duplicate)
941         docstring new_label = label_->getParam("name");
942         if (old_label == new_label)
943                 return;
944
945         // update listings parameters...
946         InsetCommandParams p(INCLUDE_CODE);
947         p = params();
948         InsetListingsParams par(to_utf8(params()["lstparams"]));
949         par.addParam("label", "{" + to_utf8(new_label) + "}", true);
950         p["lstparams"] = from_utf8(par.params());
951         setParams(p);   
952 }
953
954 void InsetInclude::updateLabels(ParIterator const & it)
955 {
956         Buffer const * const childbuffer = getChildBuffer();
957         if (childbuffer) {
958                 childbuffer->updateLabels(Buffer::UpdateChildOnly);
959                 return;
960         }
961         if (!isListings(params()))
962                 return;
963
964         if (label_)
965                 label_->updateLabels(it);
966
967         InsetListingsParams const par(to_utf8(params()["lstparams"]));
968         if (par.getParamValue("caption").empty()) {
969                 listings_label_ = buffer().B_("Program Listing");
970                 return;
971         }
972         Buffer const & master = *buffer().masterBuffer();
973         Counters & counters = master.params().documentClass().counters();
974         docstring const cnt = from_ascii("listing");
975         listings_label_ = master.B_("Program Listing");
976         if (counters.hasCounter(cnt)) {
977                 counters.step(cnt);
978                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
979         }
980 }
981
982
983 } // namespace lyx