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