]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
Missing invalidations of bibfile cache.
[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                 if (!loadIfNeeded())
529                         return false;
530
531                 Buffer * tmp = theBufferList().getBuffer(included_file);
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         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::metrics(MetricsInfo & mi, Dimension & dim) const
848 {
849         LASSERT(mi.base.bv, /**/);
850
851         bool use_preview = false;
852         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
853                 graphics::PreviewImage const * pimage =
854                         preview_->getPreviewImage(mi.base.bv->buffer());
855                 use_preview = pimage && pimage->image();
856         }
857
858         if (use_preview) {
859                 preview_->metrics(mi, dim);
860         } else {
861                 if (!set_label_) {
862                         set_label_ = true;
863                         button_.update(screenLabel(), true);
864                 }
865                 button_.metrics(mi, dim);
866         }
867
868         Box b(0, dim.wid, -dim.asc, dim.des);
869         button_.setBox(b);
870 }
871
872
873 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
874 {
875         LASSERT(pi.base.bv, /**/);
876
877         bool use_preview = false;
878         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
879                 graphics::PreviewImage const * pimage =
880                         preview_->getPreviewImage(pi.base.bv->buffer());
881                 use_preview = pimage && pimage->image();
882         }
883
884         if (use_preview)
885                 preview_->draw(pi, x, y);
886         else
887                 button_.draw(pi, x, y);
888 }
889
890
891 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
892 {
893         return from_ascii("context-include");
894 }
895
896
897 Inset::DisplayType InsetInclude::display() const
898 {
899         return type(params()) == INPUT ? Inline : AlignCenter;
900 }
901
902
903
904 //
905 // preview stuff
906 //
907
908 void InsetInclude::fileChanged() const
909 {
910         Buffer const * const buffer = updateFrontend();
911         if (!buffer)
912                 return;
913
914         preview_->removePreview(*buffer);
915         add_preview(*preview_.get(), *this, *buffer);
916         preview_->startLoading(*buffer);
917 }
918
919
920 namespace {
921
922 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
923 {
924         FileName const included_file = includedFileName(buffer, params);
925
926         return type(params) == INPUT && params.preview() &&
927                 included_file.isReadableFile();
928 }
929
930
931 docstring latexString(InsetInclude const & inset)
932 {
933         odocstringstream os;
934         // We don't need to set runparams.encoding since this will be done
935         // by latex() anyway.
936         OutputParams runparams(0);
937         runparams.flavor = OutputParams::LATEX;
938         inset.latex(os, runparams);
939
940         return os.str();
941 }
942
943
944 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
945                  Buffer const & buffer)
946 {
947         InsetCommandParams const & params = inset.params();
948         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
949             preview_wanted(params, buffer)) {
950                 renderer.setAbsFile(includedFileName(buffer, params));
951                 docstring const snippet = latexString(inset);
952                 renderer.addPreview(snippet, buffer);
953         }
954 }
955
956 } // namespace anon
957
958
959 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
960         graphics::PreviewLoader & ploader) const
961 {
962         Buffer const & buffer = ploader.buffer();
963         if (!preview_wanted(params(), buffer))
964                 return;
965         preview_->setAbsFile(includedFileName(buffer, params()));
966         docstring const snippet = latexString(*this);
967         preview_->addPreview(snippet, ploader);
968 }
969
970
971 void InsetInclude::addToToc(DocIterator const & cpit)
972 {
973         TocBackend & backend = buffer().tocBackend();
974
975         if (isListings(params())) {
976                 if (label_)
977                         label_->addToToc(cpit);
978
979                 InsetListingsParams p(to_utf8(params()["lstparams"]));
980                 string caption = p.getParamValue("caption");
981                 if (caption.empty())
982                         return;
983                 Toc & toc = backend.toc("listing");
984                 docstring str = convert<docstring>(toc.size() + 1)
985                         + ". " +  from_utf8(caption);
986                 DocIterator pit = cpit;
987                 toc.push_back(TocItem(pit, 0, str));
988                 return;
989         }
990         Buffer const * const childbuffer = getChildBuffer();
991         if (!childbuffer)
992                 return;
993
994         Toc & toc = backend.toc("child");
995         docstring str = childbuffer->fileName().displayName();
996         toc.push_back(TocItem(cpit, 0, str));
997
998         TocList & toclist = backend.tocs();
999         childbuffer->tocBackend().update();
1000         TocList const & childtoclist = childbuffer->tocBackend().tocs();
1001         TocList::const_iterator it = childtoclist.begin();
1002         TocList::const_iterator const end = childtoclist.end();
1003         for(; it != end; ++it)
1004                 toclist[it->first].insert(toclist[it->first].end(),
1005                         it->second.begin(), it->second.end());
1006 }
1007
1008
1009 void InsetInclude::updateCommand()
1010 {
1011         if (!label_)
1012                 return;
1013
1014         docstring old_label = label_->getParam("name");
1015         label_->updateCommand(old_label, false);
1016         // the label might have been adapted (duplicate)
1017         docstring new_label = label_->getParam("name");
1018         if (old_label == new_label)
1019                 return;
1020
1021         // update listings parameters...
1022         InsetCommandParams p(INCLUDE_CODE);
1023         p = params();
1024         InsetListingsParams par(to_utf8(params()["lstparams"]));
1025         par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1026         p["lstparams"] = from_utf8(par.params());
1027         setParams(p);   
1028 }
1029
1030 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1031 {
1032         Buffer const * const childbuffer = getChildBuffer();
1033         if (childbuffer) {
1034                 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1035                 return;
1036         }
1037         if (!isListings(params()))
1038                 return;
1039
1040         if (label_)
1041                 label_->updateBuffer(it, utype);
1042
1043         InsetListingsParams const par(to_utf8(params()["lstparams"]));
1044         if (par.getParamValue("caption").empty()) {
1045                 listings_label_ = buffer().B_("Program Listing");
1046                 return;
1047         }
1048         Buffer const & master = *buffer().masterBuffer();
1049         Counters & counters = master.params().documentClass().counters();
1050         docstring const cnt = from_ascii("listing");
1051         listings_label_ = master.B_("Program Listing");
1052         if (counters.hasCounter(cnt)) {
1053                 counters.step(cnt, utype);
1054                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1055         }
1056 }
1057
1058
1059 } // namespace lyx