]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
Minor fixup.
[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 <boost/bind.hpp>
61
62 using namespace std;
63 using namespace lyx::support;
64
65 namespace lyx {
66
67 namespace Alert = frontend::Alert;
68
69
70 namespace {
71
72 docstring const uniqueID()
73 {
74         static unsigned int seed = 1000;
75         return "file" + convert<docstring>(++seed);
76 }
77
78
79 /// the type of inclusion
80 enum Types {
81         INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
82 };
83
84
85 Types type(string const & s)
86 {
87         if (s == "input")
88                 return INPUT;
89         if (s == "verbatiminput")
90                 return VERB;
91         if (s == "verbatiminput*")
92                 return VERBAST;
93         if (s == "lstinputlisting")
94                 return LISTINGS;
95         if (s == "include")
96                 return INCLUDE;
97         return NONE;
98 }
99
100
101 Types type(InsetCommandParams const & params)
102 {
103         return type(params.getCmdName());
104 }
105
106
107 bool isListings(InsetCommandParams const & params)
108 {
109         return type(params) == LISTINGS;
110 }
111
112
113 bool isVerbatim(InsetCommandParams const & params)
114 {
115         Types const t = type(params);
116         return t == VERB || t == VERBAST;
117 }
118
119
120 bool isInputOrInclude(InsetCommandParams const & params)
121 {
122         Types const t = type(params);
123         return t == INPUT || t == INCLUDE;
124 }
125
126
127 FileName const masterFileName(Buffer const & buffer)
128 {
129         return buffer.masterBuffer()->fileName();
130 }
131
132
133 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
134
135
136 string const parentFilename(Buffer const & buffer)
137 {
138         return buffer.absFileName();
139 }
140
141
142 FileName const includedFilename(Buffer const & buffer,
143                               InsetCommandParams const & params)
144 {
145         return makeAbsPath(to_utf8(params["filename"]),
146                         onlyPath(parentFilename(buffer)));
147 }
148
149
150 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
151 {
152         if (label_str.empty())
153                 return 0;
154         InsetCommandParams icp(LABEL_CODE);
155         icp["name"] = label_str;
156         return new InsetLabel(buf, icp);
157 }
158
159 } // namespace anon
160
161
162 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
163         : InsetCommand(buf, p, "include"), include_label(uniqueID()),
164           preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
165           set_label_(false), label_(0), child_buffer_(0)
166 {
167         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
168
169         if (isListings(params())) {
170                 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
171                 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
172         }
173 }
174
175
176 InsetInclude::InsetInclude(InsetInclude const & other)
177         : InsetCommand(other), include_label(other.include_label),
178           preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
179           set_label_(false), label_(0), child_buffer_(0)
180 {
181         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
182
183         if (other.label_)
184                 label_ = new InsetLabel(*other.label_);
185 }
186
187
188 InsetInclude::~InsetInclude()
189 {
190         delete label_;
191 }
192
193
194 void InsetInclude::setBuffer(Buffer & buffer)
195 {
196         InsetCommand::setBuffer(buffer);
197         if (label_)
198                 label_->setBuffer(buffer);
199 }
200
201
202 void InsetInclude::setChildBuffer(Buffer * buffer)
203 {
204         child_buffer_ = buffer;
205 }
206
207
208 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
209 {
210         // FIXME
211         // This is only correct for the case of listings, but it'll do for now.
212         // In the other cases, this second parameter should just be empty.
213         static ParamInfo param_info_;
214         if (param_info_.empty()) {
215                 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
216                 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
217         }
218         return param_info_;
219 }
220
221
222 bool InsetInclude::isCompatibleCommand(string const & s)
223 {
224         return type(s) != NONE;
225 }
226
227
228 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
229 {
230         switch (cmd.action) {
231
232         case LFUN_INSET_EDIT: {
233                 editIncluded(to_utf8(params()["filename"]));
234                 break;
235         }
236
237         case LFUN_INSET_MODIFY: {
238                 // It should be OK just to invalidate the cache is setParams()
239                 // If not....
240                 // child_buffer_ = 0;
241                 InsetCommandParams p(INCLUDE_CODE);
242                 if (cmd.getArg(0) == "changetype") {
243                         InsetCommand::doDispatch(cur, cmd);
244                         p = params();
245                 } else
246                         InsetCommand::string2params("include", to_utf8(cmd.argument()), p);
247                 if (!p.getCmdName().empty()) {
248                         if (isListings(p)){
249                                 InsetListingsParams new_params(to_utf8(p["lstparams"]));
250                                 docstring const new_label =
251                                         from_utf8(new_params.getParamValue("label"));
252                                 
253                                 if (new_label.empty()) {
254                                         delete label_;
255                                         label_ = 0;
256                                 } else {
257                                         docstring old_label;
258                                         if (label_) 
259                                                 old_label = label_->getParam("name");
260                                         else {
261                                                 label_ = createLabel(buffer_, new_label);
262                                                 label_->setBuffer(buffer());
263                                         }                                       
264
265                                         if (new_label != old_label) {
266                                                 label_->updateCommand(new_label);
267                                                 // the label might have been adapted (duplicate)
268                                                 if (new_label != label_->getParam("name")) {
269                                                         new_params.addParam("label", "{" + 
270                                                                 to_utf8(label_->getParam("name")) + "}", true);
271                                                         p["lstparams"] = from_utf8(new_params.params());
272                                                 }
273                                         }
274                                 }
275                         }
276                         setParams(p);
277                 } else
278                         cur.noUpdate();
279                 break;
280         }
281
282         //pass everything else up the chain
283         default:
284                 InsetCommand::doDispatch(cur, cmd);
285                 break;
286         }
287 }
288
289
290 void InsetInclude::editIncluded(string const & file)
291 {
292         string const ext = support::getExtension(file);
293         if (ext == "lyx") {
294                 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
295                 lyx::dispatch(fr);
296         } else
297                 // tex file or other text file in verbatim mode
298                 formats.edit(buffer(),
299                         support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
300                         "text");
301 }
302
303
304 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
305                 FuncStatus & flag) const
306 {
307         switch (cmd.action) {
308
309         case LFUN_INSET_EDIT:
310                 flag.setEnabled(true);
311                 return true;
312
313         case LFUN_INSET_MODIFY:
314                 if (cmd.getArg(0) == "changetype")
315                         return InsetCommand::getStatus(cur, cmd, flag);
316                 else
317                         flag.setEnabled(true);
318                 return true;
319
320         default:
321                 return InsetCommand::getStatus(cur, cmd, flag);
322         }
323 }
324
325
326 void InsetInclude::setParams(InsetCommandParams const & p)
327 {
328         // invalidate the cache
329         child_buffer_ = 0;
330
331         InsetCommand::setParams(p);
332         set_label_ = false;
333
334         if (preview_->monitoring())
335                 preview_->stopMonitoring();
336
337         if (type(params()) == INPUT)
338                 add_preview(*preview_, *this, buffer());
339
340         buffer().updateBibfilesCache();
341 }
342
343
344 bool InsetInclude::isChildIncluded() const
345 {
346         std::list<std::string> includeonlys =
347                 buffer().params().getIncludedChildren();
348         if (includeonlys.empty())
349                 return true;
350         return (std::find(includeonlys.begin(),
351                           includeonlys.end(),
352                           to_utf8(params()["filename"])) != includeonlys.end());
353 }
354
355
356 docstring InsetInclude::screenLabel() const
357 {
358         docstring temp;
359
360         switch (type(params())) {
361                 case INPUT:
362                         temp = buffer().B_("Input");
363                         break;
364                 case VERB:
365                         temp = buffer().B_("Verbatim Input");
366                         break;
367                 case VERBAST:
368                         temp = buffer().B_("Verbatim Input*");
369                         break;
370                 case INCLUDE:
371                         if (isChildIncluded())
372                                 temp = buffer().B_("Include");
373                         else
374                                 temp += buffer().B_("Include (excluded)");
375                         break;
376                 case LISTINGS:
377                         temp = listings_label_;
378                         break;
379                 case NONE:
380                         LASSERT(false, /**/);
381         }
382
383         temp += ": ";
384
385         if (params()["filename"].empty())
386                 temp += "???";
387         else
388                 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
389
390         return temp;
391 }
392
393
394 Buffer * InsetInclude::getChildBuffer() const
395 {
396         Buffer * childBuffer = loadIfNeeded(); 
397
398         // FIXME: recursive includes
399         return (childBuffer == &buffer()) ? 0 : childBuffer;
400 }
401
402
403 Buffer * InsetInclude::loadIfNeeded() const
404 {
405         // This is for background export and preview. We don't want to load the
406         // cloned child document again.
407         if (child_buffer_ && theBufferList().isLoaded(child_buffer_)
408                   && 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         FileName const included_file = includedFilename(buffer(), params());
416         // Use cached Buffer if possible.
417         if (child_buffer_ != 0) {
418                 if (theBufferList().isLoaded(child_buffer_) 
419                                 // additional sanity check: make sure the Buffer really is
420                                 // associated with the file we want.
421                                 && child_buffer_ == theBufferList().getBuffer(included_file))
422                         return child_buffer_;
423                 // Buffer vanished, so invalidate cache and try to reload.
424                 child_buffer_ = 0;
425         }
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 << html::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 << html::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         FileName const included_file = includedFilename(buffer());
683         if (!isLyXFilename(included_file.absFilename())) {
684                 frontend::Alert::warning(_("Unsupported Inclusion"),
685                                          bformat(_("LyX does not know how to include non-LyX files when "
686                                                    "generating HTML output. Offending file:\n%1$s"),
687                                                     params()["filename"]));
688                 return docstring();
689         }
690
691         // In the other cases, we will generate the HTML and include it.
692
693         // Check we're not trying to include ourselves.
694         // FIXME RECURSIVE INCLUDE
695         if (buffer().absFileName() == included_file.absFilename()) {
696                 Alert::error(_("Recursive input"),
697                                bformat(_("Attempted to include file %1$s in itself! "
698                                "Ignoring inclusion."), params()["filename"]));
699                 return docstring();
700         }
701
702         Buffer const * const ibuf = loadIfNeeded();
703         if (!ibuf)
704                 return docstring();
705         ibuf->writeLyXHTMLSource(xs.os(), rp, true);
706         return docstring();
707 }
708
709
710 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
711 {
712         if (isVerbatim(params()) || isListings(params())) {
713                 os << '[' << screenLabel() << '\n';
714                 // FIXME: We don't know the encoding of the file, default to UTF-8.
715                 os << includedFilename(buffer(), params()).fileContents("UTF-8");
716                 os << "\n]";
717                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
718         } else {
719                 docstring const str = '[' + screenLabel() + ']';
720                 os << str;
721                 return str.size();
722         }
723 }
724
725
726 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
727 {
728         string incfile = to_utf8(params()["filename"]);
729
730         // Do nothing if no file name has been specified
731         if (incfile.empty())
732                 return 0;
733
734         string const included_file = includedFilename(buffer(), params()).absFilename();
735
736         // Check we're not trying to include ourselves.
737         // FIXME RECURSIVE INCLUDE
738         // This isn't sufficient, as the inclusion could be downstream.
739         // But it'll have to do for now.
740         if (buffer().absFileName() == included_file) {
741                 Alert::error(_("Recursive input"),
742                                bformat(_("Attempted to include file %1$s in itself! "
743                                "Ignoring inclusion."), from_utf8(incfile)));
744                 return 0;
745         }
746
747         // write it to a file (so far the complete file)
748         string const exportfile = changeExtension(incfile, ".sgml");
749         DocFileName writefile(changeExtension(included_file, ".sgml"));
750
751         if (loadIfNeeded()) {
752                 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
753
754                 string const mangled = writefile.mangledFilename();
755                 writefile = makeAbsPath(mangled,
756                                         buffer().masterBuffer()->temppath());
757                 if (!runparams.nice)
758                         incfile = mangled;
759
760                 LYXERR(Debug::LATEX, "incfile:" << incfile);
761                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
762                 LYXERR(Debug::LATEX, "writefile:" << writefile);
763
764                 tmp->makeDocBookFile(writefile, runparams, true);
765         }
766
767         runparams.exportdata->addExternalFile("docbook", writefile,
768                                               exportfile);
769         runparams.exportdata->addExternalFile("docbook-xml", writefile,
770                                               exportfile);
771
772         if (isVerbatim(params()) || isListings(params())) {
773                 os << "<inlinegraphic fileref=\""
774                    << '&' << include_label << ';'
775                    << "\" format=\"linespecific\">";
776         } else
777                 os << '&' << include_label << ';';
778
779         return 0;
780 }
781
782
783 void InsetInclude::validate(LaTeXFeatures & features) const
784 {
785         string incfile = to_utf8(params()["filename"]);
786         string writefile;
787
788         LASSERT(&buffer() == &features.buffer(), /**/);
789
790         string const included_file =
791                 includedFilename(buffer(), params()).absFilename();
792
793         if (isLyXFilename(included_file))
794                 writefile = changeExtension(included_file, ".sgml");
795         else
796                 writefile = included_file;
797
798         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
799                 incfile = DocFileName(writefile).mangledFilename();
800                 writefile = makeAbsPath(incfile,
801                                         buffer().masterBuffer()->temppath()).absFilename();
802         }
803
804         features.includeFile(include_label, writefile);
805
806         if (isVerbatim(params()))
807                 features.require("verbatim");
808         else if (isListings(params()))
809                 features.require("listings");
810
811         // Here we must do the fun stuff...
812         // Load the file in the include if it needs
813         // to be loaded:
814         if (loadIfNeeded()) {
815                 // a file got loaded
816                 Buffer * const tmp = theBufferList().getBuffer(FileName(included_file));
817                 // make sure the buffer isn't us
818                 // FIXME RECURSIVE INCLUDES
819                 // This is not sufficient, as recursive includes could be
820                 // more than a file away. But it will do for now.
821                 if (tmp && tmp != &buffer()) {
822                         // We must temporarily change features.buffer,
823                         // otherwise it would always be the master buffer,
824                         // and nested includes would not work.
825                         features.setBuffer(*tmp);
826                         tmp->validate(features);
827                         features.setBuffer(buffer());
828                 }
829         }
830 }
831
832
833 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
834         InsetIterator const & /*di*/) const
835 {
836         if (loadIfNeeded()) {
837                 string const included_file = includedFilename(buffer(), params()).absFilename();
838                 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
839                 BiblioInfo const & newkeys = tmp->localBibInfo();
840                 keys.mergeBiblioInfo(newkeys);
841         }
842 }
843
844
845 void InsetInclude::updateBibfilesCache()
846 {
847         Buffer const * const child = getChildBuffer();
848         if (child)
849                 child->updateBibfilesCache(Buffer::UpdateChildOnly);
850 }
851
852
853 support::FileNameList const &
854         InsetInclude::getBibfilesCache() const
855 {
856         Buffer const * const child = getChildBuffer();
857         if (child)
858                 return child->getBibfilesCache(Buffer::UpdateChildOnly);
859
860         static support::FileNameList const empty;
861         return empty;
862 }
863
864
865 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
866 {
867         LASSERT(mi.base.bv, /**/);
868
869         bool use_preview = false;
870         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
871                 graphics::PreviewImage const * pimage =
872                         preview_->getPreviewImage(mi.base.bv->buffer());
873                 use_preview = pimage && pimage->image();
874         }
875
876         if (use_preview) {
877                 preview_->metrics(mi, dim);
878         } else {
879                 if (!set_label_) {
880                         set_label_ = true;
881                         button_.update(screenLabel(), true);
882                 }
883                 button_.metrics(mi, dim);
884         }
885
886         Box b(0, dim.wid, -dim.asc, dim.des);
887         button_.setBox(b);
888 }
889
890
891 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
892 {
893         LASSERT(pi.base.bv, /**/);
894
895         bool use_preview = false;
896         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
897                 graphics::PreviewImage const * pimage =
898                         preview_->getPreviewImage(pi.base.bv->buffer());
899                 use_preview = pimage && pimage->image();
900         }
901
902         if (use_preview)
903                 preview_->draw(pi, x, y);
904         else
905                 button_.draw(pi, x, y);
906 }
907
908
909 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
910 {
911         return from_ascii("context-include");
912 }
913
914
915 Inset::DisplayType InsetInclude::display() const
916 {
917         return type(params()) == INPUT ? Inline : AlignCenter;
918 }
919
920
921
922 //
923 // preview stuff
924 //
925
926 void InsetInclude::fileChanged() const
927 {
928         Buffer const * const buffer = updateFrontend();
929         if (!buffer)
930                 return;
931
932         preview_->removePreview(*buffer);
933         add_preview(*preview_.get(), *this, *buffer);
934         preview_->startLoading(*buffer);
935 }
936
937
938 namespace {
939
940 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
941 {
942         FileName const included_file = includedFilename(buffer, params);
943
944         return type(params) == INPUT && params.preview() &&
945                 included_file.isReadableFile();
946 }
947
948
949 docstring latexString(InsetInclude const & inset)
950 {
951         odocstringstream os;
952         // We don't need to set runparams.encoding since this will be done
953         // by latex() anyway.
954         OutputParams runparams(0);
955         runparams.flavor = OutputParams::LATEX;
956         inset.latex(os, runparams);
957
958         return os.str();
959 }
960
961
962 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
963                  Buffer const & buffer)
964 {
965         InsetCommandParams const & params = inset.params();
966         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
967             preview_wanted(params, buffer)) {
968                 renderer.setAbsFile(includedFilename(buffer, params));
969                 docstring const snippet = latexString(inset);
970                 renderer.addPreview(snippet, buffer);
971         }
972 }
973
974 } // namespace anon
975
976
977 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
978         graphics::PreviewLoader & ploader) const
979 {
980         Buffer const & buffer = ploader.buffer();
981         if (!preview_wanted(params(), buffer))
982                 return;
983         preview_->setAbsFile(includedFilename(buffer, params()));
984         docstring const snippet = latexString(*this);
985         preview_->addPreview(snippet, ploader);
986 }
987
988
989 void InsetInclude::addToToc(DocIterator const & cpit)
990 {
991         TocBackend & backend = buffer().tocBackend();
992
993         if (isListings(params())) {
994                 if (label_)
995                         label_->addToToc(cpit);
996
997                 InsetListingsParams p(to_utf8(params()["lstparams"]));
998                 string caption = p.getParamValue("caption");
999                 if (caption.empty())
1000                         return;
1001                 Toc & toc = backend.toc("listing");
1002                 docstring str = convert<docstring>(toc.size() + 1)
1003                         + ". " +  from_utf8(caption);
1004                 DocIterator pit = cpit;
1005                 toc.push_back(TocItem(pit, 0, str));
1006                 return;
1007         }
1008         Buffer const * const childbuffer = getChildBuffer();
1009         if (!childbuffer)
1010                 return;
1011
1012         Toc & toc = backend.toc("child");
1013         docstring str = childbuffer->fileName().displayName();
1014         toc.push_back(TocItem(cpit, 0, str));
1015
1016         TocList & toclist = backend.tocs();
1017         childbuffer->tocBackend().update();
1018         TocList const & childtoclist = childbuffer->tocBackend().tocs();
1019         TocList::const_iterator it = childtoclist.begin();
1020         TocList::const_iterator const end = childtoclist.end();
1021         for(; it != end; ++it)
1022                 toclist[it->first].insert(toclist[it->first].end(),
1023                         it->second.begin(), it->second.end());
1024 }
1025
1026
1027 void InsetInclude::updateCommand()
1028 {
1029         if (!label_)
1030                 return;
1031
1032         docstring old_label = label_->getParam("name");
1033         label_->updateCommand(old_label, false);
1034         // the label might have been adapted (duplicate)
1035         docstring new_label = label_->getParam("name");
1036         if (old_label == new_label)
1037                 return;
1038
1039         // update listings parameters...
1040         InsetCommandParams p(INCLUDE_CODE);
1041         p = params();
1042         InsetListingsParams par(to_utf8(params()["lstparams"]));
1043         par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1044         p["lstparams"] = from_utf8(par.params());
1045         setParams(p);   
1046 }
1047
1048 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1049 {
1050         Buffer const * const childbuffer = getChildBuffer();
1051         if (childbuffer) {
1052                 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1053                 return;
1054         }
1055         if (!isListings(params()))
1056                 return;
1057
1058         if (label_)
1059                 label_->updateBuffer(it, utype);
1060
1061         InsetListingsParams const par(to_utf8(params()["lstparams"]));
1062         if (par.getParamValue("caption").empty()) {
1063                 listings_label_ = buffer().B_("Program Listing");
1064                 return;
1065         }
1066         Buffer const & master = *buffer().masterBuffer();
1067         Counters & counters = master.params().documentClass().counters();
1068         docstring const cnt = from_ascii("listing");
1069         listings_label_ = master.B_("Program Listing");
1070         if (counters.hasCounter(cnt)) {
1071                 counters.step(cnt, utype);
1072                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1073         }
1074 }
1075
1076
1077 } // namespace lyx