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