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"
23 #include "DispatchResult.h"
25 #include "FuncRequest.h"
26 #include "FuncStatus.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;
81 using std::istringstream;
83 using std::ostringstream;
86 namespace Alert = frontend::Alert;
91 docstring const uniqueID()
93 static unsigned int seed = 1000;
94 return "file" + convert<docstring>(++seed);
98 /// the type of inclusion
100 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
104 Types type(std::string const & s)
108 if (s == "verbatiminput")
110 if (s == "verbatiminput*")
112 if (s == "lstinputlisting")
120 Types type(InsetCommandParams const & params)
122 return type(params.getCmdName());
126 bool isListings(InsetCommandParams const & params)
128 return type(params) == LISTINGS;
132 bool isVerbatim(InsetCommandParams const & params)
134 Types const t = type(params);
135 return t == VERB || t == VERBAST;
139 bool isInputOrInclude(InsetCommandParams const & params)
141 Types const t = type(params);
142 return t == INPUT || t == INCLUDE;
148 InsetInclude::InsetInclude(InsetCommandParams const & p)
149 : InsetCommand(p, "include"), include_label(uniqueID()),
150 preview_(new RenderMonitoredPreview(this)), set_label_(false)
152 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
156 InsetInclude::InsetInclude(InsetInclude const & other)
157 : InsetCommand(other), include_label(other.include_label),
158 preview_(new RenderMonitoredPreview(this)), set_label_(false)
160 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
164 CommandInfo const * InsetInclude::findInfo(std::string const & /* cmdName */)
166 // This is only correct for the case of listings, but it'll do for now.
167 // In the other cases, this second parameter should just be empty.
168 static const char * const paramnames[] = {"filename", "lstparams", ""};
169 static const bool isoptional[] = {false, true};
170 static const CommandInfo info = {2, paramnames, isoptional};
175 bool InsetInclude::isCompatibleCommand(std::string const & s)
177 return type(s) != NONE;
181 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
183 switch (cmd.action) {
185 case LFUN_INSET_MODIFY: {
186 InsetCommandParams p(INCLUDE_CODE);
187 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
188 if (!p.getCmdName().empty()) {
190 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
191 InsetListingsParams par_new(to_utf8(p["lstparams"]));
192 if (par_old.getParamValue("label") !=
193 par_new.getParamValue("label")
194 && !par_new.getParamValue("label").empty())
195 cur.bv().buffer().changeRefsIfUnique(
196 from_utf8(par_old.getParamValue("label")),
197 from_utf8(par_new.getParamValue("label")),
200 set(p, cur.buffer());
201 cur.buffer().updateBibfilesCache();
207 //pass everything else up the chain
209 InsetCommand::doDispatch(cur, cmd);
217 FileName const masterFileName(Buffer const & buffer)
219 return buffer.masterBuffer()->fileName();
223 string const parentFilename(Buffer const & buffer)
225 return buffer.absFileName();
229 FileName const includedFilename(Buffer const & buffer,
230 InsetCommandParams const & params)
232 return makeAbsPath(to_utf8(params["filename"]),
233 onlyPath(parentFilename(buffer)));
237 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
242 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
247 if (preview_->monitoring())
248 preview_->stopMonitoring();
250 if (type(params()) == INPUT)
251 add_preview(*preview_, *this, buffer);
255 Inset * InsetInclude::clone() const
257 return new InsetInclude(*this);
261 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
265 switch (type(params())) {
267 temp = buf.B_("Input");
270 temp = buf.B_("Verbatim Input");
273 temp = buf.B_("Verbatim Input*");
276 temp = buf.B_("Include");
279 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().close(child, false);
345 child->setParentName(parent_filename);
350 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
351 OutputParams const & runparams) const
353 string incfile(to_utf8(params()["filename"]));
355 // Do nothing if no file name has been specified
359 FileName const included_file = includedFilename(buffer, params());
361 //Check we're not trying to include ourselves.
362 //FIXME RECURSIVE INCLUDE
363 //This isn't sufficient, as the inclusion could be downstream.
364 //But it'll have to do for now.
365 if (isInputOrInclude(params()) &&
366 buffer.absFileName() == included_file.absFilename())
368 Alert::error(_("Recursive input"),
369 bformat(_("Attempted to include file %1$s in itself! "
370 "Ignoring inclusion."), from_utf8(incfile)));
374 Buffer const * const masterBuffer = buffer.masterBuffer();
376 // if incfile is relative, make it relative to the master
378 if (!absolutePath(incfile)) {
380 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
381 from_utf8(masterBuffer->filePath())));
384 // write it to a file (so far the complete file)
385 string const exportfile = changeExtension(incfile, ".tex");
386 string const mangled =
387 DocFileName(changeExtension(included_file.absFilename(),".tex")).
389 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
393 else if (!isValidLaTeXFilename(incfile)) {
394 frontend::Alert::warning(_("Invalid filename"),
395 _("The following filename is likely to cause trouble "
396 "when running the exported file through LaTeX: ") +
399 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
400 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
401 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
403 if (runparams.inComment || runparams.dryrun) {
404 //Don't try to load or copy the file if we're
405 //in a comment or doing a dryrun
406 } else if (isInputOrInclude(params()) &&
407 isLyXFilename(included_file.absFilename())) {
408 //if it's a LyX file and we're inputting or including,
409 //try to load it so we can write the associated latex
410 if (!loadIfNeeded(buffer, params()))
413 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
415 if (tmp->params().getBaseClass() != masterBuffer->params().getBaseClass()) {
417 docstring text = bformat(_("Included file `%1$s'\n"
418 "has textclass `%2$s'\n"
419 "while parent file has textclass `%3$s'."),
420 included_file.displayName(),
421 from_utf8(tmp->params().getTextClass().name()),
422 from_utf8(masterBuffer->params().getTextClass().name()));
423 Alert::warning(_("Different textclasses"), text);
427 // Make sure modules used in child are all included in master
428 //FIXME It might be worth loading the children's modules into the master
429 //over in BufferParams rather than doing this check.
430 vector<string> const masterModules = masterBuffer->params().getModules();
431 vector<string> const childModules = tmp->params().getModules();
432 vector<string>::const_iterator it = childModules.begin();
433 vector<string>::const_iterator end = childModules.end();
434 for (; it != end; ++it) {
435 string const module = *it;
436 vector<string>::const_iterator found =
437 find(masterModules.begin(), masterModules.end(), module);
438 if (found != masterModules.end()) {
439 docstring text = bformat(_("Included file `%1$s'\n"
440 "uses module `%2$s'\n"
441 "which is not used in parent file."),
442 included_file.displayName(), from_utf8(module));
443 Alert::warning(_("Module not found"), text);
447 tmp->markDepClean(masterBuffer->temppath());
449 // FIXME: handle non existing files
450 // FIXME: Second argument is irrelevant!
451 // since only_body is true, makeLaTeXFile will not look at second
452 // argument. Should we set it to string(), or should makeLaTeXFile
453 // make use of it somehow? (JMarc 20031002)
454 // The included file might be written in a different encoding
455 Encoding const * const oldEnc = runparams.encoding;
456 runparams.encoding = &tmp->params().encoding();
457 tmp->makeLaTeXFile(writefile,
458 masterFileName(buffer).onlyPath(),
460 runparams.encoding = oldEnc;
462 // In this case, it's not a LyX file, so we copy the file
463 // to the temp dir, so that .aux files etc. are not created
464 // in the original dir. Files included by this file will be
465 // found via input@path, see ../Buffer.cpp.
466 unsigned long const checksum_in = sum(included_file);
467 unsigned long const checksum_out = sum(writefile);
469 if (checksum_in != checksum_out) {
470 if (!copy(included_file, writefile)) {
473 << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
474 "into the temporary directory."),
475 from_utf8(included_file.absFilename())))
482 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
483 "latex" : "pdflatex";
484 if (isVerbatim(params())) {
485 incfile = latex_path(incfile);
487 os << '\\' << from_ascii(params().getCmdName()) << '{'
488 << from_utf8(incfile) << '}';
489 } else if (type(params()) == INPUT) {
490 runparams.exportdata->addExternalFile(tex_format, writefile,
493 // \input wants file with extension (default is .tex)
494 if (!isLyXFilename(included_file.absFilename())) {
495 incfile = latex_path(incfile);
497 os << '\\' << from_ascii(params().getCmdName())
498 << '{' << from_utf8(incfile) << '}';
500 incfile = changeExtension(incfile, ".tex");
501 incfile = latex_path(incfile);
503 os << '\\' << from_ascii(params().getCmdName())
504 << '{' << from_utf8(incfile) << '}';
506 } else if (type(params()) == LISTINGS) {
507 os << '\\' << from_ascii(params().getCmdName());
508 string const opt = to_utf8(params()["lstparams"]);
509 // opt is set in QInclude dialog and should have passed validation.
510 InsetListingsParams params(opt);
511 if (!params.params().empty())
512 os << "[" << from_utf8(params.params()) << "]";
513 os << '{' << from_utf8(incfile) << '}';
515 runparams.exportdata->addExternalFile(tex_format, writefile,
518 // \include don't want extension and demands that the
519 // file really have .tex
520 incfile = changeExtension(incfile, string());
521 incfile = latex_path(incfile);
523 os << '\\' << from_ascii(params().getCmdName()) << '{'
524 << from_utf8(incfile) << '}';
531 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
532 OutputParams const &) const
534 if (isVerbatim(params()) || isListings(params())) {
535 os << '[' << getScreenLabel(buffer) << '\n';
536 // FIXME: We don't know the encoding of the file
537 docstring const str =
538 from_utf8(includedFilename(buffer, params()).fileContents());
541 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
543 docstring const str = '[' + getScreenLabel(buffer) + ']';
550 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
551 OutputParams const & runparams) const
553 string incfile = to_utf8(params()["filename"]);
555 // Do nothing if no file name has been specified
559 string const included_file = includedFilename(buffer, params()).absFilename();
561 //Check we're not trying to include ourselves.
562 //FIXME RECURSIVE INCLUDE
563 //This isn't sufficient, as the inclusion could be downstream.
564 //But it'll have to do for now.
565 if (buffer.absFileName() == included_file) {
566 Alert::error(_("Recursive input"),
567 bformat(_("Attempted to include file %1$s in itself! "
568 "Ignoring inclusion."), from_utf8(incfile)));
572 // write it to a file (so far the complete file)
573 string const exportfile = changeExtension(incfile, ".sgml");
574 DocFileName writefile(changeExtension(included_file, ".sgml"));
576 if (loadIfNeeded(buffer, params())) {
577 Buffer * tmp = theBufferList().getBuffer(included_file);
579 string const mangled = writefile.mangledFilename();
580 writefile = makeAbsPath(mangled,
581 buffer.masterBuffer()->temppath());
585 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
586 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
587 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
589 tmp->makeDocBookFile(writefile, runparams, true);
592 runparams.exportdata->addExternalFile("docbook", writefile,
594 runparams.exportdata->addExternalFile("docbook-xml", writefile,
597 if (isVerbatim(params()) || isListings(params())) {
598 os << "<inlinegraphic fileref=\""
599 << '&' << include_label << ';'
600 << "\" format=\"linespecific\">";
602 os << '&' << include_label << ';';
608 void InsetInclude::validate(LaTeXFeatures & features) const
610 string incfile = to_utf8(params()["filename"]);
613 Buffer const & buffer = features.buffer();
615 string const included_file = includedFilename(buffer, params()).absFilename();
617 if (isLyXFilename(included_file))
618 writefile = changeExtension(included_file, ".sgml");
620 writefile = included_file;
622 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
623 incfile = DocFileName(writefile).mangledFilename();
624 writefile = makeAbsPath(incfile,
625 buffer.masterBuffer()->temppath()).absFilename();
628 features.includeFile(include_label, writefile);
630 if (isVerbatim(params()))
631 features.require("verbatim");
632 else if (isListings(params()))
633 features.require("listings");
635 // Here we must do the fun stuff...
636 // Load the file in the include if it needs
638 if (loadIfNeeded(buffer, params())) {
640 Buffer * const tmp = theBufferList().getBuffer(included_file);
641 // make sure the buffer isn't us
642 // FIXME RECURSIVE INCLUDES
643 // This is not sufficient, as recursive includes could be
644 // more than a file away. But it will do for now.
645 if (tmp && tmp != & buffer) {
646 // We must temporarily change features.buffer,
647 // otherwise it would always be the master buffer,
648 // and nested includes would not work.
649 features.setBuffer(*tmp);
650 tmp->validate(features);
651 features.setBuffer(buffer);
657 void InsetInclude::getLabelList(Buffer const & buffer,
658 std::vector<docstring> & list) const
660 if (isListings(params())) {
661 InsetListingsParams p(to_utf8(params()["lstparams"]));
662 string label = p.getParamValue("label");
664 list.push_back(from_utf8(label));
666 else if (loadIfNeeded(buffer, params())) {
667 string const included_file = includedFilename(buffer, params()).absFilename();
668 Buffer * tmp = theBufferList().getBuffer(included_file);
669 tmp->setParentName("");
670 tmp->getLabelList(list);
671 tmp->setParentName(parentFilename(buffer));
676 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
677 BiblioInfo & keys, InsetIterator const & /*di*/) const
679 if (loadIfNeeded(buffer, params())) {
680 string const included_file = includedFilename(buffer, params()).absFilename();
681 Buffer * tmp = theBufferList().getBuffer(included_file);
682 //FIXME This is kind of a dirty hack and should be made reasonable.
683 tmp->setParentName("");
684 keys.fillWithBibKeys(tmp);
685 tmp->setParentName(parentFilename(buffer));
690 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
692 Buffer * const tmp = getChildBuffer(buffer, params());
694 tmp->setParentName("");
695 tmp->updateBibfilesCache();
696 tmp->setParentName(parentFilename(buffer));
701 std::vector<FileName> const &
702 InsetInclude::getBibfilesCache(Buffer const & buffer) const
704 Buffer * const tmp = getChildBuffer(buffer, params());
706 tmp->setParentName("");
707 std::vector<FileName> const & cache = tmp->getBibfilesCache();
708 tmp->setParentName(parentFilename(buffer));
711 static std::vector<FileName> const empty;
716 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
718 BOOST_ASSERT(mi.base.bv);
720 bool use_preview = false;
721 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
722 graphics::PreviewImage const * pimage =
723 preview_->getPreviewImage(mi.base.bv->buffer());
724 use_preview = pimage && pimage->image();
728 preview_->metrics(mi, dim);
732 button_.update(getScreenLabel(mi.base.bv->buffer()),
735 button_.metrics(mi, dim);
738 Box b(0, dim.wid, -dim.asc, dim.des);
743 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
745 BOOST_ASSERT(pi.base.bv);
747 bool use_preview = false;
748 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
749 graphics::PreviewImage const * pimage =
750 preview_->getPreviewImage(pi.base.bv->buffer());
751 use_preview = pimage && pimage->image();
755 preview_->draw(pi, x, y);
757 button_.draw(pi, x, y);
761 Inset::DisplayType InsetInclude::display() const
763 return type(params()) == INPUT ? Inline : AlignCenter;
772 void InsetInclude::fileChanged() const
774 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
778 Buffer const & buffer = *buffer_ptr;
779 preview_->removePreview(buffer);
780 add_preview(*preview_.get(), *this, buffer);
781 preview_->startLoading(buffer);
787 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
789 FileName const included_file = includedFilename(buffer, params);
791 return type(params) == INPUT && params.preview() &&
792 included_file.isFileReadable();
796 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
799 // We don't need to set runparams.encoding since this will be done
800 // by latex() anyway.
801 OutputParams runparams(0);
802 runparams.flavor = OutputParams::LATEX;
803 inset.latex(buffer, os, runparams);
809 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
810 Buffer const & buffer)
812 InsetCommandParams const & params = inset.params();
813 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
814 preview_wanted(params, buffer)) {
815 renderer.setAbsFile(includedFilename(buffer, params));
816 docstring const snippet = latex_string(inset, buffer);
817 renderer.addPreview(snippet, buffer);
824 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
826 Buffer const & buffer = ploader.buffer();
827 if (preview_wanted(params(), buffer)) {
828 preview_->setAbsFile(includedFilename(buffer, params()));
829 docstring const snippet = latex_string(*this, buffer);
830 preview_->addPreview(snippet, ploader);
835 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
836 ParConstIterator const & pit) const
838 if (isListings(params())) {
839 InsetListingsParams p(to_utf8(params()["lstparams"]));
840 string caption = p.getParamValue("caption");
843 Toc & toc = toclist["listing"];
844 docstring const str = convert<docstring>(toc.size() + 1)
845 + ". " + from_utf8(caption);
846 // This inset does not have a valid ParConstIterator
847 // so it has to use the iterator of its parent paragraph
848 toc.push_back(TocItem(pit, 0, str));
851 Buffer const * const childbuffer = getChildBuffer(buffer, params());
855 TocList const & childtoclist = childbuffer->tocBackend().tocs();
856 TocList::const_iterator it = childtoclist.begin();
857 TocList::const_iterator const end = childtoclist.end();
858 for(; it != end; ++it)
859 toclist[it->first].insert(toclist[it->first].end(),
860 it->second.begin(), it->second.end());
864 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
866 Buffer const * const childbuffer = getChildBuffer(buffer, params());
868 lyx::updateLabels(*childbuffer, true);
869 else if (isListings(params())) {
870 InsetListingsParams const par(to_utf8(params()["lstparams"]));
871 if (par.getParamValue("caption").empty())
872 listings_label_.clear();
874 Counters & counters = buffer.params().getTextClass().counters();
875 docstring const cnt = from_ascii("listing");
876 if (counters.hasCounter(cnt)) {
878 listings_label_ = buffer.B_("Program Listing ")
879 + convert<docstring>(counters.value(cnt));
881 listings_label_ = buffer.B_("Program Listing");
887 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
888 EmbeddedFiles & files) const
890 // include and input are temprarily not considered.
891 if (isVerbatim(params()) || isListings(params()))
892 files.registerFile(includedFilename(buffer, params()).absFilename(),