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