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