]> git.lyx.org Git - features.git/blob - src/insets/InsetInclude.cpp
Attempt to fix bug 9158 using updateBuffer.
[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" || s == "inputminted")
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
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         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                 theFormats().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
354
355 bool InsetInclude::isChildIncluded() const
356 {
357         std::list<std::string> includeonlys =
358                 buffer().params().getIncludedChildren();
359         if (includeonlys.empty())
360                 return true;
361         return (std::find(includeonlys.begin(),
362                           includeonlys.end(),
363                           to_utf8(params()["filename"])) != includeonlys.end());
364 }
365
366
367 docstring InsetInclude::screenLabel() const
368 {
369         docstring temp;
370
371         switch (type(params())) {
372                 case INPUT:
373                         temp = buffer().B_("Input");
374                         break;
375                 case VERB:
376                         temp = buffer().B_("Verbatim Input");
377                         break;
378                 case VERBAST:
379                         temp = buffer().B_("Verbatim Input*");
380                         break;
381                 case INCLUDE:
382                         if (isChildIncluded())
383                                 temp = buffer().B_("Include");
384                         else
385                                 temp += buffer().B_("Include (excluded)");
386                         break;
387                 case LISTINGS:
388                         temp = listings_label_;
389                         break;
390                 case NONE:
391                         LASSERT(false, temp = buffer().B_("Unknown"));
392                         break;
393         }
394
395         temp += ": ";
396
397         if (params()["filename"].empty())
398                 temp += "???";
399         else
400                 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
401
402         return temp;
403 }
404
405
406 Buffer * InsetInclude::getChildBuffer() const
407 {
408         Buffer * childBuffer = loadIfNeeded();
409
410         // FIXME RECURSIVE INCLUDE
411         // This isn't sufficient, as the inclusion could be downstream.
412         // But it'll have to do for now.
413         return (childBuffer == &buffer()) ? 0 : childBuffer;
414 }
415
416
417 Buffer * InsetInclude::loadIfNeeded() const
418 {
419         // This is for background export and preview. We don't even want to
420         // try to load the cloned child document again.
421         if (buffer().isClone())
422                 return child_buffer_;
423
424         // Don't try to load it again if we failed before.
425         if (failedtoload_ || isVerbatim(params()) || isListings(params()))
426                 return 0;
427
428         FileName const included_file = includedFileName(buffer(), params());
429         // Use cached Buffer if possible.
430         if (child_buffer_ != 0) {
431                 if (theBufferList().isLoaded(child_buffer_)
432                     // additional sanity check: make sure the Buffer really is
433                     // associated with the file we want.
434                     && child_buffer_ == theBufferList().getBuffer(included_file))
435                         return child_buffer_;
436                 // Buffer vanished, so invalidate cache and try to reload.
437                 child_buffer_ = 0;
438         }
439
440         if (!isLyXFileName(included_file.absFileName()))
441                 return 0;
442
443         Buffer * child = theBufferList().getBuffer(included_file);
444         if (!child) {
445                 // the readonly flag can/will be wrong, not anymore I think.
446                 if (!included_file.exists())
447                         return 0;
448
449                 child = theBufferList().newBuffer(included_file.absFileName());
450                 if (!child)
451                         // Buffer creation is not possible.
452                         return 0;
453
454                 // Set parent before loading, such that macros can be tracked
455                 child->setParent(&buffer());
456
457                 if (child->loadLyXFile() != Buffer::ReadSuccess) {
458                         failedtoload_ = true;
459                         child->setParent(0);
460                         //close the buffer we just opened
461                         theBufferList().release(child);
462                         return 0;
463                 }
464
465                 if (!child->errorList("Parse").empty()) {
466                         // FIXME: Do something.
467                 }
468         } else {
469                 // The file was already loaded, so, simply
470                 // inform parent buffer about local macros.
471                 Buffer const * parent = &buffer();
472                 child->setParent(parent);
473                 MacroNameSet macros;
474                 child->listMacroNames(macros);
475                 MacroNameSet::const_iterator cit = macros.begin();
476                 MacroNameSet::const_iterator end = macros.end();
477                 for (; cit != end; ++cit)
478                         parent->usermacros.insert(*cit);
479         }
480
481         // Cache the child buffer.
482         child_buffer_ = child;
483         return child;
484 }
485
486
487 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
488 {
489         string incfile = to_utf8(params()["filename"]);
490
491         // Do nothing if no file name has been specified
492         if (incfile.empty())
493                 return;
494
495         FileName const included_file = includedFileName(buffer(), params());
496
497         // Check we're not trying to include ourselves.
498         // FIXME RECURSIVE INCLUDE
499         // This isn't sufficient, as the inclusion could be downstream.
500         // But it'll have to do for now.
501         if (isInputOrInclude(params()) &&
502                 buffer().absFileName() == included_file.absFileName())
503         {
504                 Alert::error(_("Recursive input"),
505                                bformat(_("Attempted to include file %1$s in itself! "
506                                "Ignoring inclusion."), from_utf8(incfile)));
507                 return;
508         }
509
510         Buffer const * const masterBuffer = buffer().masterBuffer();
511
512         // if incfile is relative, make it relative to the master
513         // buffer directory.
514         if (!FileName::isAbsolute(incfile)) {
515                 // FIXME UNICODE
516                 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
517                                               from_utf8(masterBuffer->filePath())));
518         }
519
520         string exppath = incfile;
521         if (!runparams.export_folder.empty()) {
522                 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
523                 FileName(exppath).onlyPath().createPath();
524         }
525
526         // write it to a file (so far the complete file)
527         string exportfile;
528         string mangled;
529         // bug 5681
530         if (type(params()) == LISTINGS) {
531                 exportfile = exppath;
532                 mangled = DocFileName(included_file).mangledFileName();
533         } else {
534                 exportfile = changeExtension(exppath, ".tex");
535                 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
536                         mangledFileName();
537         }
538
539         if (!runparams.nice)
540                 incfile = mangled;
541         else if (!runparams.silent)
542                 ; // no warning wanted
543         else if (!isValidLaTeXFileName(incfile)) {
544                 frontend::Alert::warning(_("Invalid filename"),
545                         _("The following filename will cause troubles "
546                                 "when running the exported file through LaTeX: ") +
547                         from_utf8(incfile));
548         } else if (!isValidDVIFileName(incfile)) {
549                 frontend::Alert::warning(_("Problematic filename for DVI"),
550                         _("The following filename can cause troubles "
551                                 "when running the exported file through LaTeX "
552                                 "and opening the resulting DVI: ") +
553                         from_utf8(incfile), true);
554         }
555
556         FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
557                                                  buffer().temppath() : masterBuffer->temppath()));
558
559         LYXERR(Debug::LATEX, "incfile:" << incfile);
560         LYXERR(Debug::LATEX, "exportfile:" << exportfile);
561         LYXERR(Debug::LATEX, "writefile:" << writefile);
562
563         string const tex_format = flavor2format(runparams.flavor);
564
565         switch (type(params())) {
566         case VERB:
567         case VERBAST: {
568                 incfile = latex_path(incfile);
569                 // FIXME UNICODE
570                 os << '\\' << from_ascii(params().getCmdName()) << '{'
571                    << from_utf8(incfile) << '}';
572                 break;
573         }
574         case INPUT: {
575                 runparams.exportdata->addExternalFile(tex_format, writefile,
576                                                       exportfile);
577
578                 // \input wants file with extension (default is .tex)
579                 if (!isLyXFileName(included_file.absFileName())) {
580                         incfile = latex_path(incfile);
581                         // FIXME UNICODE
582                         os << '\\' << from_ascii(params().getCmdName())
583                            << '{' << from_utf8(incfile) << '}';
584                 } else {
585                         incfile = changeExtension(incfile, ".tex");
586                         incfile = latex_path(incfile);
587                         // FIXME UNICODE
588                         os << '\\' << from_ascii(params().getCmdName())
589                            << '{' << from_utf8(incfile) <<  '}';
590                 }
591                 break;
592         }
593         case LISTINGS: {
594                 // Here, listings and minted have sligthly different behaviors.
595                 // Using listings, it is always possible to have a caption,
596                 // even for non-floats. Using minted, only floats can have a
597                 // caption. So, with minted we use the following strategy.
598                 // If a caption was specified but the float parameter was not,
599                 // we ourselves add a caption above the listing (because the
600                 // listing comes from a file and might span several pages).
601                 // Otherwise, if float was specified, the floating listing
602                 // environment provided by minted is used. In either case, the
603                 // label parameter is taken as the label by which the float
604                 // can be referenced, otherwise it will have the meaning
605                 // intended by minted. In this last case, the label will
606                 // serve as a sort of caption that, however, will be shown
607                 // by minted only if the frame parameter is also specified.
608                 bool const use_minted = buffer().params().use_minted;
609                 runparams.exportdata->addExternalFile(tex_format, writefile,
610                                                       exportfile);
611                 string const opt = to_utf8(params()["lstparams"]);
612                 // opt is set in QInclude dialog and should have passed validation.
613                 InsetListingsParams lstparams(opt);
614                 string parameters = lstparams.params();
615                 string language;
616                 string caption;
617                 string label;
618                 string placement;
619                 bool isfloat = lstparams.isFloat();
620                 if (use_minted) {
621                         // Get float placement, language, caption, and
622                         // label, then remove the relative options.
623                         vector<string> opts =
624                                 getVectorFromString(parameters, ",", false);
625                         for (size_t i = 0; i < opts.size(); ++i) {
626                                 if (prefixIs(opts[i], "float")) {
627                                         if (prefixIs(opts[i], "float="))
628                                                 placement = opts[i].substr(6);
629                                         opts.erase(opts.begin() + i--);
630                                 } else if (prefixIs(opts[i], "language=")) {
631                                         language = opts[i].substr(9);
632                                         opts.erase(opts.begin() + i--);
633                                 } else if (prefixIs(opts[i], "caption=")) {
634                                         caption = opts[i].substr(8);
635                                         opts.erase(opts.begin() + i--);
636                                 } else if (prefixIs(opts[i], "label=")) {
637                                         label = opts[i].substr(6);
638                                         opts.erase(opts.begin() + i--);
639                                 }
640                         }
641                         if (!label.empty()) {
642                                 if (isfloat || !caption.empty())
643                                         label = trim(label, "{}");
644                                 else
645                                         opts.push_back("label=" + label);
646                         }
647                         parameters = getStringFromVector(opts, ",");
648                 }
649                 if (language.empty())
650                         language = "TeX";
651                 if (use_minted && isfloat) {
652                         os << breakln << "\\begin{listing}";
653                         if (!placement.empty())
654                                 os << '[' << placement << "]";
655                         os << breakln;
656                 } else if (use_minted && !caption.empty()) {
657                         os << breakln << "\\lyxmintcaption[t]{" << caption;
658                         if (!label.empty())
659                                 os << "\\label{" << label << "}";
660                         os << "}\n";
661                 }
662                 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
663                 if (!parameters.empty())
664                         os << "[" << parameters << "]";
665                 if (use_minted)
666                         os << '{'  << ascii_lowercase(language) << '}';
667                 os << '{'  << incfile << '}';
668                 if (use_minted && isfloat) {
669                         if (!caption.empty())
670                                 os << breakln << "\\caption{" << caption << "}";
671                         if (!label.empty())
672                                 os << breakln << "\\label{" << label << "}";
673                         os << breakln << "\\end{listing}\n";
674                 }
675                 break;
676         }
677         case INCLUDE: {
678                 runparams.exportdata->addExternalFile(tex_format, writefile,
679                                                       exportfile);
680
681                 // \include don't want extension and demands that the
682                 // file really have .tex
683                 incfile = changeExtension(incfile, string());
684                 incfile = latex_path(incfile);
685                 // FIXME UNICODE
686                 os << '\\' << from_ascii(params().getCmdName()) << '{'
687                    << from_utf8(incfile) << '}';
688                 break;
689         }
690         case NONE:
691                 break;
692         }
693
694         if (runparams.inComment || runparams.dryrun)
695                 // Don't try to load or copy the file if we're
696                 // in a comment or doing a dryrun
697                 return;
698
699         if (isInputOrInclude(params()) &&
700                  isLyXFileName(included_file.absFileName())) {
701                 // if it's a LyX file and we're inputting or including,
702                 // try to load it so we can write the associated latex
703
704                 Buffer * tmp = loadIfNeeded();
705                 if (!tmp) {
706                         if (!runparams.silent) {
707                                 docstring text = bformat(_("Could not load included "
708                                         "file\n`%1$s'\n"
709                                         "Please, check whether it actually exists."),
710                                         included_file.displayName());
711                                 throw ExceptionMessage(ErrorException, _("Error: "),
712                                                        text);
713                         }
714                         return;
715                 }
716
717                 if (!runparams.silent) {
718                         if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
719                                 // FIXME UNICODE
720                                 docstring text = bformat(_("Included file `%1$s'\n"
721                                         "has textclass `%2$s'\n"
722                                         "while parent file has textclass `%3$s'."),
723                                         included_file.displayName(),
724                                         from_utf8(tmp->params().documentClass().name()),
725                                         from_utf8(masterBuffer->params().documentClass().name()));
726                                 Alert::warning(_("Different textclasses"), text, true);
727                         }
728
729                         string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
730                         string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
731                         if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
732                                 docstring text = bformat(_("Included file `%1$s'\n"
733                                         "has use-non-TeX-fonts set to `%2$s'\n"
734                                         "while parent file has use-non-TeX-fonts set to `%3$s'."),
735                                         included_file.displayName(),
736                                         from_utf8(child_tf),
737                                         from_utf8(master_tf));
738                                 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
739                         }
740
741                         // Make sure modules used in child are all included in master
742                         // FIXME It might be worth loading the children's modules into the master
743                         // over in BufferParams rather than doing this check.
744                         LayoutModuleList const masterModules = masterBuffer->params().getModules();
745                         LayoutModuleList const childModules = tmp->params().getModules();
746                         LayoutModuleList::const_iterator it = childModules.begin();
747                         LayoutModuleList::const_iterator end = childModules.end();
748                         for (; it != end; ++it) {
749                                 string const module = *it;
750                                 LayoutModuleList::const_iterator found =
751                                         find(masterModules.begin(), masterModules.end(), module);
752                                 if (found == masterModules.end()) {
753                                         docstring text = bformat(_("Included file `%1$s'\n"
754                                                 "uses module `%2$s'\n"
755                                                 "which is not used in parent file."),
756                                                 included_file.displayName(), from_utf8(module));
757                                         Alert::warning(_("Module not found"), text);
758                                 }
759                         }
760                 }
761
762                 tmp->markDepClean(masterBuffer->temppath());
763
764                 // Don't assume the child's format is latex
765                 string const inc_format = tmp->params().bufferFormat();
766                 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
767                         theFormats().extension(inc_format)));
768
769                 // FIXME: handle non existing files
770                 // The included file might be written in a different encoding
771                 // and language.
772                 Encoding const * const oldEnc = runparams.encoding;
773                 Language const * const oldLang = runparams.master_language;
774                 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
775                 // the children must be encoded in plain utf8!
776                 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
777                         encodings.fromLyXName("utf8-plain")
778                         : &tmp->params().encoding();
779                 runparams.master_language = buffer().params().language;
780                 runparams.par_begin = 0;
781                 runparams.par_end = tmp->paragraphs().size();
782                 runparams.is_child = true;
783                 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
784                                 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
785                         if (!runparams.silent) {
786                                 docstring msg = bformat(_("Included file `%1$s' "
787                                         "was not exported correctly.\n "
788                                         "LaTeX export is probably incomplete."),
789                                         included_file.displayName());
790                                 ErrorList const & el = tmp->errorList("Export");
791                                 if (!el.empty())
792                                         msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
793                                                 msg, el.begin()->error,
794                                                 el.begin()->description);
795                                 throw ExceptionMessage(ErrorException, _("Error: "),
796                                                        msg);
797                         }
798                 }
799                 runparams.encoding = oldEnc;
800                 runparams.master_language = oldLang;
801                 runparams.is_child = false;
802
803                 // If needed, use converters to produce a latex file from the child
804                 if (tmpwritefile != writefile) {
805                         ErrorList el;
806                         bool const success =
807                                 theConverters().convert(tmp, tmpwritefile, writefile,
808                                                         included_file,
809                                                         inc_format, tex_format, el);
810
811                         if (!success && !runparams.silent) {
812                                 docstring msg = bformat(_("Included file `%1$s' "
813                                                 "was not exported correctly.\n "
814                                                 "LaTeX export is probably incomplete."),
815                                                 included_file.displayName());
816                                 if (!el.empty())
817                                         msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
818                                                         msg, el.begin()->error,
819                                                         el.begin()->description);
820                                 throw ExceptionMessage(ErrorException, _("Error: "),
821                                                        msg);
822                         }
823                 }
824         } else {
825                 // In this case, it's not a LyX file, so we copy the file
826                 // to the temp dir, so that .aux files etc. are not created
827                 // in the original dir. Files included by this file will be
828                 // found via either the environment variable TEXINPUTS, or
829                 // input@path, see ../Buffer.cpp.
830                 unsigned long const checksum_in  = included_file.checksum();
831                 unsigned long const checksum_out = writefile.checksum();
832
833                 if (checksum_in != checksum_out) {
834                         if (!included_file.copyTo(writefile)) {
835                                 // FIXME UNICODE
836                                 LYXERR(Debug::LATEX,
837                                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
838                                                                         "into the temporary directory."),
839                                                          from_utf8(included_file.absFileName()))));
840                                 return;
841                         }
842                 }
843         }
844 }
845
846
847 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
848 {
849         if (rp.inComment)
850                  return docstring();
851
852         // For verbatim and listings, we just include the contents of the file as-is.
853         // In the case of listings, we wrap it in <pre>.
854         bool const listing = isListings(params());
855         if (listing || isVerbatim(params())) {
856                 if (listing)
857                         xs << html::StartTag("pre");
858                 // FIXME: We don't know the encoding of the file, default to UTF-8.
859                 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
860                 if (listing)
861                         xs << html::EndTag("pre");
862                 return docstring();
863         }
864
865         // We don't (yet) know how to Input or Include non-LyX files.
866         // (If we wanted to get really arcane, we could run some tex2html
867         // converter on the included file. But that's just masochistic.)
868         FileName const included_file = includedFileName(buffer(), params());
869         if (!isLyXFileName(included_file.absFileName())) {
870                 if (!rp.silent)
871                         frontend::Alert::warning(_("Unsupported Inclusion"),
872                                          bformat(_("LyX does not know how to include non-LyX files when "
873                                                    "generating HTML output. Offending file:\n%1$s"),
874                                                     params()["filename"]));
875                 return docstring();
876         }
877
878         // In the other cases, we will generate the HTML and include it.
879
880         // Check we're not trying to include ourselves.
881         // FIXME RECURSIVE INCLUDE
882         if (buffer().absFileName() == included_file.absFileName()) {
883                 Alert::error(_("Recursive input"),
884                                bformat(_("Attempted to include file %1$s in itself! "
885                                "Ignoring inclusion."), params()["filename"]));
886                 return docstring();
887         }
888
889         Buffer const * const ibuf = loadIfNeeded();
890         if (!ibuf)
891                 return docstring();
892
893         // are we generating only some paragraphs, or all of them?
894         bool const all_pars = !rp.dryrun ||
895                         (rp.par_begin == 0 &&
896                          rp.par_end == (int)buffer().text().paragraphs().size());
897
898         OutputParams op = rp;
899         if (all_pars) {
900                 op.par_begin = 0;
901                 op.par_end = 0;
902                 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
903         } else
904                 xs << XHTMLStream::ESCAPE_NONE
905                    << "<!-- Included file: "
906                    << from_utf8(included_file.absFileName())
907                    << XHTMLStream::ESCAPE_NONE
908                          << " -->";
909         return docstring();
910 }
911
912
913 int InsetInclude::plaintext(odocstringstream & os,
914         OutputParams const & op, size_t) const
915 {
916         // just write the filename if we're making a tooltip or toc entry,
917         // or are generating this for advanced search
918         if (op.for_tooltip || op.for_toc || op.for_search) {
919                 os << '[' << screenLabel() << '\n'
920                    << getParam("filename") << "\n]";
921                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
922         }
923
924         if (isVerbatim(params()) || isListings(params())) {
925                 os << '[' << screenLabel() << '\n'
926                    // FIXME: We don't know the encoding of the file, default to UTF-8.
927                    << includedFileName(buffer(), params()).fileContents("UTF-8")
928                    << "\n]";
929                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
930         }
931
932         Buffer const * const ibuf = loadIfNeeded();
933         if (!ibuf) {
934                 docstring const str = '[' + screenLabel() + ']';
935                 os << str;
936                 return str.size();
937         }
938         writePlaintextFile(*ibuf, os, op);
939         return 0;
940 }
941
942
943 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
944 {
945         string incfile = to_utf8(params()["filename"]);
946
947         // Do nothing if no file name has been specified
948         if (incfile.empty())
949                 return 0;
950
951         string const included_file = includedFileName(buffer(), params()).absFileName();
952
953         // Check we're not trying to include ourselves.
954         // FIXME RECURSIVE INCLUDE
955         // This isn't sufficient, as the inclusion could be downstream.
956         // But it'll have to do for now.
957         if (buffer().absFileName() == included_file) {
958                 Alert::error(_("Recursive input"),
959                                bformat(_("Attempted to include file %1$s in itself! "
960                                "Ignoring inclusion."), from_utf8(incfile)));
961                 return 0;
962         }
963
964         string exppath = incfile;
965         if (!runparams.export_folder.empty()) {
966                 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
967                 FileName(exppath).onlyPath().createPath();
968         }
969
970         // write it to a file (so far the complete file)
971         string const exportfile = changeExtension(exppath, ".sgml");
972         DocFileName writefile(changeExtension(included_file, ".sgml"));
973
974         Buffer * tmp = loadIfNeeded();
975         if (tmp) {
976                 string const mangled = writefile.mangledFileName();
977                 writefile = makeAbsPath(mangled,
978                                         buffer().masterBuffer()->temppath());
979                 if (!runparams.nice)
980                         incfile = mangled;
981
982                 LYXERR(Debug::LATEX, "incfile:" << incfile);
983                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
984                 LYXERR(Debug::LATEX, "writefile:" << writefile);
985
986                 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
987         }
988
989         runparams.exportdata->addExternalFile("docbook", writefile,
990                                               exportfile);
991         runparams.exportdata->addExternalFile("docbook-xml", writefile,
992                                               exportfile);
993
994         if (isVerbatim(params()) || isListings(params())) {
995                 os << "<inlinegraphic fileref=\""
996                    << '&' << include_label << ';'
997                    << "\" format=\"linespecific\">";
998         } else
999                 os << '&' << include_label << ';';
1000
1001         return 0;
1002 }
1003
1004
1005 void InsetInclude::validate(LaTeXFeatures & features) const
1006 {
1007         LATTEST(&buffer() == &features.buffer());
1008
1009         string incfile = to_utf8(params()["filename"]);
1010         string const included_file =
1011                 includedFileName(buffer(), params()).absFileName();
1012
1013         string writefile;
1014         if (isLyXFileName(included_file))
1015                 writefile = changeExtension(included_file, ".sgml");
1016         else
1017                 writefile = included_file;
1018
1019         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1020                 incfile = DocFileName(writefile).mangledFileName();
1021                 writefile = makeAbsPath(incfile,
1022                                         buffer().masterBuffer()->temppath()).absFileName();
1023         }
1024
1025         features.includeFile(include_label, writefile);
1026
1027         features.useInsetLayout(getLayout());
1028         if (isVerbatim(params()))
1029                 features.require("verbatim");
1030         else if (isListings(params())) {
1031                 if (buffer().params().use_minted) {
1032                         features.require("minted");
1033                         string const opts = to_utf8(params()["lstparams"]);
1034                         InsetListingsParams lstpars(opts);
1035                         if (!lstpars.isFloat() && contains(opts, "caption="))
1036                                 features.require("lyxmintcaption");
1037                 } else
1038                         features.require("listings");
1039         }
1040
1041         // Here we must do the fun stuff...
1042         // Load the file in the include if it needs
1043         // to be loaded:
1044         Buffer * const tmp = loadIfNeeded();
1045         if (tmp) {
1046                 // the file is loaded
1047                 // make sure the buffer isn't us
1048                 // FIXME RECURSIVE INCLUDES
1049                 // This is not sufficient, as recursive includes could be
1050                 // more than a file away. But it will do for now.
1051                 if (tmp && tmp != &buffer()) {
1052                         // We must temporarily change features.buffer,
1053                         // otherwise it would always be the master buffer,
1054                         // and nested includes would not work.
1055                         features.setBuffer(*tmp);
1056                         // Maybe this is already a child
1057                         bool const is_child =
1058                                 features.runparams().is_child;
1059                         features.runparams().is_child = true;
1060                         tmp->validate(features);
1061                         features.runparams().is_child = is_child;
1062                         features.setBuffer(buffer());
1063                 }
1064         }
1065 }
1066
1067
1068 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1069 {
1070         Buffer * child = loadIfNeeded();
1071         if (!child)
1072                 return;
1073         // FIXME RECURSIVE INCLUDE
1074         // This isn't sufficient, as the inclusion could be downstream.
1075         // But it'll have to do for now.
1076         if (child == &buffer())
1077                 return;
1078         child->collectBibKeys(checkedFiles);
1079 }
1080
1081
1082 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1083 {
1084         LBUFERR(mi.base.bv);
1085
1086         bool use_preview = false;
1087         if (RenderPreview::previewText()) {
1088                 graphics::PreviewImage const * pimage =
1089                         preview_->getPreviewImage(mi.base.bv->buffer());
1090                 use_preview = pimage && pimage->image();
1091         }
1092
1093         if (use_preview) {
1094                 preview_->metrics(mi, dim);
1095         } else {
1096                 if (!set_label_) {
1097                         set_label_ = true;
1098                         button_.update(screenLabel(), true, false);
1099                 }
1100                 button_.metrics(mi, dim);
1101         }
1102
1103         Box b(0, dim.wid, -dim.asc, dim.des);
1104         button_.setBox(b);
1105 }
1106
1107
1108 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1109 {
1110         LBUFERR(pi.base.bv);
1111
1112         bool use_preview = false;
1113         if (RenderPreview::previewText()) {
1114                 graphics::PreviewImage const * pimage =
1115                         preview_->getPreviewImage(pi.base.bv->buffer());
1116                 use_preview = pimage && pimage->image();
1117         }
1118
1119         if (use_preview)
1120                 preview_->draw(pi, x, y);
1121         else
1122                 button_.draw(pi, x, y);
1123 }
1124
1125
1126 void InsetInclude::write(ostream & os) const
1127 {
1128         params().Write(os, &buffer());
1129 }
1130
1131
1132 string InsetInclude::contextMenuName() const
1133 {
1134         return "context-include";
1135 }
1136
1137
1138 Inset::DisplayType InsetInclude::display() const
1139 {
1140         return type(params()) == INPUT ? Inline : AlignCenter;
1141 }
1142
1143
1144 docstring InsetInclude::layoutName() const
1145 {
1146         if (isListings(params()))
1147                 return from_ascii("IncludeListings");
1148         return InsetCommand::layoutName();
1149 }
1150
1151
1152 //
1153 // preview stuff
1154 //
1155
1156 void InsetInclude::fileChanged() const
1157 {
1158         Buffer const * const buffer = updateFrontend();
1159         if (!buffer)
1160                 return;
1161
1162         preview_->removePreview(*buffer);
1163         add_preview(*preview_, *this, *buffer);
1164         preview_->startLoading(*buffer);
1165 }
1166
1167
1168 namespace {
1169
1170 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1171 {
1172         FileName const included_file = includedFileName(buffer, params);
1173
1174         return type(params) == INPUT && params.preview() &&
1175                 included_file.isReadableFile();
1176 }
1177
1178
1179 docstring latexString(InsetInclude const & inset)
1180 {
1181         odocstringstream ods;
1182         otexstream os(ods);
1183         // We don't need to set runparams.encoding since this will be done
1184         // by latex() anyway.
1185         OutputParams runparams(0);
1186         runparams.flavor = OutputParams::LATEX;
1187         runparams.for_preview = true;
1188         inset.latex(os, runparams);
1189
1190         return ods.str();
1191 }
1192
1193
1194 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1195                  Buffer const & buffer)
1196 {
1197         InsetCommandParams const & params = inset.params();
1198         if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1199                 renderer.setAbsFile(includedFileName(buffer, params));
1200                 docstring const snippet = latexString(inset);
1201                 renderer.addPreview(snippet, buffer);
1202         }
1203 }
1204
1205 } // namespace
1206
1207
1208 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1209         graphics::PreviewLoader & ploader) const
1210 {
1211         Buffer const & buffer = ploader.buffer();
1212         if (!preview_wanted(params(), buffer))
1213                 return;
1214         preview_->setAbsFile(includedFileName(buffer, params()));
1215         docstring const snippet = latexString(*this);
1216         preview_->addPreview(snippet, ploader);
1217 }
1218
1219
1220 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1221                             UpdateType utype, TocBackend & backend) const
1222 {
1223         if (isListings(params())) {
1224                 if (label_)
1225                         label_->addToToc(cpit, output_active, utype, backend);
1226                 TocBuilder & b = backend.builder("listing");
1227                 b.pushItem(cpit, screenLabel(), output_active);
1228                 InsetListingsParams p(to_utf8(params()["lstparams"]));
1229                 b.argumentItem(from_utf8(p.getParamValue("caption")));
1230                 b.pop();
1231         } else {
1232                 Buffer const * const childbuffer = getChildBuffer();
1233
1234                 TocBuilder & b = backend.builder("child");
1235                 docstring str = childbuffer ? childbuffer->fileName().displayName()
1236                         : from_ascii("?");
1237                 b.pushItem(cpit, str, output_active);
1238                 b.pop();
1239
1240                 if (!childbuffer)
1241                         return;
1242
1243                 // Update the child's tocBackend. The outliner uses the master's, but
1244                 // the navigation menu uses the child's.
1245                 childbuffer->tocBackend().update(output_active, utype);
1246                 // Include Tocs from children
1247                 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1248                                               backend);
1249                 //Copy missing outliner names (though the user has been warned against
1250                 //having different document class and module selection between master
1251                 //and child).
1252                 for (pair<string, docstring> const & name
1253                              : childbuffer->params().documentClass().outlinerNames())
1254                         backend.addName(name.first, translateIfPossible(name.second));
1255         }
1256 }
1257
1258
1259 void InsetInclude::updateCommand()
1260 {
1261         if (!label_)
1262                 return;
1263
1264         docstring old_label = label_->getParam("name");
1265         label_->updateLabel(old_label);
1266         // the label might have been adapted (duplicate)
1267         docstring new_label = label_->getParam("name");
1268         if (old_label == new_label)
1269                 return;
1270
1271         // update listings parameters...
1272         InsetCommandParams p(INCLUDE_CODE);
1273         p = params();
1274         InsetListingsParams par(to_utf8(params()["lstparams"]));
1275         par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1276         p["lstparams"] = from_utf8(par.params());
1277         setParams(p);
1278 }
1279
1280
1281 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1282 {
1283         button_.update(screenLabel(), true, false);
1284
1285         Buffer const * const childbuffer = getChildBuffer();
1286         if (childbuffer) {
1287                 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1288                 return;
1289         }
1290         if (!isListings(params()))
1291                 return;
1292
1293         if (label_)
1294                 label_->updateBuffer(it, utype);
1295
1296         InsetListingsParams const par(to_utf8(params()["lstparams"]));
1297         if (par.getParamValue("caption").empty()) {
1298                 listings_label_ = buffer().B_("Program Listing");
1299                 return;
1300         }
1301         Buffer const & master = *buffer().masterBuffer();
1302         Counters & counters = master.params().documentClass().counters();
1303         docstring const cnt = from_ascii("listing");
1304         listings_label_ = master.B_("Program Listing");
1305         if (counters.hasCounter(cnt)) {
1306                 counters.step(cnt, utype);
1307                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1308         }
1309 }
1310
1311
1312 } // namespace lyx