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