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