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