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/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;
79 using std::istringstream;
81 using std::ostringstream;
84 namespace Alert = frontend::Alert;
89 docstring const uniqueID()
91 static unsigned int seed = 1000;
92 return "file" + convert<docstring>(++seed);
96 /// the type of inclusion
98 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
102 Types type(std::string const & s)
106 if (s == "verbatiminput")
108 if (s == "verbatiminput*")
110 if (s == "lstinputlisting")
118 Types type(InsetCommandParams const & params)
120 return type(params.getCmdName());
124 bool isListings(InsetCommandParams const & params)
126 return type(params) == LISTINGS;
130 bool isVerbatim(InsetCommandParams const & params)
132 Types const t = type(params);
133 return t == VERB || t == VERBAST;
137 bool isInputOrInclude(InsetCommandParams const & params)
139 Types const t = type(params);
140 return t == INPUT || t == INCLUDE;
146 InsetInclude::InsetInclude(InsetCommandParams const & p)
147 : InsetCommand(p, "include"), include_label(uniqueID()),
148 preview_(new RenderMonitoredPreview(this)), set_label_(false)
150 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
154 InsetInclude::InsetInclude(InsetInclude const & other)
155 : InsetCommand(other), include_label(other.include_label),
156 preview_(new RenderMonitoredPreview(this)), set_label_(false)
158 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
162 CommandInfo const * InsetInclude::findInfo(std::string const & /* cmdName */)
164 // This is only correct for the case of listings, but it'll do for now.
165 // In the other cases, this second parameter should just be empty.
166 static const char * const paramnames[] = {"filename", "lstparams", ""};
167 static const bool isoptional[] = {false, true};
168 static const CommandInfo info = {2, paramnames, isoptional};
173 bool InsetInclude::isCompatibleCommand(std::string const & s)
175 return type(s) != NONE;
179 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
181 switch (cmd.action) {
183 case LFUN_INSET_MODIFY: {
184 InsetCommandParams p(INCLUDE_CODE);
185 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
186 if (!p.getCmdName().empty()) {
188 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
189 InsetListingsParams par_new(to_utf8(p["lstparams"]));
190 if (par_old.getParamValue("label") !=
191 par_new.getParamValue("label")
192 && !par_new.getParamValue("label").empty())
193 cur.bv().buffer().changeRefsIfUnique(
194 from_utf8(par_old.getParamValue("label")),
195 from_utf8(par_new.getParamValue("label")),
198 set(p, cur.buffer());
199 cur.buffer().updateBibfilesCache();
205 //pass everything else up the chain
207 InsetCommand::doDispatch(cur, cmd);
215 FileName const masterFileName(Buffer const & buffer)
217 return buffer.masterBuffer()->fileName();
221 string const parentFilename(Buffer const & buffer)
223 return buffer.absFileName();
227 FileName const includedFilename(Buffer const & buffer,
228 InsetCommandParams const & params)
230 return makeAbsPath(to_utf8(params["filename"]),
231 onlyPath(parentFilename(buffer)));
235 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
240 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
245 if (preview_->monitoring())
246 preview_->stopMonitoring();
248 if (type(params()) == INPUT)
249 add_preview(*preview_, *this, buffer);
253 Inset * InsetInclude::clone() const
255 return new InsetInclude(*this);
259 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
263 switch (type(params())) {
265 temp = buf.B_("Input");
268 temp = buf.B_("Verbatim Input");
271 temp = buf.B_("Verbatim Input*");
274 temp = buf.B_("Include");
277 temp = listings_label_;
285 if (params()["filename"].empty())
288 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
296 /// return the child buffer if the file is a LyX doc and is loaded
297 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
299 if (isVerbatim(params) || isListings(params))
302 string const included_file = includedFilename(buffer, params).absFilename();
303 if (!isLyXFilename(included_file))
306 Buffer * childBuffer = theBufferList().getBuffer(included_file);
308 //FIXME RECURSIVE INCLUDES
309 if (childBuffer == & buffer)
318 /// return true if the file is or got loaded.
319 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
321 if (isVerbatim(params) || isListings(params))
324 string const parent_filename = parent.absFileName();
325 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
326 onlyPath(parent_filename));
328 if (!isLyXFilename(included_file.absFilename()))
331 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
333 // the readonly flag can/will be wrong, not anymore I think.
334 if (!included_file.exists())
337 child = theBufferList().newBuffer(included_file.absFilename());
338 if (!child->loadLyXFile(included_file)) {
339 //close the buffer we just opened
340 theBufferList().close(child, false);
344 child->setParentName(parent_filename);
349 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
350 OutputParams const & runparams) const
352 string incfile(to_utf8(params()["filename"]));
354 // Do nothing if no file name has been specified
358 FileName const included_file = includedFilename(buffer, params());
360 //Check we're not trying to include ourselves.
361 //FIXME RECURSIVE INCLUDE
362 //This isn't sufficient, as the inclusion could be downstream.
363 //But it'll have to do for now.
364 if (isInputOrInclude(params()) &&
365 buffer.absFileName() == included_file.absFilename())
367 Alert::error(_("Recursive input"),
368 bformat(_("Attempted to include file %1$s in itself! "
369 "Ignoring inclusion."), from_utf8(incfile)));
373 Buffer const * const masterBuffer = buffer.masterBuffer();
375 // if incfile is relative, make it relative to the master
377 if (!absolutePath(incfile)) {
379 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
380 from_utf8(masterBuffer->filePath())));
383 // write it to a file (so far the complete file)
384 string const exportfile = changeExtension(incfile, ".tex");
385 string const mangled =
386 DocFileName(changeExtension(included_file.absFilename(),".tex")).
388 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
392 else if (!isValidLaTeXFilename(incfile)) {
393 frontend::Alert::warning(_("Invalid filename"),
394 _("The following filename is likely to cause trouble "
395 "when running the exported file through LaTeX: ") +
398 LYXERR(Debug::LATEX, "incfile:" << incfile);
399 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
400 LYXERR(Debug::LATEX, "writefile:" << writefile);
402 if (runparams.inComment || runparams.dryrun) {
403 //Don't try to load or copy the file if we're
404 //in a comment or doing a dryrun
405 } else if (isInputOrInclude(params()) &&
406 isLyXFilename(included_file.absFilename())) {
407 //if it's a LyX file and we're inputting or including,
408 //try to load it so we can write the associated latex
409 if (!loadIfNeeded(buffer, params()))
412 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
414 if (tmp->params().getBaseClass() != masterBuffer->params().getBaseClass()) {
416 docstring text = bformat(_("Included file `%1$s'\n"
417 "has textclass `%2$s'\n"
418 "while parent file has textclass `%3$s'."),
419 included_file.displayName(),
420 from_utf8(tmp->params().getTextClass().name()),
421 from_utf8(masterBuffer->params().getTextClass().name()));
422 Alert::warning(_("Different textclasses"), text);
426 // Make sure modules used in child are all included in master
427 //FIXME It might be worth loading the children's modules into the master
428 //over in BufferParams rather than doing this check.
429 vector<string> const masterModules = masterBuffer->params().getModules();
430 vector<string> const childModules = tmp->params().getModules();
431 vector<string>::const_iterator it = childModules.begin();
432 vector<string>::const_iterator end = childModules.end();
433 for (; it != end; ++it) {
434 string const module = *it;
435 vector<string>::const_iterator found =
436 find(masterModules.begin(), masterModules.end(), module);
437 if (found != masterModules.end()) {
438 docstring text = bformat(_("Included file `%1$s'\n"
439 "uses module `%2$s'\n"
440 "which is not used in parent file."),
441 included_file.displayName(), from_utf8(module));
442 Alert::warning(_("Module not found"), text);
446 tmp->markDepClean(masterBuffer->temppath());
448 // FIXME: handle non existing files
449 // FIXME: Second argument is irrelevant!
450 // since only_body is true, makeLaTeXFile will not look at second
451 // argument. Should we set it to string(), or should makeLaTeXFile
452 // make use of it somehow? (JMarc 20031002)
453 // The included file might be written in a different encoding
454 Encoding const * const oldEnc = runparams.encoding;
455 runparams.encoding = &tmp->params().encoding();
456 tmp->makeLaTeXFile(writefile,
457 masterFileName(buffer).onlyPath().absFilename(),
459 runparams.encoding = oldEnc;
461 // In this case, it's not a LyX file, so we copy the file
462 // to the temp dir, so that .aux files etc. are not created
463 // in the original dir. Files included by this file will be
464 // found via input@path, see ../Buffer.cpp.
465 unsigned long const checksum_in = included_file.checksum();
466 unsigned long const checksum_out = writefile.checksum();
468 if (checksum_in != checksum_out) {
469 if (!copy(included_file, writefile)) {
472 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
473 "into the temporary directory."),
474 from_utf8(included_file.absFilename()))));
480 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
481 "latex" : "pdflatex";
482 if (isVerbatim(params())) {
483 incfile = latex_path(incfile);
485 os << '\\' << from_ascii(params().getCmdName()) << '{'
486 << from_utf8(incfile) << '}';
487 } else if (type(params()) == INPUT) {
488 runparams.exportdata->addExternalFile(tex_format, writefile,
491 // \input wants file with extension (default is .tex)
492 if (!isLyXFilename(included_file.absFilename())) {
493 incfile = latex_path(incfile);
495 os << '\\' << from_ascii(params().getCmdName())
496 << '{' << from_utf8(incfile) << '}';
498 incfile = changeExtension(incfile, ".tex");
499 incfile = latex_path(incfile);
501 os << '\\' << from_ascii(params().getCmdName())
502 << '{' << from_utf8(incfile) << '}';
504 } else if (type(params()) == LISTINGS) {
505 os << '\\' << from_ascii(params().getCmdName());
506 string const opt = to_utf8(params()["lstparams"]);
507 // opt is set in QInclude dialog and should have passed validation.
508 InsetListingsParams params(opt);
509 if (!params.params().empty())
510 os << "[" << from_utf8(params.params()) << "]";
511 os << '{' << from_utf8(incfile) << '}';
513 runparams.exportdata->addExternalFile(tex_format, writefile,
516 // \include don't want extension and demands that the
517 // file really have .tex
518 incfile = changeExtension(incfile, string());
519 incfile = latex_path(incfile);
521 os << '\\' << from_ascii(params().getCmdName()) << '{'
522 << from_utf8(incfile) << '}';
529 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
530 OutputParams const &) const
532 if (isVerbatim(params()) || isListings(params())) {
533 os << '[' << getScreenLabel(buffer) << '\n';
534 // FIXME: We don't know the encoding of the file
535 docstring const str =
536 from_utf8(includedFilename(buffer, params()).fileContents());
539 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
541 docstring const str = '[' + getScreenLabel(buffer) + ']';
548 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
549 OutputParams const & runparams) const
551 string incfile = to_utf8(params()["filename"]);
553 // Do nothing if no file name has been specified
557 string const included_file = includedFilename(buffer, params()).absFilename();
559 //Check we're not trying to include ourselves.
560 //FIXME RECURSIVE INCLUDE
561 //This isn't sufficient, as the inclusion could be downstream.
562 //But it'll have to do for now.
563 if (buffer.absFileName() == included_file) {
564 Alert::error(_("Recursive input"),
565 bformat(_("Attempted to include file %1$s in itself! "
566 "Ignoring inclusion."), from_utf8(incfile)));
570 // write it to a file (so far the complete file)
571 string const exportfile = changeExtension(incfile, ".sgml");
572 DocFileName writefile(changeExtension(included_file, ".sgml"));
574 if (loadIfNeeded(buffer, params())) {
575 Buffer * tmp = theBufferList().getBuffer(included_file);
577 string const mangled = writefile.mangledFilename();
578 writefile = makeAbsPath(mangled,
579 buffer.masterBuffer()->temppath());
583 LYXERR(Debug::LATEX, "incfile:" << incfile);
584 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
585 LYXERR(Debug::LATEX, "writefile:" << writefile);
587 tmp->makeDocBookFile(writefile, runparams, true);
590 runparams.exportdata->addExternalFile("docbook", writefile,
592 runparams.exportdata->addExternalFile("docbook-xml", writefile,
595 if (isVerbatim(params()) || isListings(params())) {
596 os << "<inlinegraphic fileref=\""
597 << '&' << include_label << ';'
598 << "\" format=\"linespecific\">";
600 os << '&' << include_label << ';';
606 void InsetInclude::validate(LaTeXFeatures & features) const
608 string incfile = to_utf8(params()["filename"]);
611 Buffer const & buffer = features.buffer();
613 string const included_file = includedFilename(buffer, params()).absFilename();
615 if (isLyXFilename(included_file))
616 writefile = changeExtension(included_file, ".sgml");
618 writefile = included_file;
620 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
621 incfile = DocFileName(writefile).mangledFilename();
622 writefile = makeAbsPath(incfile,
623 buffer.masterBuffer()->temppath()).absFilename();
626 features.includeFile(include_label, writefile);
628 if (isVerbatim(params()))
629 features.require("verbatim");
630 else if (isListings(params()))
631 features.require("listings");
633 // Here we must do the fun stuff...
634 // Load the file in the include if it needs
636 if (loadIfNeeded(buffer, params())) {
638 Buffer * const tmp = theBufferList().getBuffer(included_file);
639 // make sure the buffer isn't us
640 // FIXME RECURSIVE INCLUDES
641 // This is not sufficient, as recursive includes could be
642 // more than a file away. But it will do for now.
643 if (tmp && tmp != & buffer) {
644 // We must temporarily change features.buffer,
645 // otherwise it would always be the master buffer,
646 // and nested includes would not work.
647 features.setBuffer(*tmp);
648 tmp->validate(features);
649 features.setBuffer(buffer);
655 void InsetInclude::getLabelList(Buffer const & buffer,
656 std::vector<docstring> & list) const
658 if (isListings(params())) {
659 InsetListingsParams p(to_utf8(params()["lstparams"]));
660 string label = p.getParamValue("label");
662 list.push_back(from_utf8(label));
664 else if (loadIfNeeded(buffer, params())) {
665 string const included_file = includedFilename(buffer, params()).absFilename();
666 Buffer * tmp = theBufferList().getBuffer(included_file);
667 tmp->setParentName("");
668 tmp->getLabelList(list);
669 tmp->setParentName(parentFilename(buffer));
674 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
675 BiblioInfo & keys, InsetIterator const & /*di*/) const
677 if (loadIfNeeded(buffer, params())) {
678 string const included_file = includedFilename(buffer, params()).absFilename();
679 Buffer * tmp = theBufferList().getBuffer(included_file);
680 //FIXME This is kind of a dirty hack and should be made reasonable.
681 tmp->setParentName("");
682 keys.fillWithBibKeys(tmp);
683 tmp->setParentName(parentFilename(buffer));
688 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
690 Buffer * const tmp = getChildBuffer(buffer, params());
692 tmp->setParentName("");
693 tmp->updateBibfilesCache();
694 tmp->setParentName(parentFilename(buffer));
699 std::vector<FileName> const &
700 InsetInclude::getBibfilesCache(Buffer const & buffer) const
702 Buffer * const tmp = getChildBuffer(buffer, params());
704 tmp->setParentName("");
705 std::vector<FileName> const & cache = tmp->getBibfilesCache();
706 tmp->setParentName(parentFilename(buffer));
709 static std::vector<FileName> const empty;
714 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
716 BOOST_ASSERT(mi.base.bv);
718 bool use_preview = false;
719 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
720 graphics::PreviewImage const * pimage =
721 preview_->getPreviewImage(mi.base.bv->buffer());
722 use_preview = pimage && pimage->image();
726 preview_->metrics(mi, dim);
730 button_.update(getScreenLabel(mi.base.bv->buffer()),
733 button_.metrics(mi, dim);
736 Box b(0, dim.wid, -dim.asc, dim.des);
741 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
743 BOOST_ASSERT(pi.base.bv);
745 bool use_preview = false;
746 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
747 graphics::PreviewImage const * pimage =
748 preview_->getPreviewImage(pi.base.bv->buffer());
749 use_preview = pimage && pimage->image();
753 preview_->draw(pi, x, y);
755 button_.draw(pi, x, y);
759 Inset::DisplayType InsetInclude::display() const
761 return type(params()) == INPUT ? Inline : AlignCenter;
770 void InsetInclude::fileChanged() const
772 Buffer const * const buffer = updateFrontend();
776 preview_->removePreview(*buffer);
777 add_preview(*preview_.get(), *this, *buffer);
778 preview_->startLoading(*buffer);
784 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
786 FileName const included_file = includedFilename(buffer, params);
788 return type(params) == INPUT && params.preview() &&
789 included_file.isReadableFile();
793 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
796 // We don't need to set runparams.encoding since this will be done
797 // by latex() anyway.
798 OutputParams runparams(0);
799 runparams.flavor = OutputParams::LATEX;
800 inset.latex(buffer, os, runparams);
806 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
807 Buffer const & buffer)
809 InsetCommandParams const & params = inset.params();
810 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
811 preview_wanted(params, buffer)) {
812 renderer.setAbsFile(includedFilename(buffer, params));
813 docstring const snippet = latex_string(inset, buffer);
814 renderer.addPreview(snippet, buffer);
821 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
823 Buffer const & buffer = ploader.buffer();
824 if (preview_wanted(params(), buffer)) {
825 preview_->setAbsFile(includedFilename(buffer, params()));
826 docstring const snippet = latex_string(*this, buffer);
827 preview_->addPreview(snippet, ploader);
832 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
833 ParConstIterator const & pit) const
835 if (isListings(params())) {
836 InsetListingsParams p(to_utf8(params()["lstparams"]));
837 string caption = p.getParamValue("caption");
840 Toc & toc = toclist["listing"];
841 docstring const str = convert<docstring>(toc.size() + 1)
842 + ". " + from_utf8(caption);
843 // This inset does not have a valid ParConstIterator
844 // so it has to use the iterator of its parent paragraph
845 toc.push_back(TocItem(pit, 0, str));
848 Buffer const * const childbuffer = getChildBuffer(buffer, params());
852 TocList const & childtoclist = childbuffer->tocBackend().tocs();
853 TocList::const_iterator it = childtoclist.begin();
854 TocList::const_iterator const end = childtoclist.end();
855 for(; it != end; ++it)
856 toclist[it->first].insert(toclist[it->first].end(),
857 it->second.begin(), it->second.end());
861 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
863 Buffer const * const childbuffer = getChildBuffer(buffer, params());
865 lyx::updateLabels(*childbuffer, true);
866 else if (isListings(params())) {
867 InsetListingsParams const par(to_utf8(params()["lstparams"]));
868 if (par.getParamValue("caption").empty())
869 listings_label_.clear();
871 Counters & counters = buffer.params().getTextClass().counters();
872 docstring const cnt = from_ascii("listing");
873 if (counters.hasCounter(cnt)) {
875 listings_label_ = buffer.B_("Program Listing ")
876 + convert<docstring>(counters.value(cnt));
878 listings_label_ = buffer.B_("Program Listing");
884 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
885 EmbeddedFiles & files) const
887 // include and input are temprarily not considered.
888 if (isVerbatim(params()) || isListings(params()))
889 files.registerFile(includedFilename(buffer, params()).absFilename(),