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