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