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