]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
Fix bug http://bugzilla.lyx.org/show_bug.cgi?id=4910 by creating InsetText::addToToc().
[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 "LayoutFile.h"
17 #include "Buffer.h"
18 #include "buffer_funcs.h"
19 #include "BufferList.h"
20 #include "BufferParams.h"
21 #include "BufferView.h"
22 #include "Cursor.h"
23 #include "DispatchResult.h"
24 #include "ErrorList.h"
25 #include "Exporter.h"
26 #include "Format.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "LaTeXFeatures.h"
30 #include "LyX.h"
31 #include "LyXFunc.h"
32 #include "LyXRC.h"
33 #include "Lexer.h"
34 #include "MetricsInfo.h"
35 #include "OutputParams.h"
36 #include "TextClass.h"
37 #include "TocBackend.h"
38
39 #include "frontends/alert.h"
40 #include "frontends/Painter.h"
41
42 #include "graphics/PreviewImage.h"
43 #include "graphics/PreviewLoader.h"
44
45 #include "insets/InsetLabel.h"
46 #include "insets/InsetListingsParams.h"
47 #include "insets/RenderPreview.h"
48
49 #include "support/lassert.h"
50 #include "support/debug.h"
51 #include "support/docstream.h"
52 #include "support/FileNameList.h"
53 #include "support/filetools.h"
54 #include "support/gettext.h"
55 #include "support/lstrings.h" // contains
56 #include "support/lyxalgo.h"
57 #include "support/convert.h"
58
59 #include <boost/bind.hpp>
60
61 using namespace std;
62 using namespace lyx::support;
63
64 namespace lyx {
65
66 namespace Alert = frontend::Alert;
67
68
69 namespace {
70
71 docstring const uniqueID()
72 {
73         static unsigned int seed = 1000;
74         return "file" + convert<docstring>(++seed);
75 }
76
77
78 /// the type of inclusion
79 enum Types {
80         INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
81 };
82
83
84 Types type(string const & s)
85 {
86         if (s == "input")
87                 return INPUT;
88         if (s == "verbatiminput")
89                 return VERB;
90         if (s == "verbatiminput*")
91                 return VERBAST;
92         if (s == "lstinputlisting")
93                 return LISTINGS;
94         if (s == "include")
95                 return INCLUDE;
96         return NONE;
97 }
98
99
100 Types type(InsetCommandParams const & params)
101 {
102         return type(params.getCmdName());
103 }
104
105
106 bool isListings(InsetCommandParams const & params)
107 {
108         return type(params) == LISTINGS;
109 }
110
111
112 bool isVerbatim(InsetCommandParams const & params)
113 {
114         Types const t = type(params);
115         return t == VERB || t == VERBAST;
116 }
117
118
119 bool isInputOrInclude(InsetCommandParams const & params)
120 {
121         Types const t = type(params);
122         return t == INPUT || t == INCLUDE;
123 }
124
125
126 FileName const masterFileName(Buffer const & buffer)
127 {
128         return buffer.masterBuffer()->fileName();
129 }
130
131
132 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
133
134
135 string const parentFilename(Buffer const & buffer)
136 {
137         return buffer.absFileName();
138 }
139
140
141 FileName const includedFilename(Buffer const & buffer,
142                               InsetCommandParams const & params)
143 {
144         return makeAbsPath(to_utf8(params["filename"]),
145                         onlyPath(parentFilename(buffer)));
146 }
147
148
149 InsetLabel * createLabel(docstring const & label_str)
150 {
151         if (label_str.empty())
152                 return 0;
153         InsetCommandParams icp(LABEL_CODE);
154         icp["name"] = label_str;
155         return new InsetLabel(icp);
156 }
157
158 } // namespace anon
159
160
161 InsetInclude::InsetInclude(InsetCommandParams const & p)
162         : InsetCommand(p, "include"), include_label(uniqueID()),
163           preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
164 {
165         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
166
167         if (isListings(params())) {
168                 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
169                 label_ = createLabel(from_utf8(listing_params.getParamValue("label")));
170         }
171 }
172
173
174 InsetInclude::InsetInclude(InsetInclude const & other)
175         : InsetCommand(other), include_label(other.include_label),
176           preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
177 {
178         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
179
180         if (other.label_)
181                 label_ = new InsetLabel(*other.label_);
182 }
183
184
185 InsetInclude::~InsetInclude()
186 {
187         delete label_;
188         if (isVerbatim(params()) || isListings(params()))
189                 return;
190
191
192         string const parent_filename = buffer().absFileName();
193         FileName const included_file = makeAbsPath(to_utf8(params()["filename"]),
194                            onlyPath(parent_filename));
195
196         if (!isLyXFilename(included_file.absFilename()))
197                 return;
198
199         Buffer * child = theBufferList().getBuffer(included_file.absFilename());
200         // File not opened, nothing to close.
201         if (!child)
202                 return;
203
204         // Child document has a different parent, don't close it.
205         if (child->parent() != &buffer())
206                 return;
207
208         //close the buffer.
209         theBufferList().release(child);
210 }
211
212
213 void InsetInclude::setBuffer(Buffer & buffer)
214 {
215         InsetCommand::setBuffer(buffer);
216         if (label_)
217                 label_->setBuffer(buffer);
218 }
219
220
221 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
222 {
223         // FIXME
224         // This is only correct for the case of listings, but it'll do for now.
225         // In the other cases, this second parameter should just be empty.
226         static ParamInfo param_info_;
227         if (param_info_.empty()) {
228                 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
229                 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
230         }
231         return param_info_;
232 }
233
234
235 bool InsetInclude::isCompatibleCommand(string const & s)
236 {
237         return type(s) != NONE;
238 }
239
240
241 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
242 {
243         LASSERT(&cur.buffer() == &buffer(), /**/);
244         switch (cmd.action) {
245
246         case LFUN_INSET_EDIT: {
247                 editIncluded(to_utf8(params()["filename"]));
248                 break;
249         }
250
251         case LFUN_INSET_MODIFY: {
252                 InsetCommandParams p(INCLUDE_CODE);
253                 if (cmd.getArg(0) == "changetype") {
254                         InsetCommand::doDispatch(cur, cmd);
255                         p = params();
256                 } else
257                         InsetCommand::string2params("include", to_utf8(cmd.argument()), p);
258                 if (!p.getCmdName().empty()) {
259                         if (isListings(p)){
260                                 InsetListingsParams new_params(to_utf8(p["lstparams"]));
261                                 docstring const label_str = from_utf8(new_params.getParamValue("label"));
262                                 if (label_str.empty())
263                                         delete label_;
264                                 else if (label_)
265                                         label_->updateCommand(label_str);
266                                 else {
267                                         label_ = createLabel(label_str);
268                                         label_->setBuffer(buffer());
269                                         label_->initView();
270                                 }
271                         }
272                         setParams(p);
273                 } else
274                         cur.noUpdate();
275                 break;
276         }
277
278         //pass everything else up the chain
279         default:
280                 InsetCommand::doDispatch(cur, cmd);
281                 break;
282         }
283 }
284
285
286 void InsetInclude::editIncluded(string const & file)
287 {
288         string const ext = support::getExtension(file);
289         if (ext == "lyx") {
290                 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
291                 lyx::dispatch(fr);
292         } else
293                 // tex file or other text file in verbatim mode
294                 formats.edit(buffer(),
295                         support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
296                         "text");
297 }
298
299
300 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
301                 FuncStatus & flag) const
302 {
303         switch (cmd.action) {
304
305         case LFUN_INSET_EDIT:
306         case LFUN_INSET_MODIFY:
307                 flag.setEnabled(true);
308                 return true;
309
310         default:
311                 return InsetCommand::getStatus(cur, cmd, flag);
312         }
313 }
314
315
316 void InsetInclude::setParams(InsetCommandParams const & p)
317 {
318         InsetCommand::setParams(p);
319         set_label_ = false;
320
321         if (preview_->monitoring())
322                 preview_->stopMonitoring();
323
324         if (type(params()) == INPUT)
325                 add_preview(*preview_, *this, buffer());
326
327         buffer().updateBibfilesCache();
328 }
329
330
331 docstring InsetInclude::screenLabel() const
332 {
333         docstring temp;
334
335         switch (type(params())) {
336                 case INPUT:
337                         temp = buffer().B_("Input");
338                         break;
339                 case VERB:
340                         temp = buffer().B_("Verbatim Input");
341                         break;
342                 case VERBAST:
343                         temp = buffer().B_("Verbatim Input*");
344                         break;
345                 case INCLUDE:
346                         temp = buffer().B_("Include");
347                         break;
348                 case LISTINGS:
349                         temp = listings_label_;
350                         break;
351                 case NONE:
352                         LASSERT(false, /**/);
353         }
354
355         temp += ": ";
356
357         if (params()["filename"].empty())
358                 temp += "???";
359         else
360                 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
361
362         return temp;
363 }
364
365
366 /// return the child buffer if the file is a LyX doc and is loaded
367 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
368 {
369         if (isVerbatim(params) || isListings(params))
370                 return 0;
371
372         string const included_file = includedFilename(buffer, params).absFilename();
373         if (!isLyXFilename(included_file))
374                 return 0;
375
376         Buffer * childBuffer = loadIfNeeded(buffer, params); 
377
378         // FIXME: recursive includes
379         return (childBuffer == &buffer) ? 0 : childBuffer;
380 }
381
382
383 /// return true if the file is or got loaded.
384 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
385 {
386         if (isVerbatim(params) || isListings(params))
387                 return 0;
388
389         string const parent_filename = parent.absFileName();
390         FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
391                            onlyPath(parent_filename));
392
393         if (!isLyXFilename(included_file.absFilename()))
394                 return 0;
395
396         Buffer * child = theBufferList().getBuffer(included_file.absFilename());
397         if (!child) {
398                 // the readonly flag can/will be wrong, not anymore I think.
399                 if (!included_file.exists())
400                         return 0;
401
402                 child = theBufferList().newBuffer(included_file.absFilename());
403                 if (!child)
404                         // Buffer creation is not possible.
405                         return 0;
406
407                 if (!child->loadLyXFile(included_file)) {
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 const exportfile = changeExtension(incfile, ".tex");
457         string const mangled =
458                 DocFileName(changeExtension(included_file.absFilename(),".tex")).
459                         mangledFilename();
460         FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
461
462         if (!runparams.nice)
463                 incfile = mangled;
464         else if (!isValidLaTeXFilename(incfile)) {
465                 frontend::Alert::warning(_("Invalid filename"),
466                                          _("The following filename is likely to cause trouble "
467                                            "when running the exported file through LaTeX: ") +
468                                             from_utf8(incfile));
469         }
470         LYXERR(Debug::LATEX, "incfile:" << incfile);
471         LYXERR(Debug::LATEX, "exportfile:" << exportfile);
472         LYXERR(Debug::LATEX, "writefile:" << writefile);
473
474         if (runparams.inComment || runparams.dryrun) {
475                 //Don't try to load or copy the file if we're
476                 //in a comment or doing a dryrun
477         } else if (isInputOrInclude(params()) &&
478                  isLyXFilename(included_file.absFilename())) {
479                 //if it's a LyX file and we're inputting or including,
480                 //try to load it so we can write the associated latex
481                 if (!loadIfNeeded(buffer(), params()))
482                         return false;
483
484                 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
485
486                 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
487                         // FIXME UNICODE
488                         docstring text = bformat(_("Included file `%1$s'\n"
489                                 "has textclass `%2$s'\n"
490                                 "while parent file has textclass `%3$s'."),
491                                 included_file.displayName(),
492                                 from_utf8(tmp->params().documentClass().name()),
493                                 from_utf8(masterBuffer->params().documentClass().name()));
494                         Alert::warning(_("Different textclasses"), text);
495                 }
496
497                 // Make sure modules used in child are all included in master
498                 //FIXME It might be worth loading the children's modules into the master
499                 //over in BufferParams rather than doing this check.
500                 vector<string> const masterModules = masterBuffer->params().getModules();
501                 vector<string> const childModules = tmp->params().getModules();
502                 vector<string>::const_iterator it = childModules.begin();
503                 vector<string>::const_iterator end = childModules.end();
504                 for (; it != end; ++it) {
505                         string const module = *it;
506                         vector<string>::const_iterator found =
507                                 find(masterModules.begin(), masterModules.end(), module);
508                         if (found == masterModules.end()) {
509                                 docstring text = bformat(_("Included file `%1$s'\n"
510                                         "uses module `%2$s'\n"
511                                         "which is not used in parent file."),
512                                         included_file.displayName(), from_utf8(module));
513                                 Alert::warning(_("Module not found"), text);
514                         }
515                 }
516
517                 tmp->markDepClean(masterBuffer->temppath());
518
519 // FIXME: handle non existing files
520 // FIXME: Second argument is irrelevant!
521 // since only_body is true, makeLaTeXFile will not look at second
522 // argument. Should we set it to string(), or should makeLaTeXFile
523 // make use of it somehow? (JMarc 20031002)
524                 // The included file might be written in a different encoding
525                 Encoding const * const oldEnc = runparams.encoding;
526                 runparams.encoding = &tmp->params().encoding();
527                 tmp->makeLaTeXFile(writefile,
528                                    masterFileName(buffer()).onlyPath().absFilename(),
529                                    runparams, false);
530                 runparams.encoding = oldEnc;
531         } else {
532                 // In this case, it's not a LyX file, so we copy the file
533                 // to the temp dir, so that .aux files etc. are not created
534                 // in the original dir. Files included by this file will be
535                 // found via input@path, see ../Buffer.cpp.
536                 unsigned long const checksum_in  = included_file.checksum();
537                 unsigned long const checksum_out = writefile.checksum();
538
539                 if (checksum_in != checksum_out) {
540                         if (!included_file.copyTo(writefile)) {
541                                 // FIXME UNICODE
542                                 LYXERR(Debug::LATEX,
543                                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
544                                                                   "into the temporary directory."),
545                                                    from_utf8(included_file.absFilename()))));
546                                 return 0;
547                         }
548                 }
549         }
550
551         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
552                         "latex" : "pdflatex";
553         if (isVerbatim(params())) {
554                 incfile = latex_path(incfile);
555                 // FIXME UNICODE
556                 os << '\\' << from_ascii(params().getCmdName()) << '{'
557                    << from_utf8(incfile) << '}';
558         } else if (type(params()) == INPUT) {
559                 runparams.exportdata->addExternalFile(tex_format, writefile,
560                                                       exportfile);
561
562                 // \input wants file with extension (default is .tex)
563                 if (!isLyXFilename(included_file.absFilename())) {
564                         incfile = latex_path(incfile);
565                         // FIXME UNICODE
566                         os << '\\' << from_ascii(params().getCmdName())
567                            << '{' << from_utf8(incfile) << '}';
568                 } else {
569                 incfile = changeExtension(incfile, ".tex");
570                 incfile = latex_path(incfile);
571                         // FIXME UNICODE
572                         os << '\\' << from_ascii(params().getCmdName())
573                            << '{' << from_utf8(incfile) <<  '}';
574                 }
575         } else if (type(params()) == LISTINGS) {
576                 os << '\\' << from_ascii(params().getCmdName());
577                 string const opt = to_utf8(params()["lstparams"]);
578                 // opt is set in QInclude dialog and should have passed validation.
579                 InsetListingsParams params(opt);
580                 if (!params.params().empty())
581                         os << "[" << from_utf8(params.params()) << "]";
582                 os << '{'  << from_utf8(incfile) << '}';
583         } else {
584                 runparams.exportdata->addExternalFile(tex_format, writefile,
585                                                       exportfile);
586
587                 // \include don't want extension and demands that the
588                 // file really have .tex
589                 incfile = changeExtension(incfile, string());
590                 incfile = latex_path(incfile);
591                 // FIXME UNICODE
592                 os << '\\' << from_ascii(params().getCmdName()) << '{'
593                    << from_utf8(incfile) << '}';
594         }
595
596         return 0;
597 }
598
599
600 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
601 {
602         if (isVerbatim(params()) || isListings(params())) {
603                 os << '[' << screenLabel() << '\n';
604                 // FIXME: We don't know the encoding of the file, default to UTF-8.
605                 os << includedFilename(buffer(), params()).fileContents("UTF-8");
606                 os << "\n]";
607                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
608         } else {
609                 docstring const str = '[' + screenLabel() + ']';
610                 os << str;
611                 return str.size();
612         }
613 }
614
615
616 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
617 {
618         string incfile = to_utf8(params()["filename"]);
619
620         // Do nothing if no file name has been specified
621         if (incfile.empty())
622                 return 0;
623
624         string const included_file = includedFilename(buffer(), params()).absFilename();
625
626         // Check we're not trying to include ourselves.
627         // FIXME RECURSIVE INCLUDE
628         // This isn't sufficient, as the inclusion could be downstream.
629         // But it'll have to do for now.
630         if (buffer().absFileName() == included_file) {
631                 Alert::error(_("Recursive input"),
632                                bformat(_("Attempted to include file %1$s in itself! "
633                                "Ignoring inclusion."), from_utf8(incfile)));
634                 return 0;
635         }
636
637         // write it to a file (so far the complete file)
638         string const exportfile = changeExtension(incfile, ".sgml");
639         DocFileName writefile(changeExtension(included_file, ".sgml"));
640
641         if (loadIfNeeded(buffer(), params())) {
642                 Buffer * tmp = theBufferList().getBuffer(included_file);
643
644                 string const mangled = writefile.mangledFilename();
645                 writefile = makeAbsPath(mangled,
646                                         buffer().masterBuffer()->temppath());
647                 if (!runparams.nice)
648                         incfile = mangled;
649
650                 LYXERR(Debug::LATEX, "incfile:" << incfile);
651                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
652                 LYXERR(Debug::LATEX, "writefile:" << writefile);
653
654                 tmp->makeDocBookFile(writefile, runparams, true);
655         }
656
657         runparams.exportdata->addExternalFile("docbook", writefile,
658                                               exportfile);
659         runparams.exportdata->addExternalFile("docbook-xml", writefile,
660                                               exportfile);
661
662         if (isVerbatim(params()) || isListings(params())) {
663                 os << "<inlinegraphic fileref=\""
664                    << '&' << include_label << ';'
665                    << "\" format=\"linespecific\">";
666         } else
667                 os << '&' << include_label << ';';
668
669         return 0;
670 }
671
672
673 void InsetInclude::validate(LaTeXFeatures & features) const
674 {
675         string incfile = to_utf8(params()["filename"]);
676         string writefile;
677
678         LASSERT(&buffer() == &features.buffer(), /**/);
679
680         string const included_file =
681                 includedFilename(buffer(), params()).absFilename();
682
683         if (isLyXFilename(included_file))
684                 writefile = changeExtension(included_file, ".sgml");
685         else
686                 writefile = included_file;
687
688         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
689                 incfile = DocFileName(writefile).mangledFilename();
690                 writefile = makeAbsPath(incfile,
691                                         buffer().masterBuffer()->temppath()).absFilename();
692         }
693
694         features.includeFile(include_label, writefile);
695
696         if (isVerbatim(params()))
697                 features.require("verbatim");
698         else if (isListings(params()))
699                 features.require("listings");
700
701         // Here we must do the fun stuff...
702         // Load the file in the include if it needs
703         // to be loaded:
704         if (loadIfNeeded(buffer(), params())) {
705                 // a file got loaded
706                 Buffer * const tmp = theBufferList().getBuffer(included_file);
707                 // make sure the buffer isn't us
708                 // FIXME RECURSIVE INCLUDES
709                 // This is not sufficient, as recursive includes could be
710                 // more than a file away. But it will do for now.
711                 if (tmp && tmp != &buffer()) {
712                         // We must temporarily change features.buffer,
713                         // otherwise it would always be the master buffer,
714                         // and nested includes would not work.
715                         features.setBuffer(*tmp);
716                         tmp->validate(features);
717                         features.setBuffer(buffer());
718                 }
719         }
720 }
721
722
723 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
724         InsetIterator const & /*di*/) const
725 {
726         if (loadIfNeeded(buffer(), params())) {
727                 string const included_file = includedFilename(buffer(), params()).absFilename();
728                 Buffer * tmp = theBufferList().getBuffer(included_file);
729                 BiblioInfo const & newkeys = tmp->localBibInfo();
730                 keys.mergeBiblioInfo(newkeys);
731         }
732 }
733
734
735 void InsetInclude::updateBibfilesCache()
736 {
737         Buffer * const tmp = getChildBuffer(buffer(), params());
738         if (tmp) {
739                 tmp->setParent(0);
740                 tmp->updateBibfilesCache();
741                 tmp->setParent(&buffer());
742         }
743 }
744
745
746 support::FileNameList const &
747         InsetInclude::getBibfilesCache(Buffer const & buffer) const
748 {
749         Buffer * const tmp = getChildBuffer(buffer, params());
750         if (tmp) {
751                 tmp->setParent(0);
752                 support::FileNameList const & cache = tmp->getBibfilesCache();
753                 tmp->setParent(&buffer);
754                 return cache;
755         }
756         static support::FileNameList const empty;
757         return empty;
758 }
759
760
761 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
762 {
763         LASSERT(mi.base.bv, /**/);
764
765         bool use_preview = false;
766         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
767                 graphics::PreviewImage const * pimage =
768                         preview_->getPreviewImage(mi.base.bv->buffer());
769                 use_preview = pimage && pimage->image();
770         }
771
772         if (use_preview) {
773                 preview_->metrics(mi, dim);
774         } else {
775                 if (!set_label_) {
776                         set_label_ = true;
777                         button_.update(screenLabel(), true);
778                 }
779                 button_.metrics(mi, dim);
780         }
781
782         Box b(0, dim.wid, -dim.asc, dim.des);
783         button_.setBox(b);
784 }
785
786
787 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
788 {
789         LASSERT(pi.base.bv, /**/);
790
791         bool use_preview = false;
792         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
793                 graphics::PreviewImage const * pimage =
794                         preview_->getPreviewImage(pi.base.bv->buffer());
795                 use_preview = pimage && pimage->image();
796         }
797
798         if (use_preview)
799                 preview_->draw(pi, x, y);
800         else
801                 button_.draw(pi, x, y);
802 }
803
804
805 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
806 {
807         return from_ascii("context-include");
808 }
809
810
811 Inset::DisplayType InsetInclude::display() const
812 {
813         return type(params()) == INPUT ? Inline : AlignCenter;
814 }
815
816
817
818 //
819 // preview stuff
820 //
821
822 void InsetInclude::fileChanged() const
823 {
824         Buffer const * const buffer = updateFrontend();
825         if (!buffer)
826                 return;
827
828         preview_->removePreview(*buffer);
829         add_preview(*preview_.get(), *this, *buffer);
830         preview_->startLoading(*buffer);
831 }
832
833
834 namespace {
835
836 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
837 {
838         FileName const included_file = includedFilename(buffer, params);
839
840         return type(params) == INPUT && params.preview() &&
841                 included_file.isReadableFile();
842 }
843
844
845 docstring latexString(InsetInclude const & inset)
846 {
847         odocstringstream os;
848         // We don't need to set runparams.encoding since this will be done
849         // by latex() anyway.
850         OutputParams runparams(0);
851         runparams.flavor = OutputParams::LATEX;
852         inset.latex(os, runparams);
853
854         return os.str();
855 }
856
857
858 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
859                  Buffer const & buffer)
860 {
861         InsetCommandParams const & params = inset.params();
862         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
863             preview_wanted(params, buffer)) {
864                 renderer.setAbsFile(includedFilename(buffer, params));
865                 docstring const snippet = latexString(inset);
866                 renderer.addPreview(snippet, buffer);
867         }
868 }
869
870 } // namespace anon
871
872
873 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
874 {
875         Buffer const & buffer = ploader.buffer();
876         if (!preview_wanted(params(), buffer))
877                 return;
878         preview_->setAbsFile(includedFilename(buffer, params()));
879         docstring const snippet = latexString(*this);
880         preview_->addPreview(snippet, ploader);
881 }
882
883
884 void InsetInclude::addToToc(DocIterator const & cpit)
885 {
886         TocBackend & backend = buffer().tocBackend();
887
888         if (isListings(params())) {
889                 if (label_)
890                         label_->addToToc(cpit);
891
892                 InsetListingsParams p(to_utf8(params()["lstparams"]));
893                 string caption = p.getParamValue("caption");
894                 if (caption.empty())
895                         return;
896                 Toc & toc = backend.toc("listing");
897                 docstring str = convert<docstring>(toc.size() + 1)
898                         + ". " +  from_utf8(caption);
899                 DocIterator pit = cpit;
900                 toc.push_back(TocItem(pit, 0, str));
901                 return;
902         }
903         Buffer const * const childbuffer = getChildBuffer(buffer(), params());
904         if (!childbuffer)
905                 return;
906
907         Toc & toc = backend.toc("child");
908         docstring str = childbuffer->fileName().displayName();
909         toc.push_back(TocItem(cpit, 0, str));
910
911         TocList & toclist = backend.tocs();
912         childbuffer->tocBackend().update();
913         TocList const & childtoclist = childbuffer->tocBackend().tocs();
914         TocList::const_iterator it = childtoclist.begin();
915         TocList::const_iterator const end = childtoclist.end();
916         for(; it != end; ++it)
917                 toclist[it->first].insert(toclist[it->first].end(),
918                         it->second.begin(), it->second.end());
919 }
920
921
922 void InsetInclude::updateLabels(ParIterator const & it)
923 {
924         Buffer const * const childbuffer = getChildBuffer(buffer(), params());
925         if (childbuffer) {
926                 lyx::updateLabels(*childbuffer, true);
927                 return;
928         }
929         if (!isListings(params()))
930                 return;
931
932         if (label_)
933                 label_->updateLabels(it);
934
935         InsetListingsParams const par(to_utf8(params()["lstparams"]));
936         if (par.getParamValue("caption").empty()) {
937                 listings_label_ = buffer().B_("Program Listing");
938                 return;
939         }
940         Buffer const & master = *buffer().masterBuffer();
941         Counters & counters = master.params().documentClass().counters();
942         docstring const cnt = from_ascii("listing");
943         listings_label_ = master.B_("Program Listing");
944         if (counters.hasCounter(cnt)) {
945                 counters.step(cnt);
946                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
947         }
948 }
949
950
951 } // namespace lyx