]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
74946504439d2c0655eb76e0c93be8f65545d5e7
[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, masterBuffer->temppath()));
559
560         LYXERR(Debug::LATEX, "incfile:" << incfile);
561         LYXERR(Debug::LATEX, "exportfile:" << exportfile);
562         LYXERR(Debug::LATEX, "writefile:" << writefile);
563
564         string const tex_format = flavor2format(runparams.flavor);
565
566         switch (type(params())) {
567         case VERB:
568         case VERBAST: {
569                 incfile = latex_path(incfile);
570                 // FIXME UNICODE
571                 os << '\\' << from_ascii(params().getCmdName()) << '{'
572                    << from_utf8(incfile) << '}';
573                 break;
574         }
575         case INPUT: {
576                 runparams.exportdata->addExternalFile(tex_format, writefile,
577                                                       exportfile);
578
579                 // \input wants file with extension (default is .tex)
580                 if (!isLyXFileName(included_file.absFileName())) {
581                         incfile = latex_path(incfile);
582                         // FIXME UNICODE
583                         os << '\\' << from_ascii(params().getCmdName())
584                            << '{' << from_utf8(incfile) << '}';
585                 } else {
586                         incfile = changeExtension(incfile, ".tex");
587                         incfile = latex_path(incfile);
588                         // FIXME UNICODE
589                         os << '\\' << from_ascii(params().getCmdName())
590                            << '{' << from_utf8(incfile) <<  '}';
591                 }
592                 break;
593         }
594         case LISTINGS: {
595                 runparams.exportdata->addExternalFile(tex_format, writefile,
596                                                       exportfile);
597                 os << '\\' << from_ascii(params().getCmdName());
598                 string const opt = to_utf8(params()["lstparams"]);
599                 // opt is set in QInclude dialog and should have passed validation.
600                 InsetListingsParams params(opt);
601                 if (!params.params().empty())
602                         os << "[" << from_utf8(params.params()) << "]";
603                 os << '{'  << from_utf8(incfile) << '}';
604                 break;
605         }
606         case INCLUDE: {
607                 runparams.exportdata->addExternalFile(tex_format, writefile,
608                                                       exportfile);
609
610                 // \include don't want extension and demands that the
611                 // file really have .tex
612                 incfile = changeExtension(incfile, string());
613                 incfile = latex_path(incfile);
614                 // FIXME UNICODE
615                 os << '\\' << from_ascii(params().getCmdName()) << '{'
616                    << from_utf8(incfile) << '}';
617                 break;
618         }
619         case NONE:
620                 break;
621         }
622
623         if (runparams.inComment || runparams.dryrun)
624                 // Don't try to load or copy the file if we're
625                 // in a comment or doing a dryrun
626                 return;
627
628         if (isInputOrInclude(params()) &&
629                  isLyXFileName(included_file.absFileName())) {
630                 // if it's a LyX file and we're inputting or including,
631                 // try to load it so we can write the associated latex
632
633                 Buffer * tmp = loadIfNeeded();
634                 if (!tmp) {
635                         if (!runparams.silent) {
636                                 docstring text = bformat(_("Could not load included "
637                                         "file\n`%1$s'\n"
638                                         "Please, check whether it actually exists."),
639                                         included_file.displayName());
640                                 Alert::warning(_("Missing included file"), text);
641                         }
642                         return;
643                 }
644
645                 if (!runparams.silent) {
646                         if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
647                                 // FIXME UNICODE
648                                 docstring text = bformat(_("Included file `%1$s'\n"
649                                         "has textclass `%2$s'\n"
650                                         "while parent file has textclass `%3$s'."),
651                                         included_file.displayName(),
652                                         from_utf8(tmp->params().documentClass().name()),
653                                         from_utf8(masterBuffer->params().documentClass().name()));
654                                 Alert::warning(_("Different textclasses"), text, true);
655                         }
656
657                         // Make sure modules used in child are all included in master
658                         // FIXME It might be worth loading the children's modules into the master
659                         // over in BufferParams rather than doing this check.
660                         LayoutModuleList const masterModules = masterBuffer->params().getModules();
661                         LayoutModuleList const childModules = tmp->params().getModules();
662                         LayoutModuleList::const_iterator it = childModules.begin();
663                         LayoutModuleList::const_iterator end = childModules.end();
664                         for (; it != end; ++it) {
665                                 string const module = *it;
666                                 LayoutModuleList::const_iterator found =
667                                         find(masterModules.begin(), masterModules.end(), module);
668                                 if (found == masterModules.end()) {
669                                         docstring text = bformat(_("Included file `%1$s'\n"
670                                                 "uses module `%2$s'\n"
671                                                 "which is not used in parent file."),
672                                                 included_file.displayName(), from_utf8(module));
673                                         Alert::warning(_("Module not found"), text);
674                                 }
675                         }
676                 }
677
678                 tmp->markDepClean(masterBuffer->temppath());
679
680                 // Don't assume the child's format is latex
681                 string const inc_format = tmp->params().bufferFormat();
682                 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
683                         formats.extension(inc_format)));
684
685                 // FIXME: handle non existing files
686                 // The included file might be written in a different encoding
687                 // and language.
688                 Encoding const * const oldEnc = runparams.encoding;
689                 Language const * const oldLang = runparams.master_language;
690                 // If the master has full unicode flavor (XeTeX, LuaTeX),
691                 // the children must be encoded in plain utf8!
692                 runparams.encoding = runparams.isFullUnicode() ?
693                         encodings.fromLyXName("utf8-plain")
694                         : &tmp->params().encoding();
695                 runparams.master_language = buffer().params().language;
696                 runparams.par_begin = 0;
697                 runparams.par_end = tmp->paragraphs().size();
698                 runparams.is_child = true;
699                 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
700                                 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
701                         if (!runparams.silent) {
702                                 docstring msg = bformat(_("Included file `%1$s' "
703                                         "was not exported correctly.\nWarning: "
704                                         "LaTeX export is probably incomplete."),
705                                         included_file.displayName());
706                                 ErrorList const & el = tmp->errorList("Export");
707                                 if (!el.empty())
708                                         msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
709                                                 msg, el.begin()->error,
710                                                 el.begin()->description);
711                                 Alert::warning(_("Export failure"), msg);
712                         }
713                 }
714                 runparams.encoding = oldEnc;
715                 runparams.master_language = oldLang;
716                 runparams.is_child = false;
717
718                 // If needed, use converters to produce a latex file from the child
719                 if (tmpwritefile != writefile) {
720                         ErrorList el;
721                         bool const success =
722                                 theConverters().convert(tmp, tmpwritefile, writefile,
723                                                         included_file,
724                                                         inc_format, tex_format, el);
725
726                         if (!success && !runparams.silent) {
727                                 docstring msg = bformat(_("Included file `%1$s' "
728                                                 "was not exported correctly.\nWarning: "
729                                                 "LaTeX export is probably incomplete."),
730                                                 included_file.displayName());
731                                 if (!el.empty())
732                                         msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
733                                                         msg, el.begin()->error,
734                                                         el.begin()->description);
735                                 Alert::warning(_("Export failure"), msg);
736                         }
737                 }
738         } else {
739                 // In this case, it's not a LyX file, so we copy the file
740                 // to the temp dir, so that .aux files etc. are not created
741                 // in the original dir. Files included by this file will be
742                 // found via either the environment variable TEXINPUTS, or
743                 // input@path, see ../Buffer.cpp.
744                 unsigned long const checksum_in  = included_file.checksum();
745                 unsigned long const checksum_out = writefile.checksum();
746
747                 if (checksum_in != checksum_out) {
748                         if (!included_file.copyTo(writefile)) {
749                                 // FIXME UNICODE
750                                 LYXERR(Debug::LATEX,
751                                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
752                                                                         "into the temporary directory."),
753                                                          from_utf8(included_file.absFileName()))));
754                                 return;
755                         }
756                 }
757         }
758 }
759
760
761 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
762 {
763         if (rp.inComment)
764                  return docstring();
765
766         // For verbatim and listings, we just include the contents of the file as-is.
767         // In the case of listings, we wrap it in <pre>.
768         bool const listing = isListings(params());
769         if (listing || isVerbatim(params())) {
770                 if (listing)
771                         xs << html::StartTag("pre");
772                 // FIXME: We don't know the encoding of the file, default to UTF-8.
773                 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
774                 if (listing)
775                         xs << html::EndTag("pre");
776                 return docstring();
777         }
778
779         // We don't (yet) know how to Input or Include non-LyX files.
780         // (If we wanted to get really arcane, we could run some tex2html
781         // converter on the included file. But that's just masochistic.)
782         FileName const included_file = includedFileName(buffer(), params());
783         if (!isLyXFileName(included_file.absFileName())) {
784                 if (!rp.silent)
785                         frontend::Alert::warning(_("Unsupported Inclusion"),
786                                          bformat(_("LyX does not know how to include non-LyX files when "
787                                                    "generating HTML output. Offending file:\n%1$s"),
788                                                     params()["filename"]));
789                 return docstring();
790         }
791
792         // In the other cases, we will generate the HTML and include it.
793
794         // Check we're not trying to include ourselves.
795         // FIXME RECURSIVE INCLUDE
796         if (buffer().absFileName() == included_file.absFileName()) {
797                 Alert::error(_("Recursive input"),
798                                bformat(_("Attempted to include file %1$s in itself! "
799                                "Ignoring inclusion."), params()["filename"]));
800                 return docstring();
801         }
802
803         Buffer const * const ibuf = loadIfNeeded();
804         if (!ibuf)
805                 return docstring();
806
807         // are we generating only some paragraphs, or all of them?
808         bool const all_pars = !rp.dryrun || 
809                         (rp.par_begin == 0 && 
810                          rp.par_end == (int)buffer().text().paragraphs().size());
811         
812         OutputParams op = rp;
813         if (all_pars) {
814                 op.par_begin = 0;
815                 op.par_end = 0;
816                 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
817         } else
818                 xs << XHTMLStream::ESCAPE_NONE 
819                    << "<!-- Included file: " 
820                    << from_utf8(included_file.absFileName()) 
821                    << XHTMLStream::ESCAPE_NONE 
822                          << " -->";
823         return docstring();
824 }
825
826
827 int InsetInclude::plaintext(odocstringstream & os,
828         OutputParams const & op, size_t) const
829 {
830         // just write the filename if we're making a tooltip or toc entry,
831         // or are generating this for advanced search
832         if (op.for_tooltip || op.for_toc || op.for_search) {
833                 os << '[' << screenLabel() << '\n'
834                    << getParam("filename") << "\n]";
835                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
836         }
837
838         if (isVerbatim(params()) || isListings(params())) {
839                 os << '[' << screenLabel() << '\n'
840                    // FIXME: We don't know the encoding of the file, default to UTF-8.
841                    << includedFileName(buffer(), params()).fileContents("UTF-8")
842                    << "\n]";
843                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
844         }
845
846         Buffer const * const ibuf = loadIfNeeded();
847         if (!ibuf) {
848                 docstring const str = '[' + screenLabel() + ']';
849                 os << str;
850                 return str.size();
851         }
852         writePlaintextFile(*ibuf, os, op);
853         return 0;
854 }
855
856
857 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
858 {
859         string incfile = to_utf8(params()["filename"]);
860
861         // Do nothing if no file name has been specified
862         if (incfile.empty())
863                 return 0;
864
865         string const included_file = includedFileName(buffer(), params()).absFileName();
866
867         // Check we're not trying to include ourselves.
868         // FIXME RECURSIVE INCLUDE
869         // This isn't sufficient, as the inclusion could be downstream.
870         // But it'll have to do for now.
871         if (buffer().absFileName() == included_file) {
872                 Alert::error(_("Recursive input"),
873                                bformat(_("Attempted to include file %1$s in itself! "
874                                "Ignoring inclusion."), from_utf8(incfile)));
875                 return 0;
876         }
877
878         string exppath = incfile;
879         if (!runparams.export_folder.empty()) {
880                 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
881                 FileName(exppath).onlyPath().createPath();
882         }
883
884         // write it to a file (so far the complete file)
885         string const exportfile = changeExtension(exppath, ".sgml");
886         DocFileName writefile(changeExtension(included_file, ".sgml"));
887
888         Buffer * tmp = loadIfNeeded();
889         if (tmp) {
890                 string const mangled = writefile.mangledFileName();
891                 writefile = makeAbsPath(mangled,
892                                         buffer().masterBuffer()->temppath());
893                 if (!runparams.nice)
894                         incfile = mangled;
895
896                 LYXERR(Debug::LATEX, "incfile:" << incfile);
897                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
898                 LYXERR(Debug::LATEX, "writefile:" << writefile);
899
900                 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
901         }
902
903         runparams.exportdata->addExternalFile("docbook", writefile,
904                                               exportfile);
905         runparams.exportdata->addExternalFile("docbook-xml", writefile,
906                                               exportfile);
907
908         if (isVerbatim(params()) || isListings(params())) {
909                 os << "<inlinegraphic fileref=\""
910                    << '&' << include_label << ';'
911                    << "\" format=\"linespecific\">";
912         } else
913                 os << '&' << include_label << ';';
914
915         return 0;
916 }
917
918
919 void InsetInclude::validate(LaTeXFeatures & features) const
920 {
921         LATTEST(&buffer() == &features.buffer());
922
923         string incfile = to_utf8(params()["filename"]);
924         string const included_file =
925                 includedFileName(buffer(), params()).absFileName();
926
927         string writefile;
928         if (isLyXFileName(included_file))
929                 writefile = changeExtension(included_file, ".sgml");
930         else
931                 writefile = included_file;
932
933         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
934                 incfile = DocFileName(writefile).mangledFileName();
935                 writefile = makeAbsPath(incfile,
936                                         buffer().masterBuffer()->temppath()).absFileName();
937         }
938
939         features.includeFile(include_label, writefile);
940
941         features.useInsetLayout(getLayout());
942         if (isVerbatim(params()))
943                 features.require("verbatim");
944         else if (isListings(params()))
945                 features.require("listings");
946
947         // Here we must do the fun stuff...
948         // Load the file in the include if it needs
949         // to be loaded:
950         Buffer * const tmp = loadIfNeeded();
951         if (tmp) {
952                 // the file is loaded
953                 // make sure the buffer isn't us
954                 // FIXME RECURSIVE INCLUDES
955                 // This is not sufficient, as recursive includes could be
956                 // more than a file away. But it will do for now.
957                 if (tmp && tmp != &buffer()) {
958                         // We must temporarily change features.buffer,
959                         // otherwise it would always be the master buffer,
960                         // and nested includes would not work.
961                         features.setBuffer(*tmp);
962                         // Maybe this is already a child
963                         bool const is_child =
964                                 features.runparams().is_child;
965                         features.runparams().is_child = true;
966                         tmp->validate(features);
967                         features.runparams().is_child = is_child;
968                         features.setBuffer(buffer());
969                 }
970         }
971 }
972
973
974 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/) const
975 {
976         Buffer * child = loadIfNeeded();
977         if (!child)
978                 return;
979         // FIXME RECURSIVE INCLUDE
980         // This isn't sufficient, as the inclusion could be downstream.
981         // But it'll have to do for now.
982         if (child == &buffer())
983                 return;
984         child->collectBibKeys();
985 }
986
987
988 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
989 {
990         LBUFERR(mi.base.bv);
991
992         bool use_preview = false;
993         if (RenderPreview::previewText()) {
994                 graphics::PreviewImage const * pimage =
995                         preview_->getPreviewImage(mi.base.bv->buffer());
996                 use_preview = pimage && pimage->image();
997         }
998
999         if (use_preview) {
1000                 preview_->metrics(mi, dim);
1001         } else {
1002                 if (!set_label_) {
1003                         set_label_ = true;
1004                         button_.update(screenLabel(), true);
1005                 }
1006                 button_.metrics(mi, dim);
1007         }
1008
1009         Box b(0, dim.wid, -dim.asc, dim.des);
1010         button_.setBox(b);
1011 }
1012
1013
1014 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1015 {
1016         LBUFERR(pi.base.bv);
1017
1018         bool use_preview = false;
1019         if (RenderPreview::previewText()) {
1020                 graphics::PreviewImage const * pimage =
1021                         preview_->getPreviewImage(pi.base.bv->buffer());
1022                 use_preview = pimage && pimage->image();
1023         }
1024
1025         if (use_preview)
1026                 preview_->draw(pi, x, y);
1027         else
1028                 button_.draw(pi, x, y);
1029 }
1030
1031
1032 string InsetInclude::contextMenuName() const
1033 {
1034         return "context-include";
1035 }
1036
1037
1038 Inset::DisplayType InsetInclude::display() const
1039 {
1040         return type(params()) == INPUT ? Inline : AlignCenter;
1041 }
1042
1043
1044 docstring InsetInclude::layoutName() const
1045 {
1046         if (isListings(params()))
1047                 return from_ascii("IncludeListings");
1048         return InsetCommand::layoutName();
1049 }
1050
1051
1052 //
1053 // preview stuff
1054 //
1055
1056 void InsetInclude::fileChanged() const
1057 {
1058         Buffer const * const buffer = updateFrontend();
1059         if (!buffer)
1060                 return;
1061
1062         preview_->removePreview(*buffer);
1063         add_preview(*preview_.get(), *this, *buffer);
1064         preview_->startLoading(*buffer);
1065 }
1066
1067
1068 namespace {
1069
1070 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1071 {
1072         FileName const included_file = includedFileName(buffer, params);
1073
1074         return type(params) == INPUT && params.preview() &&
1075                 included_file.isReadableFile();
1076 }
1077
1078
1079 docstring latexString(InsetInclude const & inset)
1080 {
1081         TexRow texrow;
1082         odocstringstream ods;
1083         otexstream os(ods, texrow);
1084         // We don't need to set runparams.encoding since this will be done
1085         // by latex() anyway.
1086         OutputParams runparams(0);
1087         runparams.flavor = OutputParams::LATEX;
1088         inset.latex(os, runparams);
1089
1090         return ods.str();
1091 }
1092
1093
1094 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1095                  Buffer const & buffer)
1096 {
1097         InsetCommandParams const & params = inset.params();
1098         if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1099                 renderer.setAbsFile(includedFileName(buffer, params));
1100                 docstring const snippet = latexString(inset);
1101                 renderer.addPreview(snippet, buffer);
1102         }
1103 }
1104
1105 } // namespace anon
1106
1107
1108 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1109         graphics::PreviewLoader & ploader) const
1110 {
1111         Buffer const & buffer = ploader.buffer();
1112         if (!preview_wanted(params(), buffer))
1113                 return;
1114         preview_->setAbsFile(includedFileName(buffer, params()));
1115         docstring const snippet = latexString(*this);
1116         preview_->addPreview(snippet, ploader);
1117 }
1118
1119
1120 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active) const
1121 {
1122         TocBackend & backend = buffer().tocBackend();
1123
1124         if (isListings(params())) {
1125                 if (label_)
1126                         label_->addToToc(cpit, output_active);
1127
1128                 InsetListingsParams p(to_utf8(params()["lstparams"]));
1129                 string caption = p.getParamValue("caption");
1130                 if (caption.empty())
1131                         return;
1132                 Toc & toc = backend.toc("listing");
1133                 docstring str = convert<docstring>(toc.size() + 1)
1134                         + ". " +  from_utf8(caption);
1135                 DocIterator pit = cpit;
1136                 toc.push_back(TocItem(pit, 0, str, output_active));
1137                 return;
1138         }
1139         Buffer const * const childbuffer = getChildBuffer();
1140         if (!childbuffer)
1141                 return;
1142
1143         Toc & toc = backend.toc("child");
1144         docstring str = childbuffer->fileName().displayName();
1145         toc.push_back(TocItem(cpit, 0, str, output_active));
1146
1147         TocList & toclist = backend.tocs();
1148         childbuffer->tocBackend().update(output_active);
1149         TocList const & childtoclist = childbuffer->tocBackend().tocs();
1150         TocList::const_iterator it = childtoclist.begin();
1151         TocList::const_iterator const end = childtoclist.end();
1152         for(; it != end; ++it)
1153                 toclist[it->first].insert(toclist[it->first].end(),
1154                         it->second.begin(), it->second.end());
1155 }
1156
1157
1158 void InsetInclude::updateCommand()
1159 {
1160         if (!label_)
1161                 return;
1162
1163         docstring old_label = label_->getParam("name");
1164         label_->updateLabel(old_label);
1165         // the label might have been adapted (duplicate)
1166         docstring new_label = label_->getParam("name");
1167         if (old_label == new_label)
1168                 return;
1169
1170         // update listings parameters...
1171         InsetCommandParams p(INCLUDE_CODE);
1172         p = params();
1173         InsetListingsParams par(to_utf8(params()["lstparams"]));
1174         par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1175         p["lstparams"] = from_utf8(par.params());
1176         setParams(p);   
1177 }
1178
1179
1180 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1181 {
1182         button_.update(screenLabel(), true);
1183
1184         Buffer const * const childbuffer = getChildBuffer();
1185         if (childbuffer) {
1186                 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1187                 return;
1188         }
1189         if (!isListings(params()))
1190                 return;
1191
1192         if (label_)
1193                 label_->updateBuffer(it, utype);
1194
1195         InsetListingsParams const par(to_utf8(params()["lstparams"]));
1196         if (par.getParamValue("caption").empty()) {
1197                 listings_label_ = buffer().B_("Program Listing");
1198                 return;
1199         }
1200         Buffer const & master = *buffer().masterBuffer();
1201         Counters & counters = master.params().documentClass().counters();
1202         docstring const cnt = from_ascii("listing");
1203         listings_label_ = master.B_("Program Listing");
1204         if (counters.hasCounter(cnt)) {
1205                 counters.step(cnt, utype);
1206                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1207         }
1208 }
1209
1210
1211 } // namespace lyx