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