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
8 * Full author contact details are available in file CREDITS.
13 #include "InsetInclude.h"
16 #include "buffer_funcs.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "BufferView.h"
22 #include "DispatchResult.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
27 #include "LaTeXFeatures.h"
31 #include "MetricsInfo.h"
32 #include "OutputParams.h"
33 #include "TocBackend.h"
35 #include "frontends/alert.h"
36 #include "frontends/Painter.h"
38 #include "graphics/PreviewImage.h"
39 #include "graphics/PreviewLoader.h"
41 #include "insets/RenderPreview.h"
42 #include "insets/InsetListingsParams.h"
44 #include "support/filetools.h"
45 #include "support/lstrings.h" // contains
46 #include "support/lyxalgo.h"
47 #include "support/lyxlib.h"
48 #include "support/convert.h"
50 #include <boost/bind.hpp>
51 #include <boost/filesystem/operations.hpp>
56 // Implementation is in LyX.cpp
57 extern void dispatch(FuncRequest const & action);
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::getFileContents;
68 using support::getVectorFromString;
69 using support::isFileReadable;
70 using support::isLyXFilename;
71 using support::isValidLaTeXFilename;
72 using support::latex_path;
73 using support::makeAbsPath;
74 using support::makeDisplayPath;
75 using support::makeRelPath;
76 using support::onlyFilename;
77 using support::onlyPath;
78 using support::prefixIs;
85 using std::istringstream;
87 using std::ostringstream;
90 namespace Alert = frontend::Alert;
91 namespace fs = boost::filesystem;
96 docstring const uniqueID()
98 static unsigned int seed = 1000;
99 return "file" + convert<docstring>(++seed);
103 bool isListings(InsetCommandParams const & params)
105 return params.getCmdName() == "lstinputlisting";
111 InsetInclude::InsetInclude(InsetCommandParams const & p)
112 : params_(p), include_label(uniqueID()),
113 preview_(new RenderMonitoredPreview(this)),
114 set_label_(false), counter_(0)
116 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
120 InsetInclude::InsetInclude(InsetInclude const & other)
122 params_(other.params_),
123 include_label(other.include_label),
124 preview_(new RenderMonitoredPreview(this)),
125 set_label_(false), counter_(0)
127 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
131 InsetInclude::~InsetInclude()
133 InsetIncludeMailer(*this).hideDialog();
137 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
139 switch (cmd.action) {
141 case LFUN_INSET_MODIFY: {
142 InsetCommandParams p("include");
143 InsetIncludeMailer::string2params(to_utf8(cmd.argument()), p);
144 if (!p.getCmdName().empty()) {
146 InsetListingsParams par_old(params().getOptions());
147 InsetListingsParams par_new(p.getOptions());
148 if (par_old.getParamValue("label") !=
149 par_new.getParamValue("label")
150 && !par_new.getParamValue("label").empty())
151 cur.bv().buffer()->changeRefsIfUnique(
152 from_utf8(par_old.getParamValue("label")),
153 from_utf8(par_new.getParamValue("label")),
156 set(p, cur.buffer());
157 cur.buffer().updateBibfilesCache();
163 case LFUN_INSET_DIALOG_UPDATE:
164 InsetIncludeMailer(*this).updateDialog(&cur.bv());
167 case LFUN_MOUSE_RELEASE:
168 if (!cur.selection())
169 InsetIncludeMailer(*this).showDialog(&cur.bv());
173 Inset::doDispatch(cur, cmd);
179 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
180 FuncStatus & flag) const
182 switch (cmd.action) {
184 case LFUN_INSET_MODIFY:
185 case LFUN_INSET_DIALOG_UPDATE:
190 return Inset::getStatus(cur, cmd, flag);
195 InsetCommandParams const & InsetInclude::params() const
203 /// the type of inclusion
213 Types type(InsetCommandParams const & params)
215 string const command_name = params.getCmdName();
217 if (command_name == "input")
219 if (command_name == "verbatiminput")
221 if (command_name == "verbatiminput*")
223 if (command_name == "lstinputlisting")
229 bool isVerbatim(InsetCommandParams const & params)
231 string const command_name = params.getCmdName();
232 return command_name == "verbatiminput" ||
233 command_name == "verbatiminput*";
237 bool isInputOrInclude(InsetCommandParams const & params)
239 Types const t = type(params);
240 return (t == INPUT) || (t == INCLUDE);
244 string const masterFilename(Buffer const & buffer)
246 return buffer.getMasterBuffer()->fileName();
250 string const parentFilename(Buffer const & buffer)
252 return buffer.fileName();
256 FileName const includedFilename(Buffer const & buffer,
257 InsetCommandParams const & params)
259 return makeAbsPath(to_utf8(params["filename"]),
260 onlyPath(parentFilename(buffer)));
264 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
269 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
274 if (preview_->monitoring())
275 preview_->stopMonitoring();
277 if (type(params_) == INPUT)
278 add_preview(*preview_, *this, buffer);
282 auto_ptr<Inset> InsetInclude::doClone() const
284 return auto_ptr<Inset>(new InsetInclude(*this));
288 void InsetInclude::write(Buffer const &, ostream & os) const
294 void InsetInclude::write(ostream & os) const
296 os << "Include " << to_utf8(params_.getCommand()) << '\n'
297 << "preview " << convert<string>(params_.preview()) << '\n';
301 void InsetInclude::read(Buffer const &, Lexer & lex)
307 void InsetInclude::read(Lexer & lex)
311 string const command = lex.getString();
312 params_.scanCommand(command);
317 token = lex.getString();
318 if (token == "\\end_inset")
320 if (token == "preview") {
322 params_.preview(lex.getBool());
324 lex.printError("Unknown parameter name `$$Token' for command " + params_.getCmdName());
326 if (token != "\\end_inset") {
327 lex.printError("Missing \\end_inset at this point. "
333 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
337 switch (type(params_)) {
339 temp += buf.B_("Input");
342 temp += buf.B_("Verbatim Input");
345 temp += buf.B_("Verbatim Input*");
348 temp += buf.B_("Include");
352 temp += buf.B_("Program Listing ") + convert<docstring>(counter_);
354 temp += buf.B_("Program Listing");
361 if (params_["filename"].empty())
364 temp += from_utf8(onlyFilename(to_utf8(params_["filename"])));
372 /// return the child buffer if the file is a LyX doc and is loaded
373 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
375 if (isVerbatim(params) || isListings(params))
378 string const included_file = includedFilename(buffer, params).absFilename();
379 if (!isLyXFilename(included_file))
382 Buffer * childBuffer = theBufferList().getBuffer(included_file);
384 //FIXME RECURSIVE INCLUDES
385 if (childBuffer == & buffer)
392 /// return true if the file is or got loaded.
393 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
395 if (isVerbatim(params) || isListings(params))
398 FileName const included_file = includedFilename(buffer, params);
399 if (!isLyXFilename(included_file.absFilename()))
402 Buffer * buf = theBufferList().getBuffer(included_file.absFilename());
404 // the readonly flag can/will be wrong, not anymore I think.
405 if (!fs::exists(included_file.toFilesystemEncoding()))
407 lyx::dispatch(FuncRequest(LFUN_BUFFER_CHILD_OPEN,
408 included_file.absFilename() + "|true"));
409 buf = theBufferList().getBuffer(included_file.absFilename());
412 buf->setParentName(parentFilename(buffer));
420 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
421 OutputParams const & runparams) const
423 string incfile(to_utf8(params_["filename"]));
425 // Do nothing if no file name has been specified
429 FileName const included_file(includedFilename(buffer, params_));
431 //Check we're not trying to include ourselves.
432 //FIXME RECURSIVE INCLUDE
433 //This isn't sufficient, as the inclusion could be downstream.
434 //But it'll have to do for now.
435 if (isInputOrInclude(params_) &&
436 buffer.fileName() == included_file.absFilename())
438 Alert::error(_("Recursive input"),
439 bformat(_("Attempted to include file %1$s in itself! "
440 "Ignoring inclusion."), from_utf8(incfile)));
444 Buffer const * const m_buffer = buffer.getMasterBuffer();
446 // if incfile is relative, make it relative to the master
448 if (!absolutePath(incfile)) {
450 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
451 from_utf8(m_buffer->filePath())));
454 // write it to a file (so far the complete file)
455 string const exportfile = changeExtension(incfile, ".tex");
456 string const mangled =
457 DocFileName(changeExtension(included_file.absFilename(),".tex")).
459 FileName const writefile(makeAbsPath(mangled, m_buffer->temppath()));
463 else if (!isValidLaTeXFilename(incfile)) {
464 frontend::Alert::warning(_("Invalid filename"),
465 _("The following filename is likely to cause trouble "
466 "when running the exported file through LaTeX: ") +
469 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
470 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
471 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
473 if (runparams.inComment || runparams.dryrun) {
474 //Don't try to load or copy the file if we're
475 //in a comment or doing a dryrun
476 } else if (isInputOrInclude(params_) &&
477 isLyXFilename(included_file.absFilename())) {
478 //if it's a LyX file and we're inputting or including,
479 //try to load it so we can write the associated latex
480 if (!loadIfNeeded(buffer, params_))
483 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
485 if (tmp->params().textclass != m_buffer->params().textclass) {
487 docstring text = bformat(_("Included file `%1$s'\n"
488 "has textclass `%2$s'\n"
489 "while parent file has textclass `%3$s'."),
490 makeDisplayPath(included_file.absFilename()),
491 from_utf8(tmp->params().getTextClass().name()),
492 from_utf8(m_buffer->params().getTextClass().name()));
493 Alert::warning(_("Different textclasses"), text);
497 tmp->markDepClean(m_buffer->temppath());
500 #warning handle non existing files
501 #warning Second argument is irrelevant!
502 // since only_body is true, makeLaTeXFile will not look at second
503 // argument. Should we set it to string(), or should makeLaTeXFile
504 // make use of it somehow? (JMarc 20031002)
506 // The included file might be written in a different encoding
507 Encoding const * const oldEnc = runparams.encoding;
508 runparams.encoding = &tmp->params().encoding();
509 tmp->makeLaTeXFile(writefile,
510 onlyPath(masterFilename(buffer)),
512 runparams.encoding = oldEnc;
514 // In this case, it's not a LyX file, so we copy the file
515 // to the temp dir, so that .aux files etc. are not created
516 // in the original dir. Files included by this file will be
517 // found via input@path, see ../Buffer.cpp.
518 unsigned long const checksum_in = sum(included_file);
519 unsigned long const checksum_out = sum(writefile);
521 if (checksum_in != checksum_out) {
522 if (!copy(included_file, writefile)) {
525 << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
526 "into the temporary directory."),
527 from_utf8(included_file.absFilename())))
534 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
535 "latex" : "pdflatex";
536 if (isVerbatim(params_)) {
537 incfile = latex_path(incfile);
539 os << '\\' << from_ascii(params_.getCmdName()) << '{'
540 << from_utf8(incfile) << '}';
541 } else if (type(params_) == INPUT) {
542 runparams.exportdata->addExternalFile(tex_format, writefile,
545 // \input wants file with extension (default is .tex)
546 if (!isLyXFilename(included_file.absFilename())) {
547 incfile = latex_path(incfile);
549 os << '\\' << from_ascii(params_.getCmdName())
550 << '{' << from_utf8(incfile) << '}';
552 incfile = changeExtension(incfile, ".tex");
553 incfile = latex_path(incfile);
555 os << '\\' << from_ascii(params_.getCmdName())
556 << '{' << from_utf8(incfile) << '}';
558 } else if (type(params_) == LISTINGS) {
559 os << '\\' << from_ascii(params_.getCmdName());
560 string opt = params_.getOptions();
561 // opt is set in QInclude dialog and should have passed validation.
562 InsetListingsParams params(opt);
563 if (!params.params().empty())
564 os << "[" << from_utf8(params.params()) << "]";
565 os << '{' << from_utf8(incfile) << '}';
567 runparams.exportdata->addExternalFile(tex_format, writefile,
570 // \include don't want extension and demands that the
571 // file really have .tex
572 incfile = changeExtension(incfile, string());
573 incfile = latex_path(incfile);
575 os << '\\' << from_ascii(params_.getCmdName()) << '{'
576 << from_utf8(incfile) << '}';
583 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
584 OutputParams const &) const
586 if (isVerbatim(params_) || isListings(params_)) {
587 os << '[' << getScreenLabel(buffer) << '\n';
588 // FIXME: We don't know the encoding of the file
589 docstring const str =
590 from_utf8(getFileContents(includedFilename(buffer, params_)));
593 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
595 docstring const str = '[' + getScreenLabel(buffer) + ']';
602 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
603 OutputParams const & runparams) const
605 string incfile = to_utf8(params_["filename"]);
607 // Do nothing if no file name has been specified
611 string const included_file = includedFilename(buffer, params_).absFilename();
613 //Check we're not trying to include ourselves.
614 //FIXME RECURSIVE INCLUDE
615 //This isn't sufficient, as the inclusion could be downstream.
616 //But it'll have to do for now.
617 if (buffer.fileName() == included_file) {
618 Alert::error(_("Recursive input"),
619 bformat(_("Attempted to include file %1$s in itself! "
620 "Ignoring inclusion."), from_utf8(incfile)));
624 // write it to a file (so far the complete file)
625 string const exportfile = changeExtension(incfile, ".sgml");
626 DocFileName writefile(changeExtension(included_file, ".sgml"));
628 if (loadIfNeeded(buffer, params_)) {
629 Buffer * tmp = theBufferList().getBuffer(included_file);
631 string const mangled = writefile.mangledFilename();
632 writefile = makeAbsPath(mangled,
633 buffer.getMasterBuffer()->temppath());
637 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
638 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
639 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
641 tmp->makeDocBookFile(writefile, runparams, true);
644 runparams.exportdata->addExternalFile("docbook", writefile,
646 runparams.exportdata->addExternalFile("docbook-xml", writefile,
649 if (isVerbatim(params_) || isListings(params_)) {
650 os << "<inlinegraphic fileref=\""
651 << '&' << include_label << ';'
652 << "\" format=\"linespecific\">";
654 os << '&' << include_label << ';';
660 void InsetInclude::validate(LaTeXFeatures & features) const
662 string incfile(to_utf8(params_["filename"]));
665 Buffer const & buffer = features.buffer();
667 string const included_file = includedFilename(buffer, params_).absFilename();
669 if (isLyXFilename(included_file))
670 writefile = changeExtension(included_file, ".sgml");
672 writefile = included_file;
674 if (!features.runparams().nice && !isVerbatim(params_) && !isListings(params_)) {
675 incfile = DocFileName(writefile).mangledFilename();
676 writefile = makeAbsPath(incfile,
677 buffer.getMasterBuffer()->temppath()).absFilename();
680 features.includeFile(include_label, writefile);
682 if (isVerbatim(params_))
683 features.require("verbatim");
684 else if (isListings(params_))
685 features.require("listings");
687 // Here we must do the fun stuff...
688 // Load the file in the include if it needs
690 if (loadIfNeeded(buffer, params_)) {
692 Buffer * const tmp = theBufferList().getBuffer(included_file);
693 // make sure the buffer isn't us
694 // FIXME RECURSIVE INCLUDES
695 // This is not sufficient, as recursive includes could be
696 // more than a file away. But it will do for now.
697 if (tmp && tmp != & buffer) {
698 // We must temporarily change features.buffer,
699 // otherwise it would always be the master buffer,
700 // and nested includes would not work.
701 features.setBuffer(*tmp);
702 tmp->validate(features);
703 features.setBuffer(buffer);
709 void InsetInclude::getLabelList(Buffer const & buffer,
710 std::vector<docstring> & list) const
712 if (isListings(params_)) {
713 InsetListingsParams params(params_.getOptions());
714 string label = params.getParamValue("label");
716 list.push_back(from_utf8(label));
718 else if (loadIfNeeded(buffer, params_)) {
719 string const included_file = includedFilename(buffer, params_).absFilename();
720 Buffer * tmp = theBufferList().getBuffer(included_file);
721 tmp->setParentName("");
722 tmp->getLabelList(list);
723 tmp->setParentName(parentFilename(buffer));
728 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
729 std::vector<std::pair<string, docstring> > & keys) const
731 if (loadIfNeeded(buffer, params_)) {
732 string const included_file = includedFilename(buffer, params_).absFilename();
733 Buffer * tmp = theBufferList().getBuffer(included_file);
734 tmp->setParentName("");
735 tmp->fillWithBibKeys(keys);
736 tmp->setParentName(parentFilename(buffer));
741 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
743 Buffer * const tmp = getChildBuffer(buffer, params_);
745 tmp->setParentName("");
746 tmp->updateBibfilesCache();
747 tmp->setParentName(parentFilename(buffer));
752 std::vector<FileName> const &
753 InsetInclude::getBibfilesCache(Buffer const & buffer) const
755 Buffer * const tmp = getChildBuffer(buffer, params_);
757 tmp->setParentName("");
758 std::vector<FileName> const & cache = tmp->getBibfilesCache();
759 tmp->setParentName(parentFilename(buffer));
762 static std::vector<FileName> const empty;
767 bool InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
769 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
771 bool use_preview = false;
772 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
773 graphics::PreviewImage const * pimage =
774 preview_->getPreviewImage(*mi.base.bv->buffer());
775 use_preview = pimage && pimage->image();
779 preview_->metrics(mi, dim);
783 button_.update(getScreenLabel(*mi.base.bv->buffer()),
786 button_.metrics(mi, dim);
789 Box b(0, dim.wid, -dim.asc, dim.des);
792 bool const changed = dim_ != dim;
798 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
800 setPosCache(pi, x, y);
802 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
804 bool use_preview = false;
805 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
806 graphics::PreviewImage const * pimage =
807 preview_->getPreviewImage(*pi.base.bv->buffer());
808 use_preview = pimage && pimage->image();
812 preview_->draw(pi, x, y);
814 button_.draw(pi, x, y);
818 Inset::DisplayType InsetInclude::display() const
820 return type(params_) == INPUT ? Inline : AlignCenter;
829 void InsetInclude::fileChanged() const
831 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
835 Buffer const & buffer = *buffer_ptr;
836 preview_->removePreview(buffer);
837 add_preview(*preview_.get(), *this, buffer);
838 preview_->startLoading(buffer);
844 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
846 FileName const included_file = includedFilename(buffer, params);
848 return type(params) == INPUT && params.preview() &&
849 isFileReadable(included_file);
853 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
856 // We don't need to set runparams.encoding since this will be done
857 // by latex() anyway.
858 OutputParams runparams(0);
859 runparams.flavor = OutputParams::LATEX;
860 inset.latex(buffer, os, runparams);
866 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
867 Buffer const & buffer)
869 InsetCommandParams const & params = inset.params();
870 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
871 preview_wanted(params, buffer)) {
872 renderer.setAbsFile(includedFilename(buffer, params));
873 docstring const snippet = latex_string(inset, buffer);
874 renderer.addPreview(snippet, buffer);
881 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
883 Buffer const & buffer = ploader.buffer();
884 if (preview_wanted(params(), buffer)) {
885 preview_->setAbsFile(includedFilename(buffer, params()));
886 docstring const snippet = latex_string(*this, buffer);
887 preview_->addPreview(snippet, ploader);
892 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer, ParConstIterator const & pit) const
894 if (isListings(params_)) {
895 InsetListingsParams params(params_.getOptions());
896 string caption = params.getParamValue("caption");
897 if (!caption.empty()) {
898 Toc & toc = toclist["listing"];
899 docstring const str = convert<docstring>(toc.size() + 1)
900 + ". " + from_utf8(caption);
901 // This inset does not have a valid ParConstIterator
902 // so it has to use the iterator of its parent paragraph
903 toc.push_back(TocItem(pit, 0, str));
907 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
911 TocList const & childtoclist = childbuffer->tocBackend().tocs();
912 TocList::const_iterator it = childtoclist.begin();
913 TocList::const_iterator const end = childtoclist.end();
914 for(; it != end; ++it)
915 toclist[it->first].insert(toclist[it->first].end(),
916 it->second.begin(), it->second.end());
920 void InsetInclude::updateLabels(Buffer const & buffer) const
922 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
926 lyx::updateLabels(*childbuffer, true);
930 void InsetInclude::updateCounter(Counters & counters)
932 if (!isListings(params_))
935 InsetListingsParams const par = params_.getOptions();
936 if (par.getParamValue("caption").empty())
939 counters.step(from_ascii("listing"));
940 counter_ = counters.value(from_ascii("listing"));
945 string const InsetIncludeMailer::name_("include");
947 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
952 string const InsetIncludeMailer::inset2string(Buffer const &) const
954 return params2string(inset_.params());
958 void InsetIncludeMailer::string2params(string const & in,
959 InsetCommandParams & params)
965 istringstream data(in);
971 if (!lex || name != name_)
972 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
974 // This is part of the inset proper that is usually swallowed
975 // by Text::readInset
978 if (!lex || id != "Include")
979 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
981 InsetInclude inset(params);
983 params = inset.params();
988 InsetIncludeMailer::params2string(InsetCommandParams const & params)
990 InsetInclude inset(params);
992 data << name_ << ' ';
994 data << "\\end_inset\n";