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