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