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