]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
Revert r35106.
[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 "support/bind.h"
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(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(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 in 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                         cur.forceBufferUpdate();
278                 } else
279                         cur.noScreenUpdate();
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().invalidateBibfileCache();
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 even want to
407         // try to load the cloned child document again.
408         if (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         FileName const included_file = includedFileName(buffer(), params());
416         // Use cached Buffer if possible.
417         if (child_buffer_ != 0) {
418                 if (theBufferList().isLoaded(child_buffer_)
419                 // additional sanity check: make sure the Buffer really is
420                     // associated with the file we want.
421                     && child_buffer_ == theBufferList().getBuffer(included_file))
422                         return child_buffer_;
423                 // Buffer vanished, so invalidate cache and try to reload.
424                 child_buffer_ = 0;
425         }
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         FileName const included_file = includedFileName(buffer(), params());
683         if (!isLyXFileName(included_file.absFileName())) {
684                 frontend::Alert::warning(_("Unsupported Inclusion"),
685                                          bformat(_("LyX does not know how to include non-LyX files when "
686                                                    "generating HTML output. Offending file:\n%1$s"),
687                                                     params()["filename"]));
688                 return docstring();
689         }
690
691         // In the other cases, we will generate the HTML and include it.
692
693         // Check we're not trying to include ourselves.
694         // FIXME RECURSIVE INCLUDE
695         if (buffer().absFileName() == included_file.absFileName()) {
696                 Alert::error(_("Recursive input"),
697                                bformat(_("Attempted to include file %1$s in itself! "
698                                "Ignoring inclusion."), params()["filename"]));
699                 return docstring();
700         }
701
702         Buffer const * const ibuf = loadIfNeeded();
703         if (!ibuf)
704                 return docstring();
705         ibuf->writeLyXHTMLSource(xs.os(), rp, true);
706         return docstring();
707 }
708
709
710 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
711 {
712         if (isVerbatim(params()) || isListings(params())) {
713                 os << '[' << screenLabel() << '\n';
714                 // FIXME: We don't know the encoding of the file, default to UTF-8.
715                 os << includedFileName(buffer(), params()).fileContents("UTF-8");
716                 os << "\n]";
717                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
718         } else {
719                 docstring const str = '[' + screenLabel() + ']';
720                 os << str;
721                 return str.size();
722         }
723 }
724
725
726 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
727 {
728         string incfile = to_utf8(params()["filename"]);
729
730         // Do nothing if no file name has been specified
731         if (incfile.empty())
732                 return 0;
733
734         string const included_file = includedFileName(buffer(), params()).absFileName();
735
736         // Check we're not trying to include ourselves.
737         // FIXME RECURSIVE INCLUDE
738         // This isn't sufficient, as the inclusion could be downstream.
739         // But it'll have to do for now.
740         if (buffer().absFileName() == included_file) {
741                 Alert::error(_("Recursive input"),
742                                bformat(_("Attempted to include file %1$s in itself! "
743                                "Ignoring inclusion."), from_utf8(incfile)));
744                 return 0;
745         }
746
747         // write it to a file (so far the complete file)
748         string const exportfile = changeExtension(incfile, ".sgml");
749         DocFileName writefile(changeExtension(included_file, ".sgml"));
750
751         if (loadIfNeeded()) {
752                 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
753
754                 string const mangled = writefile.mangledFileName();
755                 writefile = makeAbsPath(mangled,
756                                         buffer().masterBuffer()->temppath());
757                 if (!runparams.nice)
758                         incfile = mangled;
759
760                 LYXERR(Debug::LATEX, "incfile:" << incfile);
761                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
762                 LYXERR(Debug::LATEX, "writefile:" << writefile);
763
764                 tmp->makeDocBookFile(writefile, runparams, true);
765         }
766
767         runparams.exportdata->addExternalFile("docbook", writefile,
768                                               exportfile);
769         runparams.exportdata->addExternalFile("docbook-xml", writefile,
770                                               exportfile);
771
772         if (isVerbatim(params()) || isListings(params())) {
773                 os << "<inlinegraphic fileref=\""
774                    << '&' << include_label << ';'
775                    << "\" format=\"linespecific\">";
776         } else
777                 os << '&' << include_label << ';';
778
779         return 0;
780 }
781
782
783 void InsetInclude::validate(LaTeXFeatures & features) const
784 {
785         string incfile = to_utf8(params()["filename"]);
786         string writefile;
787
788         LASSERT(&buffer() == &features.buffer(), /**/);
789
790         string const included_file =
791                 includedFileName(buffer(), params()).absFileName();
792
793         if (isLyXFileName(included_file))
794                 writefile = changeExtension(included_file, ".sgml");
795         else
796                 writefile = included_file;
797
798         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
799                 incfile = DocFileName(writefile).mangledFileName();
800                 writefile = makeAbsPath(incfile,
801                                         buffer().masterBuffer()->temppath()).absFileName();
802         }
803
804         features.includeFile(include_label, writefile);
805
806         if (isVerbatim(params()))
807                 features.require("verbatim");
808         else if (isListings(params()))
809                 features.require("listings");
810
811         // Here we must do the fun stuff...
812         // Load the file in the include if it needs
813         // to be loaded:
814         if (loadIfNeeded()) {
815                 // a file got loaded
816                 Buffer * const tmp = theBufferList().getBuffer(FileName(included_file));
817                 // make sure the buffer isn't us
818                 // FIXME RECURSIVE INCLUDES
819                 // This is not sufficient, as recursive includes could be
820                 // more than a file away. But it will do for now.
821                 if (tmp && tmp != &buffer()) {
822                         // We must temporarily change features.buffer,
823                         // otherwise it would always be the master buffer,
824                         // and nested includes would not work.
825                         features.setBuffer(*tmp);
826                         tmp->validate(features);
827                         features.setBuffer(buffer());
828                 }
829         }
830 }
831
832
833 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
834         InsetIterator const & /*di*/) const
835 {
836         if (loadIfNeeded()) {
837                 string const included_file = includedFileName(buffer(), params()).absFileName();
838                 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
839                 BiblioInfo const & newkeys = tmp->localBibInfo();
840                 keys.mergeBiblioInfo(newkeys);
841         }
842 }
843
844
845 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
846 {
847         LASSERT(mi.base.bv, /**/);
848
849         bool use_preview = false;
850         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
851                 graphics::PreviewImage const * pimage =
852                         preview_->getPreviewImage(mi.base.bv->buffer());
853                 use_preview = pimage && pimage->image();
854         }
855
856         if (use_preview) {
857                 preview_->metrics(mi, dim);
858         } else {
859                 if (!set_label_) {
860                         set_label_ = true;
861                         button_.update(screenLabel(), true);
862                 }
863                 button_.metrics(mi, dim);
864         }
865
866         Box b(0, dim.wid, -dim.asc, dim.des);
867         button_.setBox(b);
868 }
869
870
871 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
872 {
873         LASSERT(pi.base.bv, /**/);
874
875         bool use_preview = false;
876         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
877                 graphics::PreviewImage const * pimage =
878                         preview_->getPreviewImage(pi.base.bv->buffer());
879                 use_preview = pimage && pimage->image();
880         }
881
882         if (use_preview)
883                 preview_->draw(pi, x, y);
884         else
885                 button_.draw(pi, x, y);
886 }
887
888
889 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
890 {
891         return from_ascii("context-include");
892 }
893
894
895 Inset::DisplayType InsetInclude::display() const
896 {
897         return type(params()) == INPUT ? Inline : AlignCenter;
898 }
899
900
901
902 //
903 // preview stuff
904 //
905
906 void InsetInclude::fileChanged() const
907 {
908         Buffer const * const buffer = updateFrontend();
909         if (!buffer)
910                 return;
911
912         preview_->removePreview(*buffer);
913         add_preview(*preview_.get(), *this, *buffer);
914         preview_->startLoading(*buffer);
915 }
916
917
918 namespace {
919
920 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
921 {
922         FileName const included_file = includedFileName(buffer, params);
923
924         return type(params) == INPUT && params.preview() &&
925                 included_file.isReadableFile();
926 }
927
928
929 docstring latexString(InsetInclude const & inset)
930 {
931         odocstringstream os;
932         // We don't need to set runparams.encoding since this will be done
933         // by latex() anyway.
934         OutputParams runparams(0);
935         runparams.flavor = OutputParams::LATEX;
936         inset.latex(os, runparams);
937
938         return os.str();
939 }
940
941
942 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
943                  Buffer const & buffer)
944 {
945         InsetCommandParams const & params = inset.params();
946         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
947             preview_wanted(params, buffer)) {
948                 renderer.setAbsFile(includedFileName(buffer, params));
949                 docstring const snippet = latexString(inset);
950                 renderer.addPreview(snippet, buffer);
951         }
952 }
953
954 } // namespace anon
955
956
957 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
958         graphics::PreviewLoader & ploader) const
959 {
960         Buffer const & buffer = ploader.buffer();
961         if (!preview_wanted(params(), buffer))
962                 return;
963         preview_->setAbsFile(includedFileName(buffer, params()));
964         docstring const snippet = latexString(*this);
965         preview_->addPreview(snippet, ploader);
966 }
967
968
969 void InsetInclude::addToToc(DocIterator const & cpit)
970 {
971         TocBackend & backend = buffer().tocBackend();
972
973         if (isListings(params())) {
974                 if (label_)
975                         label_->addToToc(cpit);
976
977                 InsetListingsParams p(to_utf8(params()["lstparams"]));
978                 string caption = p.getParamValue("caption");
979                 if (caption.empty())
980                         return;
981                 Toc & toc = backend.toc("listing");
982                 docstring str = convert<docstring>(toc.size() + 1)
983                         + ". " +  from_utf8(caption);
984                 DocIterator pit = cpit;
985                 toc.push_back(TocItem(pit, 0, str));
986                 return;
987         }
988         Buffer const * const childbuffer = getChildBuffer();
989         if (!childbuffer)
990                 return;
991
992         Toc & toc = backend.toc("child");
993         docstring str = childbuffer->fileName().displayName();
994         toc.push_back(TocItem(cpit, 0, str));
995
996         TocList & toclist = backend.tocs();
997         childbuffer->tocBackend().update();
998         TocList const & childtoclist = childbuffer->tocBackend().tocs();
999         TocList::const_iterator it = childtoclist.begin();
1000         TocList::const_iterator const end = childtoclist.end();
1001         for(; it != end; ++it)
1002                 toclist[it->first].insert(toclist[it->first].end(),
1003                         it->second.begin(), it->second.end());
1004 }
1005
1006
1007 void InsetInclude::updateCommand()
1008 {
1009         if (!label_)
1010                 return;
1011
1012         docstring old_label = label_->getParam("name");
1013         label_->updateCommand(old_label, false);
1014         // the label might have been adapted (duplicate)
1015         docstring new_label = label_->getParam("name");
1016         if (old_label == new_label)
1017                 return;
1018
1019         // update listings parameters...
1020         InsetCommandParams p(INCLUDE_CODE);
1021         p = params();
1022         InsetListingsParams par(to_utf8(params()["lstparams"]));
1023         par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1024         p["lstparams"] = from_utf8(par.params());
1025         setParams(p);   
1026 }
1027
1028 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1029 {
1030         Buffer const * const childbuffer = getChildBuffer();
1031         if (childbuffer) {
1032                 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1033                 return;
1034         }
1035         if (!isListings(params()))
1036                 return;
1037
1038         if (label_)
1039                 label_->updateBuffer(it, utype);
1040
1041         InsetListingsParams const par(to_utf8(params()["lstparams"]));
1042         if (par.getParamValue("caption").empty()) {
1043                 listings_label_ = buffer().B_("Program Listing");
1044                 return;
1045         }
1046         Buffer const & master = *buffer().masterBuffer();
1047         Counters & counters = master.params().documentClass().counters();
1048         docstring const cnt = from_ascii("listing");
1049         listings_label_ = master.B_("Program Listing");
1050         if (counters.hasCounter(cnt)) {
1051                 counters.step(cnt, utype);
1052                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1053         }
1054 }
1055
1056
1057 } // namespace lyx