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