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 "support/debug.h"
23 #include "DispatchResult.h"
25 #include "FuncRequest.h"
26 #include "FuncStatus.h"
27 #include "support/gettext.h"
28 #include "LaTeXFeatures.h"
32 #include "MetricsInfo.h"
33 #include "OutputParams.h"
34 #include "TocBackend.h"
35 #include "TextClass.h"
37 #include "frontends/alert.h"
38 #include "frontends/Painter.h"
40 #include "graphics/PreviewImage.h"
41 #include "graphics/PreviewLoader.h"
43 #include "insets/RenderPreview.h"
44 #include "insets/InsetListingsParams.h"
46 #include "support/docstream.h"
47 #include "support/filetools.h"
48 #include "support/lstrings.h" // contains
49 #include "support/lyxalgo.h"
50 #include "support/lyxlib.h"
51 #include "support/convert.h"
53 #include <boost/bind.hpp>
58 using support::addName;
59 using support::absolutePath;
60 using support::bformat;
61 using support::changeExtension;
62 using support::contains;
64 using support::DocFileName;
65 using support::FileName;
66 using support::getVectorFromString;
67 using support::isLyXFilename;
68 using support::isValidLaTeXFilename;
69 using support::latex_path;
70 using support::makeAbsPath;
71 using support::makeRelPath;
72 using support::onlyFilename;
73 using support::onlyPath;
74 using support::prefixIs;
79 using std::istringstream;
81 using std::ostringstream;
84 namespace Alert = frontend::Alert;
89 docstring const uniqueID()
91 static unsigned int seed = 1000;
92 return "file" + convert<docstring>(++seed);
96 /// the type of inclusion
98 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
102 Types type(std::string const & s)
106 if (s == "verbatiminput")
108 if (s == "verbatiminput*")
110 if (s == "lstinputlisting")
118 Types type(InsetCommandParams const & params)
120 return type(params.getCmdName());
124 bool isListings(InsetCommandParams const & params)
126 return type(params) == LISTINGS;
130 bool isVerbatim(InsetCommandParams const & params)
132 Types const t = type(params);
133 return t == VERB || t == VERBAST;
137 bool isInputOrInclude(InsetCommandParams const & params)
139 Types const t = type(params);
140 return t == INPUT || t == INCLUDE;
146 InsetInclude::InsetInclude(InsetCommandParams const & p)
147 : InsetCommand(p, "include"), include_label(uniqueID()),
148 preview_(new RenderMonitoredPreview(this)), set_label_(false)
150 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
154 InsetInclude::InsetInclude(InsetInclude const & other)
155 : InsetCommand(other), include_label(other.include_label),
156 preview_(new RenderMonitoredPreview(this)), set_label_(false)
158 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
162 CommandInfo const * InsetInclude::findInfo(std::string const & /* cmdName */)
165 // This is only correct for the case of listings, but it'll do for now.
166 // In the other cases, this second parameter should just be empty.
167 static const char * const paramnames[] = {"filename", "lstparams", ""};
168 static const bool isoptional[] = {false, true};
169 static const CommandInfo info = {2, paramnames, isoptional};
174 bool InsetInclude::isCompatibleCommand(std::string const & s)
176 return type(s) != NONE;
180 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
182 switch (cmd.action) {
184 case LFUN_INSET_MODIFY: {
185 InsetCommandParams p(INCLUDE_CODE);
186 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
187 if (!p.getCmdName().empty()) {
189 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
190 InsetListingsParams par_new(to_utf8(p["lstparams"]));
191 if (par_old.getParamValue("label") !=
192 par_new.getParamValue("label")
193 && !par_new.getParamValue("label").empty())
194 cur.bv().buffer().changeRefsIfUnique(
195 from_utf8(par_old.getParamValue("label")),
196 from_utf8(par_new.getParamValue("label")),
199 set(p, cur.buffer());
200 cur.buffer().updateBibfilesCache();
206 //pass everything else up the chain
208 InsetCommand::doDispatch(cur, cmd);
216 FileName const masterFileName(Buffer const & buffer)
218 return buffer.masterBuffer()->fileName();
222 string const parentFilename(Buffer const & buffer)
224 return buffer.absFileName();
228 FileName const includedFilename(Buffer const & buffer,
229 InsetCommandParams const & params)
231 return makeAbsPath(to_utf8(params["filename"]),
232 onlyPath(parentFilename(buffer)));
236 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
241 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
246 if (preview_->monitoring())
247 preview_->stopMonitoring();
249 if (type(params()) == INPUT)
250 add_preview(*preview_, *this, buffer);
254 Inset * InsetInclude::clone() const
256 return new InsetInclude(*this);
260 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
264 switch (type(params())) {
266 temp = buf.B_("Input");
269 temp = buf.B_("Verbatim Input");
272 temp = buf.B_("Verbatim Input*");
275 temp = buf.B_("Include");
278 temp = listings_label_;
286 if (params()["filename"].empty())
289 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
297 /// return the child buffer if the file is a LyX doc and is loaded
298 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
300 if (isVerbatim(params) || isListings(params))
303 string const included_file = includedFilename(buffer, params).absFilename();
304 if (!isLyXFilename(included_file))
307 Buffer * childBuffer = theBufferList().getBuffer(included_file);
309 //FIXME RECURSIVE INCLUDES
310 if (childBuffer == & buffer)
319 /// return true if the file is or got loaded.
320 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
322 if (isVerbatim(params) || isListings(params))
325 string const parent_filename = parent.absFileName();
326 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
327 onlyPath(parent_filename));
329 if (!isLyXFilename(included_file.absFilename()))
332 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
334 // the readonly flag can/will be wrong, not anymore I think.
335 if (!included_file.exists())
338 child = theBufferList().newBuffer(included_file.absFilename());
339 if (!child->loadLyXFile(included_file)) {
340 //close the buffer we just opened
341 theBufferList().release(child);
345 child->setParent(&parent);
350 void resetParentBuffer(Buffer const * parent, InsetCommandParams const & params,
353 if (isVerbatim(params) || isListings(params))
356 string const parent_filename = parent->absFileName();
357 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
358 onlyPath(parent_filename));
360 if (!isLyXFilename(included_file.absFilename()))
363 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
364 // File not opened, nothing to close.
368 // Child document has a different parent, don't close it.
369 if (child->parent() != parent)
375 theBufferList().release(child);
377 updateLabels(*child);
381 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
382 OutputParams const & runparams) const
384 string incfile(to_utf8(params()["filename"]));
386 // Do nothing if no file name has been specified
390 FileName const included_file = includedFilename(buffer, params());
392 //Check we're not trying to include ourselves.
393 //FIXME RECURSIVE INCLUDE
394 //This isn't sufficient, as the inclusion could be downstream.
395 //But it'll have to do for now.
396 if (isInputOrInclude(params()) &&
397 buffer.absFileName() == included_file.absFilename())
399 Alert::error(_("Recursive input"),
400 bformat(_("Attempted to include file %1$s in itself! "
401 "Ignoring inclusion."), from_utf8(incfile)));
405 Buffer const * const masterBuffer = buffer.masterBuffer();
407 // if incfile is relative, make it relative to the master
409 if (!absolutePath(incfile)) {
411 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
412 from_utf8(masterBuffer->filePath())));
415 // write it to a file (so far the complete file)
416 string const exportfile = changeExtension(incfile, ".tex");
417 string const mangled =
418 DocFileName(changeExtension(included_file.absFilename(),".tex")).
420 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
424 else if (!isValidLaTeXFilename(incfile)) {
425 frontend::Alert::warning(_("Invalid filename"),
426 _("The following filename is likely to cause trouble "
427 "when running the exported file through LaTeX: ") +
430 LYXERR(Debug::LATEX, "incfile:" << incfile);
431 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
432 LYXERR(Debug::LATEX, "writefile:" << writefile);
434 if (runparams.inComment || runparams.dryrun) {
435 //Don't try to load or copy the file if we're
436 //in a comment or doing a dryrun
437 } else if (isInputOrInclude(params()) &&
438 isLyXFilename(included_file.absFilename())) {
439 //if it's a LyX file and we're inputting or including,
440 //try to load it so we can write the associated latex
441 if (!loadIfNeeded(buffer, params()))
444 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
446 if (tmp->params().getBaseClass() != masterBuffer->params().getBaseClass()) {
448 docstring text = bformat(_("Included file `%1$s'\n"
449 "has textclass `%2$s'\n"
450 "while parent file has textclass `%3$s'."),
451 included_file.displayName(),
452 from_utf8(tmp->params().getTextClass().name()),
453 from_utf8(masterBuffer->params().getTextClass().name()));
454 Alert::warning(_("Different textclasses"), text);
458 // Make sure modules used in child are all included in master
459 //FIXME It might be worth loading the children's modules into the master
460 //over in BufferParams rather than doing this check.
461 vector<string> const masterModules = masterBuffer->params().getModules();
462 vector<string> const childModules = tmp->params().getModules();
463 vector<string>::const_iterator it = childModules.begin();
464 vector<string>::const_iterator end = childModules.end();
465 for (; it != end; ++it) {
466 string const module = *it;
467 vector<string>::const_iterator found =
468 find(masterModules.begin(), masterModules.end(), module);
469 if (found != masterModules.end()) {
470 docstring text = bformat(_("Included file `%1$s'\n"
471 "uses module `%2$s'\n"
472 "which is not used in parent file."),
473 included_file.displayName(), from_utf8(module));
474 Alert::warning(_("Module not found"), text);
478 tmp->markDepClean(masterBuffer->temppath());
480 // FIXME: handle non existing files
481 // FIXME: Second argument is irrelevant!
482 // since only_body is true, makeLaTeXFile will not look at second
483 // argument. Should we set it to string(), or should makeLaTeXFile
484 // make use of it somehow? (JMarc 20031002)
485 // The included file might be written in a different encoding
486 Encoding const * const oldEnc = runparams.encoding;
487 runparams.encoding = &tmp->params().encoding();
488 tmp->makeLaTeXFile(writefile,
489 masterFileName(buffer).onlyPath().absFilename(),
491 runparams.encoding = oldEnc;
493 // In this case, it's not a LyX file, so we copy the file
494 // to the temp dir, so that .aux files etc. are not created
495 // in the original dir. Files included by this file will be
496 // found via input@path, see ../Buffer.cpp.
497 unsigned long const checksum_in = included_file.checksum();
498 unsigned long const checksum_out = writefile.checksum();
500 if (checksum_in != checksum_out) {
501 if (!copy(included_file, writefile)) {
504 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
505 "into the temporary directory."),
506 from_utf8(included_file.absFilename()))));
512 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
513 "latex" : "pdflatex";
514 if (isVerbatim(params())) {
515 incfile = latex_path(incfile);
517 os << '\\' << from_ascii(params().getCmdName()) << '{'
518 << from_utf8(incfile) << '}';
519 } else if (type(params()) == INPUT) {
520 runparams.exportdata->addExternalFile(tex_format, writefile,
523 // \input wants file with extension (default is .tex)
524 if (!isLyXFilename(included_file.absFilename())) {
525 incfile = latex_path(incfile);
527 os << '\\' << from_ascii(params().getCmdName())
528 << '{' << from_utf8(incfile) << '}';
530 incfile = changeExtension(incfile, ".tex");
531 incfile = latex_path(incfile);
533 os << '\\' << from_ascii(params().getCmdName())
534 << '{' << from_utf8(incfile) << '}';
536 } else if (type(params()) == LISTINGS) {
537 os << '\\' << from_ascii(params().getCmdName());
538 string const opt = to_utf8(params()["lstparams"]);
539 // opt is set in QInclude dialog and should have passed validation.
540 InsetListingsParams params(opt);
541 if (!params.params().empty())
542 os << "[" << from_utf8(params.params()) << "]";
543 os << '{' << from_utf8(incfile) << '}';
545 runparams.exportdata->addExternalFile(tex_format, writefile,
548 // \include don't want extension and demands that the
549 // file really have .tex
550 incfile = changeExtension(incfile, string());
551 incfile = latex_path(incfile);
553 os << '\\' << from_ascii(params().getCmdName()) << '{'
554 << from_utf8(incfile) << '}';
561 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
562 OutputParams const &) const
564 if (isVerbatim(params()) || isListings(params())) {
565 os << '[' << getScreenLabel(buffer) << '\n';
566 // FIXME: We don't know the encoding of the file, default to UTF-8.
567 os << includedFilename(buffer, params()).fileContents("UTF-8");
569 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
571 docstring const str = '[' + getScreenLabel(buffer) + ']';
578 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
579 OutputParams const & runparams) const
581 string incfile = to_utf8(params()["filename"]);
583 // Do nothing if no file name has been specified
587 string const included_file = includedFilename(buffer, params()).absFilename();
589 //Check we're not trying to include ourselves.
590 //FIXME RECURSIVE INCLUDE
591 //This isn't sufficient, as the inclusion could be downstream.
592 //But it'll have to do for now.
593 if (buffer.absFileName() == included_file) {
594 Alert::error(_("Recursive input"),
595 bformat(_("Attempted to include file %1$s in itself! "
596 "Ignoring inclusion."), from_utf8(incfile)));
600 // write it to a file (so far the complete file)
601 string const exportfile = changeExtension(incfile, ".sgml");
602 DocFileName writefile(changeExtension(included_file, ".sgml"));
604 if (loadIfNeeded(buffer, params())) {
605 Buffer * tmp = theBufferList().getBuffer(included_file);
607 string const mangled = writefile.mangledFilename();
608 writefile = makeAbsPath(mangled,
609 buffer.masterBuffer()->temppath());
613 LYXERR(Debug::LATEX, "incfile:" << incfile);
614 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
615 LYXERR(Debug::LATEX, "writefile:" << writefile);
617 tmp->makeDocBookFile(writefile, runparams, true);
620 runparams.exportdata->addExternalFile("docbook", writefile,
622 runparams.exportdata->addExternalFile("docbook-xml", writefile,
625 if (isVerbatim(params()) || isListings(params())) {
626 os << "<inlinegraphic fileref=\""
627 << '&' << include_label << ';'
628 << "\" format=\"linespecific\">";
630 os << '&' << include_label << ';';
636 void InsetInclude::validate(LaTeXFeatures & features) const
638 string incfile = to_utf8(params()["filename"]);
641 Buffer const & buffer = features.buffer();
643 string const included_file = includedFilename(buffer, params()).absFilename();
645 if (isLyXFilename(included_file))
646 writefile = changeExtension(included_file, ".sgml");
648 writefile = included_file;
650 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
651 incfile = DocFileName(writefile).mangledFilename();
652 writefile = makeAbsPath(incfile,
653 buffer.masterBuffer()->temppath()).absFilename();
656 features.includeFile(include_label, writefile);
658 if (isVerbatim(params()))
659 features.require("verbatim");
660 else if (isListings(params()))
661 features.require("listings");
663 // Here we must do the fun stuff...
664 // Load the file in the include if it needs
666 if (loadIfNeeded(buffer, params())) {
668 Buffer * const tmp = theBufferList().getBuffer(included_file);
669 // make sure the buffer isn't us
670 // FIXME RECURSIVE INCLUDES
671 // This is not sufficient, as recursive includes could be
672 // more than a file away. But it will do for now.
673 if (tmp && tmp != & buffer) {
674 // We must temporarily change features.buffer,
675 // otherwise it would always be the master buffer,
676 // and nested includes would not work.
677 features.setBuffer(*tmp);
678 tmp->validate(features);
679 features.setBuffer(buffer);
685 void InsetInclude::getLabelList(Buffer const & buffer,
686 std::vector<docstring> & list) const
688 if (isListings(params())) {
689 InsetListingsParams p(to_utf8(params()["lstparams"]));
690 string label = p.getParamValue("label");
692 list.push_back(from_utf8(label));
694 else if (loadIfNeeded(buffer, params())) {
695 string const included_file = includedFilename(buffer, params()).absFilename();
696 Buffer * tmp = theBufferList().getBuffer(included_file);
698 tmp->getLabelList(list);
699 tmp->setParent(const_cast<Buffer *>(&buffer));
704 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
705 BiblioInfo & keys, InsetIterator const & /*di*/) const
707 if (loadIfNeeded(buffer, params())) {
708 string const included_file = includedFilename(buffer, params()).absFilename();
709 Buffer * tmp = theBufferList().getBuffer(included_file);
710 //FIXME This is kind of a dirty hack and should be made reasonable.
712 keys.fillWithBibKeys(tmp);
713 tmp->setParent(&buffer);
718 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
720 Buffer * const tmp = getChildBuffer(buffer, params());
723 tmp->updateBibfilesCache();
724 tmp->setParent(&buffer);
729 std::vector<FileName> const &
730 InsetInclude::getBibfilesCache(Buffer const & buffer) const
732 Buffer * const tmp = getChildBuffer(buffer, params());
735 std::vector<FileName> const & cache = tmp->getBibfilesCache();
736 tmp->setParent(&buffer);
739 static std::vector<FileName> const empty;
744 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
746 BOOST_ASSERT(mi.base.bv);
748 bool use_preview = false;
749 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
750 graphics::PreviewImage const * pimage =
751 preview_->getPreviewImage(mi.base.bv->buffer());
752 use_preview = pimage && pimage->image();
756 preview_->metrics(mi, dim);
760 button_.update(getScreenLabel(mi.base.bv->buffer()),
763 button_.metrics(mi, dim);
766 Box b(0, dim.wid, -dim.asc, dim.des);
771 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
773 BOOST_ASSERT(pi.base.bv);
775 bool use_preview = false;
776 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
777 graphics::PreviewImage const * pimage =
778 preview_->getPreviewImage(pi.base.bv->buffer());
779 use_preview = pimage && pimage->image();
783 preview_->draw(pi, x, y);
785 button_.draw(pi, x, y);
789 Inset::DisplayType InsetInclude::display() const
791 return type(params()) == INPUT ? Inline : AlignCenter;
800 void InsetInclude::fileChanged() const
802 Buffer const * const buffer = updateFrontend();
806 preview_->removePreview(*buffer);
807 add_preview(*preview_.get(), *this, *buffer);
808 preview_->startLoading(*buffer);
814 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
816 FileName const included_file = includedFilename(buffer, params);
818 return type(params) == INPUT && params.preview() &&
819 included_file.isReadableFile();
823 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
826 // We don't need to set runparams.encoding since this will be done
827 // by latex() anyway.
828 OutputParams runparams(0);
829 runparams.flavor = OutputParams::LATEX;
830 inset.latex(buffer, os, runparams);
836 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
837 Buffer const & buffer)
839 InsetCommandParams const & params = inset.params();
840 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
841 preview_wanted(params, buffer)) {
842 renderer.setAbsFile(includedFilename(buffer, params));
843 docstring const snippet = latex_string(inset, buffer);
844 renderer.addPreview(snippet, buffer);
851 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
853 Buffer const & buffer = ploader.buffer();
854 if (preview_wanted(params(), buffer)) {
855 preview_->setAbsFile(includedFilename(buffer, params()));
856 docstring const snippet = latex_string(*this, buffer);
857 preview_->addPreview(snippet, ploader);
862 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
863 ParConstIterator const & pit) const
865 if (isListings(params())) {
866 InsetListingsParams p(to_utf8(params()["lstparams"]));
867 string caption = p.getParamValue("caption");
870 Toc & toc = toclist["listing"];
871 docstring const str = convert<docstring>(toc.size() + 1)
872 + ". " + from_utf8(caption);
873 // This inset does not have a valid ParConstIterator
874 // so it has to use the iterator of its parent paragraph
875 toc.push_back(TocItem(pit, 0, str));
878 Buffer const * const childbuffer = getChildBuffer(buffer, params());
882 TocList const & childtoclist = childbuffer->tocBackend().tocs();
883 TocList::const_iterator it = childtoclist.begin();
884 TocList::const_iterator const end = childtoclist.end();
885 for(; it != end; ++it)
886 toclist[it->first].insert(toclist[it->first].end(),
887 it->second.begin(), it->second.end());
891 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
893 Buffer const * const childbuffer = getChildBuffer(buffer, params());
895 lyx::updateLabels(*childbuffer, true);
896 else if (isListings(params())) {
897 InsetListingsParams const par(to_utf8(params()["lstparams"]));
898 if (par.getParamValue("caption").empty())
899 listings_label_.clear();
901 Counters & counters = buffer.params().getTextClass().counters();
902 docstring const cnt = from_ascii("listing");
903 if (counters.hasCounter(cnt)) {
905 listings_label_ = buffer.B_("Program Listing ")
906 + convert<docstring>(counters.value(cnt));
908 listings_label_ = buffer.B_("Program Listing");
914 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
915 EmbeddedFiles & files) const
917 // include and input are temprarily not considered.
918 if (isVerbatim(params()) || isListings(params()))
919 files.registerFile(includedFilename(buffer, params()).absFilename(),