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