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)
8 * \author Bo Peng (embedding stuff)
10 * Full author contact details are available in file CREDITS.
15 #include "InsetInclude.h"
17 #include "BaseClassList.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
24 #include "DispatchResult.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "LaTeXFeatures.h"
32 #include "MetricsInfo.h"
33 #include "OutputParams.h"
34 #include "TextClass.h"
35 #include "TocBackend.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/debug.h"
47 #include "support/docstream.h"
48 #include "support/ExceptionMessage.h"
49 #include "support/FileNameList.h"
50 #include "support/filetools.h"
51 #include "support/gettext.h"
52 #include "support/lstrings.h" // contains
53 #include "support/lyxalgo.h"
54 #include "support/convert.h"
56 #include <boost/bind.hpp>
59 using namespace lyx::support;
63 namespace Alert = frontend::Alert;
68 docstring const uniqueID()
70 static unsigned int seed = 1000;
71 return "file" + convert<docstring>(++seed);
75 /// the type of inclusion
77 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
81 Types type(string const & s)
85 if (s == "verbatiminput")
87 if (s == "verbatiminput*")
89 if (s == "lstinputlisting")
97 Types type(InsetCommandParams const & params)
99 return type(params.getCmdName());
103 bool isListings(InsetCommandParams const & params)
105 return type(params) == LISTINGS;
109 bool isVerbatim(InsetCommandParams const & params)
111 Types const t = type(params);
112 return t == VERB || t == VERBAST;
116 bool isInputOrInclude(InsetCommandParams const & params)
118 Types const t = type(params);
119 return t == INPUT || t == INCLUDE;
123 FileName const masterFileName(Buffer const & buffer)
125 return buffer.masterBuffer()->fileName();
129 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
132 string const parentFilename(Buffer const & buffer)
134 return buffer.absFileName();
138 EmbeddedFile const includedFilename(Buffer const & buffer,
139 InsetCommandParams const & params)
141 // it is not a good idea to create this EmbeddedFile object
142 // each time, but there seems to be no easy way around.
143 EmbeddedFile file(to_utf8(params["filename"]),
144 onlyPath(parentFilename(buffer)));
145 file.setEmbed(!params["embed"].empty());
146 file.enable(buffer.embedded(), &buffer);
153 InsetInclude::InsetInclude(InsetCommandParams const & p)
154 : InsetCommand(p, "include"), include_label(uniqueID()),
155 preview_(new RenderMonitoredPreview(this)), set_label_(false)
157 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
161 InsetInclude::InsetInclude(InsetInclude const & other)
162 : InsetCommand(other), include_label(other.include_label),
163 preview_(new RenderMonitoredPreview(this)), set_label_(false)
165 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
169 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
172 // This is only correct for the case of listings, but it'll do for now.
173 // In the other cases, this second parameter should just be empty.
174 static ParamInfo param_info_;
175 if (param_info_.empty()) {
176 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
177 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
178 param_info_.add("embed", ParamInfo::LYX_INTERNAL);
184 bool InsetInclude::isCompatibleCommand(string const & s)
186 return type(s) != NONE;
190 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
192 BOOST_ASSERT(&cur.buffer() == &buffer());
193 switch (cmd.action) {
195 case LFUN_INSET_MODIFY: {
196 InsetCommandParams p(INCLUDE_CODE);
197 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
198 if (!p.getCmdName().empty()) {
200 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
201 InsetListingsParams par_new(to_utf8(p["lstparams"]));
202 if (par_old.getParamValue("label") !=
203 par_new.getParamValue("label")
204 && !par_new.getParamValue("label").empty())
205 cur.bv().buffer().changeRefsIfUnique(
206 from_utf8(par_old.getParamValue("label")),
207 from_utf8(par_new.getParamValue("label")),
211 // the embed parameter passed back from the dialog
212 // is "true" or "false", we need to change it.
213 if (p["embed"] == _("false"))
216 p["embed"] = from_utf8(EmbeddedFile(to_utf8(p["filename"]),
217 onlyPath(parentFilename(cur.buffer()))).inzipName());
219 includedFilename(cur.buffer(), p);
220 } catch (ExceptionMessage const & message) {
221 Alert::error(message.title_, message.details_);
222 // do not set parameter if an error happens
226 buffer().updateBibfilesCache();
232 //pass everything else up the chain
234 InsetCommand::doDispatch(cur, cmd);
240 void InsetInclude::setParams(InsetCommandParams const & p)
242 InsetCommand::setParams(p);
245 if (preview_->monitoring())
246 preview_->stopMonitoring();
248 if (type(params()) == INPUT)
249 add_preview(*preview_, *this, buffer());
253 docstring InsetInclude::screenLabel() const
257 switch (type(params())) {
259 temp = buffer().B_("Input");
262 temp = buffer().B_("Verbatim Input");
265 temp = buffer().B_("Verbatim Input*");
268 temp = buffer().B_("Include");
271 temp = listings_label_;
279 if (params()["filename"].empty())
282 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
284 if (!params()["embed"].empty())
285 temp += _(" (embedded)");
290 /// return the child buffer if the file is a LyX doc and is loaded
291 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
293 if (isVerbatim(params) || isListings(params))
296 string const included_file = includedFilename(buffer, params).absFilename();
297 if (!isLyXFilename(included_file))
300 Buffer * childBuffer = theBufferList().getBuffer(included_file);
302 // FIXME: recursive includes
303 return (childBuffer == &buffer) ? 0 : childBuffer;
307 /// return true if the file is or got loaded.
308 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
310 if (isVerbatim(params) || isListings(params))
313 string const parent_filename = parent.absFileName();
314 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
315 onlyPath(parent_filename));
317 if (!isLyXFilename(included_file.absFilename()))
320 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
322 // the readonly flag can/will be wrong, not anymore I think.
323 if (!included_file.exists())
326 child = theBufferList().newBuffer(included_file.absFilename());
328 // Buffer creation is not possible.
331 if (!child->loadLyXFile(included_file)) {
332 //close the buffer we just opened
333 theBufferList().release(child);
337 child->setParent(&parent);
342 void resetParentBuffer(Buffer const * parent, InsetCommandParams const & params,
345 if (isVerbatim(params) || isListings(params))
348 string const parent_filename = parent->absFileName();
349 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
350 onlyPath(parent_filename));
352 if (!isLyXFilename(included_file.absFilename()))
355 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
356 // File not opened, nothing to close.
360 // Child document has a different parent, don't close it.
361 if (child->parent() != parent)
367 theBufferList().release(child);
369 updateLabels(*child);
373 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
375 string incfile = to_utf8(params()["filename"]);
377 // Do nothing if no file name has been specified
381 FileName const included_file =
382 includedFilename(buffer(), params()).availableFile();
384 // Check we're not trying to include ourselves.
385 // FIXME RECURSIVE INCLUDE
386 // This isn't sufficient, as the inclusion could be downstream.
387 // But it'll have to do for now.
388 if (isInputOrInclude(params()) &&
389 buffer().absFileName() == included_file.absFilename())
391 Alert::error(_("Recursive input"),
392 bformat(_("Attempted to include file %1$s in itself! "
393 "Ignoring inclusion."), from_utf8(incfile)));
397 Buffer const * const masterBuffer = buffer().masterBuffer();
399 // if incfile is relative, make it relative to the master
401 if (!FileName(incfile).isAbsolute()) {
403 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
404 from_utf8(masterBuffer->filePath())));
407 // write it to a file (so far the complete file)
408 string const exportfile = changeExtension(incfile, ".tex");
409 string const mangled =
410 DocFileName(changeExtension(included_file.absFilename(),".tex")).
412 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
416 else if (!isValidLaTeXFilename(incfile)) {
417 frontend::Alert::warning(_("Invalid filename"),
418 _("The following filename is likely to cause trouble "
419 "when running the exported file through LaTeX: ") +
422 LYXERR(Debug::LATEX, "incfile:" << incfile);
423 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
424 LYXERR(Debug::LATEX, "writefile:" << writefile);
426 if (runparams.inComment || runparams.dryrun) {
427 //Don't try to load or copy the file if we're
428 //in a comment or doing a dryrun
429 } else if (isInputOrInclude(params()) &&
430 isLyXFilename(included_file.absFilename())) {
431 //if it's a LyX file and we're inputting or including,
432 //try to load it so we can write the associated latex
433 if (!loadIfNeeded(buffer(), params()))
436 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
438 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
440 docstring text = bformat(_("Included file `%1$s'\n"
441 "has textclass `%2$s'\n"
442 "while parent file has textclass `%3$s'."),
443 included_file.displayName(),
444 from_utf8(tmp->params().documentClass().name()),
445 from_utf8(masterBuffer->params().documentClass().name()));
446 Alert::warning(_("Different textclasses"), text);
450 // Make sure modules used in child are all included in master
451 //FIXME It might be worth loading the children's modules into the master
452 //over in BufferParams rather than doing this check.
453 vector<string> const masterModules = masterBuffer->params().getModules();
454 vector<string> const childModules = tmp->params().getModules();
455 vector<string>::const_iterator it = childModules.begin();
456 vector<string>::const_iterator end = childModules.end();
457 for (; it != end; ++it) {
458 string const module = *it;
459 vector<string>::const_iterator found =
460 find(masterModules.begin(), masterModules.end(), module);
461 if (found != masterModules.end()) {
462 docstring text = bformat(_("Included file `%1$s'\n"
463 "uses module `%2$s'\n"
464 "which is not used in parent file."),
465 included_file.displayName(), from_utf8(module));
466 Alert::warning(_("Module not found"), text);
470 tmp->markDepClean(masterBuffer->temppath());
472 // FIXME: handle non existing files
473 // FIXME: Second argument is irrelevant!
474 // since only_body is true, makeLaTeXFile will not look at second
475 // argument. Should we set it to string(), or should makeLaTeXFile
476 // make use of it somehow? (JMarc 20031002)
477 // The included file might be written in a different encoding
478 Encoding const * const oldEnc = runparams.encoding;
479 runparams.encoding = &tmp->params().encoding();
480 tmp->makeLaTeXFile(writefile,
481 masterFileName(buffer()).onlyPath().absFilename(),
483 runparams.encoding = oldEnc;
485 // In this case, it's not a LyX file, so we copy the file
486 // to the temp dir, so that .aux files etc. are not created
487 // in the original dir. Files included by this file will be
488 // found via input@path, see ../Buffer.cpp.
489 unsigned long const checksum_in = included_file.checksum();
490 unsigned long const checksum_out = writefile.checksum();
492 if (checksum_in != checksum_out) {
493 if (!included_file.copyTo(writefile)) {
496 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
497 "into the temporary directory."),
498 from_utf8(included_file.absFilename()))));
504 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
505 "latex" : "pdflatex";
506 if (isVerbatim(params())) {
507 incfile = latex_path(incfile);
509 os << '\\' << from_ascii(params().getCmdName()) << '{'
510 << from_utf8(incfile) << '}';
511 } else if (type(params()) == INPUT) {
512 runparams.exportdata->addExternalFile(tex_format, writefile,
515 // \input wants file with extension (default is .tex)
516 if (!isLyXFilename(included_file.absFilename())) {
517 incfile = latex_path(incfile);
519 os << '\\' << from_ascii(params().getCmdName())
520 << '{' << from_utf8(incfile) << '}';
522 incfile = changeExtension(incfile, ".tex");
523 incfile = latex_path(incfile);
525 os << '\\' << from_ascii(params().getCmdName())
526 << '{' << from_utf8(incfile) << '}';
528 } else if (type(params()) == LISTINGS) {
529 os << '\\' << from_ascii(params().getCmdName());
530 string const opt = to_utf8(params()["lstparams"]);
531 // opt is set in QInclude dialog and should have passed validation.
532 InsetListingsParams params(opt);
533 if (!params.params().empty())
534 os << "[" << from_utf8(params.params()) << "]";
535 os << '{' << from_utf8(incfile) << '}';
537 runparams.exportdata->addExternalFile(tex_format, writefile,
540 // \include don't want extension and demands that the
541 // file really have .tex
542 incfile = changeExtension(incfile, string());
543 incfile = latex_path(incfile);
545 os << '\\' << from_ascii(params().getCmdName()) << '{'
546 << from_utf8(incfile) << '}';
553 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
555 if (isVerbatim(params()) || isListings(params())) {
556 os << '[' << screenLabel() << '\n';
557 // FIXME: We don't know the encoding of the file, default to UTF-8.
558 os << includedFilename(buffer(), params()).fileContents("UTF-8");
560 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
562 docstring const str = '[' + screenLabel() + ']';
569 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
571 string incfile = to_utf8(params()["filename"]);
573 // Do nothing if no file name has been specified
577 string const included_file = includedFilename(buffer(), params()).absFilename();
579 // Check we're not trying to include ourselves.
580 // FIXME RECURSIVE INCLUDE
581 // This isn't sufficient, as the inclusion could be downstream.
582 // But it'll have to do for now.
583 if (buffer().absFileName() == included_file) {
584 Alert::error(_("Recursive input"),
585 bformat(_("Attempted to include file %1$s in itself! "
586 "Ignoring inclusion."), from_utf8(incfile)));
590 // write it to a file (so far the complete file)
591 string const exportfile = changeExtension(incfile, ".sgml");
592 DocFileName writefile(changeExtension(included_file, ".sgml"));
594 if (loadIfNeeded(buffer(), params())) {
595 Buffer * tmp = theBufferList().getBuffer(included_file);
597 string const mangled = writefile.mangledFilename();
598 writefile = makeAbsPath(mangled,
599 buffer().masterBuffer()->temppath());
603 LYXERR(Debug::LATEX, "incfile:" << incfile);
604 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
605 LYXERR(Debug::LATEX, "writefile:" << writefile);
607 tmp->makeDocBookFile(writefile, runparams, true);
610 runparams.exportdata->addExternalFile("docbook", writefile,
612 runparams.exportdata->addExternalFile("docbook-xml", writefile,
615 if (isVerbatim(params()) || isListings(params())) {
616 os << "<inlinegraphic fileref=\""
617 << '&' << include_label << ';'
618 << "\" format=\"linespecific\">";
620 os << '&' << include_label << ';';
626 void InsetInclude::validate(LaTeXFeatures & features) const
628 string incfile = to_utf8(params()["filename"]);
631 BOOST_ASSERT(&buffer() == &features.buffer());
633 string const included_file =
634 includedFilename(buffer(), params()).availableFile().absFilename();
636 if (isLyXFilename(included_file))
637 writefile = changeExtension(included_file, ".sgml");
639 writefile = included_file;
641 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
642 incfile = DocFileName(writefile).mangledFilename();
643 writefile = makeAbsPath(incfile,
644 buffer().masterBuffer()->temppath()).absFilename();
647 features.includeFile(include_label, writefile);
649 if (isVerbatim(params()))
650 features.require("verbatim");
651 else if (isListings(params()))
652 features.require("listings");
654 // Here we must do the fun stuff...
655 // Load the file in the include if it needs
657 if (loadIfNeeded(buffer(), params())) {
659 Buffer * const tmp = theBufferList().getBuffer(included_file);
660 // make sure the buffer isn't us
661 // FIXME RECURSIVE INCLUDES
662 // This is not sufficient, as recursive includes could be
663 // more than a file away. But it will do for now.
664 if (tmp && tmp != &buffer()) {
665 // We must temporarily change features.buffer,
666 // otherwise it would always be the master buffer,
667 // and nested includes would not work.
668 features.setBuffer(*tmp);
669 tmp->validate(features);
670 features.setBuffer(buffer());
676 void InsetInclude::getLabelList(vector<docstring> & list) const
678 if (isListings(params())) {
679 InsetListingsParams p(to_utf8(params()["lstparams"]));
680 string label = p.getParamValue("label");
682 list.push_back(from_utf8(label));
684 else if (loadIfNeeded(buffer(), params())) {
685 string const included_file = includedFilename(buffer(), params()).absFilename();
686 Buffer * tmp = theBufferList().getBuffer(included_file);
688 tmp->getLabelList(list);
689 tmp->setParent(const_cast<Buffer *>(&buffer()));
694 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
695 InsetIterator const & /*di*/) const
697 if (loadIfNeeded(buffer(), params())) {
698 string const included_file = includedFilename(buffer(), params()).absFilename();
699 Buffer * tmp = theBufferList().getBuffer(included_file);
700 //FIXME This is kind of a dirty hack and should be made reasonable.
702 keys.fillWithBibKeys(tmp);
703 tmp->setParent(&buffer());
708 void InsetInclude::updateBibfilesCache()
710 Buffer * const tmp = getChildBuffer(buffer(), params());
713 tmp->updateBibfilesCache();
714 tmp->setParent(&buffer());
719 EmbeddedFileList const &
720 InsetInclude::getBibfilesCache(Buffer const & buffer) const
722 Buffer * const tmp = getChildBuffer(buffer, params());
725 EmbeddedFileList const & cache = tmp->getBibfilesCache();
726 tmp->setParent(&buffer);
729 static EmbeddedFileList const empty;
734 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
736 BOOST_ASSERT(mi.base.bv);
738 bool use_preview = false;
739 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
740 graphics::PreviewImage const * pimage =
741 preview_->getPreviewImage(mi.base.bv->buffer());
742 use_preview = pimage && pimage->image();
746 preview_->metrics(mi, dim);
750 button_.update(screenLabel(), true);
752 button_.metrics(mi, dim);
755 Box b(0, dim.wid, -dim.asc, dim.des);
760 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
762 BOOST_ASSERT(pi.base.bv);
764 bool use_preview = false;
765 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
766 graphics::PreviewImage const * pimage =
767 preview_->getPreviewImage(pi.base.bv->buffer());
768 use_preview = pimage && pimage->image();
772 preview_->draw(pi, x, y);
774 button_.draw(pi, x, y);
778 Inset::DisplayType InsetInclude::display() const
780 return type(params()) == INPUT ? Inline : AlignCenter;
789 void InsetInclude::fileChanged() const
791 Buffer const * const buffer = updateFrontend();
795 preview_->removePreview(*buffer);
796 add_preview(*preview_.get(), *this, *buffer);
797 preview_->startLoading(*buffer);
803 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
805 FileName const included_file = includedFilename(buffer, params);
807 return type(params) == INPUT && params.preview() &&
808 included_file.isReadableFile();
812 docstring latexString(InsetInclude const & inset)
815 // We don't need to set runparams.encoding since this will be done
816 // by latex() anyway.
817 OutputParams runparams(0);
818 runparams.flavor = OutputParams::LATEX;
819 inset.latex(os, runparams);
825 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
826 Buffer const & buffer)
828 InsetCommandParams const & params = inset.params();
829 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
830 preview_wanted(params, buffer)) {
831 renderer.setAbsFile(includedFilename(buffer, params));
832 docstring const snippet = latexString(inset);
833 renderer.addPreview(snippet, buffer);
840 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
842 Buffer const & buffer = ploader.buffer();
843 if (!preview_wanted(params(), buffer))
845 preview_->setAbsFile(includedFilename(buffer, params()));
846 docstring const snippet = latexString(*this);
847 preview_->addPreview(snippet, ploader);
851 void InsetInclude::addToToc(ParConstIterator const & cpit) const
853 if (isListings(params())) {
854 InsetListingsParams p(to_utf8(params()["lstparams"]));
855 string caption = p.getParamValue("caption");
858 Toc & toc = buffer().tocBackend().toc("listing");
859 docstring const str = convert<docstring>(toc.size() + 1)
860 + ". " + from_utf8(caption);
861 ParConstIterator pit = cpit;
862 pit.push_back(*this);
863 toc.push_back(TocItem(pit, 0, str));
866 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
870 TocList & toclist = buffer().tocBackend().tocs();
871 TocList const & childtoclist = childbuffer->tocBackend().tocs();
872 TocList::const_iterator it = childtoclist.begin();
873 TocList::const_iterator const end = childtoclist.end();
874 for(; it != end; ++it)
875 toclist[it->first].insert(toclist[it->first].end(),
876 it->second.begin(), it->second.end());
880 void InsetInclude::updateLabels(ParIterator const &)
882 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
884 lyx::updateLabels(*childbuffer, true);
887 if (!isListings(params()))
890 InsetListingsParams const par(to_utf8(params()["lstparams"]));
891 if (par.getParamValue("caption").empty()) {
892 listings_label_.clear();
895 Counters & counters = buffer().params().documentClass().counters();
896 docstring const cnt = from_ascii("listing");
897 listings_label_ = buffer().B_("Program Listing");
898 if (counters.hasCounter(cnt)) {
900 listings_label_ += " " + convert<docstring>(counters.value(cnt));
905 void InsetInclude::registerEmbeddedFiles(EmbeddedFileList & files) const
907 files.registerFile(includedFilename(buffer(), params()), this, buffer());
911 void InsetInclude::updateEmbeddedFile(EmbeddedFile const & file)
913 InsetCommandParams p = params();
914 p["filename"] = from_utf8(file.outputFilename());
915 p["embed"] = file.embedded() ? from_utf8(file.inzipName()) : docstring();