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"
22 #include "DispatchResult.h"
23 #include "ErrorList.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "LaTeXFeatures.h"
29 #include "LayoutFile.h"
34 #include "MetricsInfo.h"
35 #include "OutputParams.h"
36 #include "TextClass.h"
37 #include "TocBackend.h"
39 #include "frontends/alert.h"
40 #include "frontends/Painter.h"
42 #include "graphics/PreviewImage.h"
43 #include "graphics/PreviewLoader.h"
45 #include "insets/InsetLabel.h"
46 #include "insets/InsetListingsParams.h"
47 #include "insets/RenderPreview.h"
49 #include "support/convert.h"
50 #include "support/debug.h"
51 #include "support/docstream.h"
52 #include "support/FileNameList.h"
53 #include "support/filetools.h"
54 #include "support/gettext.h"
55 #include "support/lassert.h"
56 #include "support/lstrings.h" // contains
57 #include "support/lyxalgo.h"
59 #include <boost/bind.hpp>
62 using namespace lyx::support;
66 namespace Alert = frontend::Alert;
71 docstring const uniqueID()
73 static unsigned int seed = 1000;
74 return "file" + convert<docstring>(++seed);
78 /// the type of inclusion
80 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
84 Types type(string const & s)
88 if (s == "verbatiminput")
90 if (s == "verbatiminput*")
92 if (s == "lstinputlisting")
100 Types type(InsetCommandParams const & params)
102 return type(params.getCmdName());
106 bool isListings(InsetCommandParams const & params)
108 return type(params) == LISTINGS;
112 bool isVerbatim(InsetCommandParams const & params)
114 Types const t = type(params);
115 return t == VERB || t == VERBAST;
119 bool isInputOrInclude(InsetCommandParams const & params)
121 Types const t = type(params);
122 return t == INPUT || t == INCLUDE;
126 FileName const masterFileName(Buffer const & buffer)
128 return buffer.masterBuffer()->fileName();
132 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
135 string const parentFilename(Buffer const & buffer)
137 return buffer.absFileName();
141 FileName const includedFilename(Buffer const & buffer,
142 InsetCommandParams const & params)
144 return makeAbsPath(to_utf8(params["filename"]),
145 onlyPath(parentFilename(buffer)));
149 InsetLabel * createLabel(docstring const & label_str)
151 if (label_str.empty())
153 InsetCommandParams icp(LABEL_CODE);
154 icp["name"] = label_str;
155 return new InsetLabel(icp);
161 InsetInclude::InsetInclude(InsetCommandParams const & p)
162 : InsetCommand(p, "include"), include_label(uniqueID()),
163 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
164 set_label_(false), label_(0)
166 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
168 if (isListings(params())) {
169 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
170 label_ = createLabel(from_utf8(listing_params.getParamValue("label")));
175 InsetInclude::InsetInclude(InsetInclude const & other)
176 : InsetCommand(other), include_label(other.include_label),
177 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
178 set_label_(false), label_(0)
180 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
183 label_ = new InsetLabel(*other.label_);
187 InsetInclude::~InsetInclude()
193 void InsetInclude::setBuffer(Buffer & buffer)
195 InsetCommand::setBuffer(buffer);
197 label_->setBuffer(buffer);
201 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
204 // This is only correct for the case of listings, but it'll do for now.
205 // In the other cases, this second parameter should just be empty.
206 static ParamInfo param_info_;
207 if (param_info_.empty()) {
208 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
209 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
215 bool InsetInclude::isCompatibleCommand(string const & s)
217 return type(s) != NONE;
221 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
223 LASSERT(cur.buffer() == &buffer(), return);
224 switch (cmd.action) {
226 case LFUN_INSET_EDIT: {
227 editIncluded(to_utf8(params()["filename"]));
231 case LFUN_INSET_MODIFY: {
232 InsetCommandParams p(INCLUDE_CODE);
233 if (cmd.getArg(0) == "changetype") {
234 InsetCommand::doDispatch(cur, cmd);
237 InsetCommand::string2params("include", to_utf8(cmd.argument()), p);
238 if (!p.getCmdName().empty()) {
240 InsetListingsParams new_params(to_utf8(p["lstparams"]));
241 docstring const new_label =
242 from_utf8(new_params.getParamValue("label"));
245 old_label = label_->getParam("name");
246 if (new_label.empty())
248 else if (label_ && old_label != new_label) {
249 label_->updateCommand(new_label);
250 // the label might have been adapted (duplicate)
251 if (new_label != label_->getParam("name")) {
252 new_params.addParam("label",
253 "{" + to_utf8(label_->getParam("name")) + "}");
254 p["lstparams"] = from_utf8(new_params.params());
256 } else if (old_label != new_label) {
257 label_ = createLabel(new_label);
258 label_->setBuffer(buffer());
268 //pass everything else up the chain
270 InsetCommand::doDispatch(cur, cmd);
276 void InsetInclude::editIncluded(string const & file)
278 string const ext = support::getExtension(file);
280 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
283 // tex file or other text file in verbatim mode
284 formats.edit(buffer(),
285 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
290 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
291 FuncStatus & flag) const
293 switch (cmd.action) {
295 case LFUN_INSET_EDIT:
296 case LFUN_INSET_MODIFY:
297 flag.setEnabled(true);
301 return InsetCommand::getStatus(cur, cmd, flag);
306 void InsetInclude::setParams(InsetCommandParams const & p)
308 InsetCommand::setParams(p);
311 if (preview_->monitoring())
312 preview_->stopMonitoring();
314 if (type(params()) == INPUT)
315 add_preview(*preview_, *this, buffer());
317 buffer().updateBibfilesCache();
321 docstring InsetInclude::screenLabel() const
325 switch (type(params())) {
327 temp = buffer().B_("Input");
330 temp = buffer().B_("Verbatim Input");
333 temp = buffer().B_("Verbatim Input*");
336 temp = buffer().B_("Include");
339 temp = listings_label_;
342 LASSERT(false, /**/);
347 if (params()["filename"].empty())
350 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
356 Buffer * InsetInclude::getChildBuffer(Buffer const & buffer) const
358 InsetCommandParams const & p = params();
359 if (isVerbatim(p) || isListings(p))
362 string const included_file = includedFilename(buffer, p).absFilename();
363 if (!isLyXFilename(included_file))
366 Buffer * childBuffer = loadIfNeeded(buffer);
368 // FIXME: recursive includes
369 return (childBuffer == &buffer) ? 0 : childBuffer;
373 Buffer * InsetInclude::loadIfNeeded(Buffer const & parent) const
375 InsetCommandParams const & p = params();
379 if (isVerbatim(p) || isListings(p))
382 string const parent_filename = parent.absFileName();
383 FileName const included_file = makeAbsPath(to_utf8(p["filename"]),
384 onlyPath(parent_filename));
386 if (!isLyXFilename(included_file.absFilename()))
389 Buffer * child = theBufferList().getBuffer(included_file);
391 // the readonly flag can/will be wrong, not anymore I think.
392 if (!included_file.exists())
395 child = theBufferList().newBuffer(included_file.absFilename());
397 // Buffer creation is not possible.
400 if (!child->loadLyXFile(included_file)) {
401 failedtoload_ = true;
402 //close the buffer we just opened
403 theBufferList().release(child);
407 if (!child->errorList("Parse").empty()) {
408 // FIXME: Do something.
411 child->setParent(&parent);
416 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
418 string incfile = to_utf8(params()["filename"]);
420 // Do nothing if no file name has been specified
424 FileName const included_file = includedFilename(buffer(), params());
426 // Check we're not trying to include ourselves.
427 // FIXME RECURSIVE INCLUDE
428 // This isn't sufficient, as the inclusion could be downstream.
429 // But it'll have to do for now.
430 if (isInputOrInclude(params()) &&
431 buffer().absFileName() == included_file.absFilename())
433 Alert::error(_("Recursive input"),
434 bformat(_("Attempted to include file %1$s in itself! "
435 "Ignoring inclusion."), from_utf8(incfile)));
439 Buffer const * const masterBuffer = buffer().masterBuffer();
441 // if incfile is relative, make it relative to the master
443 if (!FileName(incfile).isAbsolute()) {
445 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
446 from_utf8(masterBuffer->filePath())));
449 // write it to a file (so far the complete file)
452 if (type(params()) == LISTINGS) {
453 exportfile = incfile;
454 mangled = DocFileName(included_file).mangledFilename();
456 exportfile = changeExtension(incfile, ".tex");
457 mangled = DocFileName(changeExtension(included_file.absFilename(), ".tex")).
461 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
465 else if (!isValidLaTeXFilename(incfile)) {
466 frontend::Alert::warning(_("Invalid filename"),
467 _("The following filename is likely to cause trouble "
468 "when running the exported file through LaTeX: ") +
471 LYXERR(Debug::LATEX, "incfile:" << incfile);
472 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
473 LYXERR(Debug::LATEX, "writefile:" << writefile);
475 if (runparams.inComment || runparams.dryrun) {
476 //Don't try to load or copy the file if we're
477 //in a comment or doing a dryrun
478 } else if (isInputOrInclude(params()) &&
479 isLyXFilename(included_file.absFilename())) {
480 //if it's a LyX file and we're inputting or including,
481 //try to load it so we can write the associated latex
482 if (!loadIfNeeded(buffer()))
485 Buffer * tmp = theBufferList().getBuffer(included_file);
487 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
489 docstring text = bformat(_("Included file `%1$s'\n"
490 "has textclass `%2$s'\n"
491 "while parent file has textclass `%3$s'."),
492 included_file.displayName(),
493 from_utf8(tmp->params().documentClass().name()),
494 from_utf8(masterBuffer->params().documentClass().name()));
495 Alert::warning(_("Different textclasses"), text);
498 // Make sure modules used in child are all included in master
499 //FIXME It might be worth loading the children's modules into the master
500 //over in BufferParams rather than doing this check.
501 list<string> const masterModules = masterBuffer->params().getModules();
502 list<string> const childModules = tmp->params().getModules();
503 list<string>::const_iterator it = childModules.begin();
504 list<string>::const_iterator end = childModules.end();
505 for (; it != end; ++it) {
506 string const module = *it;
507 list<string>::const_iterator found =
508 find(masterModules.begin(), masterModules.end(), module);
509 if (found == masterModules.end()) {
510 docstring text = bformat(_("Included file `%1$s'\n"
511 "uses module `%2$s'\n"
512 "which is not used in parent file."),
513 included_file.displayName(), from_utf8(module));
514 Alert::warning(_("Module not found"), text);
518 tmp->markDepClean(masterBuffer->temppath());
520 // FIXME: handle non existing files
521 // FIXME: Second argument is irrelevant!
522 // since only_body is true, makeLaTeXFile will not look at second
523 // argument. Should we set it to string(), or should makeLaTeXFile
524 // make use of it somehow? (JMarc 20031002)
525 // The included file might be written in a different encoding
526 Encoding const * const oldEnc = runparams.encoding;
527 runparams.encoding = &tmp->params().encoding();
528 tmp->makeLaTeXFile(writefile,
529 masterFileName(buffer()).onlyPath().absFilename(),
531 runparams.encoding = oldEnc;
533 // In this case, it's not a LyX file, so we copy the file
534 // to the temp dir, so that .aux files etc. are not created
535 // in the original dir. Files included by this file will be
536 // found via input@path, see ../Buffer.cpp.
537 unsigned long const checksum_in = included_file.checksum();
538 unsigned long const checksum_out = writefile.checksum();
540 if (checksum_in != checksum_out) {
541 if (!included_file.copyTo(writefile)) {
544 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
545 "into the temporary directory."),
546 from_utf8(included_file.absFilename()))));
552 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
553 "latex" : "pdflatex";
554 if (isVerbatim(params())) {
555 incfile = latex_path(incfile);
557 os << '\\' << from_ascii(params().getCmdName()) << '{'
558 << from_utf8(incfile) << '}';
559 } else if (type(params()) == INPUT) {
560 runparams.exportdata->addExternalFile(tex_format, writefile,
563 // \input wants file with extension (default is .tex)
564 if (!isLyXFilename(included_file.absFilename())) {
565 incfile = latex_path(incfile);
567 os << '\\' << from_ascii(params().getCmdName())
568 << '{' << from_utf8(incfile) << '}';
570 incfile = changeExtension(incfile, ".tex");
571 incfile = latex_path(incfile);
573 os << '\\' << from_ascii(params().getCmdName())
574 << '{' << from_utf8(incfile) << '}';
576 } else if (type(params()) == LISTINGS) {
577 os << '\\' << from_ascii(params().getCmdName());
578 string const opt = to_utf8(params()["lstparams"]);
579 // opt is set in QInclude dialog and should have passed validation.
580 InsetListingsParams params(opt);
581 if (!params.params().empty())
582 os << "[" << from_utf8(params.params()) << "]";
583 os << '{' << from_utf8(incfile) << '}';
585 runparams.exportdata->addExternalFile(tex_format, writefile,
588 // \include don't want extension and demands that the
589 // file really have .tex
590 incfile = changeExtension(incfile, string());
591 incfile = latex_path(incfile);
593 os << '\\' << from_ascii(params().getCmdName()) << '{'
594 << from_utf8(incfile) << '}';
601 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
603 if (isVerbatim(params()) || isListings(params())) {
604 os << '[' << screenLabel() << '\n';
605 // FIXME: We don't know the encoding of the file, default to UTF-8.
606 os << includedFilename(buffer(), params()).fileContents("UTF-8");
608 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
610 docstring const str = '[' + screenLabel() + ']';
617 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
619 string incfile = to_utf8(params()["filename"]);
621 // Do nothing if no file name has been specified
625 string const included_file = includedFilename(buffer(), params()).absFilename();
627 // Check we're not trying to include ourselves.
628 // FIXME RECURSIVE INCLUDE
629 // This isn't sufficient, as the inclusion could be downstream.
630 // But it'll have to do for now.
631 if (buffer().absFileName() == included_file) {
632 Alert::error(_("Recursive input"),
633 bformat(_("Attempted to include file %1$s in itself! "
634 "Ignoring inclusion."), from_utf8(incfile)));
638 // write it to a file (so far the complete file)
639 string const exportfile = changeExtension(incfile, ".sgml");
640 DocFileName writefile(changeExtension(included_file, ".sgml"));
642 if (loadIfNeeded(buffer())) {
643 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
645 string const mangled = writefile.mangledFilename();
646 writefile = makeAbsPath(mangled,
647 buffer().masterBuffer()->temppath());
651 LYXERR(Debug::LATEX, "incfile:" << incfile);
652 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
653 LYXERR(Debug::LATEX, "writefile:" << writefile);
655 tmp->makeDocBookFile(writefile, runparams, true);
658 runparams.exportdata->addExternalFile("docbook", writefile,
660 runparams.exportdata->addExternalFile("docbook-xml", writefile,
663 if (isVerbatim(params()) || isListings(params())) {
664 os << "<inlinegraphic fileref=\""
665 << '&' << include_label << ';'
666 << "\" format=\"linespecific\">";
668 os << '&' << include_label << ';';
674 void InsetInclude::validate(LaTeXFeatures & features) const
676 string incfile = to_utf8(params()["filename"]);
679 LASSERT(&buffer() == &features.buffer(), /**/);
681 string const included_file =
682 includedFilename(buffer(), params()).absFilename();
684 if (isLyXFilename(included_file))
685 writefile = changeExtension(included_file, ".sgml");
687 writefile = included_file;
689 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
690 incfile = DocFileName(writefile).mangledFilename();
691 writefile = makeAbsPath(incfile,
692 buffer().masterBuffer()->temppath()).absFilename();
695 features.includeFile(include_label, writefile);
697 if (isVerbatim(params()))
698 features.require("verbatim");
699 else if (isListings(params()))
700 features.require("listings");
702 // Here we must do the fun stuff...
703 // Load the file in the include if it needs
705 if (loadIfNeeded(buffer())) {
707 Buffer * const tmp = theBufferList().getBuffer(FileName(included_file));
708 // make sure the buffer isn't us
709 // FIXME RECURSIVE INCLUDES
710 // This is not sufficient, as recursive includes could be
711 // more than a file away. But it will do for now.
712 if (tmp && tmp != &buffer()) {
713 // We must temporarily change features.buffer,
714 // otherwise it would always be the master buffer,
715 // and nested includes would not work.
716 features.setBuffer(*tmp);
717 tmp->validate(features);
718 features.setBuffer(buffer());
724 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
725 InsetIterator const & /*di*/) const
727 if (loadIfNeeded(buffer())) {
728 string const included_file = includedFilename(buffer(), params()).absFilename();
729 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
730 BiblioInfo const & newkeys = tmp->localBibInfo();
731 keys.mergeBiblioInfo(newkeys);
736 void InsetInclude::updateBibfilesCache()
738 Buffer * const tmp = getChildBuffer(buffer());
741 tmp->updateBibfilesCache();
742 tmp->setParent(&buffer());
747 support::FileNameList const &
748 InsetInclude::getBibfilesCache(Buffer const & buffer) const
750 Buffer * const tmp = getChildBuffer(buffer);
753 support::FileNameList const & cache = tmp->getBibfilesCache();
754 tmp->setParent(&buffer);
757 static support::FileNameList const empty;
762 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
764 LASSERT(mi.base.bv, /**/);
766 bool use_preview = false;
767 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
768 graphics::PreviewImage const * pimage =
769 preview_->getPreviewImage(mi.base.bv->buffer());
770 use_preview = pimage && pimage->image();
774 preview_->metrics(mi, dim);
778 button_.update(screenLabel(), true);
780 button_.metrics(mi, dim);
783 Box b(0, dim.wid, -dim.asc, dim.des);
788 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
790 LASSERT(pi.base.bv, /**/);
792 bool use_preview = false;
793 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
794 graphics::PreviewImage const * pimage =
795 preview_->getPreviewImage(pi.base.bv->buffer());
796 use_preview = pimage && pimage->image();
800 preview_->draw(pi, x, y);
802 button_.draw(pi, x, y);
806 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
808 return from_ascii("context-include");
812 Inset::DisplayType InsetInclude::display() const
814 return type(params()) == INPUT ? Inline : AlignCenter;
823 void InsetInclude::fileChanged() const
825 Buffer const * const buffer = updateFrontend();
829 preview_->removePreview(*buffer);
830 add_preview(*preview_.get(), *this, *buffer);
831 preview_->startLoading(*buffer);
837 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
839 FileName const included_file = includedFilename(buffer, params);
841 return type(params) == INPUT && params.preview() &&
842 included_file.isReadableFile();
846 docstring latexString(InsetInclude const & inset)
849 // We don't need to set runparams.encoding since this will be done
850 // by latex() anyway.
851 OutputParams runparams(0);
852 runparams.flavor = OutputParams::LATEX;
853 inset.latex(os, runparams);
859 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
860 Buffer const & buffer)
862 InsetCommandParams const & params = inset.params();
863 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
864 preview_wanted(params, buffer)) {
865 renderer.setAbsFile(includedFilename(buffer, params));
866 docstring const snippet = latexString(inset);
867 renderer.addPreview(snippet, buffer);
874 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
876 Buffer const & buffer = ploader.buffer();
877 if (!preview_wanted(params(), buffer))
879 preview_->setAbsFile(includedFilename(buffer, params()));
880 docstring const snippet = latexString(*this);
881 preview_->addPreview(snippet, ploader);
885 void InsetInclude::addToToc(DocIterator const & cpit)
887 TocBackend & backend = buffer().tocBackend();
889 if (isListings(params())) {
891 label_->addToToc(cpit);
893 InsetListingsParams p(to_utf8(params()["lstparams"]));
894 string caption = p.getParamValue("caption");
897 Toc & toc = backend.toc("listing");
898 docstring str = convert<docstring>(toc.size() + 1)
899 + ". " + from_utf8(caption);
900 DocIterator pit = cpit;
901 toc.push_back(TocItem(pit, 0, str));
904 Buffer const * const childbuffer = getChildBuffer(buffer());
908 Toc & toc = backend.toc("child");
909 docstring str = childbuffer->fileName().displayName();
910 toc.push_back(TocItem(cpit, 0, str));
912 TocList & toclist = backend.tocs();
913 childbuffer->tocBackend().update();
914 TocList const & childtoclist = childbuffer->tocBackend().tocs();
915 TocList::const_iterator it = childtoclist.begin();
916 TocList::const_iterator const end = childtoclist.end();
917 for(; it != end; ++it)
918 toclist[it->first].insert(toclist[it->first].end(),
919 it->second.begin(), it->second.end());
923 void InsetInclude::updateLabels(ParIterator const & it)
925 Buffer const * const childbuffer = getChildBuffer(buffer());
927 childbuffer->updateLabels(true);
930 if (!isListings(params()))
934 label_->updateLabels(it);
936 InsetListingsParams const par(to_utf8(params()["lstparams"]));
937 if (par.getParamValue("caption").empty()) {
938 listings_label_ = buffer().B_("Program Listing");
941 Buffer const & master = *buffer().masterBuffer();
942 Counters & counters = master.params().documentClass().counters();
943 docstring const cnt = from_ascii("listing");
944 listings_label_ = master.B_("Program Listing");
945 if (counters.hasCounter(cnt)) {
947 listings_label_ += " " + convert<docstring>(counters.value(cnt));