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