]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
Proper camel case for FileName.absFilename
[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 even want to
406         // try to load the cloned child document again.
407         if (buffer().isClone())
408                 return child_buffer_;
409         
410         // Don't try to load it again if we failed before.
411         if (failedtoload_ || isVerbatim(params()) || isListings(params()))
412                 return 0;
413
414         FileName const included_file = includedFilename(buffer(), params());
415         // Use cached Buffer if possible.
416         if (child_buffer_ != 0) {
417                 if (theBufferList().isLoaded(child_buffer_)
418                 // additional sanity check: make sure the Buffer really is
419                     // associated with the file we want.
420                     && child_buffer_ == theBufferList().getBuffer(included_file))
421                         return child_buffer_;
422                 // Buffer vanished, so invalidate cache and try to reload.
423                 child_buffer_ = 0;
424         }
425
426         if (!isLyXFilename(included_file.absFileName()))
427                 return 0;
428
429         Buffer * child = theBufferList().getBuffer(included_file);
430         if (!child) {
431                 // the readonly flag can/will be wrong, not anymore I think.
432                 if (!included_file.exists())
433                         return 0;
434
435                 child = theBufferList().newBuffer(included_file.absFileName());
436                 if (!child)
437                         // Buffer creation is not possible.
438                         return 0;
439
440                 if (!child->loadLyXFile(included_file)) {
441                         failedtoload_ = true;
442                         //close the buffer we just opened
443                         theBufferList().release(child);
444                         return 0;
445                 }
446         
447                 if (!child->errorList("Parse").empty()) {
448                         // FIXME: Do something.
449                 }
450         }
451         child->setParent(&buffer());
452         // Cache the child buffer.
453         child_buffer_ = child;
454         return child;
455 }
456
457
458 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
459 {
460         string incfile = to_utf8(params()["filename"]);
461
462         // Do nothing if no file name has been specified
463         if (incfile.empty())
464                 return 0;
465
466         FileName const included_file = includedFilename(buffer(), params());
467
468         // Check we're not trying to include ourselves.
469         // FIXME RECURSIVE INCLUDE
470         // This isn't sufficient, as the inclusion could be downstream.
471         // But it'll have to do for now.
472         if (isInputOrInclude(params()) &&
473                 buffer().absFileName() == included_file.absFileName())
474         {
475                 Alert::error(_("Recursive input"),
476                                bformat(_("Attempted to include file %1$s in itself! "
477                                "Ignoring inclusion."), from_utf8(incfile)));
478                 return 0;
479         }
480
481         Buffer const * const masterBuffer = buffer().masterBuffer();
482
483         // if incfile is relative, make it relative to the master
484         // buffer directory.
485         if (!FileName::isAbsolute(incfile)) {
486                 // FIXME UNICODE
487                 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
488                                               from_utf8(masterBuffer->filePath())));
489         }
490
491         // write it to a file (so far the complete file)
492         string exportfile;
493         string mangled;
494         // bug 5681
495         if (type(params()) == LISTINGS) {
496                 exportfile = incfile;
497                 mangled = DocFileName(included_file).mangledFilename();
498         } else {
499                 exportfile = changeExtension(incfile, ".tex");
500                 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
501                         mangledFilename();
502         }
503
504         FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
505
506         if (!runparams.nice)
507                 incfile = mangled;
508         else if (!isValidLaTeXFilename(incfile)) {
509                 frontend::Alert::warning(_("Invalid filename"),
510                                          _("The following filename is likely to cause trouble "
511                                            "when running the exported file through LaTeX: ") +
512                                             from_utf8(incfile));
513         }
514         LYXERR(Debug::LATEX, "incfile:" << incfile);
515         LYXERR(Debug::LATEX, "exportfile:" << exportfile);
516         LYXERR(Debug::LATEX, "writefile:" << writefile);
517
518         if (runparams.inComment || runparams.dryrun) {
519                 //Don't try to load or copy the file if we're
520                 //in a comment or doing a dryrun
521         } else if (isInputOrInclude(params()) &&
522                  isLyXFilename(included_file.absFileName())) {
523                 //if it's a LyX file and we're inputting or including,
524                 //try to load it so we can write the associated latex
525                 if (!loadIfNeeded())
526                         return false;
527
528                 Buffer * tmp = theBufferList().getBuffer(included_file);
529
530                 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
531                         // FIXME UNICODE
532                         docstring text = bformat(_("Included file `%1$s'\n"
533                                 "has textclass `%2$s'\n"
534                                 "while parent file has textclass `%3$s'."),
535                                 included_file.displayName(),
536                                 from_utf8(tmp->params().documentClass().name()),
537                                 from_utf8(masterBuffer->params().documentClass().name()));
538                         Alert::warning(_("Different textclasses"), text, true);
539                 }
540
541                 // Make sure modules used in child are all included in master
542                 // FIXME It might be worth loading the children's modules into the master
543                 // over in BufferParams rather than doing this check.
544                 LayoutModuleList const masterModules = masterBuffer->params().getModules();
545                 LayoutModuleList const childModules = tmp->params().getModules();
546                 LayoutModuleList::const_iterator it = childModules.begin();
547                 LayoutModuleList::const_iterator end = childModules.end();
548                 for (; it != end; ++it) {
549                         string const module = *it;
550                         LayoutModuleList::const_iterator found =
551                                 find(masterModules.begin(), masterModules.end(), module);
552                         if (found == masterModules.end()) {
553                                 docstring text = bformat(_("Included file `%1$s'\n"
554                                         "uses module `%2$s'\n"
555                                         "which is not used in parent file."),
556                                         included_file.displayName(), from_utf8(module));
557                                 Alert::warning(_("Module not found"), text);
558                         }
559                 }
560
561                 tmp->markDepClean(masterBuffer->temppath());
562
563                 // FIXME: handle non existing files
564                 // FIXME: Second argument is irrelevant!
565                 // since only_body is true, makeLaTeXFile will not look at second
566                 // argument. Should we set it to string(), or should makeLaTeXFile
567                 // make use of it somehow? (JMarc 20031002)
568                 // The included file might be written in a different encoding
569                 // and language.
570                 Encoding const * const oldEnc = runparams.encoding;
571                 Language const * const oldLang = runparams.master_language;
572                 runparams.encoding = &tmp->params().encoding();
573                 runparams.master_language = buffer().params().language;
574                 tmp->makeLaTeXFile(writefile,
575                                    masterFileName(buffer()).onlyPath().absFileName(),
576                                    runparams, false);
577                 runparams.encoding = oldEnc;
578                 runparams.master_language = oldLang;
579         } else {
580                 // In this case, it's not a LyX file, so we copy the file
581                 // to the temp dir, so that .aux files etc. are not created
582                 // in the original dir. Files included by this file will be
583                 // found via input@path, see ../Buffer.cpp.
584                 unsigned long const checksum_in  = included_file.checksum();
585                 unsigned long const checksum_out = writefile.checksum();
586
587                 if (checksum_in != checksum_out) {
588                         if (!included_file.copyTo(writefile)) {
589                                 // FIXME UNICODE
590                                 LYXERR(Debug::LATEX,
591                                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
592                                                                   "into the temporary directory."),
593                                                    from_utf8(included_file.absFileName()))));
594                                 return 0;
595                         }
596                 }
597         }
598
599         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
600                         "latex" : "pdflatex";
601         switch (type(params())) {
602         case VERB:
603         case VERBAST: {
604                 incfile = latex_path(incfile);
605                 // FIXME UNICODE
606                 os << '\\' << from_ascii(params().getCmdName()) << '{'
607                    << from_utf8(incfile) << '}';
608                 break;
609         } 
610         case INPUT: {
611                 runparams.exportdata->addExternalFile(tex_format, writefile,
612                                                       exportfile);
613
614                 // \input wants file with extension (default is .tex)
615                 if (!isLyXFilename(included_file.absFileName())) {
616                         incfile = latex_path(incfile);
617                         // FIXME UNICODE
618                         os << '\\' << from_ascii(params().getCmdName())
619                            << '{' << from_utf8(incfile) << '}';
620                 } else {
621                 incfile = changeExtension(incfile, ".tex");
622                 incfile = latex_path(incfile);
623                         // FIXME UNICODE
624                         os << '\\' << from_ascii(params().getCmdName())
625                            << '{' << from_utf8(incfile) <<  '}';
626                 }
627                 break;
628         } 
629         case LISTINGS: {
630                 os << '\\' << from_ascii(params().getCmdName());
631                 string const opt = to_utf8(params()["lstparams"]);
632                 // opt is set in QInclude dialog and should have passed validation.
633                 InsetListingsParams params(opt);
634                 if (!params.params().empty())
635                         os << "[" << from_utf8(params.params()) << "]";
636                 os << '{'  << from_utf8(incfile) << '}';
637                 break;
638         } 
639         case INCLUDE: {
640                 runparams.exportdata->addExternalFile(tex_format, writefile,
641                                                       exportfile);
642
643                 // \include don't want extension and demands that the
644                 // file really have .tex
645                 incfile = changeExtension(incfile, string());
646                 incfile = latex_path(incfile);
647                 // FIXME UNICODE
648                 os << '\\' << from_ascii(params().getCmdName()) << '{'
649                    << from_utf8(incfile) << '}';
650                 break;
651         }
652         case NONE:
653                 break;
654         }
655
656         return 0;
657 }
658
659
660 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const &rp) const
661 {
662         if (rp.inComment)
663                  return docstring();
664
665         // For verbatim and listings, we just include the contents of the file as-is.
666         // In the case of listings, we wrap it in <pre>.
667         bool const listing = isListings(params());
668         if (listing || isVerbatim(params())) {
669                 if (listing)
670                         xs << html::StartTag("pre");
671                 // FIXME: We don't know the encoding of the file, default to UTF-8.
672                 xs << includedFilename(buffer(), params()).fileContents("UTF-8");
673                 if (listing)
674                         xs << html::EndTag("pre");
675                 return docstring();
676         }
677
678         // We don't (yet) know how to Input or Include non-LyX files.
679         // (If we wanted to get really arcane, we could run some tex2html
680         // converter on the included file. But that's just masochistic.)
681         FileName const included_file = includedFilename(buffer(), params());
682         if (!isLyXFilename(included_file.absFileName())) {
683                 frontend::Alert::warning(_("Unsupported Inclusion"),
684                                          bformat(_("LyX does not know how to include non-LyX files when "
685                                                    "generating HTML output. Offending file:\n%1$s"),
686                                                     params()["filename"]));
687                 return docstring();
688         }
689
690         // In the other cases, we will generate the HTML and include it.
691
692         // Check we're not trying to include ourselves.
693         // FIXME RECURSIVE INCLUDE
694         if (buffer().absFileName() == included_file.absFileName()) {
695                 Alert::error(_("Recursive input"),
696                                bformat(_("Attempted to include file %1$s in itself! "
697                                "Ignoring inclusion."), params()["filename"]));
698                 return docstring();
699         }
700
701         Buffer const * const ibuf = loadIfNeeded();
702         if (!ibuf)
703                 return docstring();
704         ibuf->writeLyXHTMLSource(xs.os(), rp, true);
705         return docstring();
706 }
707
708
709 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
710 {
711         if (isVerbatim(params()) || isListings(params())) {
712                 os << '[' << screenLabel() << '\n';
713                 // FIXME: We don't know the encoding of the file, default to UTF-8.
714                 os << includedFilename(buffer(), params()).fileContents("UTF-8");
715                 os << "\n]";
716                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
717         } else {
718                 docstring const str = '[' + screenLabel() + ']';
719                 os << str;
720                 return str.size();
721         }
722 }
723
724
725 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
726 {
727         string incfile = to_utf8(params()["filename"]);
728
729         // Do nothing if no file name has been specified
730         if (incfile.empty())
731                 return 0;
732
733         string const included_file = includedFilename(buffer(), params()).absFileName();
734
735         // Check we're not trying to include ourselves.
736         // FIXME RECURSIVE INCLUDE
737         // This isn't sufficient, as the inclusion could be downstream.
738         // But it'll have to do for now.
739         if (buffer().absFileName() == included_file) {
740                 Alert::error(_("Recursive input"),
741                                bformat(_("Attempted to include file %1$s in itself! "
742                                "Ignoring inclusion."), from_utf8(incfile)));
743                 return 0;
744         }
745
746         // write it to a file (so far the complete file)
747         string const exportfile = changeExtension(incfile, ".sgml");
748         DocFileName writefile(changeExtension(included_file, ".sgml"));
749
750         if (loadIfNeeded()) {
751                 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
752
753                 string const mangled = writefile.mangledFilename();
754                 writefile = makeAbsPath(mangled,
755                                         buffer().masterBuffer()->temppath());
756                 if (!runparams.nice)
757                         incfile = mangled;
758
759                 LYXERR(Debug::LATEX, "incfile:" << incfile);
760                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
761                 LYXERR(Debug::LATEX, "writefile:" << writefile);
762
763                 tmp->makeDocBookFile(writefile, runparams, true);
764         }
765
766         runparams.exportdata->addExternalFile("docbook", writefile,
767                                               exportfile);
768         runparams.exportdata->addExternalFile("docbook-xml", writefile,
769                                               exportfile);
770
771         if (isVerbatim(params()) || isListings(params())) {
772                 os << "<inlinegraphic fileref=\""
773                    << '&' << include_label << ';'
774                    << "\" format=\"linespecific\">";
775         } else
776                 os << '&' << include_label << ';';
777
778         return 0;
779 }
780
781
782 void InsetInclude::validate(LaTeXFeatures & features) const
783 {
784         string incfile = to_utf8(params()["filename"]);
785         string writefile;
786
787         LASSERT(&buffer() == &features.buffer(), /**/);
788
789         string const included_file =
790                 includedFilename(buffer(), params()).absFileName();
791
792         if (isLyXFilename(included_file))
793                 writefile = changeExtension(included_file, ".sgml");
794         else
795                 writefile = included_file;
796
797         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
798                 incfile = DocFileName(writefile).mangledFilename();
799                 writefile = makeAbsPath(incfile,
800                                         buffer().masterBuffer()->temppath()).absFileName();
801         }
802
803         features.includeFile(include_label, writefile);
804
805         if (isVerbatim(params()))
806                 features.require("verbatim");
807         else if (isListings(params()))
808                 features.require("listings");
809
810         // Here we must do the fun stuff...
811         // Load the file in the include if it needs
812         // to be loaded:
813         if (loadIfNeeded()) {
814                 // a file got loaded
815                 Buffer * const tmp = theBufferList().getBuffer(FileName(included_file));
816                 // make sure the buffer isn't us
817                 // FIXME RECURSIVE INCLUDES
818                 // This is not sufficient, as recursive includes could be
819                 // more than a file away. But it will do for now.
820                 if (tmp && tmp != &buffer()) {
821                         // We must temporarily change features.buffer,
822                         // otherwise it would always be the master buffer,
823                         // and nested includes would not work.
824                         features.setBuffer(*tmp);
825                         tmp->validate(features);
826                         features.setBuffer(buffer());
827                 }
828         }
829 }
830
831
832 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
833         InsetIterator const & /*di*/) const
834 {
835         if (loadIfNeeded()) {
836                 string const included_file = includedFilename(buffer(), params()).absFileName();
837                 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
838                 BiblioInfo const & newkeys = tmp->localBibInfo();
839                 keys.mergeBiblioInfo(newkeys);
840         }
841 }
842
843
844 void InsetInclude::updateBibfilesCache()
845 {
846         Buffer const * const child = getChildBuffer();
847         if (child)
848                 child->updateBibfilesCache(Buffer::UpdateChildOnly);
849 }
850
851
852 support::FileNameList const &
853         InsetInclude::getBibfilesCache() const
854 {
855         Buffer const * const child = getChildBuffer();
856         if (child)
857                 return child->getBibfilesCache(Buffer::UpdateChildOnly);
858
859         static support::FileNameList const empty;
860         return empty;
861 }
862
863
864 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
865 {
866         LASSERT(mi.base.bv, /**/);
867
868         bool use_preview = false;
869         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
870                 graphics::PreviewImage const * pimage =
871                         preview_->getPreviewImage(mi.base.bv->buffer());
872                 use_preview = pimage && pimage->image();
873         }
874
875         if (use_preview) {
876                 preview_->metrics(mi, dim);
877         } else {
878                 if (!set_label_) {
879                         set_label_ = true;
880                         button_.update(screenLabel(), true);
881                 }
882                 button_.metrics(mi, dim);
883         }
884
885         Box b(0, dim.wid, -dim.asc, dim.des);
886         button_.setBox(b);
887 }
888
889
890 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
891 {
892         LASSERT(pi.base.bv, /**/);
893
894         bool use_preview = false;
895         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
896                 graphics::PreviewImage const * pimage =
897                         preview_->getPreviewImage(pi.base.bv->buffer());
898                 use_preview = pimage && pimage->image();
899         }
900
901         if (use_preview)
902                 preview_->draw(pi, x, y);
903         else
904                 button_.draw(pi, x, y);
905 }
906
907
908 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
909 {
910         return from_ascii("context-include");
911 }
912
913
914 Inset::DisplayType InsetInclude::display() const
915 {
916         return type(params()) == INPUT ? Inline : AlignCenter;
917 }
918
919
920
921 //
922 // preview stuff
923 //
924
925 void InsetInclude::fileChanged() const
926 {
927         Buffer const * const buffer = updateFrontend();
928         if (!buffer)
929                 return;
930
931         preview_->removePreview(*buffer);
932         add_preview(*preview_.get(), *this, *buffer);
933         preview_->startLoading(*buffer);
934 }
935
936
937 namespace {
938
939 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
940 {
941         FileName const included_file = includedFilename(buffer, params);
942
943         return type(params) == INPUT && params.preview() &&
944                 included_file.isReadableFile();
945 }
946
947
948 docstring latexString(InsetInclude const & inset)
949 {
950         odocstringstream os;
951         // We don't need to set runparams.encoding since this will be done
952         // by latex() anyway.
953         OutputParams runparams(0);
954         runparams.flavor = OutputParams::LATEX;
955         inset.latex(os, runparams);
956
957         return os.str();
958 }
959
960
961 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
962                  Buffer const & buffer)
963 {
964         InsetCommandParams const & params = inset.params();
965         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
966             preview_wanted(params, buffer)) {
967                 renderer.setAbsFile(includedFilename(buffer, params));
968                 docstring const snippet = latexString(inset);
969                 renderer.addPreview(snippet, buffer);
970         }
971 }
972
973 } // namespace anon
974
975
976 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
977         graphics::PreviewLoader & ploader) const
978 {
979         Buffer const & buffer = ploader.buffer();
980         if (!preview_wanted(params(), buffer))
981                 return;
982         preview_->setAbsFile(includedFilename(buffer, params()));
983         docstring const snippet = latexString(*this);
984         preview_->addPreview(snippet, ploader);
985 }
986
987
988 void InsetInclude::addToToc(DocIterator const & cpit)
989 {
990         TocBackend & backend = buffer().tocBackend();
991
992         if (isListings(params())) {
993                 if (label_)
994                         label_->addToToc(cpit);
995
996                 InsetListingsParams p(to_utf8(params()["lstparams"]));
997                 string caption = p.getParamValue("caption");
998                 if (caption.empty())
999                         return;
1000                 Toc & toc = backend.toc("listing");
1001                 docstring str = convert<docstring>(toc.size() + 1)
1002                         + ". " +  from_utf8(caption);
1003                 DocIterator pit = cpit;
1004                 toc.push_back(TocItem(pit, 0, str));
1005                 return;
1006         }
1007         Buffer const * const childbuffer = getChildBuffer();
1008         if (!childbuffer)
1009                 return;
1010
1011         Toc & toc = backend.toc("child");
1012         docstring str = childbuffer->fileName().displayName();
1013         toc.push_back(TocItem(cpit, 0, str));
1014
1015         TocList & toclist = backend.tocs();
1016         childbuffer->tocBackend().update();
1017         TocList const & childtoclist = childbuffer->tocBackend().tocs();
1018         TocList::const_iterator it = childtoclist.begin();
1019         TocList::const_iterator const end = childtoclist.end();
1020         for(; it != end; ++it)
1021                 toclist[it->first].insert(toclist[it->first].end(),
1022                         it->second.begin(), it->second.end());
1023 }
1024
1025
1026 void InsetInclude::updateCommand()
1027 {
1028         if (!label_)
1029                 return;
1030
1031         docstring old_label = label_->getParam("name");
1032         label_->updateCommand(old_label, false);
1033         // the label might have been adapted (duplicate)
1034         docstring new_label = label_->getParam("name");
1035         if (old_label == new_label)
1036                 return;
1037
1038         // update listings parameters...
1039         InsetCommandParams p(INCLUDE_CODE);
1040         p = params();
1041         InsetListingsParams par(to_utf8(params()["lstparams"]));
1042         par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1043         p["lstparams"] = from_utf8(par.params());
1044         setParams(p);   
1045 }
1046
1047 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1048 {
1049         Buffer const * const childbuffer = getChildBuffer();
1050         if (childbuffer) {
1051                 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1052                 return;
1053         }
1054         if (!isListings(params()))
1055                 return;
1056
1057         if (label_)
1058                 label_->updateBuffer(it, utype);
1059
1060         InsetListingsParams const par(to_utf8(params()["lstparams"]));
1061         if (par.getParamValue("caption").empty()) {
1062                 listings_label_ = buffer().B_("Program Listing");
1063                 return;
1064         }
1065         Buffer const & master = *buffer().masterBuffer();
1066         Counters & counters = master.params().documentClass().counters();
1067         docstring const cnt = from_ascii("listing");
1068         listings_label_ = master.B_("Program Listing");
1069         if (counters.hasCounter(cnt)) {
1070                 counters.step(cnt, utype);
1071                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1072         }
1073 }
1074
1075
1076 } // namespace lyx