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