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