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