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>
59 using support::addName;
60 using support::absolutePath;
61 using support::bformat;
62 using support::changeExtension;
63 using support::contains;
65 using support::DocFileName;
66 using support::FileName;
67 using support::FileNameList;
68 using support::getVectorFromString;
69 using support::isLyXFilename;
70 using support::isValidLaTeXFilename;
71 using support::latex_path;
72 using support::makeAbsPath;
73 using support::makeRelPath;
74 using support::onlyFilename;
75 using support::onlyPath;
76 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 */)
167 // This is only correct for the case of listings, but it'll do for now.
168 // In the other cases, this second parameter should just be empty.
169 static const char * const paramnames[] = {"filename", "lstparams", ""};
170 static const bool isoptional[] = {false, true};
171 static const CommandInfo info = {2, paramnames, isoptional};
176 bool InsetInclude::isCompatibleCommand(std::string const & s)
178 return type(s) != NONE;
182 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
184 switch (cmd.action) {
186 case LFUN_INSET_MODIFY: {
187 InsetCommandParams p(INCLUDE_CODE);
188 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
189 if (!p.getCmdName().empty()) {
191 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
192 InsetListingsParams par_new(to_utf8(p["lstparams"]));
193 if (par_old.getParamValue("label") !=
194 par_new.getParamValue("label")
195 && !par_new.getParamValue("label").empty())
196 cur.bv().buffer().changeRefsIfUnique(
197 from_utf8(par_old.getParamValue("label")),
198 from_utf8(par_new.getParamValue("label")),
201 set(p, cur.buffer());
202 cur.buffer().updateBibfilesCache();
208 //pass everything else up the chain
210 InsetCommand::doDispatch(cur, cmd);
218 FileName const masterFileName(Buffer const & buffer)
220 return buffer.masterBuffer()->fileName();
224 string const parentFilename(Buffer const & buffer)
226 return buffer.absFileName();
230 FileName const includedFilename(Buffer const & buffer,
231 InsetCommandParams const & params)
233 return makeAbsPath(to_utf8(params["filename"]),
234 onlyPath(parentFilename(buffer)));
238 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
243 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
248 if (preview_->monitoring())
249 preview_->stopMonitoring();
251 if (type(params()) == INPUT)
252 add_preview(*preview_, *this, buffer);
256 Inset * InsetInclude::clone() const
258 return new InsetInclude(*this);
262 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
266 switch (type(params())) {
268 temp = buf.B_("Input");
271 temp = buf.B_("Verbatim Input");
274 temp = buf.B_("Verbatim Input*");
277 temp = buf.B_("Include");
280 temp = listings_label_;
288 if (params()["filename"].empty())
291 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
299 /// return the child buffer if the file is a LyX doc and is loaded
300 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
302 if (isVerbatim(params) || isListings(params))
305 string const included_file = includedFilename(buffer, params).absFilename();
306 if (!isLyXFilename(included_file))
309 Buffer * childBuffer = theBufferList().getBuffer(included_file);
311 //FIXME RECURSIVE INCLUDES
312 if (childBuffer == & buffer)
321 /// return true if the file is or got loaded.
322 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
324 if (isVerbatim(params) || isListings(params))
327 string const parent_filename = parent.absFileName();
328 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
329 onlyPath(parent_filename));
331 if (!isLyXFilename(included_file.absFilename()))
334 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
336 // the readonly flag can/will be wrong, not anymore I think.
337 if (!included_file.exists())
340 child = theBufferList().newBuffer(included_file.absFilename());
341 if (!child->loadLyXFile(included_file)) {
342 //close the buffer we just opened
343 theBufferList().release(child);
347 child->setParent(&parent);
352 void resetParentBuffer(Buffer const * parent, InsetCommandParams const & params,
355 if (isVerbatim(params) || isListings(params))
358 string const parent_filename = parent->absFileName();
359 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
360 onlyPath(parent_filename));
362 if (!isLyXFilename(included_file.absFilename()))
365 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
366 // File not opened, nothing to close.
370 // Child document has a different parent, don't close it.
371 if (child->parent() != parent)
377 theBufferList().release(child);
379 updateLabels(*child);
383 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
384 OutputParams const & runparams) const
386 string incfile(to_utf8(params()["filename"]));
388 // Do nothing if no file name has been specified
392 FileName const included_file = includedFilename(buffer, params());
394 //Check we're not trying to include ourselves.
395 //FIXME RECURSIVE INCLUDE
396 //This isn't sufficient, as the inclusion could be downstream.
397 //But it'll have to do for now.
398 if (isInputOrInclude(params()) &&
399 buffer.absFileName() == included_file.absFilename())
401 Alert::error(_("Recursive input"),
402 bformat(_("Attempted to include file %1$s in itself! "
403 "Ignoring inclusion."), from_utf8(incfile)));
407 Buffer const * const masterBuffer = buffer.masterBuffer();
409 // if incfile is relative, make it relative to the master
411 if (!absolutePath(incfile)) {
413 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
414 from_utf8(masterBuffer->filePath())));
417 // write it to a file (so far the complete file)
418 string const exportfile = changeExtension(incfile, ".tex");
419 string const mangled =
420 DocFileName(changeExtension(included_file.absFilename(),".tex")).
422 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
426 else if (!isValidLaTeXFilename(incfile)) {
427 frontend::Alert::warning(_("Invalid filename"),
428 _("The following filename is likely to cause trouble "
429 "when running the exported file through LaTeX: ") +
432 LYXERR(Debug::LATEX, "incfile:" << incfile);
433 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
434 LYXERR(Debug::LATEX, "writefile:" << writefile);
436 if (runparams.inComment || runparams.dryrun) {
437 //Don't try to load or copy the file if we're
438 //in a comment or doing a dryrun
439 } else if (isInputOrInclude(params()) &&
440 isLyXFilename(included_file.absFilename())) {
441 //if it's a LyX file and we're inputting or including,
442 //try to load it so we can write the associated latex
443 if (!loadIfNeeded(buffer, params()))
446 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
448 if (tmp->params().getBaseClass() != masterBuffer->params().getBaseClass()) {
450 docstring text = bformat(_("Included file `%1$s'\n"
451 "has textclass `%2$s'\n"
452 "while parent file has textclass `%3$s'."),
453 included_file.displayName(),
454 from_utf8(tmp->params().getTextClass().name()),
455 from_utf8(masterBuffer->params().getTextClass().name()));
456 Alert::warning(_("Different textclasses"), text);
460 // Make sure modules used in child are all included in master
461 //FIXME It might be worth loading the children's modules into the master
462 //over in BufferParams rather than doing this check.
463 vector<string> const masterModules = masterBuffer->params().getModules();
464 vector<string> const childModules = tmp->params().getModules();
465 vector<string>::const_iterator it = childModules.begin();
466 vector<string>::const_iterator end = childModules.end();
467 for (; it != end; ++it) {
468 string const module = *it;
469 vector<string>::const_iterator found =
470 find(masterModules.begin(), masterModules.end(), module);
471 if (found != masterModules.end()) {
472 docstring text = bformat(_("Included file `%1$s'\n"
473 "uses module `%2$s'\n"
474 "which is not used in parent file."),
475 included_file.displayName(), from_utf8(module));
476 Alert::warning(_("Module not found"), text);
480 tmp->markDepClean(masterBuffer->temppath());
482 // FIXME: handle non existing files
483 // FIXME: Second argument is irrelevant!
484 // since only_body is true, makeLaTeXFile will not look at second
485 // argument. Should we set it to string(), or should makeLaTeXFile
486 // make use of it somehow? (JMarc 20031002)
487 // The included file might be written in a different encoding
488 Encoding const * const oldEnc = runparams.encoding;
489 runparams.encoding = &tmp->params().encoding();
490 tmp->makeLaTeXFile(writefile,
491 masterFileName(buffer).onlyPath().absFilename(),
493 runparams.encoding = oldEnc;
495 // In this case, it's not a LyX file, so we copy the file
496 // to the temp dir, so that .aux files etc. are not created
497 // in the original dir. Files included by this file will be
498 // found via input@path, see ../Buffer.cpp.
499 unsigned long const checksum_in = included_file.checksum();
500 unsigned long const checksum_out = writefile.checksum();
502 if (checksum_in != checksum_out) {
503 if (!copy(included_file, writefile)) {
506 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
507 "into the temporary directory."),
508 from_utf8(included_file.absFilename()))));
514 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
515 "latex" : "pdflatex";
516 if (isVerbatim(params())) {
517 incfile = latex_path(incfile);
519 os << '\\' << from_ascii(params().getCmdName()) << '{'
520 << from_utf8(incfile) << '}';
521 } else if (type(params()) == INPUT) {
522 runparams.exportdata->addExternalFile(tex_format, writefile,
525 // \input wants file with extension (default is .tex)
526 if (!isLyXFilename(included_file.absFilename())) {
527 incfile = latex_path(incfile);
529 os << '\\' << from_ascii(params().getCmdName())
530 << '{' << from_utf8(incfile) << '}';
532 incfile = changeExtension(incfile, ".tex");
533 incfile = latex_path(incfile);
535 os << '\\' << from_ascii(params().getCmdName())
536 << '{' << from_utf8(incfile) << '}';
538 } else if (type(params()) == LISTINGS) {
539 os << '\\' << from_ascii(params().getCmdName());
540 string const opt = to_utf8(params()["lstparams"]);
541 // opt is set in QInclude dialog and should have passed validation.
542 InsetListingsParams params(opt);
543 if (!params.params().empty())
544 os << "[" << from_utf8(params.params()) << "]";
545 os << '{' << from_utf8(incfile) << '}';
547 runparams.exportdata->addExternalFile(tex_format, writefile,
550 // \include don't want extension and demands that the
551 // file really have .tex
552 incfile = changeExtension(incfile, string());
553 incfile = latex_path(incfile);
555 os << '\\' << from_ascii(params().getCmdName()) << '{'
556 << from_utf8(incfile) << '}';
563 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
564 OutputParams const &) const
566 if (isVerbatim(params()) || isListings(params())) {
567 os << '[' << getScreenLabel(buffer) << '\n';
568 // FIXME: We don't know the encoding of the file, default to UTF-8.
569 os << includedFilename(buffer, params()).fileContents("UTF-8");
571 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
573 docstring const str = '[' + getScreenLabel(buffer) + ']';
580 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
581 OutputParams const & runparams) const
583 string incfile = to_utf8(params()["filename"]);
585 // Do nothing if no file name has been specified
589 string const included_file = includedFilename(buffer, params()).absFilename();
591 //Check we're not trying to include ourselves.
592 //FIXME RECURSIVE INCLUDE
593 //This isn't sufficient, as the inclusion could be downstream.
594 //But it'll have to do for now.
595 if (buffer.absFileName() == included_file) {
596 Alert::error(_("Recursive input"),
597 bformat(_("Attempted to include file %1$s in itself! "
598 "Ignoring inclusion."), from_utf8(incfile)));
602 // write it to a file (so far the complete file)
603 string const exportfile = changeExtension(incfile, ".sgml");
604 DocFileName writefile(changeExtension(included_file, ".sgml"));
606 if (loadIfNeeded(buffer, params())) {
607 Buffer * tmp = theBufferList().getBuffer(included_file);
609 string const mangled = writefile.mangledFilename();
610 writefile = makeAbsPath(mangled,
611 buffer.masterBuffer()->temppath());
615 LYXERR(Debug::LATEX, "incfile:" << incfile);
616 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
617 LYXERR(Debug::LATEX, "writefile:" << writefile);
619 tmp->makeDocBookFile(writefile, runparams, true);
622 runparams.exportdata->addExternalFile("docbook", writefile,
624 runparams.exportdata->addExternalFile("docbook-xml", writefile,
627 if (isVerbatim(params()) || isListings(params())) {
628 os << "<inlinegraphic fileref=\""
629 << '&' << include_label << ';'
630 << "\" format=\"linespecific\">";
632 os << '&' << include_label << ';';
638 void InsetInclude::validate(LaTeXFeatures & features) const
640 string incfile = to_utf8(params()["filename"]);
643 Buffer const & buffer = features.buffer();
645 string const included_file = includedFilename(buffer, params()).absFilename();
647 if (isLyXFilename(included_file))
648 writefile = changeExtension(included_file, ".sgml");
650 writefile = included_file;
652 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
653 incfile = DocFileName(writefile).mangledFilename();
654 writefile = makeAbsPath(incfile,
655 buffer.masterBuffer()->temppath()).absFilename();
658 features.includeFile(include_label, writefile);
660 if (isVerbatim(params()))
661 features.require("verbatim");
662 else if (isListings(params()))
663 features.require("listings");
665 // Here we must do the fun stuff...
666 // Load the file in the include if it needs
668 if (loadIfNeeded(buffer, params())) {
670 Buffer * const tmp = theBufferList().getBuffer(included_file);
671 // make sure the buffer isn't us
672 // FIXME RECURSIVE INCLUDES
673 // This is not sufficient, as recursive includes could be
674 // more than a file away. But it will do for now.
675 if (tmp && tmp != & buffer) {
676 // We must temporarily change features.buffer,
677 // otherwise it would always be the master buffer,
678 // and nested includes would not work.
679 features.setBuffer(*tmp);
680 tmp->validate(features);
681 features.setBuffer(buffer);
687 void InsetInclude::getLabelList(Buffer const & buffer,
688 std::vector<docstring> & list) const
690 if (isListings(params())) {
691 InsetListingsParams p(to_utf8(params()["lstparams"]));
692 string label = p.getParamValue("label");
694 list.push_back(from_utf8(label));
696 else if (loadIfNeeded(buffer, params())) {
697 string const included_file = includedFilename(buffer, params()).absFilename();
698 Buffer * tmp = theBufferList().getBuffer(included_file);
700 tmp->getLabelList(list);
701 tmp->setParent(const_cast<Buffer *>(&buffer));
706 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
707 BiblioInfo & keys, InsetIterator const & /*di*/) const
709 if (loadIfNeeded(buffer, params())) {
710 string const included_file = includedFilename(buffer, params()).absFilename();
711 Buffer * tmp = theBufferList().getBuffer(included_file);
712 //FIXME This is kind of a dirty hack and should be made reasonable.
714 keys.fillWithBibKeys(tmp);
715 tmp->setParent(&buffer);
720 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
722 Buffer * const tmp = getChildBuffer(buffer, params());
725 tmp->updateBibfilesCache();
726 tmp->setParent(&buffer);
732 InsetInclude::getBibfilesCache(Buffer const & buffer) const
734 Buffer * const tmp = getChildBuffer(buffer, params());
737 FileNameList const & cache = tmp->getBibfilesCache();
738 tmp->setParent(&buffer);
741 static FileNameList const empty;
746 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
748 BOOST_ASSERT(mi.base.bv);
750 bool use_preview = false;
751 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
752 graphics::PreviewImage const * pimage =
753 preview_->getPreviewImage(mi.base.bv->buffer());
754 use_preview = pimage && pimage->image();
758 preview_->metrics(mi, dim);
762 button_.update(getScreenLabel(mi.base.bv->buffer()),
765 button_.metrics(mi, dim);
768 Box b(0, dim.wid, -dim.asc, dim.des);
773 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
775 BOOST_ASSERT(pi.base.bv);
777 bool use_preview = false;
778 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
779 graphics::PreviewImage const * pimage =
780 preview_->getPreviewImage(pi.base.bv->buffer());
781 use_preview = pimage && pimage->image();
785 preview_->draw(pi, x, y);
787 button_.draw(pi, x, y);
791 Inset::DisplayType InsetInclude::display() const
793 return type(params()) == INPUT ? Inline : AlignCenter;
802 void InsetInclude::fileChanged() const
804 Buffer const * const buffer = updateFrontend();
808 preview_->removePreview(*buffer);
809 add_preview(*preview_.get(), *this, *buffer);
810 preview_->startLoading(*buffer);
816 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
818 FileName const included_file = includedFilename(buffer, params);
820 return type(params) == INPUT && params.preview() &&
821 included_file.isReadableFile();
825 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
828 // We don't need to set runparams.encoding since this will be done
829 // by latex() anyway.
830 OutputParams runparams(0);
831 runparams.flavor = OutputParams::LATEX;
832 inset.latex(buffer, os, runparams);
838 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
839 Buffer const & buffer)
841 InsetCommandParams const & params = inset.params();
842 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
843 preview_wanted(params, buffer)) {
844 renderer.setAbsFile(includedFilename(buffer, params));
845 docstring const snippet = latex_string(inset, buffer);
846 renderer.addPreview(snippet, buffer);
853 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
855 Buffer const & buffer = ploader.buffer();
856 if (preview_wanted(params(), buffer)) {
857 preview_->setAbsFile(includedFilename(buffer, params()));
858 docstring const snippet = latex_string(*this, buffer);
859 preview_->addPreview(snippet, ploader);
864 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
865 ParConstIterator const & pit) const
867 if (isListings(params())) {
868 InsetListingsParams p(to_utf8(params()["lstparams"]));
869 string caption = p.getParamValue("caption");
872 Toc & toc = toclist["listing"];
873 docstring const str = convert<docstring>(toc.size() + 1)
874 + ". " + from_utf8(caption);
875 // This inset does not have a valid ParConstIterator
876 // so it has to use the iterator of its parent paragraph
877 toc.push_back(TocItem(pit, 0, str));
880 Buffer const * const childbuffer = getChildBuffer(buffer, params());
884 TocList const & childtoclist = childbuffer->tocBackend().tocs();
885 TocList::const_iterator it = childtoclist.begin();
886 TocList::const_iterator const end = childtoclist.end();
887 for(; it != end; ++it)
888 toclist[it->first].insert(toclist[it->first].end(),
889 it->second.begin(), it->second.end());
893 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
895 Buffer const * const childbuffer = getChildBuffer(buffer, params());
897 lyx::updateLabels(*childbuffer, true);
898 else if (isListings(params())) {
899 InsetListingsParams const par(to_utf8(params()["lstparams"]));
900 if (par.getParamValue("caption").empty())
901 listings_label_.clear();
903 Counters & counters = buffer.params().getTextClass().counters();
904 docstring const cnt = from_ascii("listing");
905 if (counters.hasCounter(cnt)) {
907 listings_label_ = buffer.B_("Program Listing ")
908 + convert<docstring>(counters.value(cnt));
910 listings_label_ = buffer.B_("Program Listing");
916 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
917 EmbeddedFiles & files) const
919 // include and input are temprarily not considered.
920 if (isVerbatim(params()) || isListings(params()))
921 files.registerFile(includedFilename(buffer, params()).absFilename(),