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