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