]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
filetools.cpp: introduce a new method to be able to distinguish between valid LaTeX...
[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 will cause troubles "
514                                                "when running the exported file through LaTeX: ") +
515                                              from_utf8(incfile));
516         }
517         else if (!isValidDVIFileName(incfile)) {
518                         frontend::Alert::warning(_("Problematic filename for DVI"),
519                                          _("The following filename can cause troubles "
520                                                "when running the exported file through LaTeX "
521                                                    "and opening the resulting DVI: ") +
522                                              from_utf8(incfile), true);
523         }
524         LYXERR(Debug::LATEX, "incfile:" << incfile);
525         LYXERR(Debug::LATEX, "exportfile:" << exportfile);
526         LYXERR(Debug::LATEX, "writefile:" << writefile);
527
528         if (runparams.inComment || runparams.dryrun) {
529                 //Don't try to load or copy the file if we're
530                 //in a comment or doing a dryrun
531         } else if (isInputOrInclude(params()) &&
532                  isLyXFileName(included_file.absFileName())) {
533                 // if it's a LyX file and we're inputting or including,
534                 // try to load it so we can write the associated latex
535                 
536                 Buffer * tmp = loadIfNeeded();
537                 if (!tmp)
538                         return false;
539
540                 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
541                         // FIXME UNICODE
542                         docstring text = bformat(_("Included file `%1$s'\n"
543                                 "has textclass `%2$s'\n"
544                                 "while parent file has textclass `%3$s'."),
545                                 included_file.displayName(),
546                                 from_utf8(tmp->params().documentClass().name()),
547                                 from_utf8(masterBuffer->params().documentClass().name()));
548                         Alert::warning(_("Different textclasses"), text, true);
549                 }
550
551                 // Make sure modules used in child are all included in master
552                 // FIXME It might be worth loading the children's modules into the master
553                 // over in BufferParams rather than doing this check.
554                 LayoutModuleList const masterModules = masterBuffer->params().getModules();
555                 LayoutModuleList const childModules = tmp->params().getModules();
556                 LayoutModuleList::const_iterator it = childModules.begin();
557                 LayoutModuleList::const_iterator end = childModules.end();
558                 for (; it != end; ++it) {
559                         string const module = *it;
560                         LayoutModuleList::const_iterator found =
561                                 find(masterModules.begin(), masterModules.end(), module);
562                         if (found == masterModules.end()) {
563                                 docstring text = bformat(_("Included file `%1$s'\n"
564                                         "uses module `%2$s'\n"
565                                         "which is not used in parent file."),
566                                         included_file.displayName(), from_utf8(module));
567                                 Alert::warning(_("Module not found"), text);
568                         }
569                 }
570
571                 tmp->markDepClean(masterBuffer->temppath());
572
573                 // FIXME: handle non existing files
574                 // FIXME: Second argument is irrelevant!
575                 // since only_body is true, makeLaTeXFile will not look at second
576                 // argument. Should we set it to string(), or should makeLaTeXFile
577                 // make use of it somehow? (JMarc 20031002)
578                 // The included file might be written in a different encoding
579                 // and language.
580                 Encoding const * const oldEnc = runparams.encoding;
581                 Language const * const oldLang = runparams.master_language;
582                 runparams.encoding = &tmp->params().encoding();
583                 runparams.master_language = buffer().params().language;
584                 tmp->makeLaTeXFile(writefile,
585                                    masterFileName(buffer()).onlyPath().absFileName(),
586                                    runparams, false);
587                 runparams.encoding = oldEnc;
588                 runparams.master_language = oldLang;
589         } else {
590                 // In this case, it's not a LyX file, so we copy the file
591                 // to the temp dir, so that .aux files etc. are not created
592                 // in the original dir. Files included by this file will be
593                 // found via input@path, see ../Buffer.cpp.
594                 unsigned long const checksum_in  = included_file.checksum();
595                 unsigned long const checksum_out = writefile.checksum();
596
597                 if (checksum_in != checksum_out) {
598                         if (!included_file.copyTo(writefile)) {
599                                 // FIXME UNICODE
600                                 LYXERR(Debug::LATEX,
601                                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
602                                                                   "into the temporary directory."),
603                                                    from_utf8(included_file.absFileName()))));
604                                 return 0;
605                         }
606                 }
607         }
608
609         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
610                         "latex" : "pdflatex";
611         switch (type(params())) {
612         case VERB:
613         case VERBAST: {
614                 incfile = latex_path(incfile);
615                 // FIXME UNICODE
616                 os << '\\' << from_ascii(params().getCmdName()) << '{'
617                    << from_utf8(incfile) << '}';
618                 break;
619         } 
620         case INPUT: {
621                 runparams.exportdata->addExternalFile(tex_format, writefile,
622                                                       exportfile);
623
624                 // \input wants file with extension (default is .tex)
625                 if (!isLyXFileName(included_file.absFileName())) {
626                         incfile = latex_path(incfile);
627                         // FIXME UNICODE
628                         os << '\\' << from_ascii(params().getCmdName())
629                            << '{' << from_utf8(incfile) << '}';
630                 } else {
631                 incfile = changeExtension(incfile, ".tex");
632                 incfile = latex_path(incfile);
633                         // FIXME UNICODE
634                         os << '\\' << from_ascii(params().getCmdName())
635                            << '{' << from_utf8(incfile) <<  '}';
636                 }
637                 break;
638         } 
639         case LISTINGS: {
640                 os << '\\' << from_ascii(params().getCmdName());
641                 string const opt = to_utf8(params()["lstparams"]);
642                 // opt is set in QInclude dialog and should have passed validation.
643                 InsetListingsParams params(opt);
644                 if (!params.params().empty())
645                         os << "[" << from_utf8(params.params()) << "]";
646                 os << '{'  << from_utf8(incfile) << '}';
647                 break;
648         } 
649         case INCLUDE: {
650                 runparams.exportdata->addExternalFile(tex_format, writefile,
651                                                       exportfile);
652
653                 // \include don't want extension and demands that the
654                 // file really have .tex
655                 incfile = changeExtension(incfile, string());
656                 incfile = latex_path(incfile);
657                 // FIXME UNICODE
658                 os << '\\' << from_ascii(params().getCmdName()) << '{'
659                    << from_utf8(incfile) << '}';
660                 break;
661         }
662         case NONE:
663                 break;
664         }
665
666         return 0;
667 }
668
669
670 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const &rp) const
671 {
672         if (rp.inComment)
673                  return docstring();
674
675         // For verbatim and listings, we just include the contents of the file as-is.
676         // In the case of listings, we wrap it in <pre>.
677         bool const listing = isListings(params());
678         if (listing || isVerbatim(params())) {
679                 if (listing)
680                         xs << html::StartTag("pre");
681                 // FIXME: We don't know the encoding of the file, default to UTF-8.
682                 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
683                 if (listing)
684                         xs << html::EndTag("pre");
685                 return docstring();
686         }
687
688         // We don't (yet) know how to Input or Include non-LyX files.
689         // (If we wanted to get really arcane, we could run some tex2html
690         // converter on the included file. But that's just masochistic.)
691         FileName const included_file = includedFileName(buffer(), params());
692         if (!isLyXFileName(included_file.absFileName())) {
693                 frontend::Alert::warning(_("Unsupported Inclusion"),
694                                          bformat(_("LyX does not know how to include non-LyX files when "
695                                                    "generating HTML output. Offending file:\n%1$s"),
696                                                     params()["filename"]));
697                 return docstring();
698         }
699
700         // In the other cases, we will generate the HTML and include it.
701
702         // Check we're not trying to include ourselves.
703         // FIXME RECURSIVE INCLUDE
704         if (buffer().absFileName() == included_file.absFileName()) {
705                 Alert::error(_("Recursive input"),
706                                bformat(_("Attempted to include file %1$s in itself! "
707                                "Ignoring inclusion."), params()["filename"]));
708                 return docstring();
709         }
710
711         Buffer const * const ibuf = loadIfNeeded();
712         if (!ibuf)
713                 return docstring();
714         ibuf->writeLyXHTMLSource(xs.os(), rp, true);
715         return docstring();
716 }
717
718
719 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
720 {
721         if (isVerbatim(params()) || isListings(params())) {
722                 os << '[' << screenLabel() << '\n';
723                 // FIXME: We don't know the encoding of the file, default to UTF-8.
724                 os << includedFileName(buffer(), params()).fileContents("UTF-8");
725                 os << "\n]";
726                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
727         } else {
728                 docstring const str = '[' + screenLabel() + ']';
729                 os << str;
730                 return str.size();
731         }
732 }
733
734
735 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
736 {
737         string incfile = to_utf8(params()["filename"]);
738
739         // Do nothing if no file name has been specified
740         if (incfile.empty())
741                 return 0;
742
743         string const included_file = includedFileName(buffer(), params()).absFileName();
744
745         // Check we're not trying to include ourselves.
746         // FIXME RECURSIVE INCLUDE
747         // This isn't sufficient, as the inclusion could be downstream.
748         // But it'll have to do for now.
749         if (buffer().absFileName() == included_file) {
750                 Alert::error(_("Recursive input"),
751                                bformat(_("Attempted to include file %1$s in itself! "
752                                "Ignoring inclusion."), from_utf8(incfile)));
753                 return 0;
754         }
755
756         // write it to a file (so far the complete file)
757         string const exportfile = changeExtension(incfile, ".sgml");
758         DocFileName writefile(changeExtension(included_file, ".sgml"));
759
760         Buffer * tmp = loadIfNeeded();
761         if (tmp) {
762                 string const mangled = writefile.mangledFileName();
763                 writefile = makeAbsPath(mangled,
764                                         buffer().masterBuffer()->temppath());
765                 if (!runparams.nice)
766                         incfile = mangled;
767
768                 LYXERR(Debug::LATEX, "incfile:" << incfile);
769                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
770                 LYXERR(Debug::LATEX, "writefile:" << writefile);
771
772                 tmp->makeDocBookFile(writefile, runparams, true);
773         }
774
775         runparams.exportdata->addExternalFile("docbook", writefile,
776                                               exportfile);
777         runparams.exportdata->addExternalFile("docbook-xml", writefile,
778                                               exportfile);
779
780         if (isVerbatim(params()) || isListings(params())) {
781                 os << "<inlinegraphic fileref=\""
782                    << '&' << include_label << ';'
783                    << "\" format=\"linespecific\">";
784         } else
785                 os << '&' << include_label << ';';
786
787         return 0;
788 }
789
790
791 void InsetInclude::validate(LaTeXFeatures & features) const
792 {
793         string incfile = to_utf8(params()["filename"]);
794         string writefile;
795
796         LASSERT(&buffer() == &features.buffer(), /**/);
797
798         string const included_file =
799                 includedFileName(buffer(), params()).absFileName();
800
801         if (isLyXFileName(included_file))
802                 writefile = changeExtension(included_file, ".sgml");
803         else
804                 writefile = included_file;
805
806         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
807                 incfile = DocFileName(writefile).mangledFileName();
808                 writefile = makeAbsPath(incfile,
809                                         buffer().masterBuffer()->temppath()).absFileName();
810         }
811
812         features.includeFile(include_label, writefile);
813
814         if (isVerbatim(params()))
815                 features.require("verbatim");
816         else if (isListings(params()))
817                 features.require("listings");
818
819         // Here we must do the fun stuff...
820         // Load the file in the include if it needs
821         // to be loaded:
822         Buffer * const tmp = loadIfNeeded();
823         if (tmp) {
824                 // the file is loaded
825                 // make sure the buffer isn't us
826                 // FIXME RECURSIVE INCLUDES
827                 // This is not sufficient, as recursive includes could be
828                 // more than a file away. But it will do for now.
829                 if (tmp && tmp != &buffer()) {
830                         // We must temporarily change features.buffer,
831                         // otherwise it would always be the master buffer,
832                         // and nested includes would not work.
833                         features.setBuffer(*tmp);
834                         tmp->validate(features);
835                         features.setBuffer(buffer());
836                 }
837         }
838 }
839
840
841 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
842         InsetIterator const & /*di*/) const
843 {
844         Buffer * child = loadIfNeeded();
845         if (!child)
846                 return;
847         child->fillWithBibKeys(keys);
848 }
849
850
851 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
852 {
853         LASSERT(mi.base.bv, /**/);
854
855         bool use_preview = false;
856         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
857                 graphics::PreviewImage const * pimage =
858                         preview_->getPreviewImage(mi.base.bv->buffer());
859                 use_preview = pimage && pimage->image();
860         }
861
862         if (use_preview) {
863                 preview_->metrics(mi, dim);
864         } else {
865                 if (!set_label_) {
866                         set_label_ = true;
867                         button_.update(screenLabel(), true);
868                 }
869                 button_.metrics(mi, dim);
870         }
871
872         Box b(0, dim.wid, -dim.asc, dim.des);
873         button_.setBox(b);
874 }
875
876
877 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
878 {
879         LASSERT(pi.base.bv, /**/);
880
881         bool use_preview = false;
882         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
883                 graphics::PreviewImage const * pimage =
884                         preview_->getPreviewImage(pi.base.bv->buffer());
885                 use_preview = pimage && pimage->image();
886         }
887
888         if (use_preview)
889                 preview_->draw(pi, x, y);
890         else
891                 button_.draw(pi, x, y);
892 }
893
894
895 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
896 {
897         return from_ascii("context-include");
898 }
899
900
901 Inset::DisplayType InsetInclude::display() const
902 {
903         return type(params()) == INPUT ? Inline : AlignCenter;
904 }
905
906
907
908 //
909 // preview stuff
910 //
911
912 void InsetInclude::fileChanged() const
913 {
914         Buffer const * const buffer = updateFrontend();
915         if (!buffer)
916                 return;
917
918         preview_->removePreview(*buffer);
919         add_preview(*preview_.get(), *this, *buffer);
920         preview_->startLoading(*buffer);
921 }
922
923
924 namespace {
925
926 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
927 {
928         FileName const included_file = includedFileName(buffer, params);
929
930         return type(params) == INPUT && params.preview() &&
931                 included_file.isReadableFile();
932 }
933
934
935 docstring latexString(InsetInclude const & inset)
936 {
937         odocstringstream os;
938         // We don't need to set runparams.encoding since this will be done
939         // by latex() anyway.
940         OutputParams runparams(0);
941         runparams.flavor = OutputParams::LATEX;
942         inset.latex(os, runparams);
943
944         return os.str();
945 }
946
947
948 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
949                  Buffer const & buffer)
950 {
951         InsetCommandParams const & params = inset.params();
952         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
953             preview_wanted(params, buffer)) {
954                 renderer.setAbsFile(includedFileName(buffer, params));
955                 docstring const snippet = latexString(inset);
956                 renderer.addPreview(snippet, buffer);
957         }
958 }
959
960 } // namespace anon
961
962
963 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
964         graphics::PreviewLoader & ploader) const
965 {
966         Buffer const & buffer = ploader.buffer();
967         if (!preview_wanted(params(), buffer))
968                 return;
969         preview_->setAbsFile(includedFileName(buffer, params()));
970         docstring const snippet = latexString(*this);
971         preview_->addPreview(snippet, ploader);
972 }
973
974
975 void InsetInclude::addToToc(DocIterator const & cpit)
976 {
977         TocBackend & backend = buffer().tocBackend();
978
979         if (isListings(params())) {
980                 if (label_)
981                         label_->addToToc(cpit);
982
983                 InsetListingsParams p(to_utf8(params()["lstparams"]));
984                 string caption = p.getParamValue("caption");
985                 if (caption.empty())
986                         return;
987                 Toc & toc = backend.toc("listing");
988                 docstring str = convert<docstring>(toc.size() + 1)
989                         + ". " +  from_utf8(caption);
990                 DocIterator pit = cpit;
991                 toc.push_back(TocItem(pit, 0, str));
992                 return;
993         }
994         Buffer const * const childbuffer = getChildBuffer();
995         if (!childbuffer)
996                 return;
997
998         Toc & toc = backend.toc("child");
999         docstring str = childbuffer->fileName().displayName();
1000         toc.push_back(TocItem(cpit, 0, str));
1001
1002         TocList & toclist = backend.tocs();
1003         childbuffer->tocBackend().update();
1004         TocList const & childtoclist = childbuffer->tocBackend().tocs();
1005         TocList::const_iterator it = childtoclist.begin();
1006         TocList::const_iterator const end = childtoclist.end();
1007         for(; it != end; ++it)
1008                 toclist[it->first].insert(toclist[it->first].end(),
1009                         it->second.begin(), it->second.end());
1010 }
1011
1012
1013 void InsetInclude::updateCommand()
1014 {
1015         if (!label_)
1016                 return;
1017
1018         docstring old_label = label_->getParam("name");
1019         label_->updateCommand(old_label, false);
1020         // the label might have been adapted (duplicate)
1021         docstring new_label = label_->getParam("name");
1022         if (old_label == new_label)
1023                 return;
1024
1025         // update listings parameters...
1026         InsetCommandParams p(INCLUDE_CODE);
1027         p = params();
1028         InsetListingsParams par(to_utf8(params()["lstparams"]));
1029         par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1030         p["lstparams"] = from_utf8(par.params());
1031         setParams(p);   
1032 }
1033
1034 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1035 {
1036         Buffer const * const childbuffer = getChildBuffer();
1037         if (childbuffer) {
1038                 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1039                 return;
1040         }
1041         if (!isListings(params()))
1042                 return;
1043
1044         if (label_)
1045                 label_->updateBuffer(it, utype);
1046
1047         InsetListingsParams const par(to_utf8(params()["lstparams"]));
1048         if (par.getParamValue("caption").empty()) {
1049                 listings_label_ = buffer().B_("Program Listing");
1050                 return;
1051         }
1052         Buffer const & master = *buffer().masterBuffer();
1053         Counters & counters = master.params().documentClass().counters();
1054         docstring const cnt = from_ascii("listing");
1055         listings_label_ = master.B_("Program Listing");
1056         if (counters.hasCounter(cnt)) {
1057                 counters.step(cnt, utype);
1058                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1059         }
1060 }
1061
1062
1063 } // namespace lyx