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