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