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/FileNameList.h"
48 #include "support/filetools.h"
49 #include "support/lstrings.h" // contains
50 #include "support/lyxalgo.h"
51 #include "support/convert.h"
53 #include <boost/bind.hpp>
56 using namespace lyx::support;
60 namespace Alert = frontend::Alert;
65 docstring const uniqueID()
67 static unsigned int seed = 1000;
68 return "file" + convert<docstring>(++seed);
72 /// the type of inclusion
74 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
78 Types type(string const & s)
82 if (s == "verbatiminput")
84 if (s == "verbatiminput*")
86 if (s == "lstinputlisting")
94 Types type(InsetCommandParams const & params)
96 return type(params.getCmdName());
100 bool isListings(InsetCommandParams const & params)
102 return type(params) == LISTINGS;
106 bool isVerbatim(InsetCommandParams const & params)
108 Types const t = type(params);
109 return t == VERB || t == VERBAST;
113 bool isInputOrInclude(InsetCommandParams const & params)
115 Types const t = type(params);
116 return t == INPUT || t == INCLUDE;
122 InsetInclude::InsetInclude(InsetCommandParams const & p)
123 : InsetCommand(p, "include"), include_label(uniqueID()),
124 preview_(new RenderMonitoredPreview(this)), set_label_(false)
126 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
130 InsetInclude::InsetInclude(InsetInclude const & other)
131 : InsetCommand(other), include_label(other.include_label),
132 preview_(new RenderMonitoredPreview(this)), set_label_(false)
134 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
138 CommandInfo const * InsetInclude::findInfo(string const & /* cmdName */)
141 // This is only correct for the case of listings, but it'll do for now.
142 // In the other cases, this second parameter should just be empty.
143 static const char * const paramnames[] = {"filename", "lstparams", ""};
144 static const bool isoptional[] = {false, true};
145 static const CommandInfo info = {2, paramnames, isoptional};
150 bool InsetInclude::isCompatibleCommand(string const & s)
152 return type(s) != NONE;
156 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
158 switch (cmd.action) {
160 case LFUN_INSET_MODIFY: {
161 InsetCommandParams p(INCLUDE_CODE);
162 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
163 if (!p.getCmdName().empty()) {
165 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
166 InsetListingsParams par_new(to_utf8(p["lstparams"]));
167 if (par_old.getParamValue("label") !=
168 par_new.getParamValue("label")
169 && !par_new.getParamValue("label").empty())
170 cur.bv().buffer().changeRefsIfUnique(
171 from_utf8(par_old.getParamValue("label")),
172 from_utf8(par_new.getParamValue("label")),
175 set(p, cur.buffer());
176 cur.buffer().updateBibfilesCache();
182 //pass everything else up the chain
184 InsetCommand::doDispatch(cur, cmd);
192 FileName const masterFileName(Buffer const & buffer)
194 return buffer.masterBuffer()->fileName();
198 string const parentFilename(Buffer const & buffer)
200 return buffer.absFileName();
204 FileName const includedFilename(Buffer const & buffer,
205 InsetCommandParams const & params)
207 return makeAbsPath(to_utf8(params["filename"]),
208 onlyPath(parentFilename(buffer)));
212 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
217 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
222 if (preview_->monitoring())
223 preview_->stopMonitoring();
225 if (type(params()) == INPUT)
226 add_preview(*preview_, *this, buffer);
230 Inset * InsetInclude::clone() const
232 return new InsetInclude(*this);
236 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
240 switch (type(params())) {
242 temp = buf.B_("Input");
245 temp = buf.B_("Verbatim Input");
248 temp = buf.B_("Verbatim Input*");
251 temp = buf.B_("Include");
254 temp = listings_label_;
262 if (params()["filename"].empty())
265 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
273 /// return the child buffer if the file is a LyX doc and is loaded
274 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
276 if (isVerbatim(params) || isListings(params))
279 string const included_file = includedFilename(buffer, params).absFilename();
280 if (!isLyXFilename(included_file))
283 Buffer * childBuffer = theBufferList().getBuffer(included_file);
285 //FIXME RECURSIVE INCLUDES
286 if (childBuffer == & buffer)
295 /// return true if the file is or got loaded.
296 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
298 if (isVerbatim(params) || isListings(params))
301 string const parent_filename = parent.absFileName();
302 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
303 onlyPath(parent_filename));
305 if (!isLyXFilename(included_file.absFilename()))
308 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
310 // the readonly flag can/will be wrong, not anymore I think.
311 if (!included_file.exists())
314 child = theBufferList().newBuffer(included_file.absFilename());
316 // Buffer creation is not possible.
319 if (!child->loadLyXFile(included_file)) {
320 //close the buffer we just opened
321 theBufferList().release(child);
325 child->setParent(&parent);
330 void resetParentBuffer(Buffer const * parent, InsetCommandParams const & params,
333 if (isVerbatim(params) || isListings(params))
336 string const parent_filename = parent->absFileName();
337 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
338 onlyPath(parent_filename));
340 if (!isLyXFilename(included_file.absFilename()))
343 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
344 // File not opened, nothing to close.
348 // Child document has a different parent, don't close it.
349 if (child->parent() != parent)
355 theBufferList().release(child);
357 updateLabels(*child);
361 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
362 OutputParams const & runparams) const
364 string incfile(to_utf8(params()["filename"]));
366 // Do nothing if no file name has been specified
370 FileName const included_file = includedFilename(buffer, params());
372 //Check we're not trying to include ourselves.
373 //FIXME RECURSIVE INCLUDE
374 //This isn't sufficient, as the inclusion could be downstream.
375 //But it'll have to do for now.
376 if (isInputOrInclude(params()) &&
377 buffer.absFileName() == included_file.absFilename())
379 Alert::error(_("Recursive input"),
380 bformat(_("Attempted to include file %1$s in itself! "
381 "Ignoring inclusion."), from_utf8(incfile)));
385 Buffer const * const masterBuffer = buffer.masterBuffer();
387 // if incfile is relative, make it relative to the master
389 if (!FileName(incfile).isAbsolute()) {
391 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
392 from_utf8(masterBuffer->filePath())));
395 // write it to a file (so far the complete file)
396 string const exportfile = changeExtension(incfile, ".tex");
397 string const mangled =
398 DocFileName(changeExtension(included_file.absFilename(),".tex")).
400 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
404 else if (!isValidLaTeXFilename(incfile)) {
405 frontend::Alert::warning(_("Invalid filename"),
406 _("The following filename is likely to cause trouble "
407 "when running the exported file through LaTeX: ") +
410 LYXERR(Debug::LATEX, "incfile:" << incfile);
411 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
412 LYXERR(Debug::LATEX, "writefile:" << writefile);
414 if (runparams.inComment || runparams.dryrun) {
415 //Don't try to load or copy the file if we're
416 //in a comment or doing a dryrun
417 } else if (isInputOrInclude(params()) &&
418 isLyXFilename(included_file.absFilename())) {
419 //if it's a LyX file and we're inputting or including,
420 //try to load it so we can write the associated latex
421 if (!loadIfNeeded(buffer, params()))
424 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
426 if (tmp->params().getBaseClass() != masterBuffer->params().getBaseClass()) {
428 docstring text = bformat(_("Included file `%1$s'\n"
429 "has textclass `%2$s'\n"
430 "while parent file has textclass `%3$s'."),
431 included_file.displayName(),
432 from_utf8(tmp->params().getTextClass().name()),
433 from_utf8(masterBuffer->params().getTextClass().name()));
434 Alert::warning(_("Different textclasses"), text);
438 // Make sure modules used in child are all included in master
439 //FIXME It might be worth loading the children's modules into the master
440 //over in BufferParams rather than doing this check.
441 vector<string> const masterModules = masterBuffer->params().getModules();
442 vector<string> const childModules = tmp->params().getModules();
443 vector<string>::const_iterator it = childModules.begin();
444 vector<string>::const_iterator end = childModules.end();
445 for (; it != end; ++it) {
446 string const module = *it;
447 vector<string>::const_iterator found =
448 find(masterModules.begin(), masterModules.end(), module);
449 if (found != masterModules.end()) {
450 docstring text = bformat(_("Included file `%1$s'\n"
451 "uses module `%2$s'\n"
452 "which is not used in parent file."),
453 included_file.displayName(), from_utf8(module));
454 Alert::warning(_("Module not found"), text);
458 tmp->markDepClean(masterBuffer->temppath());
460 // FIXME: handle non existing files
461 // FIXME: Second argument is irrelevant!
462 // since only_body is true, makeLaTeXFile will not look at second
463 // argument. Should we set it to string(), or should makeLaTeXFile
464 // make use of it somehow? (JMarc 20031002)
465 // The included file might be written in a different encoding
466 Encoding const * const oldEnc = runparams.encoding;
467 runparams.encoding = &tmp->params().encoding();
468 tmp->makeLaTeXFile(writefile,
469 masterFileName(buffer).onlyPath().absFilename(),
471 runparams.encoding = oldEnc;
473 // In this case, it's not a LyX file, so we copy the file
474 // to the temp dir, so that .aux files etc. are not created
475 // in the original dir. Files included by this file will be
476 // found via input@path, see ../Buffer.cpp.
477 unsigned long const checksum_in = included_file.checksum();
478 unsigned long const checksum_out = writefile.checksum();
480 if (checksum_in != checksum_out) {
481 if (!included_file.copyTo(writefile)) {
484 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
485 "into the temporary directory."),
486 from_utf8(included_file.absFilename()))));
492 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
493 "latex" : "pdflatex";
494 if (isVerbatim(params())) {
495 incfile = latex_path(incfile);
497 os << '\\' << from_ascii(params().getCmdName()) << '{'
498 << from_utf8(incfile) << '}';
499 } else if (type(params()) == INPUT) {
500 runparams.exportdata->addExternalFile(tex_format, writefile,
503 // \input wants file with extension (default is .tex)
504 if (!isLyXFilename(included_file.absFilename())) {
505 incfile = latex_path(incfile);
507 os << '\\' << from_ascii(params().getCmdName())
508 << '{' << from_utf8(incfile) << '}';
510 incfile = changeExtension(incfile, ".tex");
511 incfile = latex_path(incfile);
513 os << '\\' << from_ascii(params().getCmdName())
514 << '{' << from_utf8(incfile) << '}';
516 } else if (type(params()) == LISTINGS) {
517 os << '\\' << from_ascii(params().getCmdName());
518 string const opt = to_utf8(params()["lstparams"]);
519 // opt is set in QInclude dialog and should have passed validation.
520 InsetListingsParams params(opt);
521 if (!params.params().empty())
522 os << "[" << from_utf8(params.params()) << "]";
523 os << '{' << from_utf8(incfile) << '}';
525 runparams.exportdata->addExternalFile(tex_format, writefile,
528 // \include don't want extension and demands that the
529 // file really have .tex
530 incfile = changeExtension(incfile, string());
531 incfile = latex_path(incfile);
533 os << '\\' << from_ascii(params().getCmdName()) << '{'
534 << from_utf8(incfile) << '}';
541 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
542 OutputParams const &) const
544 if (isVerbatim(params()) || isListings(params())) {
545 os << '[' << getScreenLabel(buffer) << '\n';
546 // FIXME: We don't know the encoding of the file, default to UTF-8.
547 os << includedFilename(buffer, params()).fileContents("UTF-8");
549 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
551 docstring const str = '[' + getScreenLabel(buffer) + ']';
558 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
559 OutputParams const & runparams) const
561 string incfile = to_utf8(params()["filename"]);
563 // Do nothing if no file name has been specified
567 string const included_file = includedFilename(buffer, params()).absFilename();
569 //Check we're not trying to include ourselves.
570 //FIXME RECURSIVE INCLUDE
571 //This isn't sufficient, as the inclusion could be downstream.
572 //But it'll have to do for now.
573 if (buffer.absFileName() == included_file) {
574 Alert::error(_("Recursive input"),
575 bformat(_("Attempted to include file %1$s in itself! "
576 "Ignoring inclusion."), from_utf8(incfile)));
580 // write it to a file (so far the complete file)
581 string const exportfile = changeExtension(incfile, ".sgml");
582 DocFileName writefile(changeExtension(included_file, ".sgml"));
584 if (loadIfNeeded(buffer, params())) {
585 Buffer * tmp = theBufferList().getBuffer(included_file);
587 string const mangled = writefile.mangledFilename();
588 writefile = makeAbsPath(mangled,
589 buffer.masterBuffer()->temppath());
593 LYXERR(Debug::LATEX, "incfile:" << incfile);
594 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
595 LYXERR(Debug::LATEX, "writefile:" << writefile);
597 tmp->makeDocBookFile(writefile, runparams, true);
600 runparams.exportdata->addExternalFile("docbook", writefile,
602 runparams.exportdata->addExternalFile("docbook-xml", writefile,
605 if (isVerbatim(params()) || isListings(params())) {
606 os << "<inlinegraphic fileref=\""
607 << '&' << include_label << ';'
608 << "\" format=\"linespecific\">";
610 os << '&' << include_label << ';';
616 void InsetInclude::validate(LaTeXFeatures & features) const
618 string incfile = to_utf8(params()["filename"]);
621 Buffer const & buffer = features.buffer();
623 string const included_file = includedFilename(buffer, params()).absFilename();
625 if (isLyXFilename(included_file))
626 writefile = changeExtension(included_file, ".sgml");
628 writefile = included_file;
630 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
631 incfile = DocFileName(writefile).mangledFilename();
632 writefile = makeAbsPath(incfile,
633 buffer.masterBuffer()->temppath()).absFilename();
636 features.includeFile(include_label, writefile);
638 if (isVerbatim(params()))
639 features.require("verbatim");
640 else if (isListings(params()))
641 features.require("listings");
643 // Here we must do the fun stuff...
644 // Load the file in the include if it needs
646 if (loadIfNeeded(buffer, params())) {
648 Buffer * const tmp = theBufferList().getBuffer(included_file);
649 // make sure the buffer isn't us
650 // FIXME RECURSIVE INCLUDES
651 // This is not sufficient, as recursive includes could be
652 // more than a file away. But it will do for now.
653 if (tmp && tmp != & buffer) {
654 // We must temporarily change features.buffer,
655 // otherwise it would always be the master buffer,
656 // and nested includes would not work.
657 features.setBuffer(*tmp);
658 tmp->validate(features);
659 features.setBuffer(buffer);
665 void InsetInclude::getLabelList(Buffer const & buffer,
666 vector<docstring> & list) const
668 if (isListings(params())) {
669 InsetListingsParams p(to_utf8(params()["lstparams"]));
670 string label = p.getParamValue("label");
672 list.push_back(from_utf8(label));
674 else if (loadIfNeeded(buffer, params())) {
675 string const included_file = includedFilename(buffer, params()).absFilename();
676 Buffer * tmp = theBufferList().getBuffer(included_file);
678 tmp->getLabelList(list);
679 tmp->setParent(const_cast<Buffer *>(&buffer));
684 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
685 BiblioInfo & keys, InsetIterator const & /*di*/) const
687 if (loadIfNeeded(buffer, params())) {
688 string const included_file = includedFilename(buffer, params()).absFilename();
689 Buffer * tmp = theBufferList().getBuffer(included_file);
690 //FIXME This is kind of a dirty hack and should be made reasonable.
692 keys.fillWithBibKeys(tmp);
693 tmp->setParent(&buffer);
698 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
700 Buffer * const tmp = getChildBuffer(buffer, params());
703 tmp->updateBibfilesCache();
704 tmp->setParent(&buffer);
710 InsetInclude::getBibfilesCache(Buffer const & buffer) const
712 Buffer * const tmp = getChildBuffer(buffer, params());
715 FileNameList const & cache = tmp->getBibfilesCache();
716 tmp->setParent(&buffer);
719 static FileNameList const empty;
724 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
726 BOOST_ASSERT(mi.base.bv);
728 bool use_preview = false;
729 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
730 graphics::PreviewImage const * pimage =
731 preview_->getPreviewImage(mi.base.bv->buffer());
732 use_preview = pimage && pimage->image();
736 preview_->metrics(mi, dim);
740 button_.update(getScreenLabel(mi.base.bv->buffer()),
743 button_.metrics(mi, dim);
746 Box b(0, dim.wid, -dim.asc, dim.des);
751 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
753 BOOST_ASSERT(pi.base.bv);
755 bool use_preview = false;
756 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
757 graphics::PreviewImage const * pimage =
758 preview_->getPreviewImage(pi.base.bv->buffer());
759 use_preview = pimage && pimage->image();
763 preview_->draw(pi, x, y);
765 button_.draw(pi, x, y);
769 Inset::DisplayType InsetInclude::display() const
771 return type(params()) == INPUT ? Inline : AlignCenter;
780 void InsetInclude::fileChanged() const
782 Buffer const * const buffer = updateFrontend();
786 preview_->removePreview(*buffer);
787 add_preview(*preview_.get(), *this, *buffer);
788 preview_->startLoading(*buffer);
794 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
796 FileName const included_file = includedFilename(buffer, params);
798 return type(params) == INPUT && params.preview() &&
799 included_file.isReadableFile();
803 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
806 // We don't need to set runparams.encoding since this will be done
807 // by latex() anyway.
808 OutputParams runparams(0);
809 runparams.flavor = OutputParams::LATEX;
810 inset.latex(buffer, os, runparams);
816 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
817 Buffer const & buffer)
819 InsetCommandParams const & params = inset.params();
820 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
821 preview_wanted(params, buffer)) {
822 renderer.setAbsFile(includedFilename(buffer, params));
823 docstring const snippet = latex_string(inset, buffer);
824 renderer.addPreview(snippet, buffer);
831 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
833 Buffer const & buffer = ploader.buffer();
834 if (preview_wanted(params(), buffer)) {
835 preview_->setAbsFile(includedFilename(buffer, params()));
836 docstring const snippet = latex_string(*this, buffer);
837 preview_->addPreview(snippet, ploader);
842 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
843 ParConstIterator const & pit) const
845 if (isListings(params())) {
846 InsetListingsParams p(to_utf8(params()["lstparams"]));
847 string caption = p.getParamValue("caption");
850 Toc & toc = toclist["listing"];
851 docstring const str = convert<docstring>(toc.size() + 1)
852 + ". " + from_utf8(caption);
853 // This inset does not have a valid ParConstIterator
854 // so it has to use the iterator of its parent paragraph
855 toc.push_back(TocItem(pit, 0, str));
858 Buffer const * const childbuffer = getChildBuffer(buffer, params());
862 TocList const & childtoclist = childbuffer->tocBackend().tocs();
863 TocList::const_iterator it = childtoclist.begin();
864 TocList::const_iterator const end = childtoclist.end();
865 for(; it != end; ++it)
866 toclist[it->first].insert(toclist[it->first].end(),
867 it->second.begin(), it->second.end());
871 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
873 Buffer const * const childbuffer = getChildBuffer(buffer, params());
875 lyx::updateLabels(*childbuffer, true);
876 else if (isListings(params())) {
877 InsetListingsParams const par(to_utf8(params()["lstparams"]));
878 if (par.getParamValue("caption").empty())
879 listings_label_.clear();
881 Counters & counters = buffer.params().getTextClass().counters();
882 docstring const cnt = from_ascii("listing");
883 if (counters.hasCounter(cnt)) {
885 listings_label_ = buffer.B_("Program Listing ")
886 + convert<docstring>(counters.value(cnt));
888 listings_label_ = buffer.B_("Program Listing");
894 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
895 EmbeddedFiles & files) const
897 // include and input are temprarily not considered.
898 if (isVerbatim(params()) || isListings(params()))
899 files.registerFile(includedFilename(buffer, params()).absFilename(),