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/lyxlib.h"
52 #include "support/convert.h"
54 #include <boost/bind.hpp>
57 using namespace lyx::support;
61 namespace Alert = frontend::Alert;
66 docstring const uniqueID()
68 static unsigned int seed = 1000;
69 return "file" + convert<docstring>(++seed);
73 /// the type of inclusion
75 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
79 Types type(string const & s)
83 if (s == "verbatiminput")
85 if (s == "verbatiminput*")
87 if (s == "lstinputlisting")
95 Types type(InsetCommandParams const & params)
97 return type(params.getCmdName());
101 bool isListings(InsetCommandParams const & params)
103 return type(params) == LISTINGS;
107 bool isVerbatim(InsetCommandParams const & params)
109 Types const t = type(params);
110 return t == VERB || t == VERBAST;
114 bool isInputOrInclude(InsetCommandParams const & params)
116 Types const t = type(params);
117 return t == INPUT || t == INCLUDE;
123 InsetInclude::InsetInclude(InsetCommandParams const & p)
124 : InsetCommand(p, "include"), include_label(uniqueID()),
125 preview_(new RenderMonitoredPreview(this)), set_label_(false)
127 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
131 InsetInclude::InsetInclude(InsetInclude const & other)
132 : InsetCommand(other), include_label(other.include_label),
133 preview_(new RenderMonitoredPreview(this)), set_label_(false)
135 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
139 CommandInfo const * InsetInclude::findInfo(string const & /* cmdName */)
142 // This is only correct for the case of listings, but it'll do for now.
143 // In the other cases, this second parameter should just be empty.
144 static const char * const paramnames[] = {"filename", "lstparams", ""};
145 static const bool isoptional[] = {false, true};
146 static const CommandInfo info = {2, paramnames, isoptional};
151 bool InsetInclude::isCompatibleCommand(string const & s)
153 return type(s) != NONE;
157 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
159 switch (cmd.action) {
161 case LFUN_INSET_MODIFY: {
162 InsetCommandParams p(INCLUDE_CODE);
163 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
164 if (!p.getCmdName().empty()) {
166 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
167 InsetListingsParams par_new(to_utf8(p["lstparams"]));
168 if (par_old.getParamValue("label") !=
169 par_new.getParamValue("label")
170 && !par_new.getParamValue("label").empty())
171 cur.bv().buffer().changeRefsIfUnique(
172 from_utf8(par_old.getParamValue("label")),
173 from_utf8(par_new.getParamValue("label")),
176 set(p, cur.buffer());
177 cur.buffer().updateBibfilesCache();
183 //pass everything else up the chain
185 InsetCommand::doDispatch(cur, cmd);
193 FileName const masterFileName(Buffer const & buffer)
195 return buffer.masterBuffer()->fileName();
199 string const parentFilename(Buffer const & buffer)
201 return buffer.absFileName();
205 FileName const includedFilename(Buffer const & buffer,
206 InsetCommandParams const & params)
208 return makeAbsPath(to_utf8(params["filename"]),
209 onlyPath(parentFilename(buffer)));
213 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
218 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
223 if (preview_->monitoring())
224 preview_->stopMonitoring();
226 if (type(params()) == INPUT)
227 add_preview(*preview_, *this, buffer);
231 Inset * InsetInclude::clone() const
233 return new InsetInclude(*this);
237 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
241 switch (type(params())) {
243 temp = buf.B_("Input");
246 temp = buf.B_("Verbatim Input");
249 temp = buf.B_("Verbatim Input*");
252 temp = buf.B_("Include");
255 temp = listings_label_;
263 if (params()["filename"].empty())
266 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
274 /// return the child buffer if the file is a LyX doc and is loaded
275 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
277 if (isVerbatim(params) || isListings(params))
280 string const included_file = includedFilename(buffer, params).absFilename();
281 if (!isLyXFilename(included_file))
284 Buffer * childBuffer = theBufferList().getBuffer(included_file);
286 //FIXME RECURSIVE INCLUDES
287 if (childBuffer == & buffer)
296 /// return true if the file is or got loaded.
297 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
299 if (isVerbatim(params) || isListings(params))
302 string const parent_filename = parent.absFileName();
303 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
304 onlyPath(parent_filename));
306 if (!isLyXFilename(included_file.absFilename()))
309 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
311 // the readonly flag can/will be wrong, not anymore I think.
312 if (!included_file.exists())
315 child = theBufferList().newBuffer(included_file.absFilename());
316 if (!child->loadLyXFile(included_file)) {
317 //close the buffer we just opened
318 theBufferList().release(child);
322 child->setParent(&parent);
327 void resetParentBuffer(Buffer const * parent, InsetCommandParams const & params,
330 if (isVerbatim(params) || isListings(params))
333 string const parent_filename = parent->absFileName();
334 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
335 onlyPath(parent_filename));
337 if (!isLyXFilename(included_file.absFilename()))
340 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
341 // File not opened, nothing to close.
345 // Child document has a different parent, don't close it.
346 if (child->parent() != parent)
352 theBufferList().release(child);
354 updateLabels(*child);
358 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
359 OutputParams const & runparams) const
361 string incfile(to_utf8(params()["filename"]));
363 // Do nothing if no file name has been specified
367 FileName const included_file = includedFilename(buffer, params());
369 //Check we're not trying to include ourselves.
370 //FIXME RECURSIVE INCLUDE
371 //This isn't sufficient, as the inclusion could be downstream.
372 //But it'll have to do for now.
373 if (isInputOrInclude(params()) &&
374 buffer.absFileName() == included_file.absFilename())
376 Alert::error(_("Recursive input"),
377 bformat(_("Attempted to include file %1$s in itself! "
378 "Ignoring inclusion."), from_utf8(incfile)));
382 Buffer const * const masterBuffer = buffer.masterBuffer();
384 // if incfile is relative, make it relative to the master
386 if (!absolutePath(incfile)) {
388 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
389 from_utf8(masterBuffer->filePath())));
392 // write it to a file (so far the complete file)
393 string const exportfile = changeExtension(incfile, ".tex");
394 string const mangled =
395 DocFileName(changeExtension(included_file.absFilename(),".tex")).
397 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
401 else if (!isValidLaTeXFilename(incfile)) {
402 frontend::Alert::warning(_("Invalid filename"),
403 _("The following filename is likely to cause trouble "
404 "when running the exported file through LaTeX: ") +
407 LYXERR(Debug::LATEX, "incfile:" << incfile);
408 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
409 LYXERR(Debug::LATEX, "writefile:" << writefile);
411 if (runparams.inComment || runparams.dryrun) {
412 //Don't try to load or copy the file if we're
413 //in a comment or doing a dryrun
414 } else if (isInputOrInclude(params()) &&
415 isLyXFilename(included_file.absFilename())) {
416 //if it's a LyX file and we're inputting or including,
417 //try to load it so we can write the associated latex
418 if (!loadIfNeeded(buffer, params()))
421 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
423 if (tmp->params().getBaseClass() != masterBuffer->params().getBaseClass()) {
425 docstring text = bformat(_("Included file `%1$s'\n"
426 "has textclass `%2$s'\n"
427 "while parent file has textclass `%3$s'."),
428 included_file.displayName(),
429 from_utf8(tmp->params().getTextClass().name()),
430 from_utf8(masterBuffer->params().getTextClass().name()));
431 Alert::warning(_("Different textclasses"), text);
435 // Make sure modules used in child are all included in master
436 //FIXME It might be worth loading the children's modules into the master
437 //over in BufferParams rather than doing this check.
438 vector<string> const masterModules = masterBuffer->params().getModules();
439 vector<string> const childModules = tmp->params().getModules();
440 vector<string>::const_iterator it = childModules.begin();
441 vector<string>::const_iterator end = childModules.end();
442 for (; it != end; ++it) {
443 string const module = *it;
444 vector<string>::const_iterator found =
445 find(masterModules.begin(), masterModules.end(), module);
446 if (found != masterModules.end()) {
447 docstring text = bformat(_("Included file `%1$s'\n"
448 "uses module `%2$s'\n"
449 "which is not used in parent file."),
450 included_file.displayName(), from_utf8(module));
451 Alert::warning(_("Module not found"), text);
455 tmp->markDepClean(masterBuffer->temppath());
457 // FIXME: handle non existing files
458 // FIXME: Second argument is irrelevant!
459 // since only_body is true, makeLaTeXFile will not look at second
460 // argument. Should we set it to string(), or should makeLaTeXFile
461 // make use of it somehow? (JMarc 20031002)
462 // The included file might be written in a different encoding
463 Encoding const * const oldEnc = runparams.encoding;
464 runparams.encoding = &tmp->params().encoding();
465 tmp->makeLaTeXFile(writefile,
466 masterFileName(buffer).onlyPath().absFilename(),
468 runparams.encoding = oldEnc;
470 // In this case, it's not a LyX file, so we copy the file
471 // to the temp dir, so that .aux files etc. are not created
472 // in the original dir. Files included by this file will be
473 // found via input@path, see ../Buffer.cpp.
474 unsigned long const checksum_in = included_file.checksum();
475 unsigned long const checksum_out = writefile.checksum();
477 if (checksum_in != checksum_out) {
478 if (!included_file.copyTo(writefile)) {
481 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
482 "into the temporary directory."),
483 from_utf8(included_file.absFilename()))));
489 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
490 "latex" : "pdflatex";
491 if (isVerbatim(params())) {
492 incfile = latex_path(incfile);
494 os << '\\' << from_ascii(params().getCmdName()) << '{'
495 << from_utf8(incfile) << '}';
496 } else if (type(params()) == INPUT) {
497 runparams.exportdata->addExternalFile(tex_format, writefile,
500 // \input wants file with extension (default is .tex)
501 if (!isLyXFilename(included_file.absFilename())) {
502 incfile = latex_path(incfile);
504 os << '\\' << from_ascii(params().getCmdName())
505 << '{' << from_utf8(incfile) << '}';
507 incfile = changeExtension(incfile, ".tex");
508 incfile = latex_path(incfile);
510 os << '\\' << from_ascii(params().getCmdName())
511 << '{' << from_utf8(incfile) << '}';
513 } else if (type(params()) == LISTINGS) {
514 os << '\\' << from_ascii(params().getCmdName());
515 string const opt = to_utf8(params()["lstparams"]);
516 // opt is set in QInclude dialog and should have passed validation.
517 InsetListingsParams params(opt);
518 if (!params.params().empty())
519 os << "[" << from_utf8(params.params()) << "]";
520 os << '{' << from_utf8(incfile) << '}';
522 runparams.exportdata->addExternalFile(tex_format, writefile,
525 // \include don't want extension and demands that the
526 // file really have .tex
527 incfile = changeExtension(incfile, string());
528 incfile = latex_path(incfile);
530 os << '\\' << from_ascii(params().getCmdName()) << '{'
531 << from_utf8(incfile) << '}';
538 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
539 OutputParams const &) const
541 if (isVerbatim(params()) || isListings(params())) {
542 os << '[' << getScreenLabel(buffer) << '\n';
543 // FIXME: We don't know the encoding of the file, default to UTF-8.
544 os << includedFilename(buffer, params()).fileContents("UTF-8");
546 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
548 docstring const str = '[' + getScreenLabel(buffer) + ']';
555 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
556 OutputParams const & runparams) const
558 string incfile = to_utf8(params()["filename"]);
560 // Do nothing if no file name has been specified
564 string const included_file = includedFilename(buffer, params()).absFilename();
566 //Check we're not trying to include ourselves.
567 //FIXME RECURSIVE INCLUDE
568 //This isn't sufficient, as the inclusion could be downstream.
569 //But it'll have to do for now.
570 if (buffer.absFileName() == included_file) {
571 Alert::error(_("Recursive input"),
572 bformat(_("Attempted to include file %1$s in itself! "
573 "Ignoring inclusion."), from_utf8(incfile)));
577 // write it to a file (so far the complete file)
578 string const exportfile = changeExtension(incfile, ".sgml");
579 DocFileName writefile(changeExtension(included_file, ".sgml"));
581 if (loadIfNeeded(buffer, params())) {
582 Buffer * tmp = theBufferList().getBuffer(included_file);
584 string const mangled = writefile.mangledFilename();
585 writefile = makeAbsPath(mangled,
586 buffer.masterBuffer()->temppath());
590 LYXERR(Debug::LATEX, "incfile:" << incfile);
591 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
592 LYXERR(Debug::LATEX, "writefile:" << writefile);
594 tmp->makeDocBookFile(writefile, runparams, true);
597 runparams.exportdata->addExternalFile("docbook", writefile,
599 runparams.exportdata->addExternalFile("docbook-xml", writefile,
602 if (isVerbatim(params()) || isListings(params())) {
603 os << "<inlinegraphic fileref=\""
604 << '&' << include_label << ';'
605 << "\" format=\"linespecific\">";
607 os << '&' << include_label << ';';
613 void InsetInclude::validate(LaTeXFeatures & features) const
615 string incfile = to_utf8(params()["filename"]);
618 Buffer const & buffer = features.buffer();
620 string const included_file = includedFilename(buffer, params()).absFilename();
622 if (isLyXFilename(included_file))
623 writefile = changeExtension(included_file, ".sgml");
625 writefile = included_file;
627 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
628 incfile = DocFileName(writefile).mangledFilename();
629 writefile = makeAbsPath(incfile,
630 buffer.masterBuffer()->temppath()).absFilename();
633 features.includeFile(include_label, writefile);
635 if (isVerbatim(params()))
636 features.require("verbatim");
637 else if (isListings(params()))
638 features.require("listings");
640 // Here we must do the fun stuff...
641 // Load the file in the include if it needs
643 if (loadIfNeeded(buffer, params())) {
645 Buffer * const tmp = theBufferList().getBuffer(included_file);
646 // make sure the buffer isn't us
647 // FIXME RECURSIVE INCLUDES
648 // This is not sufficient, as recursive includes could be
649 // more than a file away. But it will do for now.
650 if (tmp && tmp != & buffer) {
651 // We must temporarily change features.buffer,
652 // otherwise it would always be the master buffer,
653 // and nested includes would not work.
654 features.setBuffer(*tmp);
655 tmp->validate(features);
656 features.setBuffer(buffer);
662 void InsetInclude::getLabelList(Buffer const & buffer,
663 vector<docstring> & list) const
665 if (isListings(params())) {
666 InsetListingsParams p(to_utf8(params()["lstparams"]));
667 string label = p.getParamValue("label");
669 list.push_back(from_utf8(label));
671 else if (loadIfNeeded(buffer, params())) {
672 string const included_file = includedFilename(buffer, params()).absFilename();
673 Buffer * tmp = theBufferList().getBuffer(included_file);
675 tmp->getLabelList(list);
676 tmp->setParent(const_cast<Buffer *>(&buffer));
681 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
682 BiblioInfo & keys, InsetIterator const & /*di*/) const
684 if (loadIfNeeded(buffer, params())) {
685 string const included_file = includedFilename(buffer, params()).absFilename();
686 Buffer * tmp = theBufferList().getBuffer(included_file);
687 //FIXME This is kind of a dirty hack and should be made reasonable.
689 keys.fillWithBibKeys(tmp);
690 tmp->setParent(&buffer);
695 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
697 Buffer * const tmp = getChildBuffer(buffer, params());
700 tmp->updateBibfilesCache();
701 tmp->setParent(&buffer);
707 InsetInclude::getBibfilesCache(Buffer const & buffer) const
709 Buffer * const tmp = getChildBuffer(buffer, params());
712 FileNameList const & cache = tmp->getBibfilesCache();
713 tmp->setParent(&buffer);
716 static FileNameList const empty;
721 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
723 BOOST_ASSERT(mi.base.bv);
725 bool use_preview = false;
726 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
727 graphics::PreviewImage const * pimage =
728 preview_->getPreviewImage(mi.base.bv->buffer());
729 use_preview = pimage && pimage->image();
733 preview_->metrics(mi, dim);
737 button_.update(getScreenLabel(mi.base.bv->buffer()),
740 button_.metrics(mi, dim);
743 Box b(0, dim.wid, -dim.asc, dim.des);
748 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
750 BOOST_ASSERT(pi.base.bv);
752 bool use_preview = false;
753 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
754 graphics::PreviewImage const * pimage =
755 preview_->getPreviewImage(pi.base.bv->buffer());
756 use_preview = pimage && pimage->image();
760 preview_->draw(pi, x, y);
762 button_.draw(pi, x, y);
766 Inset::DisplayType InsetInclude::display() const
768 return type(params()) == INPUT ? Inline : AlignCenter;
777 void InsetInclude::fileChanged() const
779 Buffer const * const buffer = updateFrontend();
783 preview_->removePreview(*buffer);
784 add_preview(*preview_.get(), *this, *buffer);
785 preview_->startLoading(*buffer);
791 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
793 FileName const included_file = includedFilename(buffer, params);
795 return type(params) == INPUT && params.preview() &&
796 included_file.isReadableFile();
800 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
803 // We don't need to set runparams.encoding since this will be done
804 // by latex() anyway.
805 OutputParams runparams(0);
806 runparams.flavor = OutputParams::LATEX;
807 inset.latex(buffer, os, runparams);
813 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
814 Buffer const & buffer)
816 InsetCommandParams const & params = inset.params();
817 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
818 preview_wanted(params, buffer)) {
819 renderer.setAbsFile(includedFilename(buffer, params));
820 docstring const snippet = latex_string(inset, buffer);
821 renderer.addPreview(snippet, buffer);
828 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
830 Buffer const & buffer = ploader.buffer();
831 if (preview_wanted(params(), buffer)) {
832 preview_->setAbsFile(includedFilename(buffer, params()));
833 docstring const snippet = latex_string(*this, buffer);
834 preview_->addPreview(snippet, ploader);
839 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
840 ParConstIterator const & pit) const
842 if (isListings(params())) {
843 InsetListingsParams p(to_utf8(params()["lstparams"]));
844 string caption = p.getParamValue("caption");
847 Toc & toc = toclist["listing"];
848 docstring const str = convert<docstring>(toc.size() + 1)
849 + ". " + from_utf8(caption);
850 // This inset does not have a valid ParConstIterator
851 // so it has to use the iterator of its parent paragraph
852 toc.push_back(TocItem(pit, 0, str));
855 Buffer const * const childbuffer = getChildBuffer(buffer, params());
859 TocList const & childtoclist = childbuffer->tocBackend().tocs();
860 TocList::const_iterator it = childtoclist.begin();
861 TocList::const_iterator const end = childtoclist.end();
862 for(; it != end; ++it)
863 toclist[it->first].insert(toclist[it->first].end(),
864 it->second.begin(), it->second.end());
868 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
870 Buffer const * const childbuffer = getChildBuffer(buffer, params());
872 lyx::updateLabels(*childbuffer, true);
873 else if (isListings(params())) {
874 InsetListingsParams const par(to_utf8(params()["lstparams"]));
875 if (par.getParamValue("caption").empty())
876 listings_label_.clear();
878 Counters & counters = buffer.params().getTextClass().counters();
879 docstring const cnt = from_ascii("listing");
880 if (counters.hasCounter(cnt)) {
882 listings_label_ = buffer.B_("Program Listing ")
883 + convert<docstring>(counters.value(cnt));
885 listings_label_ = buffer.B_("Program Listing");
891 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
892 EmbeddedFiles & files) const
894 // include and input are temprarily not considered.
895 if (isVerbatim(params()) || isListings(params()))
896 files.registerFile(includedFilename(buffer, params()).absFilename(),