2 * \file InsetInclude.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Richard Heck (conversion to InsetCommand)
9 * Full author contact details are available in file CREDITS.
14 #include "InsetInclude.h"
17 #include "buffer_funcs.h"
18 #include "BufferList.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "Converter.h"
23 #include "DispatchResult.h"
25 #include "ErrorList.h"
28 #include "FuncRequest.h"
29 #include "FuncStatus.h"
30 #include "LaTeXFeatures.h"
31 #include "LayoutFile.h"
32 #include "LayoutModuleList.h"
35 #include "MetricsInfo.h"
36 #include "output_plaintext.h"
37 #include "output_xhtml.h"
38 #include "OutputParams.h"
39 #include "TextClass.h"
40 #include "TocBackend.h"
42 #include "frontends/alert.h"
43 #include "frontends/Painter.h"
45 #include "graphics/PreviewImage.h"
46 #include "graphics/PreviewLoader.h"
48 #include "insets/InsetLabel.h"
49 #include "insets/InsetListingsParams.h"
50 #include "insets/RenderPreview.h"
52 #include "mathed/MacroTable.h"
54 #include "support/convert.h"
55 #include "support/debug.h"
56 #include "support/docstream.h"
57 #include "support/FileNameList.h"
58 #include "support/filetools.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/lstrings.h" // contains
62 #include "support/lyxalgo.h"
63 #include "support/mutex.h"
65 #include "support/bind.h"
68 using namespace lyx::support;
72 namespace Alert = frontend::Alert;
77 docstring const uniqueID()
79 static unsigned int seed = 1000;
81 Mutex::Locker lock(&mutex);
82 return "file" + convert<docstring>(++seed);
86 /// the type of inclusion
88 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
92 Types type(string const & s)
96 if (s == "verbatiminput")
98 if (s == "verbatiminput*")
100 if (s == "lstinputlisting")
108 Types type(InsetCommandParams const & params)
110 return type(params.getCmdName());
114 bool isListings(InsetCommandParams const & params)
116 return type(params) == LISTINGS;
120 bool isVerbatim(InsetCommandParams const & params)
122 Types const t = type(params);
123 return t == VERB || t == VERBAST;
127 bool isInputOrInclude(InsetCommandParams const & params)
129 Types const t = type(params);
130 return t == INPUT || t == INCLUDE;
134 FileName const masterFileName(Buffer const & buffer)
136 return buffer.masterBuffer()->fileName();
140 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
143 string const parentFileName(Buffer const & buffer)
145 return buffer.absFileName();
149 FileName const includedFileName(Buffer const & buffer,
150 InsetCommandParams const & params)
152 return makeAbsPath(to_utf8(params["filename"]),
153 onlyPath(parentFileName(buffer)));
157 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
159 if (label_str.empty())
161 InsetCommandParams icp(LABEL_CODE);
162 icp["name"] = label_str;
163 return new InsetLabel(buf, icp);
169 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
170 : InsetCommand(buf, p), include_label(uniqueID()),
171 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
172 set_label_(false), label_(0), child_buffer_(0)
174 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
176 if (isListings(params())) {
177 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
178 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
179 } else if (isInputOrInclude(params()) && buf)
184 InsetInclude::InsetInclude(InsetInclude const & other)
185 : InsetCommand(other), include_label(other.include_label),
186 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
187 set_label_(false), label_(0), child_buffer_(0)
189 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
192 label_ = new InsetLabel(*other.label_);
196 InsetInclude::~InsetInclude()
198 if (isBufferLoaded())
199 buffer().invalidateBibfileCache();
204 void InsetInclude::setBuffer(Buffer & buffer)
206 InsetCommand::setBuffer(buffer);
208 label_->setBuffer(buffer);
212 void InsetInclude::setChildBuffer(Buffer * buffer)
214 child_buffer_ = buffer;
218 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
221 // This is only correct for the case of listings, but it'll do for now.
222 // In the other cases, this second parameter should just be empty.
223 static ParamInfo param_info_;
224 if (param_info_.empty()) {
225 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
226 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
232 bool InsetInclude::isCompatibleCommand(string const & s)
234 return type(s) != NONE;
238 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
240 switch (cmd.action()) {
242 case LFUN_INSET_EDIT: {
243 editIncluded(to_utf8(params()["filename"]));
247 case LFUN_INSET_MODIFY: {
248 // It should be OK just to invalidate the cache in setParams()
250 // child_buffer_ = 0;
251 InsetCommandParams p(INCLUDE_CODE);
252 if (cmd.getArg(0) == "changetype") {
254 InsetCommand::doDispatch(cur, cmd);
257 InsetCommand::string2params(to_utf8(cmd.argument()), p);
258 if (!p.getCmdName().empty()) {
260 InsetListingsParams new_params(to_utf8(p["lstparams"]));
261 docstring const new_label =
262 from_utf8(new_params.getParamValue("label"));
264 if (new_label.empty()) {
270 old_label = label_->getParam("name");
272 label_ = createLabel(buffer_, new_label);
273 label_->setBuffer(buffer());
276 if (new_label != old_label) {
277 label_->updateLabelAndRefs(new_label, &cur);
278 // the label might have been adapted (duplicate)
279 if (new_label != label_->getParam("name")) {
280 new_params.addParam("label", "{" +
281 to_utf8(label_->getParam("name")) + "}", true);
282 p["lstparams"] = from_utf8(new_params.params());
289 cur.forceBufferUpdate();
291 cur.noScreenUpdate();
295 //pass everything else up the chain
297 InsetCommand::doDispatch(cur, cmd);
303 void InsetInclude::editIncluded(string const & file)
305 string const ext = support::getExtension(file);
307 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
310 // tex file or other text file in verbatim mode
311 formats.edit(buffer(),
312 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
317 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
318 FuncStatus & flag) const
320 switch (cmd.action()) {
322 case LFUN_INSET_EDIT:
323 flag.setEnabled(true);
326 case LFUN_INSET_MODIFY:
327 if (cmd.getArg(0) == "changetype")
328 return InsetCommand::getStatus(cur, cmd, flag);
330 flag.setEnabled(true);
334 return InsetCommand::getStatus(cur, cmd, flag);
339 void InsetInclude::setParams(InsetCommandParams const & p)
341 // invalidate the cache
344 InsetCommand::setParams(p);
347 if (preview_->monitoring())
348 preview_->stopMonitoring();
350 if (type(params()) == INPUT)
351 add_preview(*preview_, *this, buffer());
353 buffer().invalidateBibfileCache();
357 bool InsetInclude::isChildIncluded() const
359 std::list<std::string> includeonlys =
360 buffer().params().getIncludedChildren();
361 if (includeonlys.empty())
363 return (std::find(includeonlys.begin(),
365 to_utf8(params()["filename"])) != includeonlys.end());
369 docstring InsetInclude::screenLabel() const
373 switch (type(params())) {
375 temp = buffer().B_("Input");
378 temp = buffer().B_("Verbatim Input");
381 temp = buffer().B_("Verbatim Input*");
384 if (isChildIncluded())
385 temp = buffer().B_("Include");
387 temp += buffer().B_("Include (excluded)");
390 temp = listings_label_;
393 LASSERT(false, temp = buffer().B_("Unknown"));
399 if (params()["filename"].empty())
402 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
408 Buffer * InsetInclude::getChildBuffer() const
410 Buffer * childBuffer = loadIfNeeded();
412 // FIXME RECURSIVE INCLUDE
413 // This isn't sufficient, as the inclusion could be downstream.
414 // But it'll have to do for now.
415 return (childBuffer == &buffer()) ? 0 : childBuffer;
419 Buffer * InsetInclude::loadIfNeeded() const
421 // This is for background export and preview. We don't even want to
422 // try to load the cloned child document again.
423 if (buffer().isClone())
424 return child_buffer_;
426 // Don't try to load it again if we failed before.
427 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
430 FileName const included_file = includedFileName(buffer(), params());
431 // Use cached Buffer if possible.
432 if (child_buffer_ != 0) {
433 if (theBufferList().isLoaded(child_buffer_)
434 // additional sanity check: make sure the Buffer really is
435 // associated with the file we want.
436 && child_buffer_ == theBufferList().getBuffer(included_file))
437 return child_buffer_;
438 // Buffer vanished, so invalidate cache and try to reload.
442 if (!isLyXFileName(included_file.absFileName()))
445 Buffer * child = theBufferList().getBuffer(included_file);
447 // the readonly flag can/will be wrong, not anymore I think.
448 if (!included_file.exists())
451 child = theBufferList().newBuffer(included_file.absFileName());
453 // Buffer creation is not possible.
456 // Set parent before loading, such that macros can be tracked
457 child->setParent(&buffer());
459 if (child->loadLyXFile() != Buffer::ReadSuccess) {
460 failedtoload_ = true;
462 //close the buffer we just opened
463 theBufferList().release(child);
467 if (!child->errorList("Parse").empty()) {
468 // FIXME: Do something.
471 // The file was already loaded, so, simply
472 // inform parent buffer about local macros.
473 Buffer const * parent = &buffer();
474 child->setParent(parent);
476 child->listMacroNames(macros);
477 MacroNameSet::const_iterator cit = macros.begin();
478 MacroNameSet::const_iterator end = macros.end();
479 for (; cit != end; ++cit)
480 parent->usermacros.insert(*cit);
483 // Cache the child buffer.
484 child_buffer_ = child;
489 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
491 string incfile = to_utf8(params()["filename"]);
493 // Do nothing if no file name has been specified
497 FileName const included_file = includedFileName(buffer(), params());
499 // Check we're not trying to include ourselves.
500 // FIXME RECURSIVE INCLUDE
501 // This isn't sufficient, as the inclusion could be downstream.
502 // But it'll have to do for now.
503 if (isInputOrInclude(params()) &&
504 buffer().absFileName() == included_file.absFileName())
506 Alert::error(_("Recursive input"),
507 bformat(_("Attempted to include file %1$s in itself! "
508 "Ignoring inclusion."), from_utf8(incfile)));
512 Buffer const * const masterBuffer = buffer().masterBuffer();
514 // if incfile is relative, make it relative to the master
516 if (!FileName::isAbsolute(incfile)) {
518 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
519 from_utf8(masterBuffer->filePath())));
522 string exppath = incfile;
523 if (!runparams.export_folder.empty()) {
524 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
525 FileName(exppath).onlyPath().createPath();
528 // write it to a file (so far the complete file)
532 if (type(params()) == LISTINGS) {
533 exportfile = exppath;
534 mangled = DocFileName(included_file).mangledFileName();
536 exportfile = changeExtension(exppath, ".tex");
537 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
543 else if (!runparams.silent)
544 ; // no warning wanted
545 else if (!isValidLaTeXFileName(incfile)) {
546 frontend::Alert::warning(_("Invalid filename"),
547 _("The following filename will cause troubles "
548 "when running the exported file through LaTeX: ") +
550 } else if (!isValidDVIFileName(incfile)) {
551 frontend::Alert::warning(_("Problematic filename for DVI"),
552 _("The following filename can cause troubles "
553 "when running the exported file through LaTeX "
554 "and opening the resulting DVI: ") +
555 from_utf8(incfile), true);
558 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
560 LYXERR(Debug::LATEX, "incfile:" << incfile);
561 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
562 LYXERR(Debug::LATEX, "writefile:" << writefile);
564 string const tex_format = flavor2format(runparams.flavor);
566 switch (type(params())) {
569 incfile = latex_path(incfile);
571 os << '\\' << from_ascii(params().getCmdName()) << '{'
572 << from_utf8(incfile) << '}';
576 runparams.exportdata->addExternalFile(tex_format, writefile,
579 // \input wants file with extension (default is .tex)
580 if (!isLyXFileName(included_file.absFileName())) {
581 incfile = latex_path(incfile);
583 os << '\\' << from_ascii(params().getCmdName())
584 << '{' << from_utf8(incfile) << '}';
586 incfile = changeExtension(incfile, ".tex");
587 incfile = latex_path(incfile);
589 os << '\\' << from_ascii(params().getCmdName())
590 << '{' << from_utf8(incfile) << '}';
595 runparams.exportdata->addExternalFile(tex_format, writefile,
597 os << '\\' << from_ascii(params().getCmdName());
598 string const opt = to_utf8(params()["lstparams"]);
599 // opt is set in QInclude dialog and should have passed validation.
600 InsetListingsParams params(opt);
601 if (!params.params().empty())
602 os << "[" << from_utf8(params.params()) << "]";
603 os << '{' << from_utf8(incfile) << '}';
607 runparams.exportdata->addExternalFile(tex_format, writefile,
610 // \include don't want extension and demands that the
611 // file really have .tex
612 incfile = changeExtension(incfile, string());
613 incfile = latex_path(incfile);
615 os << '\\' << from_ascii(params().getCmdName()) << '{'
616 << from_utf8(incfile) << '}';
623 if (runparams.inComment || runparams.dryrun)
624 // Don't try to load or copy the file if we're
625 // in a comment or doing a dryrun
628 if (isInputOrInclude(params()) &&
629 isLyXFileName(included_file.absFileName())) {
630 // if it's a LyX file and we're inputting or including,
631 // try to load it so we can write the associated latex
633 Buffer * tmp = loadIfNeeded();
635 if (!runparams.silent) {
636 docstring text = bformat(_("Could not load included "
638 "Please, check whether it actually exists."),
639 included_file.displayName());
640 Alert::warning(_("Missing included file"), text);
645 if (!runparams.silent) {
646 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
648 docstring text = bformat(_("Included file `%1$s'\n"
649 "has textclass `%2$s'\n"
650 "while parent file has textclass `%3$s'."),
651 included_file.displayName(),
652 from_utf8(tmp->params().documentClass().name()),
653 from_utf8(masterBuffer->params().documentClass().name()));
654 Alert::warning(_("Different textclasses"), text, true);
657 // Make sure modules used in child are all included in master
658 // FIXME It might be worth loading the children's modules into the master
659 // over in BufferParams rather than doing this check.
660 LayoutModuleList const masterModules = masterBuffer->params().getModules();
661 LayoutModuleList const childModules = tmp->params().getModules();
662 LayoutModuleList::const_iterator it = childModules.begin();
663 LayoutModuleList::const_iterator end = childModules.end();
664 for (; it != end; ++it) {
665 string const module = *it;
666 LayoutModuleList::const_iterator found =
667 find(masterModules.begin(), masterModules.end(), module);
668 if (found == masterModules.end()) {
669 docstring text = bformat(_("Included file `%1$s'\n"
670 "uses module `%2$s'\n"
671 "which is not used in parent file."),
672 included_file.displayName(), from_utf8(module));
673 Alert::warning(_("Module not found"), text);
678 tmp->markDepClean(masterBuffer->temppath());
680 // Don't assume the child's format is latex
681 string const inc_format = tmp->params().bufferFormat();
682 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
683 formats.extension(inc_format)));
685 // FIXME: handle non existing files
686 // The included file might be written in a different encoding
688 Encoding const * const oldEnc = runparams.encoding;
689 Language const * const oldLang = runparams.master_language;
690 // If the master has full unicode flavor (XeTeX, LuaTeX),
691 // the children must be encoded in plain utf8!
692 runparams.encoding = runparams.isFullUnicode() ?
693 encodings.fromLyXName("utf8-plain")
694 : &tmp->params().encoding();
695 runparams.master_language = buffer().params().language;
696 runparams.par_begin = 0;
697 runparams.par_end = tmp->paragraphs().size();
698 runparams.is_child = true;
699 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
700 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
701 if (!runparams.silent) {
702 docstring msg = bformat(_("Included file `%1$s' "
703 "was not exported correctly.\nWarning: "
704 "LaTeX export is probably incomplete."),
705 included_file.displayName());
706 ErrorList const & el = tmp->errorList("Export");
708 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
709 msg, el.begin()->error,
710 el.begin()->description);
711 Alert::warning(_("Export failure"), msg);
714 runparams.encoding = oldEnc;
715 runparams.master_language = oldLang;
716 runparams.is_child = false;
718 // If needed, use converters to produce a latex file from the child
719 if (tmpwritefile != writefile) {
722 theConverters().convert(tmp, tmpwritefile, writefile,
724 inc_format, tex_format, el);
726 if (!success && !runparams.silent) {
727 docstring msg = bformat(_("Included file `%1$s' "
728 "was not exported correctly.\nWarning: "
729 "LaTeX export is probably incomplete."),
730 included_file.displayName());
732 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
733 msg, el.begin()->error,
734 el.begin()->description);
735 Alert::warning(_("Export failure"), msg);
739 // In this case, it's not a LyX file, so we copy the file
740 // to the temp dir, so that .aux files etc. are not created
741 // in the original dir. Files included by this file will be
742 // found via either the environment variable TEXINPUTS, or
743 // input@path, see ../Buffer.cpp.
744 unsigned long const checksum_in = included_file.checksum();
745 unsigned long const checksum_out = writefile.checksum();
747 if (checksum_in != checksum_out) {
748 if (!included_file.copyTo(writefile)) {
751 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
752 "into the temporary directory."),
753 from_utf8(included_file.absFileName()))));
761 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
766 // For verbatim and listings, we just include the contents of the file as-is.
767 // In the case of listings, we wrap it in <pre>.
768 bool const listing = isListings(params());
769 if (listing || isVerbatim(params())) {
771 xs << html::StartTag("pre");
772 // FIXME: We don't know the encoding of the file, default to UTF-8.
773 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
775 xs << html::EndTag("pre");
779 // We don't (yet) know how to Input or Include non-LyX files.
780 // (If we wanted to get really arcane, we could run some tex2html
781 // converter on the included file. But that's just masochistic.)
782 FileName const included_file = includedFileName(buffer(), params());
783 if (!isLyXFileName(included_file.absFileName())) {
785 frontend::Alert::warning(_("Unsupported Inclusion"),
786 bformat(_("LyX does not know how to include non-LyX files when "
787 "generating HTML output. Offending file:\n%1$s"),
788 params()["filename"]));
792 // In the other cases, we will generate the HTML and include it.
794 // Check we're not trying to include ourselves.
795 // FIXME RECURSIVE INCLUDE
796 if (buffer().absFileName() == included_file.absFileName()) {
797 Alert::error(_("Recursive input"),
798 bformat(_("Attempted to include file %1$s in itself! "
799 "Ignoring inclusion."), params()["filename"]));
803 Buffer const * const ibuf = loadIfNeeded();
807 // are we generating only some paragraphs, or all of them?
808 bool const all_pars = !rp.dryrun ||
809 (rp.par_begin == 0 &&
810 rp.par_end == (int)buffer().text().paragraphs().size());
812 OutputParams op = rp;
816 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
818 xs << XHTMLStream::ESCAPE_NONE
819 << "<!-- Included file: "
820 << from_utf8(included_file.absFileName())
821 << XHTMLStream::ESCAPE_NONE
827 int InsetInclude::plaintext(odocstringstream & os,
828 OutputParams const & op, size_t) const
830 // just write the filename if we're making a tooltip or toc entry,
831 // or are generating this for advanced search
832 if (op.for_tooltip || op.for_toc || op.for_search) {
833 os << '[' << screenLabel() << '\n'
834 << getParam("filename") << "\n]";
835 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
838 if (isVerbatim(params()) || isListings(params())) {
839 os << '[' << screenLabel() << '\n'
840 // FIXME: We don't know the encoding of the file, default to UTF-8.
841 << includedFileName(buffer(), params()).fileContents("UTF-8")
843 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
846 Buffer const * const ibuf = loadIfNeeded();
848 docstring const str = '[' + screenLabel() + ']';
852 writePlaintextFile(*ibuf, os, op);
857 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
859 string incfile = to_utf8(params()["filename"]);
861 // Do nothing if no file name has been specified
865 string const included_file = includedFileName(buffer(), params()).absFileName();
867 // Check we're not trying to include ourselves.
868 // FIXME RECURSIVE INCLUDE
869 // This isn't sufficient, as the inclusion could be downstream.
870 // But it'll have to do for now.
871 if (buffer().absFileName() == included_file) {
872 Alert::error(_("Recursive input"),
873 bformat(_("Attempted to include file %1$s in itself! "
874 "Ignoring inclusion."), from_utf8(incfile)));
878 string exppath = incfile;
879 if (!runparams.export_folder.empty()) {
880 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
881 FileName(exppath).onlyPath().createPath();
884 // write it to a file (so far the complete file)
885 string const exportfile = changeExtension(exppath, ".sgml");
886 DocFileName writefile(changeExtension(included_file, ".sgml"));
888 Buffer * tmp = loadIfNeeded();
890 string const mangled = writefile.mangledFileName();
891 writefile = makeAbsPath(mangled,
892 buffer().masterBuffer()->temppath());
896 LYXERR(Debug::LATEX, "incfile:" << incfile);
897 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
898 LYXERR(Debug::LATEX, "writefile:" << writefile);
900 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
903 runparams.exportdata->addExternalFile("docbook", writefile,
905 runparams.exportdata->addExternalFile("docbook-xml", writefile,
908 if (isVerbatim(params()) || isListings(params())) {
909 os << "<inlinegraphic fileref=\""
910 << '&' << include_label << ';'
911 << "\" format=\"linespecific\">";
913 os << '&' << include_label << ';';
919 void InsetInclude::validate(LaTeXFeatures & features) const
921 LATTEST(&buffer() == &features.buffer());
923 string incfile = to_utf8(params()["filename"]);
924 string const included_file =
925 includedFileName(buffer(), params()).absFileName();
928 if (isLyXFileName(included_file))
929 writefile = changeExtension(included_file, ".sgml");
931 writefile = included_file;
933 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
934 incfile = DocFileName(writefile).mangledFileName();
935 writefile = makeAbsPath(incfile,
936 buffer().masterBuffer()->temppath()).absFileName();
939 features.includeFile(include_label, writefile);
941 features.useInsetLayout(getLayout());
942 if (isVerbatim(params()))
943 features.require("verbatim");
944 else if (isListings(params()))
945 features.require("listings");
947 // Here we must do the fun stuff...
948 // Load the file in the include if it needs
950 Buffer * const tmp = loadIfNeeded();
952 // the file is loaded
953 // make sure the buffer isn't us
954 // FIXME RECURSIVE INCLUDES
955 // This is not sufficient, as recursive includes could be
956 // more than a file away. But it will do for now.
957 if (tmp && tmp != &buffer()) {
958 // We must temporarily change features.buffer,
959 // otherwise it would always be the master buffer,
960 // and nested includes would not work.
961 features.setBuffer(*tmp);
962 // Maybe this is already a child
963 bool const is_child =
964 features.runparams().is_child;
965 features.runparams().is_child = true;
966 tmp->validate(features);
967 features.runparams().is_child = is_child;
968 features.setBuffer(buffer());
974 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/) const
976 Buffer * child = loadIfNeeded();
979 // FIXME RECURSIVE INCLUDE
980 // This isn't sufficient, as the inclusion could be downstream.
981 // But it'll have to do for now.
982 if (child == &buffer())
984 child->collectBibKeys();
988 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
992 bool use_preview = false;
993 if (RenderPreview::previewText()) {
994 graphics::PreviewImage const * pimage =
995 preview_->getPreviewImage(mi.base.bv->buffer());
996 use_preview = pimage && pimage->image();
1000 preview_->metrics(mi, dim);
1004 button_.update(screenLabel(), true);
1006 button_.metrics(mi, dim);
1009 Box b(0, dim.wid, -dim.asc, dim.des);
1014 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1016 LBUFERR(pi.base.bv);
1018 bool use_preview = false;
1019 if (RenderPreview::previewText()) {
1020 graphics::PreviewImage const * pimage =
1021 preview_->getPreviewImage(pi.base.bv->buffer());
1022 use_preview = pimage && pimage->image();
1026 preview_->draw(pi, x, y);
1028 button_.draw(pi, x, y);
1032 string InsetInclude::contextMenuName() const
1034 return "context-include";
1038 Inset::DisplayType InsetInclude::display() const
1040 return type(params()) == INPUT ? Inline : AlignCenter;
1044 docstring InsetInclude::layoutName() const
1046 if (isListings(params()))
1047 return from_ascii("IncludeListings");
1048 return InsetCommand::layoutName();
1056 void InsetInclude::fileChanged() const
1058 Buffer const * const buffer = updateFrontend();
1062 preview_->removePreview(*buffer);
1063 add_preview(*preview_.get(), *this, *buffer);
1064 preview_->startLoading(*buffer);
1070 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1072 FileName const included_file = includedFileName(buffer, params);
1074 return type(params) == INPUT && params.preview() &&
1075 included_file.isReadableFile();
1079 docstring latexString(InsetInclude const & inset)
1082 odocstringstream ods;
1083 otexstream os(ods, texrow);
1084 // We don't need to set runparams.encoding since this will be done
1085 // by latex() anyway.
1086 OutputParams runparams(0);
1087 runparams.flavor = OutputParams::LATEX;
1088 inset.latex(os, runparams);
1094 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1095 Buffer const & buffer)
1097 InsetCommandParams const & params = inset.params();
1098 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1099 renderer.setAbsFile(includedFileName(buffer, params));
1100 docstring const snippet = latexString(inset);
1101 renderer.addPreview(snippet, buffer);
1108 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1109 graphics::PreviewLoader & ploader) const
1111 Buffer const & buffer = ploader.buffer();
1112 if (!preview_wanted(params(), buffer))
1114 preview_->setAbsFile(includedFileName(buffer, params()));
1115 docstring const snippet = latexString(*this);
1116 preview_->addPreview(snippet, ploader);
1120 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active) const
1122 TocBackend & backend = buffer().tocBackend();
1124 if (isListings(params())) {
1126 label_->addToToc(cpit, output_active);
1128 InsetListingsParams p(to_utf8(params()["lstparams"]));
1129 string caption = p.getParamValue("caption");
1130 if (caption.empty())
1132 Toc & toc = backend.toc("listing");
1133 docstring str = convert<docstring>(toc.size() + 1)
1134 + ". " + from_utf8(caption);
1135 DocIterator pit = cpit;
1136 toc.push_back(TocItem(pit, 0, str, output_active));
1139 Buffer const * const childbuffer = getChildBuffer();
1143 Toc & toc = backend.toc("child");
1144 docstring str = childbuffer->fileName().displayName();
1145 toc.push_back(TocItem(cpit, 0, str, output_active));
1147 TocList & toclist = backend.tocs();
1148 childbuffer->tocBackend().update(output_active);
1149 TocList const & childtoclist = childbuffer->tocBackend().tocs();
1150 TocList::const_iterator it = childtoclist.begin();
1151 TocList::const_iterator const end = childtoclist.end();
1152 for(; it != end; ++it)
1153 toclist[it->first].insert(toclist[it->first].end(),
1154 it->second.begin(), it->second.end());
1158 void InsetInclude::updateCommand()
1163 docstring old_label = label_->getParam("name");
1164 label_->updateLabel(old_label);
1165 // the label might have been adapted (duplicate)
1166 docstring new_label = label_->getParam("name");
1167 if (old_label == new_label)
1170 // update listings parameters...
1171 InsetCommandParams p(INCLUDE_CODE);
1173 InsetListingsParams par(to_utf8(params()["lstparams"]));
1174 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1175 p["lstparams"] = from_utf8(par.params());
1180 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1182 button_.update(screenLabel(), true);
1184 Buffer const * const childbuffer = getChildBuffer();
1186 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1189 if (!isListings(params()))
1193 label_->updateBuffer(it, utype);
1195 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1196 if (par.getParamValue("caption").empty()) {
1197 listings_label_ = buffer().B_("Program Listing");
1200 Buffer const & master = *buffer().masterBuffer();
1201 Counters & counters = master.params().documentClass().counters();
1202 docstring const cnt = from_ascii("listing");
1203 listings_label_ = master.B_("Program Listing");
1204 if (counters.hasCounter(cnt)) {
1205 counters.step(cnt, utype);
1206 listings_label_ += " " + convert<docstring>(counters.value(cnt));