]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
Fix for bug 3637, joint work of Bo Peng and myself:
[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)
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)
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                 InsetIncludeMailer(*this).showDialog(&cur.bv());
165                 break;
166
167         default:
168                 Inset::doDispatch(cur, cmd);
169                 break;
170         }
171 }
172
173
174 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
175                 FuncStatus & flag) const
176 {
177         switch (cmd.action) {
178
179         case LFUN_INSET_MODIFY:
180         case LFUN_INSET_DIALOG_UPDATE:
181                 flag.enabled(true);
182                 return true;
183
184         default:
185                 return Inset::getStatus(cur, cmd, flag);
186         }
187 }
188
189
190 InsetCommandParams const & InsetInclude::params() const
191 {
192         return params_;
193 }
194
195
196 namespace {
197
198 /// the type of inclusion
199 enum Types {
200         INCLUDE = 0,
201         VERB = 1,
202         INPUT = 2,
203         VERBAST = 3,
204         LISTINGS = 4,
205 };
206
207
208 Types type(InsetCommandParams const & params)
209 {
210         string const command_name = params.getCmdName();
211
212         if (command_name == "input")
213                 return INPUT;
214         if  (command_name == "verbatiminput")
215                 return VERB;
216         if  (command_name == "verbatiminput*")
217                 return VERBAST;
218         if  (command_name == "lstinputlisting")
219                 return LISTINGS;
220         return INCLUDE;
221 }
222
223
224 bool isVerbatim(InsetCommandParams const & params)
225 {
226         string const command_name = params.getCmdName();
227         return command_name == "verbatiminput" ||
228                 command_name == "verbatiminput*";
229 }
230
231
232 string const masterFilename(Buffer const & buffer)
233 {
234         return buffer.getMasterBuffer()->fileName();
235 }
236
237
238 string const parentFilename(Buffer const & buffer)
239 {
240         return buffer.fileName();
241 }
242
243
244 FileName const includedFilename(Buffer const & buffer,
245                               InsetCommandParams const & params)
246 {
247         return makeAbsPath(to_utf8(params["filename"]),
248                            onlyPath(parentFilename(buffer)));
249 }
250
251
252 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
253
254 } // namespace anon
255
256
257 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
258 {
259         params_ = p;
260         set_label_ = false;
261
262         if (preview_->monitoring())
263                 preview_->stopMonitoring();
264
265         if (type(params_) == INPUT)
266                 add_preview(*preview_, *this, buffer);
267 }
268
269
270 auto_ptr<Inset> InsetInclude::doClone() const
271 {
272         return auto_ptr<Inset>(new InsetInclude(*this));
273 }
274
275
276 void InsetInclude::write(Buffer const &, ostream & os) const
277 {
278         write(os);
279 }
280
281
282 void InsetInclude::write(ostream & os) const
283 {
284         os << "Include " << to_utf8(params_.getCommand()) << '\n'
285            << "preview " << convert<string>(params_.preview()) << '\n';
286 }
287
288
289 void InsetInclude::read(Buffer const &, Lexer & lex)
290 {
291         read(lex);
292 }
293
294
295 void InsetInclude::read(Lexer & lex)
296 {
297         if (lex.isOK()) {
298                 lex.eatLine();
299                 string const command = lex.getString();
300                 params_.scanCommand(command);
301         }
302         string token;
303         while (lex.isOK()) {
304                 lex.next();
305                 token = lex.getString();
306                 if (token == "\\end_inset")
307                         break;
308                 if (token == "preview") {
309                         lex.next();
310                         params_.preview(lex.getBool());
311                 } else
312                         lex.printError("Unknown parameter name `$$Token' for command " + params_.getCmdName());
313         }
314         if (token != "\\end_inset") {
315                 lex.printError("Missing \\end_inset at this point. "
316                                "Read: `$$Token'");
317         }
318 }
319
320
321 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
322 {
323         docstring temp;
324
325         switch (type(params_)) {
326                 case INPUT:
327                         temp += buf.B_("Input");
328                         break;
329                 case VERB:
330                         temp += buf.B_("Verbatim Input");
331                         break;
332                 case VERBAST:
333                         temp += buf.B_("Verbatim Input*");
334                         break;
335                 case INCLUDE:
336                         temp += buf.B_("Include");
337                         break;
338                 case LISTINGS:
339                         temp += buf.B_("Program Listing");
340                         break;
341         }
342
343         temp += ": ";
344
345         if (params_["filename"].empty())
346                 temp += "???";
347         else
348                 temp += from_utf8(onlyFilename(to_utf8(params_["filename"])));
349
350         return temp;
351 }
352
353
354 namespace {
355
356 /// return the child buffer if the file is a LyX doc and is loaded
357 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
358 {
359         if (isVerbatim(params) || isListings(params))
360                 return 0;
361
362         string const included_file = includedFilename(buffer, params).absFilename();
363         if (!isLyXFilename(included_file))
364                 return 0;
365
366         return theBufferList().getBuffer(included_file);
367 }
368
369
370 /// return true if the file is or got loaded.
371 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
372 {
373         if (isVerbatim(params) || isListings(params))
374                 return false;
375
376         FileName const included_file = includedFilename(buffer, params);
377         if (!isLyXFilename(included_file.absFilename()))
378                 return false;
379
380         Buffer * buf = theBufferList().getBuffer(included_file.absFilename());
381         if (!buf) {
382                 // the readonly flag can/will be wrong, not anymore I think.
383                 if (!fs::exists(included_file.toFilesystemEncoding()))
384                         return false;
385                 buf = theBufferList().newBuffer(included_file.absFilename());
386                 if (!loadLyXFile(buf, included_file))
387                         return false;
388         }
389         if (buf)
390                 buf->setParentName(parentFilename(buffer));
391         return buf != 0;
392 }
393
394
395 } // namespace anon
396
397
398 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
399                         OutputParams const & runparams) const
400 {
401         string incfile(to_utf8(params_["filename"]));
402
403         // Do nothing if no file name has been specified
404         if (incfile.empty())
405                 return 0;
406
407         FileName const included_file(includedFilename(buffer, params_));
408         Buffer const * const m_buffer = buffer.getMasterBuffer();
409
410         // if incfile is relative, make it relative to the master
411         // buffer directory.
412         if (!absolutePath(incfile)) {
413                 // FIXME UNICODE
414                 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
415                                               from_utf8(m_buffer->filePath())));
416         }
417
418         // write it to a file (so far the complete file)
419         string const exportfile = changeExtension(incfile, ".tex");
420         string const mangled = DocFileName(changeExtension(included_file.absFilename(),
421                                                         ".tex")).mangledFilename();
422         FileName const writefile(makeAbsPath(mangled, m_buffer->temppath()));
423
424         if (!runparams.nice)
425                 incfile = mangled;
426         LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
427         LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
428         LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
429
430         if (runparams.inComment || runparams.dryrun)
431                 // Don't try to load or copy the file
432                 ;
433         else if (loadIfNeeded(buffer, params_)) {
434                 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
435
436                 if (tmp->params().textclass != m_buffer->params().textclass) {
437                         // FIXME UNICODE
438                         docstring text = bformat(_("Included file `%1$s'\n"
439                                                 "has textclass `%2$s'\n"
440                                                              "while parent file has textclass `%3$s'."),
441                                               makeDisplayPath(included_file.absFilename()),
442                                               from_utf8(tmp->params().getTextClass().name()),
443                                               from_utf8(m_buffer->params().getTextClass().name()));
444                         Alert::warning(_("Different textclasses"), text);
445                         //return 0;
446                 }
447
448                 tmp->markDepClean(m_buffer->temppath());
449
450 #ifdef WITH_WARNINGS
451 #warning handle non existing files
452 #warning Second argument is irrelevant!
453 // since only_body is true, makeLaTeXFile will not look at second
454 // argument. Should we set it to string(), or should makeLaTeXFile
455 // make use of it somehow? (JMarc 20031002)
456 #endif
457                 // The included file might be written in a different encoding
458                 Encoding const * const oldEnc = runparams.encoding;
459                 runparams.encoding = &tmp->params().encoding();
460                 tmp->makeLaTeXFile(writefile,
461                                    onlyPath(masterFilename(buffer)),
462                                    runparams, false);
463                 runparams.encoding = oldEnc;
464         } else {
465                 // Copy the file to the temp dir, so that .aux files etc.
466                 // are not created in the original dir. Files included by
467                 // this file will be found via input@path, see ../Buffer.cpp.
468                 unsigned long const checksum_in  = sum(included_file);
469                 unsigned long const checksum_out = sum(writefile);
470
471                 if (checksum_in != checksum_out) {
472                         if (!copy(included_file, writefile)) {
473                                 // FIXME UNICODE
474                                 LYXERR(Debug::LATEX)
475                                         << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
476                                                                   "into the temporary directory."),
477                                                    from_utf8(included_file.absFilename())))
478                                         << endl;
479                                 return 0;
480                         }
481                 }
482         }
483
484         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
485                         "latex" : "pdflatex";
486         if (isVerbatim(params_)) {
487                 incfile = latex_path(incfile);
488                 // FIXME UNICODE
489                 os << '\\' << from_ascii(params_.getCmdName()) << '{'
490                    << from_utf8(incfile) << '}';
491         } else if (type(params_) == INPUT) {
492                 runparams.exportdata->addExternalFile(tex_format, writefile,
493                                                       exportfile);
494
495                 // \input wants file with extension (default is .tex)
496                 if (!isLyXFilename(included_file.absFilename())) {
497                         incfile = latex_path(incfile);
498                         // FIXME UNICODE
499                         os << '\\' << from_ascii(params_.getCmdName())
500                            << '{' << from_utf8(incfile) << '}';
501                 } else {
502                 incfile = changeExtension(incfile, ".tex");
503                 incfile = latex_path(incfile);
504                         // FIXME UNICODE
505                         os << '\\' << from_ascii(params_.getCmdName())
506                            << '{' << from_utf8(incfile) <<  '}';
507                 }
508         } else if (type(params_) == LISTINGS) {
509                 os << '\\' << from_ascii(params_.getCmdName());
510                 string opt = params_.getOptions();
511                 // opt is set in QInclude dialog and should have passed validation.
512                 InsetListingsParams params(opt);
513                 if (!params.params().empty())
514                         os << "[" << from_utf8(params.encodedString()) << "]";
515                 os << '{'  << from_utf8(incfile) << '}';
516         } else {
517                 runparams.exportdata->addExternalFile(tex_format, writefile,
518                                                       exportfile);
519
520                 // \include don't want extension and demands that the
521                 // file really have .tex
522                 incfile = changeExtension(incfile, string());
523                 incfile = latex_path(incfile);
524                 // FIXME UNICODE
525                 os << '\\' << from_ascii(params_.getCmdName()) << '{'
526                    << from_utf8(incfile) << '}';
527         }
528
529         return 0;
530 }
531
532
533 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
534                             OutputParams const &) const
535 {
536         if (isVerbatim(params_) || isListings(params_)) {
537                 os << '[' << getScreenLabel(buffer) << '\n';
538                 // FIXME: We don't know the encoding of the file
539                 docstring const str =
540                      from_utf8(getFileContents(includedFilename(buffer, params_)));
541                 os << str;
542                 os << "\n]";
543                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
544         } else {
545                 docstring const str = '[' + getScreenLabel(buffer) + ']';
546                 os << str;
547                 return str.size();
548         }
549 }
550
551
552 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
553                           OutputParams const & runparams) const
554 {
555         string incfile = to_utf8(params_["filename"]);
556
557         // Do nothing if no file name has been specified
558         if (incfile.empty())
559                 return 0;
560
561         string const included_file = includedFilename(buffer, params_).absFilename();
562
563         // write it to a file (so far the complete file)
564         string const exportfile = changeExtension(incfile, ".sgml");
565         DocFileName writefile(changeExtension(included_file, ".sgml"));
566
567         if (loadIfNeeded(buffer, params_)) {
568                 Buffer * tmp = theBufferList().getBuffer(included_file);
569
570                 string const mangled = writefile.mangledFilename();
571                 writefile = makeAbsPath(mangled,
572                                         buffer.getMasterBuffer()->temppath());
573                 if (!runparams.nice)
574                         incfile = mangled;
575
576                 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
577                 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
578                 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
579
580                 tmp->makeDocBookFile(writefile, runparams, true);
581         }
582
583         runparams.exportdata->addExternalFile("docbook", writefile,
584                                               exportfile);
585         runparams.exportdata->addExternalFile("docbook-xml", writefile,
586                                               exportfile);
587
588         if (isVerbatim(params_) || isListings(params_)) {
589                 os << "<inlinegraphic fileref=\""
590                    << '&' << include_label << ';'
591                    << "\" format=\"linespecific\">";
592         } else
593                 os << '&' << include_label << ';';
594
595         return 0;
596 }
597
598
599 void InsetInclude::validate(LaTeXFeatures & features) const
600 {
601         string incfile(to_utf8(params_["filename"]));
602         string writefile;
603
604         Buffer const & buffer = features.buffer();
605
606         string const included_file = includedFilename(buffer, params_).absFilename();
607
608         if (isLyXFilename(included_file))
609                 writefile = changeExtension(included_file, ".sgml");
610         else
611                 writefile = included_file;
612
613         if (!features.runparams().nice && !isVerbatim(params_) && !isListings(params_)) {
614                 incfile = DocFileName(writefile).mangledFilename();
615                 writefile = makeAbsPath(incfile,
616                                         buffer.getMasterBuffer()->temppath()).absFilename();
617         }
618
619         features.includeFile(include_label, writefile);
620
621         if (isVerbatim(params_))
622                 features.require("verbatim");
623         else if (isListings(params_))
624                 features.require("listings");
625
626         // Here we must do the fun stuff...
627         // Load the file in the include if it needs
628         // to be loaded:
629         if (loadIfNeeded(buffer, params_)) {
630                 // a file got loaded
631                 Buffer * const tmp = theBufferList().getBuffer(included_file);
632                 if (tmp) {
633                         // We must temporarily change features.buffer,
634                         // otherwise it would always be the master buffer,
635                         // and nested includes would not work.
636                         features.setBuffer(*tmp);
637                         tmp->validate(features);
638                         features.setBuffer(buffer);
639                 }
640         }
641 }
642
643
644 void InsetInclude::getLabelList(Buffer const & buffer,
645                                 std::vector<docstring> & list) const
646 {
647         if (isListings(params_)) {
648                 InsetListingsParams params(params_.getOptions());
649                 string label = params.getParamValue("label");
650                 if (!label.empty())
651                         list.push_back(from_utf8(label));
652         }
653         else if (loadIfNeeded(buffer, params_)) {
654                 string const included_file = includedFilename(buffer, params_).absFilename();
655                 Buffer * tmp = theBufferList().getBuffer(included_file);
656                 tmp->setParentName("");
657                 tmp->getLabelList(list);
658                 tmp->setParentName(parentFilename(buffer));
659         }
660 }
661
662
663 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
664                 std::vector<std::pair<string, docstring> > & keys) const
665 {
666         if (loadIfNeeded(buffer, params_)) {
667                 string const included_file = includedFilename(buffer, params_).absFilename();
668                 Buffer * tmp = theBufferList().getBuffer(included_file);
669                 tmp->setParentName("");
670                 tmp->fillWithBibKeys(keys);
671                 tmp->setParentName(parentFilename(buffer));
672         }
673 }
674
675
676 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
677 {
678         Buffer * const tmp = getChildBuffer(buffer, params_);
679         if (tmp) {
680                 tmp->setParentName("");
681                 tmp->updateBibfilesCache();
682                 tmp->setParentName(parentFilename(buffer));
683         }
684 }
685
686
687 std::vector<FileName> const &
688 InsetInclude::getBibfilesCache(Buffer const & buffer) const
689 {
690         Buffer * const tmp = getChildBuffer(buffer, params_);
691         if (tmp) {
692                 tmp->setParentName("");
693                 std::vector<FileName> const & cache = tmp->getBibfilesCache();
694                 tmp->setParentName(parentFilename(buffer));
695                 return cache;
696         }
697         static std::vector<FileName> const empty;
698         return empty;
699 }
700
701
702 bool InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
703 {
704         BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
705
706         bool use_preview = false;
707         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
708                 graphics::PreviewImage const * pimage =
709                         preview_->getPreviewImage(*mi.base.bv->buffer());
710                 use_preview = pimage && pimage->image();
711         }
712
713         if (use_preview) {
714                 preview_->metrics(mi, dim);
715         } else {
716                 if (!set_label_) {
717                         set_label_ = true;
718                         button_.update(getScreenLabel(*mi.base.bv->buffer()),
719                                        true);
720                 }
721                 button_.metrics(mi, dim);
722         }
723
724         Box b(0, dim.wid, -dim.asc, dim.des);
725         button_.setBox(b);
726
727         bool const changed = dim_ != dim;
728         dim_ = dim;
729         return changed;
730 }
731
732
733 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
734 {
735         setPosCache(pi, x, y);
736
737         BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
738
739         bool use_preview = false;
740         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
741                 graphics::PreviewImage const * pimage =
742                         preview_->getPreviewImage(*pi.base.bv->buffer());
743                 use_preview = pimage && pimage->image();
744         }
745
746         if (use_preview)
747                 preview_->draw(pi, x, y);
748         else
749                 button_.draw(pi, x, y);
750 }
751
752
753 Inset::DisplayType InsetInclude::display() const
754 {
755         return type(params_) == INPUT ? Inline : AlignCenter;
756 }
757
758
759
760 //
761 // preview stuff
762 //
763
764 void InsetInclude::fileChanged() const
765 {
766         Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
767         if (!buffer_ptr)
768                 return;
769
770         Buffer const & buffer = *buffer_ptr;
771         preview_->removePreview(buffer);
772         add_preview(*preview_.get(), *this, buffer);
773         preview_->startLoading(buffer);
774 }
775
776
777 namespace {
778
779 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
780 {
781         FileName const included_file = includedFilename(buffer, params);
782
783         return type(params) == INPUT && params.preview() &&
784                 isFileReadable(included_file);
785 }
786
787
788 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
789 {
790         odocstringstream os;
791         // We don't need to set runparams.encoding since this will be done
792         // by latex() anyway.
793         OutputParams runparams(0);
794         runparams.flavor = OutputParams::LATEX;
795         inset.latex(buffer, os, runparams);
796
797         return os.str();
798 }
799
800
801 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
802                  Buffer const & buffer)
803 {
804         InsetCommandParams const & params = inset.params();
805         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
806             preview_wanted(params, buffer)) {
807                 renderer.setAbsFile(includedFilename(buffer, params));
808                 docstring const snippet = latex_string(inset, buffer);
809                 renderer.addPreview(snippet, buffer);
810         }
811 }
812
813 } // namespace anon
814
815
816 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
817 {
818         Buffer const & buffer = ploader.buffer();
819         if (preview_wanted(params(), buffer)) {
820                 preview_->setAbsFile(includedFilename(buffer, params()));
821                 docstring const snippet = latex_string(*this, buffer);
822                 preview_->addPreview(snippet, ploader);
823         }
824 }
825
826
827 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer) const
828 {
829         Buffer const * const childbuffer = getChildBuffer(buffer, params_);
830         if (!childbuffer)
831                 return;
832
833         TocList const & childtoclist = childbuffer->tocBackend().tocs();
834         TocList::const_iterator it = childtoclist.begin();
835         TocList::const_iterator const end = childtoclist.end();
836         for(; it != end; ++it)
837                 toclist[it->first].insert(toclist[it->first].end(),
838                                 it->second.begin(), it->second.end());
839 }
840
841
842 void InsetInclude::updateLabels(Buffer const & buffer) const
843 {
844         Buffer const * const childbuffer = getChildBuffer(buffer, params_);
845         if (!childbuffer)
846                 return;
847
848         lyx::updateLabels(*childbuffer, true);
849 }
850
851
852 string const InsetIncludeMailer::name_("include");
853
854 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
855         : inset_(inset)
856 {}
857
858
859 string const InsetIncludeMailer::inset2string(Buffer const &) const
860 {
861         return params2string(inset_.params());
862 }
863
864
865 void InsetIncludeMailer::string2params(string const & in,
866                                        InsetCommandParams & params)
867 {
868         params.clear();
869         if (in.empty())
870                 return;
871
872         istringstream data(in);
873         Lexer lex(0,0);
874         lex.setStream(data);
875
876         string name;
877         lex >> name;
878         if (!lex || name != name_)
879                 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
880
881         // This is part of the inset proper that is usually swallowed
882         // by Text::readInset
883         string id;
884         lex >> id;
885         if (!lex || id != "Include")
886                 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
887
888         InsetInclude inset(params);
889         inset.read(lex);
890         params = inset.params();
891 }
892
893
894 string const
895 InsetIncludeMailer::params2string(InsetCommandParams const & params)
896 {
897         InsetInclude inset(params);
898         ostringstream data;
899         data << name_ << ' ';
900         inset.write(data);
901         data << "\\end_inset\n";
902         return data.str();
903 }
904
905
906 } // namespace lyx