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