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"
16 #include "LayoutFile.h"
18 #include "buffer_funcs.h"
19 #include "BufferList.h"
20 #include "BufferParams.h"
21 #include "BufferView.h"
23 #include "DispatchResult.h"
24 #include "ErrorList.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "LaTeXFeatures.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/lassert.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/lstrings.h" // contains
56 #include "support/lyxalgo.h"
57 #include "support/convert.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)), set_label_(false), label_(0)
165 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
167 if (isListings(params())) {
168 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
169 label_ = createLabel(from_utf8(listing_params.getParamValue("label")));
174 InsetInclude::InsetInclude(InsetInclude const & other)
175 : InsetCommand(other), include_label(other.include_label),
176 preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
178 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
181 label_ = new InsetLabel(*other.label_);
185 InsetInclude::~InsetInclude()
188 if (isVerbatim(params()) || isListings(params()))
192 string const parent_filename = buffer().absFileName();
193 FileName const included_file = makeAbsPath(to_utf8(params()["filename"]),
194 onlyPath(parent_filename));
196 if (!isLyXFilename(included_file.absFilename()))
199 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
200 // File not opened, nothing to close.
204 // Child document has a different parent, don't close it.
205 if (child->parent() != &buffer())
209 theBufferList().release(child);
213 void InsetInclude::setBuffer(Buffer & buffer)
215 InsetCommand::setBuffer(buffer);
217 label_->setBuffer(buffer);
221 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
224 // This is only correct for the case of listings, but it'll do for now.
225 // In the other cases, this second parameter should just be empty.
226 static ParamInfo param_info_;
227 if (param_info_.empty()) {
228 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
229 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
235 bool InsetInclude::isCompatibleCommand(string const & s)
237 return type(s) != NONE;
241 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
243 LASSERT(&cur.buffer() == &buffer(), /**/);
244 switch (cmd.action) {
246 case LFUN_INSET_EDIT: {
247 editIncluded(to_utf8(params()["filename"]));
251 case LFUN_INSET_MODIFY: {
252 InsetCommandParams p(INCLUDE_CODE);
253 if (cmd.getArg(0) == "changetype") {
254 InsetCommand::doDispatch(cur, cmd);
257 InsetCommand::string2params("include", to_utf8(cmd.argument()), p);
258 if (!p.getCmdName().empty()) {
260 InsetListingsParams new_params(to_utf8(p["lstparams"]));
261 docstring const label_str = from_utf8(new_params.getParamValue("label"));
262 if (label_str.empty())
265 label_->updateCommand(label_str);
267 label_ = createLabel(label_str);
268 label_->setBuffer(buffer());
278 //pass everything else up the chain
280 InsetCommand::doDispatch(cur, cmd);
286 void InsetInclude::editIncluded(string const & file)
288 string const ext = support::getExtension(file);
290 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
293 // tex file or other text file in verbatim mode
294 formats.edit(buffer(),
295 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
300 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
301 FuncStatus & flag) const
303 switch (cmd.action) {
305 case LFUN_INSET_EDIT:
306 case LFUN_INSET_MODIFY:
311 return InsetCommand::getStatus(cur, cmd, flag);
316 void InsetInclude::setParams(InsetCommandParams const & p)
318 InsetCommand::setParams(p);
321 if (preview_->monitoring())
322 preview_->stopMonitoring();
324 if (type(params()) == INPUT)
325 add_preview(*preview_, *this, buffer());
327 buffer().updateBibfilesCache();
331 docstring InsetInclude::screenLabel() const
335 switch (type(params())) {
337 temp = buffer().B_("Input");
340 temp = buffer().B_("Verbatim Input");
343 temp = buffer().B_("Verbatim Input*");
346 temp = buffer().B_("Include");
349 temp = listings_label_;
352 LASSERT(false, /**/);
357 if (params()["filename"].empty())
360 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
366 /// return the child buffer if the file is a LyX doc and is loaded
367 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
369 if (isVerbatim(params) || isListings(params))
372 string const included_file = includedFilename(buffer, params).absFilename();
373 if (!isLyXFilename(included_file))
376 Buffer * childBuffer = loadIfNeeded(buffer, params);
378 // FIXME: recursive includes
379 return (childBuffer == &buffer) ? 0 : childBuffer;
383 /// return true if the file is or got loaded.
384 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
386 if (isVerbatim(params) || isListings(params))
389 string const parent_filename = parent.absFileName();
390 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
391 onlyPath(parent_filename));
393 if (!isLyXFilename(included_file.absFilename()))
396 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
398 // the readonly flag can/will be wrong, not anymore I think.
399 if (!included_file.exists())
402 child = theBufferList().newBuffer(included_file.absFilename());
404 // Buffer creation is not possible.
407 if (!child->loadLyXFile(included_file)) {
408 //close the buffer we just opened
409 theBufferList().release(child);
413 if (!child->errorList("Parse").empty()) {
414 // FIXME: Do something.
417 child->setParent(&parent);
422 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
424 string incfile = to_utf8(params()["filename"]);
426 // Do nothing if no file name has been specified
430 FileName const included_file = includedFilename(buffer(), params());
432 // Check we're not trying to include ourselves.
433 // FIXME RECURSIVE INCLUDE
434 // This isn't sufficient, as the inclusion could be downstream.
435 // But it'll have to do for now.
436 if (isInputOrInclude(params()) &&
437 buffer().absFileName() == included_file.absFilename())
439 Alert::error(_("Recursive input"),
440 bformat(_("Attempted to include file %1$s in itself! "
441 "Ignoring inclusion."), from_utf8(incfile)));
445 Buffer const * const masterBuffer = buffer().masterBuffer();
447 // if incfile is relative, make it relative to the master
449 if (!FileName(incfile).isAbsolute()) {
451 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
452 from_utf8(masterBuffer->filePath())));
455 // write it to a file (so far the complete file)
456 string const exportfile = changeExtension(incfile, ".tex");
457 string const mangled =
458 DocFileName(changeExtension(included_file.absFilename(),".tex")).
460 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
464 else if (!isValidLaTeXFilename(incfile)) {
465 frontend::Alert::warning(_("Invalid filename"),
466 _("The following filename is likely to cause trouble "
467 "when running the exported file through LaTeX: ") +
470 LYXERR(Debug::LATEX, "incfile:" << incfile);
471 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
472 LYXERR(Debug::LATEX, "writefile:" << writefile);
474 if (runparams.inComment || runparams.dryrun) {
475 //Don't try to load or copy the file if we're
476 //in a comment or doing a dryrun
477 } else if (isInputOrInclude(params()) &&
478 isLyXFilename(included_file.absFilename())) {
479 //if it's a LyX file and we're inputting or including,
480 //try to load it so we can write the associated latex
481 if (!loadIfNeeded(buffer(), params()))
484 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
486 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
488 docstring text = bformat(_("Included file `%1$s'\n"
489 "has textclass `%2$s'\n"
490 "while parent file has textclass `%3$s'."),
491 included_file.displayName(),
492 from_utf8(tmp->params().documentClass().name()),
493 from_utf8(masterBuffer->params().documentClass().name()));
494 Alert::warning(_("Different textclasses"), text);
497 // Make sure modules used in child are all included in master
498 //FIXME It might be worth loading the children's modules into the master
499 //over in BufferParams rather than doing this check.
500 vector<string> const masterModules = masterBuffer->params().getModules();
501 vector<string> const childModules = tmp->params().getModules();
502 vector<string>::const_iterator it = childModules.begin();
503 vector<string>::const_iterator end = childModules.end();
504 for (; it != end; ++it) {
505 string const module = *it;
506 vector<string>::const_iterator found =
507 find(masterModules.begin(), masterModules.end(), module);
508 if (found == masterModules.end()) {
509 docstring text = bformat(_("Included file `%1$s'\n"
510 "uses module `%2$s'\n"
511 "which is not used in parent file."),
512 included_file.displayName(), from_utf8(module));
513 Alert::warning(_("Module not found"), text);
517 tmp->markDepClean(masterBuffer->temppath());
519 // FIXME: handle non existing files
520 // FIXME: Second argument is irrelevant!
521 // since only_body is true, makeLaTeXFile will not look at second
522 // argument. Should we set it to string(), or should makeLaTeXFile
523 // make use of it somehow? (JMarc 20031002)
524 // The included file might be written in a different encoding
525 Encoding const * const oldEnc = runparams.encoding;
526 runparams.encoding = &tmp->params().encoding();
527 tmp->makeLaTeXFile(writefile,
528 masterFileName(buffer()).onlyPath().absFilename(),
530 runparams.encoding = oldEnc;
532 // In this case, it's not a LyX file, so we copy the file
533 // to the temp dir, so that .aux files etc. are not created
534 // in the original dir. Files included by this file will be
535 // found via input@path, see ../Buffer.cpp.
536 unsigned long const checksum_in = included_file.checksum();
537 unsigned long const checksum_out = writefile.checksum();
539 if (checksum_in != checksum_out) {
540 if (!included_file.copyTo(writefile)) {
543 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
544 "into the temporary directory."),
545 from_utf8(included_file.absFilename()))));
551 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
552 "latex" : "pdflatex";
553 if (isVerbatim(params())) {
554 incfile = latex_path(incfile);
556 os << '\\' << from_ascii(params().getCmdName()) << '{'
557 << from_utf8(incfile) << '}';
558 } else if (type(params()) == INPUT) {
559 runparams.exportdata->addExternalFile(tex_format, writefile,
562 // \input wants file with extension (default is .tex)
563 if (!isLyXFilename(included_file.absFilename())) {
564 incfile = latex_path(incfile);
566 os << '\\' << from_ascii(params().getCmdName())
567 << '{' << from_utf8(incfile) << '}';
569 incfile = changeExtension(incfile, ".tex");
570 incfile = latex_path(incfile);
572 os << '\\' << from_ascii(params().getCmdName())
573 << '{' << from_utf8(incfile) << '}';
575 } else if (type(params()) == LISTINGS) {
576 os << '\\' << from_ascii(params().getCmdName());
577 string const opt = to_utf8(params()["lstparams"]);
578 // opt is set in QInclude dialog and should have passed validation.
579 InsetListingsParams params(opt);
580 if (!params.params().empty())
581 os << "[" << from_utf8(params.params()) << "]";
582 os << '{' << from_utf8(incfile) << '}';
584 runparams.exportdata->addExternalFile(tex_format, writefile,
587 // \include don't want extension and demands that the
588 // file really have .tex
589 incfile = changeExtension(incfile, string());
590 incfile = latex_path(incfile);
592 os << '\\' << from_ascii(params().getCmdName()) << '{'
593 << from_utf8(incfile) << '}';
600 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
602 if (isVerbatim(params()) || isListings(params())) {
603 os << '[' << screenLabel() << '\n';
604 // FIXME: We don't know the encoding of the file, default to UTF-8.
605 os << includedFilename(buffer(), params()).fileContents("UTF-8");
607 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
609 docstring const str = '[' + screenLabel() + ']';
616 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
618 string incfile = to_utf8(params()["filename"]);
620 // Do nothing if no file name has been specified
624 string const included_file = includedFilename(buffer(), params()).absFilename();
626 // Check we're not trying to include ourselves.
627 // FIXME RECURSIVE INCLUDE
628 // This isn't sufficient, as the inclusion could be downstream.
629 // But it'll have to do for now.
630 if (buffer().absFileName() == included_file) {
631 Alert::error(_("Recursive input"),
632 bformat(_("Attempted to include file %1$s in itself! "
633 "Ignoring inclusion."), from_utf8(incfile)));
637 // write it to a file (so far the complete file)
638 string const exportfile = changeExtension(incfile, ".sgml");
639 DocFileName writefile(changeExtension(included_file, ".sgml"));
641 if (loadIfNeeded(buffer(), params())) {
642 Buffer * tmp = theBufferList().getBuffer(included_file);
644 string const mangled = writefile.mangledFilename();
645 writefile = makeAbsPath(mangled,
646 buffer().masterBuffer()->temppath());
650 LYXERR(Debug::LATEX, "incfile:" << incfile);
651 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
652 LYXERR(Debug::LATEX, "writefile:" << writefile);
654 tmp->makeDocBookFile(writefile, runparams, true);
657 runparams.exportdata->addExternalFile("docbook", writefile,
659 runparams.exportdata->addExternalFile("docbook-xml", writefile,
662 if (isVerbatim(params()) || isListings(params())) {
663 os << "<inlinegraphic fileref=\""
664 << '&' << include_label << ';'
665 << "\" format=\"linespecific\">";
667 os << '&' << include_label << ';';
673 void InsetInclude::validate(LaTeXFeatures & features) const
675 string incfile = to_utf8(params()["filename"]);
678 LASSERT(&buffer() == &features.buffer(), /**/);
680 string const included_file =
681 includedFilename(buffer(), params()).absFilename();
683 if (isLyXFilename(included_file))
684 writefile = changeExtension(included_file, ".sgml");
686 writefile = included_file;
688 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
689 incfile = DocFileName(writefile).mangledFilename();
690 writefile = makeAbsPath(incfile,
691 buffer().masterBuffer()->temppath()).absFilename();
694 features.includeFile(include_label, writefile);
696 if (isVerbatim(params()))
697 features.require("verbatim");
698 else if (isListings(params()))
699 features.require("listings");
701 // Here we must do the fun stuff...
702 // Load the file in the include if it needs
704 if (loadIfNeeded(buffer(), params())) {
706 Buffer * const tmp = theBufferList().getBuffer(included_file);
707 // make sure the buffer isn't us
708 // FIXME RECURSIVE INCLUDES
709 // This is not sufficient, as recursive includes could be
710 // more than a file away. But it will do for now.
711 if (tmp && tmp != &buffer()) {
712 // We must temporarily change features.buffer,
713 // otherwise it would always be the master buffer,
714 // and nested includes would not work.
715 features.setBuffer(*tmp);
716 tmp->validate(features);
717 features.setBuffer(buffer());
723 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
724 InsetIterator const & /*di*/) const
726 if (loadIfNeeded(buffer(), params())) {
727 string const included_file = includedFilename(buffer(), params()).absFilename();
728 Buffer * tmp = theBufferList().getBuffer(included_file);
729 BiblioInfo const & newkeys = tmp->localBibInfo();
730 keys.mergeBiblioInfo(newkeys);
735 void InsetInclude::updateBibfilesCache()
737 Buffer * const tmp = getChildBuffer(buffer(), params());
740 tmp->updateBibfilesCache();
741 tmp->setParent(&buffer());
746 support::FileNameList const &
747 InsetInclude::getBibfilesCache(Buffer const & buffer) const
749 Buffer * const tmp = getChildBuffer(buffer, params());
752 support::FileNameList const & cache = tmp->getBibfilesCache();
753 tmp->setParent(&buffer);
756 static support::FileNameList const empty;
761 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
763 LASSERT(mi.base.bv, /**/);
765 bool use_preview = false;
766 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
767 graphics::PreviewImage const * pimage =
768 preview_->getPreviewImage(mi.base.bv->buffer());
769 use_preview = pimage && pimage->image();
773 preview_->metrics(mi, dim);
777 button_.update(screenLabel(), true);
779 button_.metrics(mi, dim);
782 Box b(0, dim.wid, -dim.asc, dim.des);
787 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
789 LASSERT(pi.base.bv, /**/);
791 bool use_preview = false;
792 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
793 graphics::PreviewImage const * pimage =
794 preview_->getPreviewImage(pi.base.bv->buffer());
795 use_preview = pimage && pimage->image();
799 preview_->draw(pi, x, y);
801 button_.draw(pi, x, y);
805 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
807 return from_ascii("context-include");
811 Inset::DisplayType InsetInclude::display() const
813 return type(params()) == INPUT ? Inline : AlignCenter;
822 void InsetInclude::fileChanged() const
824 Buffer const * const buffer = updateFrontend();
828 preview_->removePreview(*buffer);
829 add_preview(*preview_.get(), *this, *buffer);
830 preview_->startLoading(*buffer);
836 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
838 FileName const included_file = includedFilename(buffer, params);
840 return type(params) == INPUT && params.preview() &&
841 included_file.isReadableFile();
845 docstring latexString(InsetInclude const & inset)
848 // We don't need to set runparams.encoding since this will be done
849 // by latex() anyway.
850 OutputParams runparams(0);
851 runparams.flavor = OutputParams::LATEX;
852 inset.latex(os, runparams);
858 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
859 Buffer const & buffer)
861 InsetCommandParams const & params = inset.params();
862 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
863 preview_wanted(params, buffer)) {
864 renderer.setAbsFile(includedFilename(buffer, params));
865 docstring const snippet = latexString(inset);
866 renderer.addPreview(snippet, buffer);
873 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
875 Buffer const & buffer = ploader.buffer();
876 if (!preview_wanted(params(), buffer))
878 preview_->setAbsFile(includedFilename(buffer, params()));
879 docstring const snippet = latexString(*this);
880 preview_->addPreview(snippet, ploader);
884 void InsetInclude::addToToc(DocIterator const & cpit)
886 TocBackend & backend = buffer().tocBackend();
888 if (isListings(params())) {
890 label_->addToToc(cpit);
892 InsetListingsParams p(to_utf8(params()["lstparams"]));
893 string caption = p.getParamValue("caption");
896 Toc & toc = backend.toc("listing");
897 docstring str = convert<docstring>(toc.size() + 1)
898 + ". " + from_utf8(caption);
899 DocIterator pit = cpit;
900 toc.push_back(TocItem(pit, 0, str));
903 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
907 Toc & toc = backend.toc("child");
908 docstring str = childbuffer->fileName().displayName();
909 toc.push_back(TocItem(cpit, 0, str));
911 TocList & toclist = backend.tocs();
912 childbuffer->tocBackend().update();
913 TocList const & childtoclist = childbuffer->tocBackend().tocs();
914 TocList::const_iterator it = childtoclist.begin();
915 TocList::const_iterator const end = childtoclist.end();
916 for(; it != end; ++it)
917 toclist[it->first].insert(toclist[it->first].end(),
918 it->second.begin(), it->second.end());
922 void InsetInclude::updateLabels(ParIterator const & it)
924 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
926 lyx::updateLabels(*childbuffer, true);
929 if (!isListings(params()))
933 label_->updateLabels(it);
935 InsetListingsParams const par(to_utf8(params()["lstparams"]));
936 if (par.getParamValue("caption").empty()) {
937 listings_label_.clear();
940 Buffer const & master = *buffer().masterBuffer();
941 Counters & counters = master.params().documentClass().counters();
942 docstring const cnt = from_ascii("listing");
943 listings_label_ = master.B_("Program Listing");
944 if (counters.hasCounter(cnt)) {
946 listings_label_ += " " + convert<docstring>(counters.value(cnt));