]> git.lyx.org Git - features.git/blob - src/insets/InsetInclude.cpp
Remove execute permission from two source files
[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 0;
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_(0), child_buffer_(0), file_exist_(false)
193 {
194         preview_->connect([=](){ fileChanged(); });
195
196         if (isListings(params())) {
197                 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
198                 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
199         } else if (isInputOrInclude(params()) && buf)
200                 loadIfNeeded();
201 }
202
203
204 InsetInclude::InsetInclude(InsetInclude const & other)
205         : InsetCommand(other), include_label(other.include_label),
206           preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
207           set_label_(false), label_(0), child_buffer_(0), file_exist_(other.file_exist_)
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_ = 0;
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_ = 0;
378
379         InsetCommand::setParams(p);
380         set_label_ = false;
381
382         if (preview_->monitoring())
383                 preview_->stopMonitoring();
384
385         if (type(params()) == INPUT)
386                 add_preview(*preview_, *this, buffer());
387 }
388
389
390 bool InsetInclude::isChildIncluded() const
391 {
392         std::list<std::string> includeonlys =
393                 buffer().params().getIncludedChildren();
394         if (includeonlys.empty())
395                 return true;
396         return (std::find(includeonlys.begin(),
397                           includeonlys.end(),
398                           ltrim(to_utf8(params()["filename"]))) != includeonlys.end());
399 }
400
401
402 docstring InsetInclude::screenLabel() const
403 {
404         docstring pre = file_exist_ ? docstring() : _("FILE MISSING:");
405
406         docstring temp;
407
408         switch (type(params())) {
409                 case INPUT:
410                         temp = buffer().B_("Input");
411                         break;
412                 case VERB:
413             temp = buffer().B_("Verbatim");
414                         break;
415                 case VERBAST:
416             temp = buffer().B_("Verbatim*");
417                         break;
418                 case INCLUDE:
419                         if (isChildIncluded())
420                                 temp = buffer().B_("Include");
421                         else
422                                 temp += buffer().B_("Include (excluded)");
423                         break;
424                 case LISTINGS:
425                         temp = listings_label_;
426                         break;
427                 case NONE:
428                         LASSERT(false, temp = buffer().B_("Unknown"));
429                         break;
430         }
431
432         temp += ": ";
433
434         if (ltrim(params()["filename"]).empty())
435                 temp += "???";
436         else
437                 temp += from_utf8(onlyFileName(ltrim(to_utf8(params()["filename"]))));
438
439         return pre.empty() ? temp : pre + from_ascii(" ") + temp;
440 }
441
442
443 Buffer * InsetInclude::getChildBuffer() const
444 {
445         Buffer * childBuffer = loadIfNeeded();
446
447         // FIXME RECURSIVE INCLUDE
448         // This isn't sufficient, as the inclusion could be downstream.
449         // But it'll have to do for now.
450         return (childBuffer == &buffer()) ? 0 : childBuffer;
451 }
452
453
454 Buffer * InsetInclude::loadIfNeeded() const
455 {
456         // This is for background export and preview. We don't even want to
457         // try to load the cloned child document again.
458         if (buffer().isClone())
459                 return child_buffer_;
460
461         // Don't try to load it again if we failed before.
462         if (failedtoload_ || isVerbatim(params()) || isListings(params()))
463                 return 0;
464
465         FileName const included_file = includedFileName(buffer(), params());
466         // Use cached Buffer if possible.
467         if (child_buffer_ != 0) {
468                 if (theBufferList().isLoaded(child_buffer_)
469                     // additional sanity check: make sure the Buffer really is
470                     // associated with the file we want.
471                     && child_buffer_ == theBufferList().getBuffer(included_file))
472                         return child_buffer_;
473                 // Buffer vanished, so invalidate cache and try to reload.
474                 child_buffer_ = 0;
475         }
476
477         if (!isLyXFileName(included_file.absFileName()))
478                 return 0;
479
480         Buffer * child = theBufferList().getBuffer(included_file);
481         if (!child) {
482                 // the readonly flag can/will be wrong, not anymore I think.
483                 if (!included_file.exists())
484                         return 0;
485
486                 child = theBufferList().newBuffer(included_file.absFileName());
487                 if (!child)
488                         // Buffer creation is not possible.
489                         return 0;
490
491                 // Set parent before loading, such that macros can be tracked
492                 child->setParent(&buffer());
493
494                 if (child->loadLyXFile() != Buffer::ReadSuccess) {
495                         failedtoload_ = true;
496                         child->setParent(0);
497                         //close the buffer we just opened
498                         theBufferList().release(child);
499                         return 0;
500                 }
501
502                 if (!child->errorList("Parse").empty()) {
503                         // FIXME: Do something.
504                 }
505         } else {
506                 // The file was already loaded, so, simply
507                 // inform parent buffer about local macros.
508                 Buffer const * parent = &buffer();
509                 child->setParent(parent);
510                 MacroNameSet macros;
511                 child->listMacroNames(macros);
512                 MacroNameSet::const_iterator cit = macros.begin();
513                 MacroNameSet::const_iterator end = macros.end();
514                 for (; cit != end; ++cit)
515                         parent->usermacros.insert(*cit);
516         }
517
518         // Cache the child buffer.
519         child_buffer_ = child;
520         return child;
521 }
522
523
524 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
525 {
526         string incfile = ltrim(to_utf8(params()["filename"]));
527
528         // Warn if no file name has been specified
529         if (incfile.empty()) {
530                 frontend::Alert::warning(_("No file name specified"),
531                         _("An included file name is empty.\n"
532                            "Ignoring Inclusion"),
533                         true);
534                 return;
535         }
536         // Warn if file doesn't exist
537         if (!includedFileExist()) {
538                 frontend::Alert::warning(_("Included file not found"),
539                         bformat(_("The included file\n"
540                                   "'%1$s'\n"
541                                   "has not been found. LyX will ignore the inclusion."),
542                                 from_utf8(incfile)),
543                         true);
544                  return;
545         }
546
547         FileName const included_file = includedFileName(buffer(), params());
548
549         // Check we're not trying to include ourselves.
550         // FIXME RECURSIVE INCLUDE
551         // This isn't sufficient, as the inclusion could be downstream.
552         // But it'll have to do for now.
553         if (isInputOrInclude(params()) &&
554                 buffer().absFileName() == included_file.absFileName())
555         {
556                 Alert::error(_("Recursive input"),
557                                bformat(_("Attempted to include file %1$s in itself! "
558                                "Ignoring inclusion."), from_utf8(incfile)));
559                 return;
560         }
561
562         Buffer const * const masterBuffer = buffer().masterBuffer();
563
564         // if incfile is relative, make it relative to the master
565         // buffer directory.
566         if (!FileName::isAbsolute(incfile)) {
567                 // FIXME UNICODE
568                 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
569                                               from_utf8(masterBuffer->filePath())));
570         }
571
572         string exppath = incfile;
573         if (!runparams.export_folder.empty()) {
574                 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
575         }
576
577         // write it to a file (so far the complete file)
578         string exportfile;
579         string mangled;
580         // bug 5681
581         if (type(params()) == LISTINGS) {
582                 exportfile = exppath;
583                 mangled = DocFileName(included_file).mangledFileName();
584         } else {
585                 exportfile = changeExtension(exppath, ".tex");
586                 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
587                         mangledFileName();
588         }
589
590         if (!runparams.nice)
591                 incfile = mangled;
592         else if (!runparams.silent)
593                 ; // no warning wanted
594         else if (!isValidLaTeXFileName(incfile)) {
595                 frontend::Alert::warning(_("Invalid filename"),
596                         _("The following filename will cause troubles "
597                                 "when running the exported file through LaTeX: ") +
598                         from_utf8(incfile));
599         } else if (!isValidDVIFileName(incfile)) {
600                 frontend::Alert::warning(_("Problematic filename for DVI"),
601                         _("The following filename can cause troubles "
602                                 "when running the exported file through LaTeX "
603                                 "and opening the resulting DVI: ") +
604                         from_utf8(incfile), true);
605         }
606
607         FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
608                                                  buffer().temppath() : masterBuffer->temppath()));
609
610         LYXERR(Debug::LATEX, "incfile:" << incfile);
611         LYXERR(Debug::LATEX, "exportfile:" << exportfile);
612         LYXERR(Debug::LATEX, "writefile:" << writefile);
613
614         string const tex_format = flavor2format(runparams.flavor);
615
616         switch (type(params())) {
617         case VERB:
618         case VERBAST: {
619                 incfile = latex_path(incfile);
620                 // FIXME UNICODE
621                 os << '\\' << from_ascii(params().getCmdName()) << '{'
622                    << from_utf8(incfile) << '}';
623                 break;
624         }
625         case INPUT: {
626                 runparams.exportdata->addExternalFile(tex_format, writefile,
627                                                       exportfile);
628
629                 // \input wants file with extension (default is .tex)
630                 if (!isLyXFileName(included_file.absFileName())) {
631                         incfile = latex_path(incfile);
632                         // FIXME UNICODE
633                         os << '\\' << from_ascii(params().getCmdName())
634                            << '{' << from_utf8(incfile) << '}';
635                 } else {
636                         incfile = changeExtension(incfile, ".tex");
637                         incfile = latex_path(incfile);
638                         // FIXME UNICODE
639                         os << '\\' << from_ascii(params().getCmdName())
640                            << '{' << from_utf8(incfile) <<  '}';
641                 }
642                 break;
643         }
644         case LISTINGS: {
645                 // Here, listings and minted have sligthly different behaviors.
646                 // Using listings, it is always possible to have a caption,
647                 // even for non-floats. Using minted, only floats can have a
648                 // caption. So, with minted we use the following strategy.
649                 // If a caption was specified but the float parameter was not,
650                 // we ourselves add a caption above the listing (because the
651                 // listing comes from a file and might span several pages).
652                 // Otherwise, if float was specified, the floating listing
653                 // environment provided by minted is used. In either case, the
654                 // label parameter is taken as the label by which the float
655                 // can be referenced, otherwise it will have the meaning
656                 // intended by minted. In this last case, the label will
657                 // serve as a sort of caption that, however, will be shown
658                 // by minted only if the frame parameter is also specified.
659                 bool const use_minted = buffer().params().use_minted;
660                 runparams.exportdata->addExternalFile(tex_format, writefile,
661                                                       exportfile);
662                 string const opt = to_utf8(params()["lstparams"]);
663                 // opt is set in QInclude dialog and should have passed validation.
664                 InsetListingsParams lstparams(opt);
665                 docstring parameters = from_utf8(lstparams.params());
666                 docstring language;
667                 docstring caption;
668                 docstring label;
669                 docstring placement;
670                 bool isfloat = lstparams.isFloat();
671                 // We are going to split parameters at commas, so
672                 // replace commas that are not parameter separators
673                 // with a code point from the private use area
674                 char_type comma = replaceCommaInBraces(parameters);
675                 // Get float placement, language, caption, and
676                 // label, then remove the relative options if minted.
677                 vector<docstring> opts =
678                         getVectorFromString(parameters, from_ascii(","), false);
679                 vector<docstring> latexed_opts;
680                 for (size_t i = 0; i < opts.size(); ++i) {
681                         // Restore replaced commas
682                         opts[i] = subst(opts[i], comma, ',');
683                         if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
684                                 if (prefixIs(opts[i], from_ascii("float=")))
685                                         placement = opts[i].substr(6);
686                                 opts.erase(opts.begin() + i--);
687                         } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
688                                 language = opts[i].substr(9);
689                                 opts.erase(opts.begin() + i--);
690                         } else if (prefixIs(opts[i], from_ascii("caption="))) {
691                                 caption = params().prepareCommand(runparams, trim(opts[i].substr(8), "{}"),
692                                                                   ParamInfo::HANDLING_LATEXIFY);
693                                 opts.erase(opts.begin() + i--);
694                                 if (!use_minted)
695                                         latexed_opts.push_back(from_ascii("caption={") + caption + "}");
696                         } else if (prefixIs(opts[i], from_ascii("label="))) {
697                                 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
698                                                                 ParamInfo::HANDLING_ESCAPE);
699                                 opts.erase(opts.begin() + i--);
700                                 if (!use_minted)
701                                         latexed_opts.push_back(from_ascii("label={") + label + "}");
702                         }
703                         if (use_minted && !label.empty()) {
704                                 if (isfloat || !caption.empty())
705                                         label = trim(label, "{}");
706                                 else
707                                         opts.push_back(from_ascii("label=") + label);
708                         }
709                 }
710                 if (!latexed_opts.empty())
711                         opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
712                 parameters = getStringFromVector(opts, from_ascii(","));
713                 if (language.empty())
714                         language = from_ascii("TeX");
715                 if (use_minted && isfloat) {
716                         os << breakln << "\\begin{listing}";
717                         if (!placement.empty())
718                                 os << '[' << placement << "]";
719                         os << breakln;
720                 } else if (use_minted && !caption.empty()) {
721                         os << breakln << "\\lyxmintcaption[t]{" << caption;
722                         if (!label.empty())
723                                 os << "\\label{" << label << "}";
724                         os << "}\n";
725                 }
726                 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
727                 if (!parameters.empty())
728                         os << "[" << parameters << "]";
729                 if (use_minted)
730                         os << '{'  << ascii_lowercase(language) << '}';
731                 os << '{'  << incfile << '}';
732                 if (use_minted && isfloat) {
733                         if (!caption.empty())
734                                 os << breakln << "\\caption{" << caption << "}";
735                         if (!label.empty())
736                                 os << breakln << "\\label{" << label << "}";
737                         os << breakln << "\\end{listing}\n";
738                 }
739                 break;
740         }
741         case INCLUDE: {
742                 runparams.exportdata->addExternalFile(tex_format, writefile,
743                                                       exportfile);
744
745                 // \include don't want extension and demands that the
746                 // file really have .tex
747                 incfile = changeExtension(incfile, string());
748                 incfile = latex_path(incfile);
749                 // FIXME UNICODE
750                 os << '\\' << from_ascii(params().getCmdName()) << '{'
751                    << from_utf8(incfile) << '}';
752                 break;
753         }
754         case NONE:
755                 break;
756         }
757
758         if (runparams.inComment || runparams.dryrun)
759                 // Don't try to load or copy the file if we're
760                 // in a comment or doing a dryrun
761                 return;
762
763         if (isInputOrInclude(params()) &&
764                  isLyXFileName(included_file.absFileName())) {
765                 // if it's a LyX file and we're inputting or including,
766                 // try to load it so we can write the associated latex
767
768                 Buffer * tmp = loadIfNeeded();
769                 if (!tmp) {
770                         if (!runparams.silent) {
771                                 docstring text = bformat(_("Could not load included "
772                                         "file\n`%1$s'\n"
773                                         "Please, check whether it actually exists."),
774                                         included_file.displayName());
775                                 throw ExceptionMessage(ErrorException, _("Error: "),
776                                                        text);
777                         }
778                         return;
779                 }
780
781                 if (!runparams.silent) {
782                         if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
783                                 // FIXME UNICODE
784                                 docstring text = bformat(_("Included file `%1$s'\n"
785                                         "has textclass `%2$s'\n"
786                                         "while parent file has textclass `%3$s'."),
787                                         included_file.displayName(),
788                                         from_utf8(tmp->params().documentClass().name()),
789                                         from_utf8(masterBuffer->params().documentClass().name()));
790                                 Alert::warning(_("Different textclasses"), text, true);
791                         }
792
793                         string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
794                         string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
795                         if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
796                                 docstring text = bformat(_("Included file `%1$s'\n"
797                                         "has use-non-TeX-fonts set to `%2$s'\n"
798                                         "while parent file has use-non-TeX-fonts set to `%3$s'."),
799                                         included_file.displayName(),
800                                         from_utf8(child_tf),
801                                         from_utf8(master_tf));
802                                 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
803                         } 
804                         else if (tmp->params().inputenc != masterBuffer->params().inputenc) {
805                                 docstring text = bformat(_("Included file `%1$s'\n"
806                                         "uses input encoding \"%2$s\" [%3$s]\n"
807                                         "while parent file uses input encoding \"%4$s\" [%5$s]."),
808                                         included_file.displayName(),
809                                         _(tmp->params().inputenc),
810                                         from_utf8(tmp->params().encoding().guiName()),
811                                         _(masterBuffer->params().inputenc),
812                                         from_utf8(masterBuffer->params().encoding().guiName()));
813                                 Alert::warning(_("Different LaTeX input encodings"), text, true);
814                         }
815
816                         // Make sure modules used in child are all included in master
817                         // FIXME It might be worth loading the children's modules into the master
818                         // over in BufferParams rather than doing this check.
819                         LayoutModuleList const masterModules = masterBuffer->params().getModules();
820                         LayoutModuleList const childModules = tmp->params().getModules();
821                         LayoutModuleList::const_iterator it = childModules.begin();
822                         LayoutModuleList::const_iterator end = childModules.end();
823                         for (; it != end; ++it) {
824                                 string const module = *it;
825                                 LayoutModuleList::const_iterator found =
826                                         find(masterModules.begin(), masterModules.end(), module);
827                                 if (found == masterModules.end()) {
828                                         docstring text = bformat(_("Included file `%1$s'\n"
829                                                 "uses module `%2$s'\n"
830                                                 "which is not used in parent file."),
831                                                 included_file.displayName(), from_utf8(module));
832                                         Alert::warning(_("Module not found"), text, true);
833                                 }
834                         }
835                 }
836
837                 tmp->markDepClean(masterBuffer->temppath());
838
839                 // Don't assume the child's format is latex
840                 string const inc_format = tmp->params().bufferFormat();
841                 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
842                         theFormats().extension(inc_format)));
843
844                 // FIXME: handle non existing files
845                 // The included file might be written in a different encoding
846                 // and language.
847                 Encoding const * const oldEnc = runparams.encoding;
848                 Language const * const oldLang = runparams.master_language;
849                 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
850                 // the children must be encoded in plain utf8!
851                 if (masterBuffer->params().useNonTeXFonts)
852                         runparams.encoding = encodings.fromLyXName("utf8-plain");
853                 else if (oldEnc)
854                         runparams.encoding = oldEnc;
855                 else runparams.encoding = &tmp->params().encoding();
856                 runparams.master_language = buffer().params().language;
857                 runparams.par_begin = 0;
858                 runparams.par_end = tmp->paragraphs().size();
859                 runparams.is_child = true;
860                 Buffer::ExportStatus retval =
861                         tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
862                                 onlyPath().absFileName(), runparams, Buffer::OnlyBody);
863                 if (retval == Buffer::ExportKilled && buffer().isClone() &&
864                       buffer().isExporting()) {
865                   // We really shouldn't get here, I don't think.
866                   LYXERR0("No conversion exception?");
867                         throw ConversionException();
868                 }
869                 else if (retval != Buffer::ExportSuccess) {
870                         if (!runparams.silent) {
871                                 docstring msg = bformat(_("Included file `%1$s' "
872                                         "was not exported correctly.\n "
873                                         "LaTeX export is probably incomplete."),
874                                         included_file.displayName());
875                                 ErrorList const & el = tmp->errorList("Export");
876                                 if (!el.empty())
877                                         msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
878                                                 msg, el.begin()->error, el.begin()->description);
879                                 throw ExceptionMessage(ErrorException, _("Error: "), msg);
880                         }
881                 }
882                 runparams.encoding = oldEnc;
883                 runparams.master_language = oldLang;
884                 runparams.is_child = false;
885
886                 // If needed, use converters to produce a latex file from the child
887                 if (tmpwritefile != writefile) {
888                         ErrorList el;
889                         Converters::RetVal const conv_retval =
890                                 theConverters().convert(tmp, tmpwritefile, writefile,
891                                     included_file, inc_format, tex_format, el);
892                         if (conv_retval == Converters::KILLED && 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                         } else if (conv_retval != Converters::SUCCESS && !runparams.silent) {
898                                 docstring msg = bformat(_("Included file `%1$s' "
899                                                 "was not exported correctly.\n "
900                                                 "LaTeX export is probably incomplete."),
901                                                 included_file.displayName());
902                                 if (!el.empty())
903                                         msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
904                                                 msg, el.begin()->error, el.begin()->description);
905                                 throw ExceptionMessage(ErrorException, _("Error: "), msg);
906                         }
907                 }
908         } else {
909                 // In this case, it's not a LyX file, so we copy the file
910                 // to the temp dir, so that .aux files etc. are not created
911                 // in the original dir. Files included by this file will be
912                 // found via either the environment variable TEXINPUTS, or
913                 // input@path, see ../Buffer.cpp.
914                 unsigned long const checksum_in  = included_file.checksum();
915                 unsigned long const checksum_out = writefile.checksum();
916
917                 if (checksum_in != checksum_out) {
918                         if (!included_file.copyTo(writefile)) {
919                                 // FIXME UNICODE
920                                 LYXERR(Debug::LATEX,
921                                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
922                                                                         "into the temporary directory."),
923                                                          from_utf8(included_file.absFileName()))));
924                                 return;
925                         }
926                 }
927         }
928 }
929
930
931 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
932 {
933         if (rp.inComment)
934                  return docstring();
935
936         // For verbatim and listings, we just include the contents of the file as-is.
937         // In the case of listings, we wrap it in <pre>.
938         bool const listing = isListings(params());
939         if (listing || isVerbatim(params())) {
940                 if (listing)
941                         xs << html::StartTag("pre");
942                 // FIXME: We don't know the encoding of the file, default to UTF-8.
943                 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
944                 if (listing)
945                         xs << html::EndTag("pre");
946                 return docstring();
947         }
948
949         // We don't (yet) know how to Input or Include non-LyX files.
950         // (If we wanted to get really arcane, we could run some tex2html
951         // converter on the included file. But that's just masochistic.)
952         FileName const included_file = includedFileName(buffer(), params());
953         if (!isLyXFileName(included_file.absFileName())) {
954                 if (!rp.silent)
955                         frontend::Alert::warning(_("Unsupported Inclusion"),
956                                          bformat(_("LyX does not know how to include non-LyX files when "
957                                                    "generating HTML output. Offending file:\n%1$s"),
958                                                     ltrim(params()["filename"])));
959                 return docstring();
960         }
961
962         // In the other cases, we will generate the HTML and include it.
963
964         // Check we're not trying to include ourselves.
965         // FIXME RECURSIVE INCLUDE
966         if (buffer().absFileName() == included_file.absFileName()) {
967                 Alert::error(_("Recursive input"),
968                                bformat(_("Attempted to include file %1$s in itself! "
969                                "Ignoring inclusion."), ltrim(params()["filename"])));
970                 return docstring();
971         }
972
973         Buffer const * const ibuf = loadIfNeeded();
974         if (!ibuf)
975                 return docstring();
976
977         // are we generating only some paragraphs, or all of them?
978         bool const all_pars = !rp.dryrun ||
979                         (rp.par_begin == 0 &&
980                          rp.par_end == (int)buffer().text().paragraphs().size());
981
982         OutputParams op = rp;
983         if (all_pars) {
984                 op.par_begin = 0;
985                 op.par_end = 0;
986                 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
987         } else
988                 xs << XHTMLStream::ESCAPE_NONE
989                    << "<!-- Included file: "
990                    << from_utf8(included_file.absFileName())
991                    << XHTMLStream::ESCAPE_NONE
992                          << " -->";
993         return docstring();
994 }
995
996
997 int InsetInclude::plaintext(odocstringstream & os,
998         OutputParams const & op, size_t) const
999 {
1000         // just write the filename if we're making a tooltip or toc entry,
1001         // or are generating this for advanced search
1002         if (op.for_tooltip || op.for_toc || op.for_search) {
1003                 os << '[' << screenLabel() << '\n'
1004                    << ltrim(getParam("filename")) << "\n]";
1005                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1006         }
1007
1008         if (isVerbatim(params()) || isListings(params())) {
1009                 if (op.for_search) {
1010                         os << '[' << screenLabel() << ']';
1011                 }
1012                 else {
1013                         os << '[' << screenLabel() << '\n'
1014                            // FIXME: We don't know the encoding of the file, default to UTF-8.
1015                            << includedFileName(buffer(), params()).fileContents("UTF-8")
1016                            << "\n]";
1017                 }
1018                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1019         }
1020
1021         Buffer const * const ibuf = loadIfNeeded();
1022         if (!ibuf) {
1023                 docstring const str = '[' + screenLabel() + ']';
1024                 os << str;
1025                 return str.size();
1026         }
1027         writePlaintextFile(*ibuf, os, op);
1028         return 0;
1029 }
1030
1031
1032 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
1033 {
1034         string incfile = ltrim(to_utf8(params()["filename"]));
1035
1036         // Do nothing if no file name has been specified
1037         if (incfile.empty())
1038                 return 0;
1039
1040         string const included_file = includedFileName(buffer(), params()).absFileName();
1041
1042         // Check we're not trying to include ourselves.
1043         // FIXME RECURSIVE INCLUDE
1044         // This isn't sufficient, as the inclusion could be downstream.
1045         // But it'll have to do for now.
1046         if (buffer().absFileName() == included_file) {
1047                 Alert::error(_("Recursive input"),
1048                                bformat(_("Attempted to include file %1$s in itself! "
1049                                "Ignoring inclusion."), from_utf8(incfile)));
1050                 return 0;
1051         }
1052
1053         string exppath = incfile;
1054         if (!runparams.export_folder.empty()) {
1055                 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
1056                 FileName(exppath).onlyPath().createPath();
1057         }
1058
1059         // write it to a file (so far the complete file)
1060         string const exportfile = changeExtension(exppath, ".sgml");
1061         DocFileName writefile(changeExtension(included_file, ".sgml"));
1062
1063         Buffer * tmp = loadIfNeeded();
1064         if (tmp) {
1065                 string const mangled = writefile.mangledFileName();
1066                 writefile = makeAbsPath(mangled,
1067                                         buffer().masterBuffer()->temppath());
1068                 if (!runparams.nice)
1069                         incfile = mangled;
1070
1071                 LYXERR(Debug::LATEX, "incfile:" << incfile);
1072                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
1073                 LYXERR(Debug::LATEX, "writefile:" << writefile);
1074
1075                 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
1076         }
1077
1078         runparams.exportdata->addExternalFile("docbook", writefile,
1079                                               exportfile);
1080         runparams.exportdata->addExternalFile("docbook-xml", writefile,
1081                                               exportfile);
1082
1083         if (isVerbatim(params()) || isListings(params())) {
1084                 os << "<inlinegraphic fileref=\""
1085                    << '&' << include_label << ';'
1086                    << "\" format=\"linespecific\">";
1087         } else
1088                 os << '&' << include_label << ';';
1089
1090         return 0;
1091 }
1092
1093
1094 void InsetInclude::validate(LaTeXFeatures & features) const
1095 {
1096         LATTEST(&buffer() == &features.buffer());
1097
1098         string incfile = ltrim(to_utf8(params()["filename"]));
1099         string const included_file =
1100                 includedFileName(buffer(), params()).absFileName();
1101
1102         string writefile;
1103         if (isLyXFileName(included_file))
1104                 writefile = changeExtension(included_file, ".sgml");
1105         else
1106                 writefile = included_file;
1107
1108         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1109                 incfile = DocFileName(writefile).mangledFileName();
1110                 writefile = makeAbsPath(incfile,
1111                                         buffer().masterBuffer()->temppath()).absFileName();
1112         }
1113
1114         features.includeFile(include_label, writefile);
1115
1116         features.useInsetLayout(getLayout());
1117         if (isVerbatim(params()))
1118                 features.require("verbatim");
1119         else if (isListings(params())) {
1120                 if (buffer().params().use_minted) {
1121                         features.require("minted");
1122                         string const opts = to_utf8(params()["lstparams"]);
1123                         InsetListingsParams lstpars(opts);
1124                         if (!lstpars.isFloat() && contains(opts, "caption="))
1125                                 features.require("lyxmintcaption");
1126                 } else
1127                         features.require("listings");
1128         }
1129
1130         // Here we must do the fun stuff...
1131         // Load the file in the include if it needs
1132         // to be loaded:
1133         Buffer * const tmp = loadIfNeeded();
1134         if (tmp) {
1135                 // the file is loaded
1136                 // make sure the buffer isn't us
1137                 // FIXME RECURSIVE INCLUDES
1138                 // This is not sufficient, as recursive includes could be
1139                 // more than a file away. But it will do for now.
1140                 if (tmp && tmp != &buffer()) {
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         }
1154 }
1155
1156
1157 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1158 {
1159         Buffer * child = loadIfNeeded();
1160         if (!child)
1161                 return;
1162         // FIXME RECURSIVE INCLUDE
1163         // This isn't sufficient, as the inclusion could be downstream.
1164         // But it'll have to do for now.
1165         if (child == &buffer())
1166                 return;
1167         child->collectBibKeys(checkedFiles);
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);
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(0);
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 = getChildBuffer();
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                 // Update the child's tocBackend. The outliner uses the master's, but
1337                 // the navigation menu uses the child's.
1338                 childbuffer->tocBackend().update(output_active, utype);
1339                 // Include Tocs from children
1340                 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1341                                               backend);
1342                 //Copy missing outliner names (though the user has been warned against
1343                 //having different document class and module selection between master
1344                 //and child).
1345                 for (pair<string, docstring> const & name
1346                              : childbuffer->params().documentClass().outlinerNames())
1347                         backend.addName(name.first, translateIfPossible(name.second));
1348         }
1349 }
1350
1351
1352 void InsetInclude::updateCommand()
1353 {
1354         if (!label_)
1355                 return;
1356
1357         docstring old_label = label_->getParam("name");
1358         label_->updateLabel(old_label);
1359         // the label might have been adapted (duplicate)
1360         docstring new_label = label_->getParam("name");
1361         if (old_label == new_label)
1362                 return;
1363
1364         // update listings parameters...
1365         InsetCommandParams p(INCLUDE_CODE);
1366         p = params();
1367         InsetListingsParams par(to_utf8(params()["lstparams"]));
1368         par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1369         p["lstparams"] = from_utf8(par.params());
1370         setParams(p);
1371 }
1372
1373
1374 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1375 {
1376         file_exist_ = includedFileExist();
1377
1378         button_.update(screenLabel(), true, false);
1379
1380         Buffer const * const childbuffer = getChildBuffer();
1381         if (childbuffer) {
1382                 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1383                 return;
1384         }
1385         if (!isListings(params()))
1386                 return;
1387
1388         if (label_)
1389                 label_->updateBuffer(it, utype);
1390
1391         InsetListingsParams const par(to_utf8(params()["lstparams"]));
1392         if (par.getParamValue("caption").empty()) {
1393                 listings_label_ = buffer().B_("Program Listing");
1394                 return;
1395         }
1396         Buffer const & master = *buffer().masterBuffer();
1397         Counters & counters = master.params().documentClass().counters();
1398         docstring const cnt = from_ascii("listing");
1399         listings_label_ = master.B_("Program Listing");
1400         if (counters.hasCounter(cnt)) {
1401                 counters.step(cnt, utype);
1402                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1403         }
1404 }
1405
1406
1407 bool InsetInclude::includedFileExist() const
1408 {
1409         // check whether the included file exist
1410         string incFileName = ltrim(to_utf8(params()["filename"]));
1411         FileName fn =
1412                 support::makeAbsPath(incFileName,
1413                                      support::onlyPath(buffer().absFileName()));
1414         return fn.exists();
1415 }
1416
1417 } // namespace lyx