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