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