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