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