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