]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
Make listings dialog translatable (mostly strings from InsetListingsParams), fix...
[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         Buffer * childBuffer = theBufferList().getBuffer(included_file);
367         
368         //FIXME RECURSIVE INCLUDES
369         if (childBuffer == & buffer)
370                 return 0;
371         else return childBuffer;
372 }
373
374
375 /// return true if the file is or got loaded.
376 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
377 {
378         if (isVerbatim(params) || isListings(params))
379                 return false;
380
381         FileName const included_file = includedFilename(buffer, params);
382         if (!isLyXFilename(included_file.absFilename()))
383                 return false;
384
385         Buffer * buf = theBufferList().getBuffer(included_file.absFilename());
386         if (!buf) {
387                 // the readonly flag can/will be wrong, not anymore I think.
388                 if (!fs::exists(included_file.toFilesystemEncoding()))
389                         return false;
390                 buf = theBufferList().newBuffer(included_file.absFilename());
391                 if (!loadLyXFile(buf, included_file))
392                         return false;
393         }
394         if (buf)
395                 buf->setParentName(parentFilename(buffer));
396         return buf != 0;
397 }
398
399
400 } // namespace anon
401
402
403 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
404                         OutputParams const & runparams) const
405 {
406         string incfile(to_utf8(params_["filename"]));
407
408         // Do nothing if no file name has been specified
409         if (incfile.empty())
410                 return 0;
411
412         FileName const included_file(includedFilename(buffer, params_));
413         
414         //Check we're not trying to include ourselves.
415         //FIXME RECURSIVE INCLUDE
416         //This isn't sufficient, as the inclusion could be downstream.
417         //But it'll have to do for now.
418         if (buffer.fileName() == included_file.toFilesystemEncoding()) {
419                 Alert::error(_("Recursive input"), 
420                                bformat(_("Attempted to include file %1$s in itself! "
421                                "Ignoring inclusion."), from_utf8(incfile)));
422                 return 0;
423         }
424
425         Buffer const * const m_buffer = buffer.getMasterBuffer();
426
427         // if incfile is relative, make it relative to the master
428         // buffer directory.
429         if (!absolutePath(incfile)) {
430                 // FIXME UNICODE
431                 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
432                                               from_utf8(m_buffer->filePath())));
433         }
434
435         // write it to a file (so far the complete file)
436         string const exportfile = changeExtension(incfile, ".tex");
437         string const mangled = DocFileName(changeExtension(included_file.absFilename(),
438                                                         ".tex")).mangledFilename();
439         FileName const writefile(makeAbsPath(mangled, m_buffer->temppath()));
440
441         if (!runparams.nice)
442                 incfile = mangled;
443         LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
444         LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
445         LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
446
447         if (runparams.inComment || runparams.dryrun)
448                 // Don't try to load or copy the file
449                 ;
450         else if (loadIfNeeded(buffer, params_)) {
451                 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
452
453                 if (tmp->params().textclass != m_buffer->params().textclass) {
454                         // FIXME UNICODE
455                         docstring text = bformat(_("Included file `%1$s'\n"
456                                                 "has textclass `%2$s'\n"
457                                                              "while parent file has textclass `%3$s'."),
458                                               makeDisplayPath(included_file.absFilename()),
459                                               from_utf8(tmp->params().getTextClass().name()),
460                                               from_utf8(m_buffer->params().getTextClass().name()));
461                         Alert::warning(_("Different textclasses"), text);
462                         //return 0;
463                 }
464
465                 tmp->markDepClean(m_buffer->temppath());
466
467 #ifdef WITH_WARNINGS
468 #warning handle non existing files
469 #warning Second argument is irrelevant!
470 // since only_body is true, makeLaTeXFile will not look at second
471 // argument. Should we set it to string(), or should makeLaTeXFile
472 // make use of it somehow? (JMarc 20031002)
473 #endif
474                 // The included file might be written in a different encoding
475                 Encoding const * const oldEnc = runparams.encoding;
476                 runparams.encoding = &tmp->params().encoding();
477                 tmp->makeLaTeXFile(writefile,
478                                    onlyPath(masterFilename(buffer)),
479                                    runparams, false);
480                 runparams.encoding = oldEnc;
481         } else {
482                 // Copy the file to the temp dir, so that .aux files etc.
483                 // are not created in the original dir. Files included by
484                 // this file will be found via input@path, see ../Buffer.cpp.
485                 unsigned long const checksum_in  = sum(included_file);
486                 unsigned long const checksum_out = sum(writefile);
487
488                 if (checksum_in != checksum_out) {
489                         if (!copy(included_file, writefile)) {
490                                 // FIXME UNICODE
491                                 LYXERR(Debug::LATEX)
492                                         << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
493                                                                   "into the temporary directory."),
494                                                    from_utf8(included_file.absFilename())))
495                                         << endl;
496                                 return 0;
497                         }
498                 }
499         }
500
501         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
502                         "latex" : "pdflatex";
503         if (isVerbatim(params_)) {
504                 incfile = latex_path(incfile);
505                 // FIXME UNICODE
506                 os << '\\' << from_ascii(params_.getCmdName()) << '{'
507                    << from_utf8(incfile) << '}';
508         } else if (type(params_) == INPUT) {
509                 runparams.exportdata->addExternalFile(tex_format, writefile,
510                                                       exportfile);
511
512                 // \input wants file with extension (default is .tex)
513                 if (!isLyXFilename(included_file.absFilename())) {
514                         incfile = latex_path(incfile);
515                         // FIXME UNICODE
516                         os << '\\' << from_ascii(params_.getCmdName())
517                            << '{' << from_utf8(incfile) << '}';
518                 } else {
519                 incfile = changeExtension(incfile, ".tex");
520                 incfile = latex_path(incfile);
521                         // FIXME UNICODE
522                         os << '\\' << from_ascii(params_.getCmdName())
523                            << '{' << from_utf8(incfile) <<  '}';
524                 }
525         } else if (type(params_) == LISTINGS) {
526                 os << '\\' << from_ascii(params_.getCmdName());
527                 string opt = params_.getOptions();
528                 // opt is set in QInclude dialog and should have passed validation.
529                 InsetListingsParams params(opt);
530                 if (!params.params().empty())
531                         os << "[" << from_utf8(params.encodedString()) << "]";
532                 os << '{'  << from_utf8(incfile) << '}';
533         } else {
534                 runparams.exportdata->addExternalFile(tex_format, writefile,
535                                                       exportfile);
536
537                 // \include don't want extension and demands that the
538                 // file really have .tex
539                 incfile = changeExtension(incfile, string());
540                 incfile = latex_path(incfile);
541                 // FIXME UNICODE
542                 os << '\\' << from_ascii(params_.getCmdName()) << '{'
543                    << from_utf8(incfile) << '}';
544         }
545
546         return 0;
547 }
548
549
550 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
551                             OutputParams const &) const
552 {
553         if (isVerbatim(params_) || isListings(params_)) {
554                 os << '[' << getScreenLabel(buffer) << '\n';
555                 // FIXME: We don't know the encoding of the file
556                 docstring const str =
557                      from_utf8(getFileContents(includedFilename(buffer, params_)));
558                 os << str;
559                 os << "\n]";
560                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
561         } else {
562                 docstring const str = '[' + getScreenLabel(buffer) + ']';
563                 os << str;
564                 return str.size();
565         }
566 }
567
568
569 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
570                           OutputParams const & runparams) const
571 {
572         string incfile = to_utf8(params_["filename"]);
573
574         // Do nothing if no file name has been specified
575         if (incfile.empty())
576                 return 0;
577
578         string const included_file = includedFilename(buffer, params_).absFilename();
579
580         //Check we're not trying to include ourselves.
581         //FIXME RECURSIVE INCLUDE
582         //This isn't sufficient, as the inclusion could be downstream.
583         //But it'll have to do for now.
584         if (buffer.fileName() == included_file) {
585                 Alert::error(_("Recursive input"), 
586                                bformat(_("Attempted to include file %1$s in itself! "
587                                "Ignoring inclusion."), from_utf8(incfile)));
588                 return 0;
589         }
590
591         // write it to a file (so far the complete file)
592         string const exportfile = changeExtension(incfile, ".sgml");
593         DocFileName writefile(changeExtension(included_file, ".sgml"));
594
595         if (loadIfNeeded(buffer, params_)) {
596                 Buffer * tmp = theBufferList().getBuffer(included_file);
597
598                 string const mangled = writefile.mangledFilename();
599                 writefile = makeAbsPath(mangled,
600                                         buffer.getMasterBuffer()->temppath());
601                 if (!runparams.nice)
602                         incfile = mangled;
603
604                 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
605                 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
606                 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
607
608                 tmp->makeDocBookFile(writefile, runparams, true);
609         }
610
611         runparams.exportdata->addExternalFile("docbook", writefile,
612                                               exportfile);
613         runparams.exportdata->addExternalFile("docbook-xml", writefile,
614                                               exportfile);
615
616         if (isVerbatim(params_) || isListings(params_)) {
617                 os << "<inlinegraphic fileref=\""
618                    << '&' << include_label << ';'
619                    << "\" format=\"linespecific\">";
620         } else
621                 os << '&' << include_label << ';';
622
623         return 0;
624 }
625
626
627 void InsetInclude::validate(LaTeXFeatures & features) const
628 {
629         string incfile(to_utf8(params_["filename"]));
630         string writefile;
631
632         Buffer const & buffer = features.buffer();
633
634         string const included_file = includedFilename(buffer, params_).absFilename();
635
636         if (isLyXFilename(included_file))
637                 writefile = changeExtension(included_file, ".sgml");
638         else
639                 writefile = included_file;
640
641         if (!features.runparams().nice && !isVerbatim(params_) && !isListings(params_)) {
642                 incfile = DocFileName(writefile).mangledFilename();
643                 writefile = makeAbsPath(incfile,
644                                         buffer.getMasterBuffer()->temppath()).absFilename();
645         }
646
647         features.includeFile(include_label, writefile);
648
649         if (isVerbatim(params_))
650                 features.require("verbatim");
651         else if (isListings(params_))
652                 features.require("listings");
653
654         // Here we must do the fun stuff...
655         // Load the file in the include if it needs
656         // to be loaded:
657         if (loadIfNeeded(buffer, params_)) {
658                 // a file got loaded
659                 Buffer * const tmp = theBufferList().getBuffer(included_file);
660                 // make sure the buffer isn't us
661                 // FIXME RECURSIVE INCLUDES
662                 // This is not sufficient, as recursive includes could be
663                 // more than a file away. But it will do for now.
664                 if (tmp && tmp != & buffer) {
665                         // We must temporarily change features.buffer,
666                         // otherwise it would always be the master buffer,
667                         // and nested includes would not work.
668                         features.setBuffer(*tmp);
669                         tmp->validate(features);
670                         features.setBuffer(buffer);
671                 }
672         }
673 }
674
675
676 void InsetInclude::getLabelList(Buffer const & buffer,
677                                 std::vector<docstring> & list) const
678 {
679         if (isListings(params_)) {
680                 InsetListingsParams params(params_.getOptions());
681                 string label = params.getParamValue("label");
682                 if (!label.empty())
683                         list.push_back(from_utf8(label));
684         }
685         else if (loadIfNeeded(buffer, params_)) {
686                 string const included_file = includedFilename(buffer, params_).absFilename();
687                 Buffer * tmp = theBufferList().getBuffer(included_file);
688                 tmp->setParentName("");
689                 tmp->getLabelList(list);
690                 tmp->setParentName(parentFilename(buffer));
691         }
692 }
693
694
695 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
696                 std::vector<std::pair<string, docstring> > & keys) const
697 {
698         if (loadIfNeeded(buffer, params_)) {
699                 string const included_file = includedFilename(buffer, params_).absFilename();
700                 Buffer * tmp = theBufferList().getBuffer(included_file);
701                 tmp->setParentName("");
702                 tmp->fillWithBibKeys(keys);
703                 tmp->setParentName(parentFilename(buffer));
704         }
705 }
706
707
708 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
709 {
710         Buffer * const tmp = getChildBuffer(buffer, params_);
711         if (tmp) {
712                 tmp->setParentName("");
713                 tmp->updateBibfilesCache();
714                 tmp->setParentName(parentFilename(buffer));
715         }
716 }
717
718
719 std::vector<FileName> const &
720 InsetInclude::getBibfilesCache(Buffer const & buffer) const
721 {
722         Buffer * const tmp = getChildBuffer(buffer, params_);
723         if (tmp) {
724                 tmp->setParentName("");
725                 std::vector<FileName> const & cache = tmp->getBibfilesCache();
726                 tmp->setParentName(parentFilename(buffer));
727                 return cache;
728         }
729         static std::vector<FileName> const empty;
730         return empty;
731 }
732
733
734 bool InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
735 {
736         BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
737
738         bool use_preview = false;
739         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
740                 graphics::PreviewImage const * pimage =
741                         preview_->getPreviewImage(*mi.base.bv->buffer());
742                 use_preview = pimage && pimage->image();
743         }
744
745         if (use_preview) {
746                 preview_->metrics(mi, dim);
747         } else {
748                 if (!set_label_) {
749                         set_label_ = true;
750                         button_.update(getScreenLabel(*mi.base.bv->buffer()),
751                                        true);
752                 }
753                 button_.metrics(mi, dim);
754         }
755
756         Box b(0, dim.wid, -dim.asc, dim.des);
757         button_.setBox(b);
758
759         bool const changed = dim_ != dim;
760         dim_ = dim;
761         return changed;
762 }
763
764
765 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
766 {
767         setPosCache(pi, x, y);
768
769         BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
770
771         bool use_preview = false;
772         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
773                 graphics::PreviewImage const * pimage =
774                         preview_->getPreviewImage(*pi.base.bv->buffer());
775                 use_preview = pimage && pimage->image();
776         }
777
778         if (use_preview)
779                 preview_->draw(pi, x, y);
780         else
781                 button_.draw(pi, x, y);
782 }
783
784
785 Inset::DisplayType InsetInclude::display() const
786 {
787         return type(params_) == INPUT ? Inline : AlignCenter;
788 }
789
790
791
792 //
793 // preview stuff
794 //
795
796 void InsetInclude::fileChanged() const
797 {
798         Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
799         if (!buffer_ptr)
800                 return;
801
802         Buffer const & buffer = *buffer_ptr;
803         preview_->removePreview(buffer);
804         add_preview(*preview_.get(), *this, buffer);
805         preview_->startLoading(buffer);
806 }
807
808
809 namespace {
810
811 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
812 {
813         FileName const included_file = includedFilename(buffer, params);
814
815         return type(params) == INPUT && params.preview() &&
816                 isFileReadable(included_file);
817 }
818
819
820 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
821 {
822         odocstringstream os;
823         // We don't need to set runparams.encoding since this will be done
824         // by latex() anyway.
825         OutputParams runparams(0);
826         runparams.flavor = OutputParams::LATEX;
827         inset.latex(buffer, os, runparams);
828
829         return os.str();
830 }
831
832
833 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
834                  Buffer const & buffer)
835 {
836         InsetCommandParams const & params = inset.params();
837         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
838             preview_wanted(params, buffer)) {
839                 renderer.setAbsFile(includedFilename(buffer, params));
840                 docstring const snippet = latex_string(inset, buffer);
841                 renderer.addPreview(snippet, buffer);
842         }
843 }
844
845 } // namespace anon
846
847
848 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
849 {
850         Buffer const & buffer = ploader.buffer();
851         if (preview_wanted(params(), buffer)) {
852                 preview_->setAbsFile(includedFilename(buffer, params()));
853                 docstring const snippet = latex_string(*this, buffer);
854                 preview_->addPreview(snippet, ploader);
855         }
856 }
857
858
859 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer) const
860 {
861         Buffer const * const childbuffer = getChildBuffer(buffer, params_);
862         if (!childbuffer)
863                 return;
864
865         TocList const & childtoclist = childbuffer->tocBackend().tocs();
866         TocList::const_iterator it = childtoclist.begin();
867         TocList::const_iterator const end = childtoclist.end();
868         for(; it != end; ++it)
869                 toclist[it->first].insert(toclist[it->first].end(),
870                                 it->second.begin(), it->second.end());
871 }
872
873
874 void InsetInclude::updateLabels(Buffer const & buffer) const
875 {
876         Buffer const * const childbuffer = getChildBuffer(buffer, params_);
877         if (!childbuffer)
878                 return;
879
880         lyx::updateLabels(*childbuffer, true);
881 }
882
883
884 string const InsetIncludeMailer::name_("include");
885
886 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
887         : inset_(inset)
888 {}
889
890
891 string const InsetIncludeMailer::inset2string(Buffer const &) const
892 {
893         return params2string(inset_.params());
894 }
895
896
897 void InsetIncludeMailer::string2params(string const & in,
898                                        InsetCommandParams & params)
899 {
900         params.clear();
901         if (in.empty())
902                 return;
903
904         istringstream data(in);
905         Lexer lex(0,0);
906         lex.setStream(data);
907
908         string name;
909         lex >> name;
910         if (!lex || name != name_)
911                 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
912
913         // This is part of the inset proper that is usually swallowed
914         // by Text::readInset
915         string id;
916         lex >> id;
917         if (!lex || id != "Include")
918                 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
919
920         InsetInclude inset(params);
921         inset.read(lex);
922         params = inset.params();
923 }
924
925
926 string const
927 InsetIncludeMailer::params2string(InsetCommandParams const & params)
928 {
929         InsetInclude inset(params);
930         ostringstream data;
931         data << name_ << ' ';
932         inset.write(data);
933         data << "\\end_inset\n";
934         return data.str();
935 }
936
937
938 } // namespace lyx