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