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