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;
80 using std::istringstream;
82 using std::ostringstream;
85 namespace Alert = frontend::Alert;
90 docstring const uniqueID()
92 static unsigned int seed = 1000;
93 return "file" + convert<docstring>(++seed);
97 /// the type of inclusion
99 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
103 Types type(std::string const & s)
107 if (s == "verbatiminput")
109 if (s == "verbatiminput*")
111 if (s == "lstinputlisting")
119 Types type(InsetCommandParams const & params)
121 return type(params.getCmdName());
125 bool isListings(InsetCommandParams const & params)
127 return type(params) == LISTINGS;
131 bool isVerbatim(InsetCommandParams const & params)
133 Types const t = type(params);
134 return t == VERB || t == VERBAST;
138 bool isInputOrInclude(InsetCommandParams const & params)
140 Types const t = type(params);
141 return t == INPUT || t == INCLUDE;
147 InsetInclude::InsetInclude(InsetCommandParams const & p)
148 : InsetCommand(p, "include"), include_label(uniqueID()),
149 preview_(new RenderMonitoredPreview(this)), set_label_(false)
151 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
155 InsetInclude::InsetInclude(InsetInclude const & other)
156 : InsetCommand(other), include_label(other.include_label),
157 preview_(new RenderMonitoredPreview(this)), set_label_(false)
159 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
163 CommandInfo const * InsetInclude::findInfo(std::string const & /* cmdName */)
165 // This is only correct for the case of listings, but it'll do for now.
166 // In the other cases, this second parameter should just be empty.
167 static const char * const paramnames[] = {"filename", "lstparams", ""};
168 static const bool isoptional[] = {false, true};
169 static const CommandInfo info = {2, paramnames, isoptional};
174 bool InsetInclude::isCompatibleCommand(std::string const & s)
176 return type(s) != NONE;
180 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
182 switch (cmd.action) {
184 case LFUN_INSET_MODIFY: {
185 InsetCommandParams p(INCLUDE_CODE);
186 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
187 if (!p.getCmdName().empty()) {
189 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
190 InsetListingsParams par_new(to_utf8(p["lstparams"]));
191 if (par_old.getParamValue("label") !=
192 par_new.getParamValue("label")
193 && !par_new.getParamValue("label").empty())
194 cur.bv().buffer().changeRefsIfUnique(
195 from_utf8(par_old.getParamValue("label")),
196 from_utf8(par_new.getParamValue("label")),
199 set(p, cur.buffer());
200 cur.buffer().updateBibfilesCache();
206 //pass everything else up the chain
208 InsetCommand::doDispatch(cur, cmd);
216 FileName const masterFileName(Buffer const & buffer)
218 return buffer.masterBuffer()->fileName();
222 string const parentFilename(Buffer const & buffer)
224 return buffer.absFileName();
228 FileName const includedFilename(Buffer const & buffer,
229 InsetCommandParams const & params)
231 return makeAbsPath(to_utf8(params["filename"]),
232 onlyPath(parentFilename(buffer)));
236 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
241 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
246 if (preview_->monitoring())
247 preview_->stopMonitoring();
249 if (type(params()) == INPUT)
250 add_preview(*preview_, *this, buffer);
254 Inset * InsetInclude::clone() const
256 return new InsetInclude(*this);
260 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
264 switch (type(params())) {
266 temp = buf.B_("Input");
269 temp = buf.B_("Verbatim Input");
272 temp = buf.B_("Verbatim Input*");
275 temp = buf.B_("Include");
278 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);
400 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
401 LYXERR(Debug::LATEX, "writefile:" << writefile);
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()))));
481 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
482 "latex" : "pdflatex";
483 if (isVerbatim(params())) {
484 incfile = latex_path(incfile);
486 os << '\\' << from_ascii(params().getCmdName()) << '{'
487 << from_utf8(incfile) << '}';
488 } else if (type(params()) == INPUT) {
489 runparams.exportdata->addExternalFile(tex_format, writefile,
492 // \input wants file with extension (default is .tex)
493 if (!isLyXFilename(included_file.absFilename())) {
494 incfile = latex_path(incfile);
496 os << '\\' << from_ascii(params().getCmdName())
497 << '{' << from_utf8(incfile) << '}';
499 incfile = changeExtension(incfile, ".tex");
500 incfile = latex_path(incfile);
502 os << '\\' << from_ascii(params().getCmdName())
503 << '{' << from_utf8(incfile) << '}';
505 } else if (type(params()) == LISTINGS) {
506 os << '\\' << from_ascii(params().getCmdName());
507 string const opt = to_utf8(params()["lstparams"]);
508 // opt is set in QInclude dialog and should have passed validation.
509 InsetListingsParams params(opt);
510 if (!params.params().empty())
511 os << "[" << from_utf8(params.params()) << "]";
512 os << '{' << from_utf8(incfile) << '}';
514 runparams.exportdata->addExternalFile(tex_format, writefile,
517 // \include don't want extension and demands that the
518 // file really have .tex
519 incfile = changeExtension(incfile, string());
520 incfile = latex_path(incfile);
522 os << '\\' << from_ascii(params().getCmdName()) << '{'
523 << from_utf8(incfile) << '}';
530 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
531 OutputParams const &) const
533 if (isVerbatim(params()) || isListings(params())) {
534 os << '[' << getScreenLabel(buffer) << '\n';
535 // FIXME: We don't know the encoding of the file
536 docstring const str =
537 from_utf8(includedFilename(buffer, params()).fileContents());
540 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
542 docstring const str = '[' + getScreenLabel(buffer) + ']';
549 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
550 OutputParams const & runparams) const
552 string incfile = to_utf8(params()["filename"]);
554 // Do nothing if no file name has been specified
558 string const included_file = includedFilename(buffer, params()).absFilename();
560 //Check we're not trying to include ourselves.
561 //FIXME RECURSIVE INCLUDE
562 //This isn't sufficient, as the inclusion could be downstream.
563 //But it'll have to do for now.
564 if (buffer.absFileName() == included_file) {
565 Alert::error(_("Recursive input"),
566 bformat(_("Attempted to include file %1$s in itself! "
567 "Ignoring inclusion."), from_utf8(incfile)));
571 // write it to a file (so far the complete file)
572 string const exportfile = changeExtension(incfile, ".sgml");
573 DocFileName writefile(changeExtension(included_file, ".sgml"));
575 if (loadIfNeeded(buffer, params())) {
576 Buffer * tmp = theBufferList().getBuffer(included_file);
578 string const mangled = writefile.mangledFilename();
579 writefile = makeAbsPath(mangled,
580 buffer.masterBuffer()->temppath());
584 LYXERR(Debug::LATEX, "incfile:" << incfile);
585 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
586 LYXERR(Debug::LATEX, "writefile:" << writefile);
588 tmp->makeDocBookFile(writefile, runparams, true);
591 runparams.exportdata->addExternalFile("docbook", writefile,
593 runparams.exportdata->addExternalFile("docbook-xml", writefile,
596 if (isVerbatim(params()) || isListings(params())) {
597 os << "<inlinegraphic fileref=\""
598 << '&' << include_label << ';'
599 << "\" format=\"linespecific\">";
601 os << '&' << include_label << ';';
607 void InsetInclude::validate(LaTeXFeatures & features) const
609 string incfile = to_utf8(params()["filename"]);
612 Buffer const & buffer = features.buffer();
614 string const included_file = includedFilename(buffer, params()).absFilename();
616 if (isLyXFilename(included_file))
617 writefile = changeExtension(included_file, ".sgml");
619 writefile = included_file;
621 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
622 incfile = DocFileName(writefile).mangledFilename();
623 writefile = makeAbsPath(incfile,
624 buffer.masterBuffer()->temppath()).absFilename();
627 features.includeFile(include_label, writefile);
629 if (isVerbatim(params()))
630 features.require("verbatim");
631 else if (isListings(params()))
632 features.require("listings");
634 // Here we must do the fun stuff...
635 // Load the file in the include if it needs
637 if (loadIfNeeded(buffer, params())) {
639 Buffer * const tmp = theBufferList().getBuffer(included_file);
640 // make sure the buffer isn't us
641 // FIXME RECURSIVE INCLUDES
642 // This is not sufficient, as recursive includes could be
643 // more than a file away. But it will do for now.
644 if (tmp && tmp != & buffer) {
645 // We must temporarily change features.buffer,
646 // otherwise it would always be the master buffer,
647 // and nested includes would not work.
648 features.setBuffer(*tmp);
649 tmp->validate(features);
650 features.setBuffer(buffer);
656 void InsetInclude::getLabelList(Buffer const & buffer,
657 std::vector<docstring> & list) const
659 if (isListings(params())) {
660 InsetListingsParams p(to_utf8(params()["lstparams"]));
661 string label = p.getParamValue("label");
663 list.push_back(from_utf8(label));
665 else if (loadIfNeeded(buffer, params())) {
666 string const included_file = includedFilename(buffer, params()).absFilename();
667 Buffer * tmp = theBufferList().getBuffer(included_file);
668 tmp->setParentName("");
669 tmp->getLabelList(list);
670 tmp->setParentName(parentFilename(buffer));
675 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
676 BiblioInfo & keys, InsetIterator const & /*di*/) const
678 if (loadIfNeeded(buffer, params())) {
679 string const included_file = includedFilename(buffer, params()).absFilename();
680 Buffer * tmp = theBufferList().getBuffer(included_file);
681 //FIXME This is kind of a dirty hack and should be made reasonable.
682 tmp->setParentName("");
683 keys.fillWithBibKeys(tmp);
684 tmp->setParentName(parentFilename(buffer));
689 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
691 Buffer * const tmp = getChildBuffer(buffer, params());
693 tmp->setParentName("");
694 tmp->updateBibfilesCache();
695 tmp->setParentName(parentFilename(buffer));
700 std::vector<FileName> const &
701 InsetInclude::getBibfilesCache(Buffer const & buffer) const
703 Buffer * const tmp = getChildBuffer(buffer, params());
705 tmp->setParentName("");
706 std::vector<FileName> const & cache = tmp->getBibfilesCache();
707 tmp->setParentName(parentFilename(buffer));
710 static std::vector<FileName> const empty;
715 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
717 BOOST_ASSERT(mi.base.bv);
719 bool use_preview = false;
720 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
721 graphics::PreviewImage const * pimage =
722 preview_->getPreviewImage(mi.base.bv->buffer());
723 use_preview = pimage && pimage->image();
727 preview_->metrics(mi, dim);
731 button_.update(getScreenLabel(mi.base.bv->buffer()),
734 button_.metrics(mi, dim);
737 Box b(0, dim.wid, -dim.asc, dim.des);
742 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
744 BOOST_ASSERT(pi.base.bv);
746 bool use_preview = false;
747 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
748 graphics::PreviewImage const * pimage =
749 preview_->getPreviewImage(pi.base.bv->buffer());
750 use_preview = pimage && pimage->image();
754 preview_->draw(pi, x, y);
756 button_.draw(pi, x, y);
760 Inset::DisplayType InsetInclude::display() const
762 return type(params()) == INPUT ? Inline : AlignCenter;
771 void InsetInclude::fileChanged() const
773 Buffer const * const buffer = updateFrontend();
777 preview_->removePreview(*buffer);
778 add_preview(*preview_.get(), *this, *buffer);
779 preview_->startLoading(*buffer);
785 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
787 FileName const included_file = includedFilename(buffer, params);
789 return type(params) == INPUT && params.preview() &&
790 included_file.isFileReadable();
794 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
797 // We don't need to set runparams.encoding since this will be done
798 // by latex() anyway.
799 OutputParams runparams(0);
800 runparams.flavor = OutputParams::LATEX;
801 inset.latex(buffer, os, runparams);
807 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
808 Buffer const & buffer)
810 InsetCommandParams const & params = inset.params();
811 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
812 preview_wanted(params, buffer)) {
813 renderer.setAbsFile(includedFilename(buffer, params));
814 docstring const snippet = latex_string(inset, buffer);
815 renderer.addPreview(snippet, buffer);
822 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
824 Buffer const & buffer = ploader.buffer();
825 if (preview_wanted(params(), buffer)) {
826 preview_->setAbsFile(includedFilename(buffer, params()));
827 docstring const snippet = latex_string(*this, buffer);
828 preview_->addPreview(snippet, ploader);
833 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
834 ParConstIterator const & pit) const
836 if (isListings(params())) {
837 InsetListingsParams p(to_utf8(params()["lstparams"]));
838 string caption = p.getParamValue("caption");
841 Toc & toc = toclist["listing"];
842 docstring const str = convert<docstring>(toc.size() + 1)
843 + ". " + from_utf8(caption);
844 // This inset does not have a valid ParConstIterator
845 // so it has to use the iterator of its parent paragraph
846 toc.push_back(TocItem(pit, 0, str));
849 Buffer const * const childbuffer = getChildBuffer(buffer, params());
853 TocList const & childtoclist = childbuffer->tocBackend().tocs();
854 TocList::const_iterator it = childtoclist.begin();
855 TocList::const_iterator const end = childtoclist.end();
856 for(; it != end; ++it)
857 toclist[it->first].insert(toclist[it->first].end(),
858 it->second.begin(), it->second.end());
862 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
864 Buffer const * const childbuffer = getChildBuffer(buffer, params());
866 lyx::updateLabels(*childbuffer, true);
867 else if (isListings(params())) {
868 InsetListingsParams const par(to_utf8(params()["lstparams"]));
869 if (par.getParamValue("caption").empty())
870 listings_label_.clear();
872 Counters & counters = buffer.params().getTextClass().counters();
873 docstring const cnt = from_ascii("listing");
874 if (counters.hasCounter(cnt)) {
876 listings_label_ = buffer.B_("Program Listing ")
877 + convert<docstring>(counters.value(cnt));
879 listings_label_ = buffer.B_("Program Listing");
885 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
886 EmbeddedFiles & files) const
888 // include and input are temprarily not considered.
889 if (isVerbatim(params()) || isListings(params()))
890 files.registerFile(includedFilename(buffer, params()).absFilename(),