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:
310 return InsetCommand::getStatus(cur, cmd, flag);
315 void InsetInclude::setParams(InsetCommandParams const & p)
317 InsetCommand::setParams(p);
320 if (preview_->monitoring())
321 preview_->stopMonitoring();
323 if (type(params()) == INPUT)
324 add_preview(*preview_, *this, buffer());
326 buffer().updateBibfilesCache();
330 docstring InsetInclude::screenLabel() const
334 switch (type(params())) {
336 temp = buffer().B_("Input");
339 temp = buffer().B_("Verbatim Input");
342 temp = buffer().B_("Verbatim Input*");
345 temp = buffer().B_("Include");
348 temp = listings_label_;
351 LASSERT(false, /**/);
356 if (params()["filename"].empty())
359 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
365 /// return the child buffer if the file is a LyX doc and is loaded
366 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
368 if (isVerbatim(params) || isListings(params))
371 string const included_file = includedFilename(buffer, params).absFilename();
372 if (!isLyXFilename(included_file))
375 Buffer * childBuffer = loadIfNeeded(buffer, params);
377 // FIXME: recursive includes
378 return (childBuffer == &buffer) ? 0 : childBuffer;
382 /// return true if the file is or got loaded.
383 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
385 if (isVerbatim(params) || isListings(params))
388 string const parent_filename = parent.absFileName();
389 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
390 onlyPath(parent_filename));
392 if (!isLyXFilename(included_file.absFilename()))
395 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
397 // the readonly flag can/will be wrong, not anymore I think.
398 if (!included_file.exists())
401 child = theBufferList().newBuffer(included_file.absFilename());
403 // Buffer creation is not possible.
406 if (!child->loadLyXFile(included_file)) {
407 //close the buffer we just opened
408 theBufferList().release(child);
412 if (!child->errorList("Parse").empty()) {
413 // FIXME: Do something.
416 child->setParent(&parent);
421 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
423 string incfile = to_utf8(params()["filename"]);
425 // Do nothing if no file name has been specified
429 FileName const included_file = includedFilename(buffer(), params());
431 // Check we're not trying to include ourselves.
432 // FIXME RECURSIVE INCLUDE
433 // This isn't sufficient, as the inclusion could be downstream.
434 // But it'll have to do for now.
435 if (isInputOrInclude(params()) &&
436 buffer().absFileName() == included_file.absFilename())
438 Alert::error(_("Recursive input"),
439 bformat(_("Attempted to include file %1$s in itself! "
440 "Ignoring inclusion."), from_utf8(incfile)));
444 Buffer const * const masterBuffer = buffer().masterBuffer();
446 // if incfile is relative, make it relative to the master
448 if (!FileName(incfile).isAbsolute()) {
450 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
451 from_utf8(masterBuffer->filePath())));
454 // write it to a file (so far the complete file)
455 string const exportfile = changeExtension(incfile, ".tex");
456 string const mangled =
457 DocFileName(changeExtension(included_file.absFilename(),".tex")).
459 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
463 else if (!isValidLaTeXFilename(incfile)) {
464 frontend::Alert::warning(_("Invalid filename"),
465 _("The following filename is likely to cause trouble "
466 "when running the exported file through LaTeX: ") +
469 LYXERR(Debug::LATEX, "incfile:" << incfile);
470 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
471 LYXERR(Debug::LATEX, "writefile:" << writefile);
473 if (runparams.inComment || runparams.dryrun) {
474 //Don't try to load or copy the file if we're
475 //in a comment or doing a dryrun
476 } else if (isInputOrInclude(params()) &&
477 isLyXFilename(included_file.absFilename())) {
478 //if it's a LyX file and we're inputting or including,
479 //try to load it so we can write the associated latex
480 if (!loadIfNeeded(buffer(), params()))
483 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
485 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
487 docstring text = bformat(_("Included file `%1$s'\n"
488 "has textclass `%2$s'\n"
489 "while parent file has textclass `%3$s'."),
490 included_file.displayName(),
491 from_utf8(tmp->params().documentClass().name()),
492 from_utf8(masterBuffer->params().documentClass().name()));
493 Alert::warning(_("Different textclasses"), text);
496 // Make sure modules used in child are all included in master
497 //FIXME It might be worth loading the children's modules into the master
498 //over in BufferParams rather than doing this check.
499 vector<string> const masterModules = masterBuffer->params().getModules();
500 vector<string> const childModules = tmp->params().getModules();
501 vector<string>::const_iterator it = childModules.begin();
502 vector<string>::const_iterator end = childModules.end();
503 for (; it != end; ++it) {
504 string const module = *it;
505 vector<string>::const_iterator found =
506 find(masterModules.begin(), masterModules.end(), module);
507 if (found == masterModules.end()) {
508 docstring text = bformat(_("Included file `%1$s'\n"
509 "uses module `%2$s'\n"
510 "which is not used in parent file."),
511 included_file.displayName(), from_utf8(module));
512 Alert::warning(_("Module not found"), text);
516 tmp->markDepClean(masterBuffer->temppath());
518 // FIXME: handle non existing files
519 // FIXME: Second argument is irrelevant!
520 // since only_body is true, makeLaTeXFile will not look at second
521 // argument. Should we set it to string(), or should makeLaTeXFile
522 // make use of it somehow? (JMarc 20031002)
523 // The included file might be written in a different encoding
524 Encoding const * const oldEnc = runparams.encoding;
525 runparams.encoding = &tmp->params().encoding();
526 tmp->makeLaTeXFile(writefile,
527 masterFileName(buffer()).onlyPath().absFilename(),
529 runparams.encoding = oldEnc;
531 // In this case, it's not a LyX file, so we copy the file
532 // to the temp dir, so that .aux files etc. are not created
533 // in the original dir. Files included by this file will be
534 // found via input@path, see ../Buffer.cpp.
535 unsigned long const checksum_in = included_file.checksum();
536 unsigned long const checksum_out = writefile.checksum();
538 if (checksum_in != checksum_out) {
539 if (!included_file.copyTo(writefile)) {
542 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
543 "into the temporary directory."),
544 from_utf8(included_file.absFilename()))));
550 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
551 "latex" : "pdflatex";
552 if (isVerbatim(params())) {
553 incfile = latex_path(incfile);
555 os << '\\' << from_ascii(params().getCmdName()) << '{'
556 << from_utf8(incfile) << '}';
557 } else if (type(params()) == INPUT) {
558 runparams.exportdata->addExternalFile(tex_format, writefile,
561 // \input wants file with extension (default is .tex)
562 if (!isLyXFilename(included_file.absFilename())) {
563 incfile = latex_path(incfile);
565 os << '\\' << from_ascii(params().getCmdName())
566 << '{' << from_utf8(incfile) << '}';
568 incfile = changeExtension(incfile, ".tex");
569 incfile = latex_path(incfile);
571 os << '\\' << from_ascii(params().getCmdName())
572 << '{' << from_utf8(incfile) << '}';
574 } else if (type(params()) == LISTINGS) {
575 os << '\\' << from_ascii(params().getCmdName());
576 string const opt = to_utf8(params()["lstparams"]);
577 // opt is set in QInclude dialog and should have passed validation.
578 InsetListingsParams params(opt);
579 if (!params.params().empty())
580 os << "[" << from_utf8(params.params()) << "]";
581 os << '{' << from_utf8(incfile) << '}';
583 runparams.exportdata->addExternalFile(tex_format, writefile,
586 // \include don't want extension and demands that the
587 // file really have .tex
588 incfile = changeExtension(incfile, string());
589 incfile = latex_path(incfile);
591 os << '\\' << from_ascii(params().getCmdName()) << '{'
592 << from_utf8(incfile) << '}';
599 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
601 if (isVerbatim(params()) || isListings(params())) {
602 os << '[' << screenLabel() << '\n';
603 // FIXME: We don't know the encoding of the file, default to UTF-8.
604 os << includedFilename(buffer(), params()).fileContents("UTF-8");
606 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
608 docstring const str = '[' + screenLabel() + ']';
615 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
617 string incfile = to_utf8(params()["filename"]);
619 // Do nothing if no file name has been specified
623 string const included_file = includedFilename(buffer(), params()).absFilename();
625 // Check we're not trying to include ourselves.
626 // FIXME RECURSIVE INCLUDE
627 // This isn't sufficient, as the inclusion could be downstream.
628 // But it'll have to do for now.
629 if (buffer().absFileName() == included_file) {
630 Alert::error(_("Recursive input"),
631 bformat(_("Attempted to include file %1$s in itself! "
632 "Ignoring inclusion."), from_utf8(incfile)));
636 // write it to a file (so far the complete file)
637 string const exportfile = changeExtension(incfile, ".sgml");
638 DocFileName writefile(changeExtension(included_file, ".sgml"));
640 if (loadIfNeeded(buffer(), params())) {
641 Buffer * tmp = theBufferList().getBuffer(included_file);
643 string const mangled = writefile.mangledFilename();
644 writefile = makeAbsPath(mangled,
645 buffer().masterBuffer()->temppath());
649 LYXERR(Debug::LATEX, "incfile:" << incfile);
650 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
651 LYXERR(Debug::LATEX, "writefile:" << writefile);
653 tmp->makeDocBookFile(writefile, runparams, true);
656 runparams.exportdata->addExternalFile("docbook", writefile,
658 runparams.exportdata->addExternalFile("docbook-xml", writefile,
661 if (isVerbatim(params()) || isListings(params())) {
662 os << "<inlinegraphic fileref=\""
663 << '&' << include_label << ';'
664 << "\" format=\"linespecific\">";
666 os << '&' << include_label << ';';
672 void InsetInclude::validate(LaTeXFeatures & features) const
674 string incfile = to_utf8(params()["filename"]);
677 LASSERT(&buffer() == &features.buffer(), /**/);
679 string const included_file =
680 includedFilename(buffer(), params()).absFilename();
682 if (isLyXFilename(included_file))
683 writefile = changeExtension(included_file, ".sgml");
685 writefile = included_file;
687 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
688 incfile = DocFileName(writefile).mangledFilename();
689 writefile = makeAbsPath(incfile,
690 buffer().masterBuffer()->temppath()).absFilename();
693 features.includeFile(include_label, writefile);
695 if (isVerbatim(params()))
696 features.require("verbatim");
697 else if (isListings(params()))
698 features.require("listings");
700 // Here we must do the fun stuff...
701 // Load the file in the include if it needs
703 if (loadIfNeeded(buffer(), params())) {
705 Buffer * const tmp = theBufferList().getBuffer(included_file);
706 // make sure the buffer isn't us
707 // FIXME RECURSIVE INCLUDES
708 // This is not sufficient, as recursive includes could be
709 // more than a file away. But it will do for now.
710 if (tmp && tmp != &buffer()) {
711 // We must temporarily change features.buffer,
712 // otherwise it would always be the master buffer,
713 // and nested includes would not work.
714 features.setBuffer(*tmp);
715 tmp->validate(features);
716 features.setBuffer(buffer());
722 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
723 InsetIterator const & /*di*/) const
725 if (loadIfNeeded(buffer(), params())) {
726 string const included_file = includedFilename(buffer(), params()).absFilename();
727 Buffer * tmp = theBufferList().getBuffer(included_file);
728 BiblioInfo const & newkeys = tmp->localBibInfo();
729 keys.mergeBiblioInfo(newkeys);
734 void InsetInclude::updateBibfilesCache()
736 Buffer * const tmp = getChildBuffer(buffer(), params());
739 tmp->updateBibfilesCache();
740 tmp->setParent(&buffer());
745 support::FileNameList const &
746 InsetInclude::getBibfilesCache(Buffer const & buffer) const
748 Buffer * const tmp = getChildBuffer(buffer, params());
751 support::FileNameList const & cache = tmp->getBibfilesCache();
752 tmp->setParent(&buffer);
755 static support::FileNameList const empty;
760 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
762 LASSERT(mi.base.bv, /**/);
764 bool use_preview = false;
765 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
766 graphics::PreviewImage const * pimage =
767 preview_->getPreviewImage(mi.base.bv->buffer());
768 use_preview = pimage && pimage->image();
772 preview_->metrics(mi, dim);
776 button_.update(screenLabel(), true);
778 button_.metrics(mi, dim);
781 Box b(0, dim.wid, -dim.asc, dim.des);
786 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
788 LASSERT(pi.base.bv, /**/);
790 bool use_preview = false;
791 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
792 graphics::PreviewImage const * pimage =
793 preview_->getPreviewImage(pi.base.bv->buffer());
794 use_preview = pimage && pimage->image();
798 preview_->draw(pi, x, y);
800 button_.draw(pi, x, y);
804 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
806 return from_ascii("context-include");
810 Inset::DisplayType InsetInclude::display() const
812 return type(params()) == INPUT ? Inline : AlignCenter;
821 void InsetInclude::fileChanged() const
823 Buffer const * const buffer = updateFrontend();
827 preview_->removePreview(*buffer);
828 add_preview(*preview_.get(), *this, *buffer);
829 preview_->startLoading(*buffer);
835 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
837 FileName const included_file = includedFilename(buffer, params);
839 return type(params) == INPUT && params.preview() &&
840 included_file.isReadableFile();
844 docstring latexString(InsetInclude const & inset)
847 // We don't need to set runparams.encoding since this will be done
848 // by latex() anyway.
849 OutputParams runparams(0);
850 runparams.flavor = OutputParams::LATEX;
851 inset.latex(os, runparams);
857 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
858 Buffer const & buffer)
860 InsetCommandParams const & params = inset.params();
861 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
862 preview_wanted(params, buffer)) {
863 renderer.setAbsFile(includedFilename(buffer, params));
864 docstring const snippet = latexString(inset);
865 renderer.addPreview(snippet, buffer);
872 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
874 Buffer const & buffer = ploader.buffer();
875 if (!preview_wanted(params(), buffer))
877 preview_->setAbsFile(includedFilename(buffer, params()));
878 docstring const snippet = latexString(*this);
879 preview_->addPreview(snippet, ploader);
883 void InsetInclude::addToToc(DocIterator const & cpit)
885 TocBackend & backend = buffer().tocBackend();
887 if (isListings(params())) {
889 label_->addToToc(cpit);
891 InsetListingsParams p(to_utf8(params()["lstparams"]));
892 string caption = p.getParamValue("caption");
895 Toc & toc = backend.toc("listing");
896 docstring str = convert<docstring>(toc.size() + 1)
897 + ". " + from_utf8(caption);
898 DocIterator pit = cpit;
899 toc.push_back(TocItem(pit, 0, str));
902 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
906 Toc & toc = backend.toc("child");
907 docstring str = childbuffer->fileName().displayName();
908 toc.push_back(TocItem(cpit, 0, str));
910 TocList & toclist = backend.tocs();
911 childbuffer->tocBackend().update();
912 TocList const & childtoclist = childbuffer->tocBackend().tocs();
913 TocList::const_iterator it = childtoclist.begin();
914 TocList::const_iterator const end = childtoclist.end();
915 for(; it != end; ++it)
916 toclist[it->first].insert(toclist[it->first].end(),
917 it->second.begin(), it->second.end());
921 void InsetInclude::updateLabels(ParIterator const & it)
923 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
925 lyx::updateLabels(*childbuffer, true);
928 if (!isListings(params()))
932 label_->updateLabels(it);
934 InsetListingsParams const par(to_utf8(params()["lstparams"]));
935 if (par.getParamValue("caption").empty()) {
936 listings_label_.clear();
939 Buffer const & master = *buffer().masterBuffer();
940 Counters & counters = master.params().documentClass().counters();
941 docstring const cnt = from_ascii("listing");
942 listings_label_ = master.B_("Program Listing");
943 if (counters.hasCounter(cnt)) {
945 listings_label_ += " " + convert<docstring>(counters.value(cnt));