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