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