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