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