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