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