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