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